// ============================================================
// ChatPanel — 消息展示面板
// 职责：渲染对话消息列表、流式光标、元数据、自动滚动、文本输入
// ============================================================

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

interface ChatPanelProps {
  messages: ChatMessage[];
  currentReply?: string;
  connectionStatus: ConnectionStatus;
  onSendText?: (text: string) => void;
}

export function ChatPanel({ messages, currentReply, connectionStatus, onSendText }: 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";

  // 用户上滚时暂停自动滚动，滚到底部时恢复
  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("");
  };

  return (
    <div className="chat-panel">
      <div className="chat-panel__messages" ref={containerRef}>
        {/* 空状态提示 */}
        {messages.length === 0 && !currentReply && (
          <div className="chat-panel__welcome">
            <span className="chat-panel__welcome-icon">💬</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>
          </div>
        )}

        {messages.map((msg, index) => (
          <div key={index} 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>
        )}

        <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"}
          />
          <button
            type="submit"
            className="chat-input__send"
            disabled={!inputText.trim() || connectionStatus === "connecting"}
            title={t("chat.send")}
          >
            ➤
          </button>
        </form>
      )}
    </div>
  );
}
