// ============================================================
// ChatPanel — 消息展示面板
// 职责：渲染对话消息列表、流式光标、元数据、自动滚动、文本输入
// 增强：空状态情景选择卡片、语音输入按钮
// ============================================================

import { useEffect, useRef, useState, type ReactNode } from "react";
import { useI18n } from "../../lib/i18n";
import { scenarios } from "../../lib/scenarios";
import type { ChatMessage } from "../../types";
import type { ConnectionStatus } from "../../lib/websocket";

interface ChatPanelProps {
  messages: ChatMessage[];
  currentReply?: string;
  connectionStatus: ConnectionStatus;
  currentScenario?: string;
  isProcessing?: boolean;
  isVADReady?: boolean;
  vadError?: string | null;
  isCameraOn?: boolean;
  isMicOn?: boolean;
  isSpeaking?: boolean;
  onSendText?: (text: string) => void;
  onToggleMic?: () => void;
  onSceneCard?: (prompt: string) => void;
  onSelectScenario?: (scenarioId: string) => void;
}

/** 场景卡片数据（视觉分析快捷） */
function getSceneCards(t: (key: string) => string): { icon: ReactNode; titleKey: string; descKey: string; prompt: string }[] {
  const svgProps = { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round" as const, strokeLinejoin: "round" as const };
  return [
    { icon: <svg {...svgProps}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>, titleKey: "scene.describe", descKey: "scene.describe.desc", prompt: t("scene.describe") },
    { icon: <svg {...svgProps}><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>, titleKey: "scene.text", descKey: "scene.text.desc", prompt: t("scene.text") },
    { icon: <svg {...svgProps}><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>, titleKey: "scene.object", descKey: "scene.object.desc", prompt: t("scene.object") },
    { icon: <svg {...svgProps}><line x1="9" y1="18" x2="15" y2="18"/><line x1="10" y1="22" x2="14" y2="22"/><path d="M15.09 14c.18-.98.65-1.74 1.41-2.5A4.65 4.65 0 0 0 18 8 6 6 0 0 0 6 8c0 1 .23 2.23 1.5 3.5A4.61 4.61 0 0 1 8.91 14"/></svg>, titleKey: "scene.suggest", descKey: "scene.suggest.desc", prompt: t("scene.suggest") },
  ];
}

export function ChatPanel({
  messages,
  currentReply,
  connectionStatus,
  currentScenario,
  isProcessing,
  isVADReady,
  vadError,
  isCameraOn,
  isMicOn,
  isSpeaking,
  onSendText,
  onToggleMic,
  onSceneCard,
}: ChatPanelProps) {
  const bottomRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const isAutoScroll = useRef(true);
  const [inputText, setInputText] = useState("");
  const { t } = useI18n();

  const isConnected = connectionStatus === "connected";
  const isEmpty = messages.length === 0 && !currentReply;
  const sceneCards = getSceneCards(t);
  const activeScenario = currentScenario || "free_chat";
  const isFreeChat = activeScenario === "free_chat";

  // 用户上滚时暂停自动滚动，滚到底部时恢复
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      isAutoScroll.current = scrollHeight - scrollTop - clientHeight < 60;
    };

    container.addEventListener("scroll", handleScroll);
    return () => container.removeEventListener("scroll", handleScroll);
  }, []);

  // 新消息或流式更新时自动滚动
  useEffect(() => {
    if (isAutoScroll.current) {
      bottomRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, currentReply]);

  // 提交文本消息
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputText.trim() || !onSendText) return;
    onSendText(inputText);
    setInputText("");
  };

  // 点击场景卡片
  const handleSceneCard = (prompt: string) => {
    if (onSceneCard) {
      onSceneCard(prompt);
    } else if (onSendText) {
      onSendText(prompt);
    }
  };

  return (
    <div className="chat-panel">
      <div className="chat-panel__messages" ref={containerRef}>
        {/* 情景提示卡片（非空状态 + 非自由对话） */}
        {messages.length > 0 && !isFreeChat && (
          <div className="chat-panel__scenario-hint">
            <div className="scenario-hint-card">
              <span className="scenario-hint-card__icon">
                {scenarios.find(s => s.id === activeScenario)?.icon}
              </span>
              <div className="scenario-hint-card__text">
                <strong>{t(scenarios.find(s => s.id === activeScenario)?.nameKey || "")}</strong>
                <p>{t(`scenario.${activeScenario}.hint`)}</p>
              </div>
            </div>
          </div>
        )}

        {/* 空状态：欢迎信息 */}
        {isEmpty && (
          <div className="chat-panel__welcome">
            <span className="chat-panel__welcome-icon">{scenarios.find(s => s.id === activeScenario)?.icon || <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>}</span>
            <p>{isConnected ? t("chat.welcome.prompt") : t("chat.empty.prompt")}</p>
            <span className="chat-panel__welcome-hint">{isConnected ? t("chat.welcome.hint") : t("chat.empty.hint")}</span>

            {/* 视觉分析快捷卡片（仅 free_chat 模式 + 已连接） */}
            {isFreeChat && isConnected && (
              <div className="scene-cards">
                {sceneCards.map((card) => (
                  <button
                    key={card.titleKey}
                    className="scene-card"
                    onClick={() => handleSceneCard(card.prompt)}
                  >
                    <span className="scene-card__icon">{card.icon}</span>
                    <div className="scene-card__text">
                      <span className="scene-card__title">{t(card.titleKey)}</span>
                      <span className="scene-card__desc">{t(card.descKey)}</span>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

        {messages.map((msg) => (
          msg.role === "system" ? (
            <div key={msg.id} className="chat-message chat-message--system">
              <span className="chat-message--system__text">{msg.content}</span>
            </div>
          ) : (
            <div key={msg.id} className={`chat-message chat-message--${msg.role}`}>
              <div className="chat-message__role">
                {msg.role === "user" ? t("chat.userLabel") : "AI"}
              </div>
              <div className="chat-message__content">{msg.content}</div>
              {msg.role === "assistant" && msg.tokensUsed !== undefined && (
                <div className="chat-message__meta">
                  {msg.tokensUsed} tokens
                  {msg.latencyMs !== undefined && ` · ${(msg.latencyMs / 1000).toFixed(1)}s`}
                  {msg.model && ` · ${msg.model}`}
                </div>
              )}
            </div>
          )
        ))}

        {/* 流式回复（尚未完成） */}
        {currentReply && (
          <div className="chat-message chat-message--assistant chat-message--streaming">
            <div className="chat-message__role">AI</div>
            <div className="chat-message__content">
              {currentReply}
              <span className="cursor">▌</span>
            </div>
          </div>
        )}

        {/* 连接中状态 */}
        {connectionStatus === "connecting" && (
          <div className="system-message system-message--info">
            <span className="typing-indicator">
              <span className="typing-indicator__dot" />
              <span className="typing-indicator__dot" />
              <span className="typing-indicator__dot" />
            </span>
            <span>{t("chat.connecting")}</span>
          </div>
        )}

        {/* VAD 初始化中 */}
        {isConnected && isCameraOn && isVADReady === false && !vadError && (
          <div className="system-message system-message--info">
            <span className="typing-indicator">
              <span className="typing-indicator__dot" />
              <span className="typing-indicator__dot" />
              <span className="typing-indicator__dot" />
            </span>
            <span>{t("chat.vadInit")}</span>
          </div>
        )}

        {/* AI 处理中（尚未开始流式输出） */}
        {isProcessing && !currentReply && (
          <div className="chat-message chat-message--assistant">
            <div className="chat-message__role">AI</div>
            <div className="chat-message__content">
              <span className="typing-indicator">
                <span className="typing-indicator__dot" />
                <span className="typing-indicator__dot" />
                <span className="typing-indicator__dot" />
              </span>
            </div>
          </div>
        )}

        <div ref={bottomRef} />
      </div>

      {/* 文本输入框 - 始终显示 */}
      {onSendText && (
        <form className="chat-input" onSubmit={handleSubmit}>
          <input
            type="text"
            className="chat-input__field"
            placeholder={t("chat.input.placeholder")}
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            disabled={connectionStatus === "connecting"}
          />
          {/* 语音输入按钮 */}
          {onToggleMic && (
            <button
              type="button"
              className={`chat-input__voice ${isMicOn ? "chat-input__voice--active" : ""} ${isSpeaking ? "btn--speaking" : ""}`}
              onClick={onToggleMic}
              title={t("chat.input.voice")}
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
            </button>
          )}
          <button
            type="submit"
            className="chat-input__send"
            disabled={!inputText.trim() || connectionStatus === "connecting"}
            title={t("chat.send")}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
          </button>
        </form>
      )}
    </div>
  );
}
