"use client";

import { useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

type Message = {
  id: string;
  role: "user" | "bot";
  type?: "text" | "menu"; // "menu" = bong bóng hiển thị danh sách nút bấm (option) thay vì text
  text?: string;
  attachment?: {
    dataUrl: string;
    mimeType: string;
    name: string;
  };
};

type MenuOption = {
  label: string;
  url: string;
};
 
// ----- Cấu hình đa agent -----
// Mỗi agent map với 1 số ID cuối trong URL API: https://sagent.io.vn/sarvis/<id>
type AgentKey = "SARVIS" | "SCRMAI" | "SEDUAI";
 
const AGENT_CONFIG: Record<AgentKey, { label: string; endpointId: number }> = {
  SARVIS: { label: "SARVIS", endpointId: 177 },
  SCRMAI: { label: "SCRMAI", endpointId: 180 },
  SEDUAI: { label: "SEDUAI", endpointId: 190 },
};
 
const AGENT_LIST: AgentKey[] = ["SARVIS", "SCRMAI", "SEDUAI"];
const DEFAULT_AGENT: AgentKey = "SARVIS";
 
// Lưu agent đang chọn vào localStorage — F5 vẫn giữ đúng agent đang trò chuyện
const AGENT_STORAGE_KEY = "nks_selected_agent_v1";

// Bộ emoji thường dùng cho emoji picker đơn giản (không cần thư viện ngoài)
const EMOJI_LIST = [
  "😀", "😂", "😍", "🥰", "😅", "😊", "🙏", "👍",
  "👏", "🎉", "❤️", "🔥", "✅", "❌", "🤔", "😮",
  "😢", "😴", "💬", "📌", "⭐", "💯", "🙌", "👋",
];

const GREETING =
  "SARVIS xin chào. Bạn cần hỗ trợ gì hôm nay? 👋";

// Lưu lịch sử chat vào localStorage — F5 vẫn còn (chỉ mất khi người dùng xoá cache trình duyệt)
const STORAGE_KEY = "nks_chat_history_v1";

// ⚠️ TODO: thay 2 link Zalo bên dưới bằng link thật trước khi deploy
const MENU_OPTIONS: MenuOption[] = [
  { label: "💬 Chat với Boss Sunny", url: "https://zalo.me/THAY_LINK_ZALO_BOSS_SUNNY" },
  { label: "🤖 Hệ thống AI Agent", url: "https://nks.com.vn" },
  { label: "📣 Quan tâm Zalo OA", url: "https://zalo.me/THAY_LINK_ZALO_OA" },
];

// ----- Cấu hình chủ động bắt chuyện (proactive trigger) -----
// Thời gian không thao tác (di chuột/gõ phím/cuộn/chạm) trước khi AI chủ động lên tiếng
const IDLE_TRIGGER_MS = 20000; // 20 giây
 
const IDLE_MESSAGE =
  "Chào bạn! Mình thấy bạn đang tìm hiểu — bạn cần mình tư vấn thêm về dịch vụ nào không? 😊";
 
const EXIT_INTENT_MESSAGE =
  "Trước khi bạn rời đi — để lại câu hỏi, mình tư vấn ngay giúp bạn nhé! 🙌";
 
// Dùng sessionStorage để mỗi trigger chỉ hiện 1 lần / phiên truy cập (đóng tab mới reset)
const SESSION_IDLE_KEY = "nks_idle_triggered_v1";
const SESSION_EXIT_KEY = "nks_exit_triggered_v1";

export default function ChatWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([
    { id: "greeting", role: "bot", type: "text", text: GREETING },
  ]);
  const [input, setInput] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [pendingAttachment, setPendingAttachment] = useState<
    Message["attachment"] | null
  >(null);
  const [isRecording, setIsRecording] = useState(false);
  const [voiceSupported, setVoiceSupported] = useState(false);
  const [historyLoaded, setHistoryLoaded] = useState(false);
  const [teaserMessage, setTeaserMessage] = useState<string | null>(null);
  const [hasUnread, setHasUnread] = useState(false);
  const [selectedAgent, setSelectedAgent] = useState<AgentKey>(DEFAULT_AGENT);
  const [isAgentMenuOpen, setIsAgentMenuOpen] = useState(false);
  const [isEmojiPickerOpen, setIsEmojiPickerOpen] = useState(false);
  const [isInputFocused, setIsInputFocused] = useState(false);
 
  const scrollRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const recognitionRef = useRef<any>(null);
  // Giữ tham chiếu tới bản sendMessage mới nhất — cần thiết vì recognition.onresult
  // được gán 1 lần lúc mount (useEffect deps rỗng) nên không tự lấy được state mới nhất
  // nếu gọi sendMessage trực tiếp (sẽ bị "đóng băng" state tại thời điểm mount).
  const sendMessageRef = useRef<(overrideText?: string) => void>(() => {});

  // ----- 1. Lưu / khôi phục lịch sử chat (localStorage) -----
  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const parsed = JSON.parse(saved);
        if (Array.isArray(parsed) && parsed.length > 0) setMessages(parsed);
      }
    } catch (err) {
      console.warn("Không đọc được lịch sử chat đã lưu:", err);
    } finally {
      setHistoryLoaded(true);
    }
  }, []);
 
  useEffect(() => {
    if (!historyLoaded) return; // tránh ghi đè lịch sử cũ bằng state mặc định lúc mới mount
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
    } catch (err) {
      // Lỗi thường gặp: vượt quota localStorage (~5-10MB) nếu đính kèm nhiều ảnh/video lớn
      console.warn("Không lưu được lịch sử chat (có thể do vượt dung lượng):", err);
    }
  }, [messages, historyLoaded]);
 
  // ----- Khôi phục / lưu agent đang chọn -----
  useEffect(() => {
    try {
      const saved = localStorage.getItem(AGENT_STORAGE_KEY) as AgentKey | null;
      if (saved && AGENT_CONFIG[saved]) setSelectedAgent(saved);
    } catch (err) {
      console.warn("Không đọc được agent đã chọn:", err);
    }
  }, []);
 
  useEffect(() => {
    try {
      localStorage.setItem(AGENT_STORAGE_KEY, selectedAgent);
    } catch (err) {
      console.warn("Không lưu được agent đang chọn:", err);
    }
  }, [selectedAgent]);
 
  // Chọn agent mới -> đổi header + báo cho người dùng biết đã chuyển kênh trò chuyện
  function handleSelectAgent(agent: AgentKey) {
    setIsAgentMenuOpen(false);
    if (agent === selectedAgent) return;
    setSelectedAgent(agent);
    setMessages((prev) => [
      ...prev,
      {
        id: crypto.randomUUID(),
        role: "bot",
        type: "text",
        text: `Đã chuyển sang trò chuyện với ${AGENT_CONFIG[agent].label}. Bạn cần hỗ trợ gì?`,
      },
    ]);
  }

  // ----- 2. Khởi tạo Web Speech API cho voice chat -----
  useEffect(() => {
    const SpeechRecognition =
      (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;

    if (!SpeechRecognition) {
      setVoiceSupported(false);
      return;
    }

    const recognition = new SpeechRecognition();
    recognition.lang = "vi-VN";
    recognition.interimResults = false;
    recognition.maxAlternatives = 1;

    recognition.onresult = (event: any) => {
      const transcript = event.results?.[0]?.[0]?.transcript ?? "";
      setInput((prev) => (prev ? `${prev} ${transcript}` : transcript));
    };
    recognition.onerror = () => setIsRecording(false);
    recognition.onend = () => setIsRecording(false);

    recognitionRef.current = recognition;
    setVoiceSupported(true);

    return () => {
      recognition.onresult = null;
      recognition.onerror = null;
      recognition.onend = null;
    };
  }, []);

  function toggleRecording() {
    if (!recognitionRef.current) return;
    if (isRecording) {
      recognitionRef.current.stop();
      setIsRecording(false);
    } else {
      try {
        recognitionRef.current.start();
        setIsRecording(true);
      } catch (err) {
        // start() ném lỗi nếu đang chạy sẵn — bỏ qua an toàn
        console.warn("Không thể bắt đầu ghi âm:", err);
      }
    }
  }

  useEffect(() => {
    scrollRef.current?.scrollTo({
      top: scrollRef.current.scrollHeight,
      behavior: "smooth",
    });
  }, [messages, isOpen]);

  useEffect(() => {
    if (isOpen) inputRef.current?.focus();
  }, [isOpen]);

  useEffect(() => {
    if (!isFullscreen) return;
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") setIsFullscreen(false);
    }
    window.addEventListener("keydown", handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [isFullscreen]);

  useEffect(() => {
    if (!isOpen) setIsFullscreen(false);
  }, [isOpen]);

  // Khi mở chat, coi như khách đã "được chăm sóc" — tắt bong bóng gợi ý + badge chưa đọc
  useEffect(() => {
    if (isOpen) {
      setTeaserMessage(null);
      setHasUnread(false);
    }
  }, [isOpen]);

  // Đưa 1 tin nhắn "bot" vào lịch sử chat một cách chủ động (không do người dùng hỏi trước).
  // autoOpen=true: tự mở hẳn hộp thoại (dùng cho exit-intent — tình huống gấp, cần thu hút chú ý ngay).
  // autoOpen=false: chỉ hiện bong bóng gợi ý nhỏ cạnh icon chat, không làm phiền màn hình (dùng cho idle).
  function triggerProactiveMessage(text: string, autoOpen: boolean) {
    setMessages((prev) => [
      ...prev,
      { id: crypto.randomUUID(), role: "bot", type: "text", text },
    ]);

    if (autoOpen) {
      setIsOpen(true);
    } else {
      setTeaserMessage(text);
      setHasUnread(true);
    }
  }

  // ----- Idle-timer: khách không thao tác gì trong IDLE_TRIGGER_MS -> AI chủ động gợi chuyện -----
  useEffect(() => {
    if (isOpen) return; // đã đang chat rồi thì không cần gợi ý nữa
    if (typeof window === "undefined") return;
    if (sessionStorage.getItem(SESSION_IDLE_KEY)) return; // đã hiện 1 lần trong phiên này rồi

    let timer: ReturnType<typeof setTimeout>;

    function resetTimer() {
      clearTimeout(timer);
      timer = setTimeout(() => {
        triggerProactiveMessage(IDLE_MESSAGE, false);
        sessionStorage.setItem(SESSION_IDLE_KEY, "1");
        removeListeners();
      }, IDLE_TRIGGER_MS);
    }

    function removeListeners() {
      clearTimeout(timer);
      window.removeEventListener("mousemove", resetTimer);
      window.removeEventListener("keydown", resetTimer);
      window.removeEventListener("scroll", resetTimer);
      window.removeEventListener("touchstart", resetTimer);
    }

    window.addEventListener("mousemove", resetTimer);
    window.addEventListener("keydown", resetTimer);
    window.addEventListener("scroll", resetTimer);
    window.addEventListener("touchstart", resetTimer);
    resetTimer(); // bắt đầu đếm ngay khi vào trang

    return removeListeners;
  }, [isOpen]);

  // ----- Exit-intent: chuột rời khỏi mép trên cửa sổ (dấu hiệu sắp rời trang) -> AI giữ chân -----
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (sessionStorage.getItem(SESSION_EXIT_KEY)) return; // đã hiện 1 lần trong phiên này rồi
    if (isOpen) return; // đang chat sẵn rồi thì thôi

    function handleMouseOut(e: MouseEvent) {
      // clientY <= 0 nghĩa là chuột rời lên phía trên cùng trình duyệt (thường là để bấm nút back/đóng tab)
      if (e.clientY <= 0) {
        triggerProactiveMessage(EXIT_INTENT_MESSAGE, true);
        sessionStorage.setItem(SESSION_EXIT_KEY, "1");
      }
    }

    document.addEventListener("mouseout", handleMouseOut);
    return () => document.removeEventListener("mouseout", handleMouseOut);
  }, [isOpen]);

  // ----- 4. Chọn ảnh/media để đính kèm -----
  function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    // Giới hạn ~8MB để tránh localStorage bị đầy / request quá nặng
    if (file.size > 8 * 1024 * 1024) {
      alert("File quá lớn (giới hạn 8MB). Vui lòng chọn file nhỏ hơn.");
      e.target.value = "";
      return;
    }

    const reader = new FileReader();
    reader.onload = () => {
      setPendingAttachment({
        dataUrl: reader.result as string,
        mimeType: file.type,
        name: file.name,
      });
    };
    reader.readAsDataURL(file);
    e.target.value = ""; // cho phép chọn lại cùng 1 file lần sau
  }

  // ----- 3. Hiện menu 3 option dạng bong bóng bot -----
  function showMenu() {
    setMessages((prev) => [
      ...prev,
      { id: crypto.randomUUID(), role: "bot", type: "menu" },
    ]);
  }

  async function sendMessage(overrideText?: string) {
    const trimmed = input.trim();
    if (!trimmed && !pendingAttachment) return;
    if (isLoading) return;

    const userMsg: Message = {
      id: crypto.randomUUID(),
      role: "user",
      type: "text",
      text: trimmed || undefined,
      attachment: pendingAttachment || undefined,
    };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");
    setPendingAttachment(null);
    setIsLoading(true);

    try {
      const res = await fetch(`https://sagent.io.vn/sarvis/${AGENT_CONFIG[localStorage.getItem(AGENT_STORAGE_KEY)].endpointId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        // Lưu ý: gửi kèm "attachment" — xem ghi chú giả định API trong route.ts
        body: JSON.stringify({
          message: trimmed,
          attachment: userMsg.attachment ?? null,
        }),
      });

      const data = await res.json();

      const botText: string = res.ok
        ? data.result
        : data.error || "Đã có lỗi xảy ra, vui lòng thử lại.";

      setMessages((prev) => [
        ...prev,
        { id: crypto.randomUUID(), role: "bot", type: "text", text: botText },
      ]);
    } catch (err) {
      setMessages((prev) => [
        ...prev,
        {
          id: crypto.randomUUID(),
          role: "bot",
          type: "text",
          text: "Không thể kết nối tới máy chủ. Vui lòng kiểm tra mạng và thử lại.",
        },
      ]);
    } finally {
      setIsLoading(false);
    }
  }

  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") sendMessage();
  }
 
  // Luôn trỏ tới bản sendMessage mới nhất (state input/isLoading/pendingAttachment hiện tại)
  useEffect(() => {
    sendMessageRef.current = sendMessage;
  });
 
  // Người dùng click vào 1 "tên" (in đậm) trong danh sách bot trả về -> gửi thẳng tên đó lên chat
  function handleQuickReplyClick(text: string) {
    if (!text.trim()) return;
    sendMessage(text.trim());
  }
 
  const bubbleBase = {
    maxWidth: "78%",
    padding: "10px 14px",
    fontSize: 14,
    lineHeight: 1.5,
    wordBreak: "break-word" as const,
  };
 
  // Component render cho thẻ <strong> trong markdown — biến "tên" in đậm (vd: tên vị trí tuyển dụng)
  // thành 1 nút bấm được: click vào -> tự gửi đúng tên đó lên chat như 1 tin nhắn mới.
  const markdownComponents = {
    a: (props: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
      <a {...props} target="_blank" rel="noopener noreferrer" />
    ),
    strong: ({ children, ...props }: React.HTMLAttributes<HTMLElement>) => {
      const text = extractPlainText(children);
      return (
        <strong
          {...props}
          onClick={() => handleQuickReplyClick(text)}
          role="button"
          tabIndex={0}
          className="chat-quick-reply"
          onKeyDown={(e: React.KeyboardEvent) => {
            if (e.key === "Enter") handleQuickReplyClick(text);
          }}
        >
          {children}
        </strong>
      );
    },
  };

  return (
    <>
      {isOpen && isFullscreen && (
        <div
          style={{ position: "fixed", inset: 0, background: "#FAF9F6", zIndex: 999 }}
        />
      )}

      {isOpen && (
        <div
          role="dialog"
          aria-label="Hộp thoại chat"
          aria-modal={isFullscreen}
          style={
            isFullscreen
              ? {
                  position: "fixed",
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  width: "100vw",
                  height: "100vh",
                  background: "#FAF9F6",
                  borderRadius: 0,
                  boxShadow: "none",
                  display: "flex",
                  flexDirection: "column",
                  overflow: "hidden",
                  zIndex: 1008,
                  fontFamily:
                    "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
                }
              : {
                  position: "fixed",
                  bottom: 48,
                  right: 79,
                  width: 380,
                  maxWidth: "calc(100vw - 32px)",
                  height: 560,
                  maxHeight: "calc(100vh - 140px)",
                  background: "#FAF9F6",
                  borderRadius: 20,
                  boxShadow:
                    "0 20px 50px rgba(15, 76, 92, 0.25), 0 2px 8px rgba(0,0,0,0.08)",
                  display: "flex",
                  flexDirection: "column",
                  overflow: "hidden",
                  zIndex: 1005,
                  fontFamily:
                    "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
                  animation: "chatbox-slide-up 0.25s ease-out",
                }
          }
        >
          {/* Header */}
          <div
            style={{
              background: "#0077bb",
              color: "#fff",
              padding: "16px 20px",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              flexShrink: 0,
            }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div
                style={{ width: 10, height: 10, borderRadius: "50%", background: "#4ADE80" }}
              />
              <span style={{ fontWeight: 600, fontSize: 15 }}>
                {AGENT_CONFIG[selectedAgent].label}
              </span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
              <button
                onClick={() => setIsAgentMenuOpen((v) => !v)}
                aria-label="Chọn agent trò chuyện"
                title="Chọn agent trò chuyện"
                style={iconBtnStyle}
              >
                <UserIcon />
              </button>
              <button
                onClick={() => setIsFullscreen((v) => !v)}
                aria-label={isFullscreen ? "Thu nhỏ hộp thoại" : "Xem toàn màn hình"}
                title={isFullscreen ? "Thu nhỏ" : "Toàn màn hình"}
                style={iconBtnStyle}
              >
                {isFullscreen ? <CompressIcon /> : <ExpandIcon />}
              </button>
              <button
                onClick={() => setIsOpen(false)}
                aria-label="Đóng hộp thoại"
                style={iconBtnStyle}
              >
                <CloseIcon />
              </button>
            </div>
 
            {/* Popup chọn agent */}
            {isAgentMenuOpen && (
              <div
                style={{
                  position: "absolute",
                  top: "calc(100% + 8px)",
                  right: 20,
                  background: "#fff",
                  borderRadius: 12,
                  boxShadow: "0 10px 30px rgba(0,0,0,0.2)",
                  padding: 6,
                  width: 200,
                  zIndex: 10,
                }}
              >
                <div
                  style={{
                    fontSize: 11,
                    fontWeight: 600,
                    color: "#9CA3AF",
                    padding: "6px 10px 4px",
                    textTransform: "uppercase",
                    letterSpacing: 0.4,
                  }}
                >
                  Trao đổi với agent
                </div>
                {AGENT_LIST.map((key) => (
                  <button
                    key={key}
                    onClick={() => handleSelectAgent(key)}
                    style={{
                      width: "100%",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      textAlign: "left",
                      padding: "9px 10px",
                      borderRadius: 8,
                      border: "none",
                      background: key === selectedAgent ? "#0077bb" : "transparent",
                      color: "#1F2937",
                      fontSize: 13.5,
                      fontWeight: key === selectedAgent ? 600 : 500,
                      cursor: "pointer",
                    }}
                  >
                    {AGENT_CONFIG[key].label} <CheckIcon />
                    {key === selectedAgent}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Messages */}
          <div
            ref={scrollRef}
            style={{
              flex: 1,
              overflowY: "auto",
              padding: "16px",
              display: "flex",
              flexDirection: "column",
              gap: 10,
            }}
          >
            {messages.map((m) => (
              <div
                key={m.id}
                style={{
                  display: "flex",
                  justifyContent: m.role === "user" ? "flex-end" : "flex-start",
                }}
              >
                {m.type === "menu" ? (
                  <div
                    className="chat-bubble"
                    style={{
                      ...bubbleBase,
                      borderRadius: "16px 16px 16px 4px",
                      background: "#EDEEF0",
                      color: "#1F2937",
                    }}
                  >
                    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                      {MENU_OPTIONS.map((opt) => (
                        <button
                          key={opt.label}
                          onClick={() =>
                            window.open(opt.url, "_blank", "noopener,noreferrer")
                          }
                          style={menuOptionBtnStyle}
                        >
                          {opt.label}
                        </button>
                      ))}
                    </div>
                  </div>
                ) : (
                  <div
                    className="chat-bubble"
                    style={{
                      ...bubbleBase,
                      borderRadius:
                        m.role === "user" ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
                      background: m.role === "user" ? "#0077bb" : "#EDEEF0",
                      color: m.role === "user" ? "#fff" : "#1F2937",
                    }}
                  >
                    {m.attachment && (
                      <AttachmentPreview attachment={m.attachment} hasText={!!m.text} />
                    )}
                    {m.text &&
                      (m.role === "bot" ? (
                        <ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
                          {m.text}
                        </ReactMarkdown>
                      ) : (
                        <span style={{ whiteSpace: "pre-wrap" }}>{m.text}</span>
                      ))}
                  </div>
                )}
              </div>
            ))}

            {isLoading && (
              <div style={{ display: "flex", justifyContent: "flex-start" }}>
                <div
                  style={{
                    padding: "10px 14px",
                    borderRadius: "16px 16px 16px 4px",
                    background: "#EDEEF0",
                    display: "flex",
                    gap: 4,
                  }}
                >
                  <Dot delay={0} />
                  <Dot delay={0.15} />
                  <Dot delay={0.3} />
                </div>
              </div>
            )}
          </div>

          {/* Preview file đang chờ gửi */}
          {pendingAttachment && (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 10,
                padding: "8px 12px",
                borderTop: "1px solid #E5E7EB",
                background: "#fff",
              }}
            >
              <AttachmentPreview attachment={pendingAttachment} hasText={false} compact />
              <span style={{ fontSize: 12, color: "#6B7280", flex: 1 }}>
                {pendingAttachment.name}
              </span>
              <button
                onClick={() => setPendingAttachment(null)}
                aria-label="Bỏ file đính kèm"
                style={{ ...iconBtnStyle, color: "#6B7280", width: 26, height: 26 }}
              >
                <CloseIcon size={14} />
              </button>
            </div>
          )}

          {/* Input toolbar */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              padding: 10,
              borderTop: pendingAttachment ? "none" : "1px solid #E5E7EB",
              background: "#fff",
              flexShrink: 0,
            }}
          >
            <button
              onClick={showMenu}
              aria-label="Xem các kênh liên hệ"
              title="Các kênh liên hệ"
              style={toolbarBtnStyle}
            >
              <MenuIcon />
            </button>

            <button
              onClick={() => fileInputRef.current?.click()}
              aria-label="Đính kèm ảnh/media"
              title="Gửi hình ảnh, media"
              style={toolbarBtnStyle}
            >
              <PlusIcon />
            </button>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*,video/*"
              onChange={handleFileSelect}
              style={{ display: "none" }}
            />

            <input
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={isRecording ? "Đang nghe..." : "Nhập tin nhắn..."}
              disabled={isLoading}
              style={{
                color: "#000",
                flex: 1,
                minWidth: 0,
                border: "1px solid #E5E7EB",
                borderRadius: 999,
                padding: "10px 14px",
                fontSize: 14,
                outline: "none",
                background: "#F9FAFB",
              }}
            />

            {voiceSupported && (
              <button
                onClick={toggleRecording}
                aria-label={isRecording ? "Dừng ghi âm" : "Nhập bằng giọng nói"}
                title={isRecording ? "Dừng ghi âm" : "Nhập bằng giọng nói"}
                style={{
                  ...toolbarBtnStyle,
                  background: isRecording ? "#EF4444" : "transparent",
                  color: isRecording ? "#fff" : "#374151",
                  animation: isRecording ? "chatbox-mic-pulse 1.2s infinite" : "none",
                }}
              >
                <MicIcon />
              </button>
            )}

            <button
              onClick={sendMessage}
              disabled={isLoading || (!input.trim() && !pendingAttachment)}
              aria-label="Gửi tin nhắn"
              style={{
                width: 40,
                height: 40,
                borderRadius: "50%",
                border: "none",
                background:
                  input.trim() || pendingAttachment ? "#0F4C5C" : "#CBD5E1",
                color: "#fff",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                cursor: input.trim() || pendingAttachment ? "pointer" : "default",
                flexShrink: 0,
                transition: "background 0.15s ease",
              }}
            >
              <SendIcon />
            </button>
          </div>
        </div>
      )}

      {/* Bong bóng gợi ý chủ động (idle-timer) — chỉ hiện khi chat đang đóng */}
      {!isOpen && !isFullscreen && teaserMessage && (
        <div
          role="status"
          style={{
            position: "fixed",
            bottom: 166,
            right: 24,
            maxWidth: 260,
            background: "#fff",
            borderRadius: 16,
            borderBottomRightRadius: 4,
            padding: "12px 14px",
            boxShadow: "0 10px 30px rgba(15, 76, 92, 0.25), 0 2px 8px rgba(0,0,0,0.08)",
            display: "flex",
            gap: 8,
            alignItems: "flex-start",
            zIndex: 1001,
            fontFamily:
              "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
            animation: "chatbox-slide-up 0.25s ease-out",
          }}
        >
          <div
            onClick={() => setIsOpen(true)}
            style={{ flex: 1, fontSize: 13, lineHeight: 1.5, color: "#1F2937", cursor: "pointer" }}
          >
            {teaserMessage}
          </div>
          <button
            onClick={() => setTeaserMessage(null)}
            aria-label="Đóng gợi ý"
            style={{
              background: "transparent",
              border: "none",
              cursor: "pointer",
              color: "#9CA3AF",
              padding: 2,
              display: "flex",
              flexShrink: 0,
            }}
          >
            <CloseIcon size={14} />
          </button>
        </div>
      )}

      {!isFullscreen && (
        <button
          onClick={() => setIsOpen((v) => !v)}
          aria-label={isOpen ? "Đóng chat" : "Mở chat"}
          style={{
            position: "fixed",
            bottom: 105,
            right: 18,
            width: 50,
            height: 50,
            borderRadius: "50%",
            border: "none",
            background: "#0077bb",
            color: "#fff",
            boxShadow: "0 10px 30px rgba(15, 76, 92, 0.4)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            cursor: "pointer",
            zIndex: 1001,
            transition: "transform 0.15s ease",
          }}
          onMouseDown={(e) => (e.currentTarget.style.transform = "scale(0.92)")}
          onMouseUp={(e) => (e.currentTarget.style.transform = "scale(1)")}
        >
          {isOpen ? <CloseIcon size={26} /> : <ChatIcon />}
          {!isOpen && hasUnread && (
            <span
              style={{
                position: "absolute",
                top: 4,
                right: 4,
                width: 12,
                height: 12,
                borderRadius: "50%",
                background: "#EF4444",
                border: "2px solid #fff",
              }}
            />
          )}
        </button>
      )}

      <style>{`
        @keyframes chatbox-slide-up {
          from { opacity: 0; transform: translateY(16px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @keyframes chatbox-dot-bounce {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
          30% { transform: translateY(-4px); opacity: 1; }
        }
        @keyframes chatbox-mic-pulse {
          0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.5); }
          70% { box-shadow: 0 0 0 8px rgba(239, 68, 68, 0); }
          100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
        }

        .chat-bubble p { margin: 0 0 8px 0; }
        .chat-bubble p:last-child { margin-bottom: 0; }
        .chat-bubble ul, .chat-bubble ol { margin: 0 0 8px 0; padding-left: 20px; }
        .chat-bubble li { margin-bottom: 4px; }
        .chat-bubble a { color: #0077bb; text-decoration: underline; }
        .chat-bubble strong { font-weight: 700; }
        .chat-bubble blockquote {
          margin: 0 0 8px 0;
          padding-left: 10px;
          border-left: 3px solid #CBD5E1;
          color: #4B5563;
        }
        .chat-bubble code {
          background: rgba(0,0,0,0.06);
          padding: 2px 5px;
          border-radius: 4px;
          font-size: 13px;
          font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
        }
        .chat-bubble pre {
          background: #1F2937;
          color: #F9FAFB;
          padding: 10px 12px;
          border-radius: 8px;
          overflow-x: auto;
          margin: 0 0 8px 0;
        }
        .chat-bubble pre code { background: transparent; padding: 0; color: inherit; }
        .chat-bubble table { border-collapse: collapse; margin-bottom: 8px; font-size: 13px; }
        .chat-bubble th, .chat-bubble td { border: 1px solid #D1D5DB; padding: 4px 8px; text-align: left; }
      `}</style>
    </>
  );
}
 
const iconBtnStyle: React.CSSProperties = {
  background: "transparent",
  border: "none",
  color: "#fff",
  cursor: "pointer",
  padding: 6,
  display: "flex",
  opacity: 0.85,
};
 
const toolbarBtnStyle: React.CSSProperties = {
  width: 36,
  height: 36,
  borderRadius: "50%",
  border: "none",
  background: "transparent",
  color: "#374151",
  cursor: "pointer",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  flexShrink: 0,
  transition: "background 0.15s ease",
};
 
const menuOptionBtnStyle: React.CSSProperties = {
  textAlign: "left",
  padding: "10px 12px",
  borderRadius: 10,
  border: "1px solid #D1D5DB",
  background: "#fff",
  color: "#1F2937",
  fontSize: 13,
  cursor: "pointer",
};
 
// Lấy text thuần từ 1 React node (đệ quy) — dùng để lấy nội dung click gửi lên chat
// từ thẻ <strong> markdown, kể cả khi nó chứa nhiều node con lồng nhau.
function extractPlainText(node: React.ReactNode): string {
  if (typeof node === "string") return node;
  if (typeof node === "number") return String(node);
  if (Array.isArray(node)) return node.map(extractPlainText).join("");
  if (isValidElement(node)) {
    return extractPlainText((node.props as { children?: React.ReactNode }).children);
  }
  return "";
}
 
function AttachmentPreview({
  attachment,
  hasText,
  compact,
}: {
  attachment: NonNullable<Message["attachment"]>;
  hasText: boolean;
  compact?: boolean;
}) {
  const size = compact ? 40 : 200;
 
  if (attachment.mimeType.startsWith("image/")) {
    return (
      <img
        src={attachment.dataUrl}
        alt={attachment.name}
        style={{
          maxWidth: size,
          maxHeight: size,
          borderRadius: 10,
          display: "block",
          marginBottom: hasText ? 8 : 0,
          objectFit: "cover",
        }}
      />
    );
  }
 
  if (attachment.mimeType.startsWith("video/")) {
    return (
      <video
        src={attachment.dataUrl}
        controls={!compact}
        style={{
          maxWidth: compact ? size : 220,
          maxHeight: compact ? size : 220,
          borderRadius: 10,
          display: "block",
          marginBottom: hasText ? 8 : 0,
        }}
      />
    );
  }
 
  return (
    <a
      href={attachment.dataUrl}
      download={attachment.name}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 6,
        fontSize: 12,
        color: "inherit",
        textDecoration: "underline",
        marginBottom: hasText ? 8 : 0,
      }}
    >
      📎 {attachment.name}
    </a>
  );
}
 
function Dot({ delay }: { delay: number }) {
  return (
    <span
      style={{
        width: 6,
        height: 6,
        borderRadius: "50%",
        background: "#9CA3AF",
        display: "inline-block",
        animation: `chatbox-dot-bounce 1s ${delay}s infinite ease-in-out`,
      }}
    />
  );
}
 
function ChatIcon() {
  return (
    <svg width="26" height="26" viewBox="0 0 24 24" fill="none">
      <path
        d="M12 3C6.48 3 2 6.83 2 11.5c0 2.4 1.17 4.55 3.06 6.08-.1 1.02-.42 2.26-1.19 3.42-.1.15.03.34.2.3 1.62-.36 3-1.15 3.86-1.79.98.32 2.02.49 3.07.49 5.52 0 10-3.83 10-8.5S17.52 3 12 3z"
        fill="currentColor"
      />
    </svg>
  );
}
 
function CloseIcon({ size = 20 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
 
function ExpandIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path
        d="M9 3H3v6M15 3h6v6M21 15v6h-6M3 15v6h6"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}
 
function CompressIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path
        d="M4 9h5V4M20 9h-5V4M4 15h5v5M20 15h-5v5"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}
 
function SendIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path d="M3 11l18-8-8 18-2-8-8-2z" fill="currentColor" />
    </svg>
  );
}
 
function MenuIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <circle cx="5" cy="12" r="1.6" fill="currentColor" />
      <circle cx="12" cy="12" r="1.6" fill="currentColor" />
      <circle cx="19" cy="12" r="1.6" fill="currentColor" />
    </svg>
  );
}
 
function PlusIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
 
function MicIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <rect x="9" y="2" width="6" height="12" rx="3" fill="currentColor" />
      <path
        d="M5 11a7 7 0 0 0 14 0M12 18v4"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function UserIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2M12 11a4 4 0 100-8 4 4 0 000 8z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}
