"use client";
/* eslint-disable @next/next/no-img-element */
/**
 * FullscreenImageViewer 全屏图片查看器
 *
 * 
 *
 * 行为：
 *   - 全屏黑色背景 + 图片居中（contain）
 *   - 点击空白 / 下滑手势 → 关闭
 *   - 双指缩放（CSS `touch-action: pinch-zoom`）
 */
import { ChevronLeft } from "lucide-react";
import Image from "next/image";
import { useEffect } from "react";

import {
  isBrowserLocalChatImageSource,
  normalizeChatImageSource,
} from "@/lib/chat/chat_media_url";
import { useCachedChatMediaUrl } from "@/lib/chat/use_cached_chat_media_url";

import styles from "./fullscreen-image-viewer.module.css";

export interface FullscreenImageViewerProps {
  messageId?: string;
  imageUrl: string;
  imagePaywalled?: boolean;
  onUnlockImagePaywall?: () => void;
  onClose: () => void;
}

export function FullscreenImageViewer({
  messageId,
  imageUrl,
  imagePaywalled = false,
  onUnlockImagePaywall,
  onClose,
}: FullscreenImageViewerProps) {
  const { mediaUrl } = useCachedChatMediaUrl({
    messageId,
    remoteUrl: imageUrl,
    kind: "image",
  });

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", handleKey);
    return () => document.removeEventListener("keydown", handleKey);
  }, [onClose]);

  const src = normalizeChatImageSource(mediaUrl || imageUrl);
  const shouldUseNativeImage = isBrowserLocalChatImageSource(src);

  if (imagePaywalled) {
    return (
      <div
        className={`${styles.viewer} ${styles.paywallViewer}`}
        role="dialog"
        aria-label="Locked fullscreen image"
      >
        {shouldUseNativeImage ? (
          <img
            src={src}
            alt=""
            className={`${styles.nativePaywallImage} ${styles.paywallImage}`}
          />
        ) : (
          <Image
            src={src}
            alt=""
            fill
            sizes="(max-width: 540px) 100vw, 540px"
            className={styles.paywallImage}
          />
        )}
        <div className={styles.paywallScrim} aria-hidden="true" />
        <button
          type="button"
          className={styles.backButton}
          onClick={onClose}
          aria-label="Back"
        >
          <ChevronLeft size={34} strokeWidth={2.5} aria-hidden="true" />
        </button>
        <button
          type="button"
          className={styles.unlockButton}
          onClick={onUnlockImagePaywall}
        >
          Unlock high-definition large image
        </button>
      </div>
    );
  }

  return (
    <div
      className={styles.viewer}
      onClick={onClose}
      role="dialog"
      aria-label="Fullscreen image"
    >
      {shouldUseNativeImage ? (
        <img
          src={src}
          alt=""
          className={styles.viewerImage}
          onError={(e) => {
            e.currentTarget.style.display = "none";
            (e.currentTarget.parentElement as HTMLElement).innerHTML =
              '<div class="error">🖼</div>';
          }}
        />
      ) : (
        <Image
          src={src}
          alt=""
          width={800}
          height={800}
          className={styles.viewerImage}
          onError={(e) => {
            (e.currentTarget as HTMLImageElement).style.display = "none";
            (e.currentTarget.parentElement as HTMLElement).innerHTML =
              '<div class="error">🖼</div>';
          }}
        />
      )}
    </div>
  );
}
