"use client";
/* eslint-disable @next/next/no-img-element */
/**
 * ImageBubble 图片气泡
 *
 * 支持：
 *   - base64 data URI 解码（`data:image/png;base64,...`）
 *   - 点击 → 通知聊天页打开页内全屏查看器
 *   - 错误占位符（broken image icon）
 */
import Image from "next/image";
import { useState } from "react";

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

import styles from "./image-bubble.module.css";

export interface ImageBubbleProps {
  messageId?: string;
  imageUrl: string; // base64 data URI 或 URL
  imagePaywalled?: boolean;
  onOpenImage?: (messageId: string) => void;
}

export function ImageBubble({
  messageId,
  imageUrl,
  imagePaywalled = false,
  onOpenImage,
}: ImageBubbleProps) {
  const [errorSrc, setErrorSrc] = useState<string | null>(null);
  const { mediaUrl, isUsingCachedMedia, reportMediaError } =
    useCachedChatMediaUrl({
      messageId,
      remoteUrl: imageUrl,
      kind: "image",
    });

  const src = normalizeChatImageSource(mediaUrl || imageUrl);
  const canOpen = Boolean(messageId && onOpenImage);
  const shouldUseNativeImage = isBrowserLocalChatImageSource(src);
  const error = errorSrc === src;

  const handleImageError = () => {
    if (isUsingCachedMedia) {
      reportMediaError();
      return;
    }
    setErrorSrc(src);
  };

  const openImage = () => {
    if (!messageId || !onOpenImage) return;
    onOpenImage(messageId);
  };

  return (
    <div
      className={`${styles.bubble} ${imagePaywalled ? styles.paywalled : ""}`}
      onClick={openImage}
      role={canOpen ? "button" : undefined}
      tabIndex={canOpen ? 0 : undefined}
      onKeyDown={(e) => {
        if (!canOpen) return;
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          openImage();
        }
      }}
      aria-label={canOpen ? "Open image in fullscreen" : undefined}
    >
      {error ? (
        <div className={styles.errorFallback}>🖼</div>
      ) : shouldUseNativeImage ? (
        <img
          className={styles.image}
          src={src}
          alt=""
          onError={handleImageError}
        />
      ) : (
        <Image
          className={styles.image}
          src={src}
          alt=""
          width={240}
          height={240}
          onError={handleImageError}
        />
      )}
      {!error && imagePaywalled ? (
        <div className={styles.paywallOverlay} aria-hidden="true" />
      ) : null}
    </div>
  );
}
