/* ============================================================
   Dinasty AI Chat — conversational interface with Nova
   ============================================================ */

function ChatAI({ data }) {
  const [messages, setMessages] = useState([
    {
      role: "assistant",
      content:
        "Halo! Saya Nova, asisten AI Dinasty Control Anda.\n\nTanya apa saja tentang posisi terbuka, performa set, status AI, atau analisis trading. Data dashboard aktif saya sertakan sebagai konteks.",
    },
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const bottomRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, loading]);

  const buildContext = () => {
    const ov = (data && data.overview) || {};
    const rows = (data && data.rows) || [];
    const counts = ov.counts || {};
    const et = ov.equityTruth || {};
    const parts = [
      `Equity: $${fmtInt(ov.totalEquity || 0)}`,
      `Floating P/L: ${fmtSignedMoney(ov.floatingPL || 0)}`,
      `Daily P/L: ${fmtSignedMoney(ov.dailyPL || 0)}`,
      `AI Status: ${ov.aiStatus || "NORMAL"}`,
      `Open positions: ${counts.openPositions || 0}`,
      `Open sets: ${counts.openSets || 0}/${rows.length} total`,
      `PAUSE: ${counts.pause || 0} | REDUCE: ${counts.reduce || 0} | NORMAL: ${counts.normal || 0}`,
      et.equityChange24h != null ? `Equity Δ24h: ${fmtSignedMoney(et.equityChange24h)}` : null,
      et.closedProfit24h != null ? `Closed P/L 24h: ${fmtSignedMoney(et.closedProfit24h)}` : null,
    ]
      .filter(Boolean)
      .join(" | ");

    const riskyRows = rows.filter((r) => r.risky).slice(0, 5);
    const riskyStr = riskyRows.length
      ? " | Risky sets: " + riskyRows.map((r) => `${r.id}(${r.rec})`).join(", ")
      : "";

    return parts + riskyStr;
  };

  const send = async () => {
    const text = input.trim();
    if (!text || loading) return;

    const newMessages = [...messages, { role: "user", content: text }];
    setMessages(newMessages);
    setInput("");
    setLoading(true);

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          messages: newMessages,
          dashboardContext: buildContext(),
        }),
      });
      const json = await res.json();
      if (json.ok) {
        setMessages([...newMessages, { role: "assistant", content: json.reply }]);
      } else {
        setMessages([
          ...newMessages,
          { role: "assistant", content: `Gagal: ${json.message || "Error tidak diketahui."}` },
        ]);
      }
    } catch (err) {
      setMessages([
        ...newMessages,
        { role: "assistant", content: "Koneksi ke server gagal. Coba lagi." },
      ]);
    } finally {
      setLoading(false);
      setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
    }
  };

  const handleKey = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  const handleInput = (e) => {
    setInput(e.target.value);
    e.target.style.height = "auto";
    e.target.style.height = Math.min(e.target.scrollHeight, 120) + "px";
  };

  const clearChat = () => {
    setMessages([
      {
        role: "assistant",
        content: "Chat dibersihkan. Ada yang bisa saya bantu?",
      },
    ]);
    setInput("");
  };

  return (
    <div className="screen screen-chat">
      <div className="screen-head">
        <span className="screen-title">AI Chat</span>
        <span className="screen-sub">
          Tanya <b>Nova</b> tentang trading — data dashboard disertakan sebagai konteks
        </span>
        <button
          className="reset"
          onClick={clearChat}
          style={{ marginLeft: "auto", fontSize: "11px" }}
          title="Bersihkan chat"
        >
          Bersihkan
        </button>
      </div>

      <div className="chat-wrap">
        <div className="chat-messages">
          {messages.map((msg, i) => (
            <div key={i} className={`chat-msg chat-msg-${msg.role}`}>
              {msg.role === "assistant" && <span className="chat-avatar">◆</span>}
              <div className="chat-bubble">{msg.content}</div>
            </div>
          ))}

          {loading && (
            <div className="chat-msg chat-msg-assistant">
              <span className="chat-avatar">◆</span>
              <div className="chat-bubble chat-typing">
                <span className="chat-dot" />
                <span className="chat-dot" />
                <span className="chat-dot" />
              </div>
            </div>
          )}

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

        <div className="chat-input-row">
          <textarea
            ref={inputRef}
            className="chat-input mono"
            placeholder="Tanya tentang posisi, set, performa, atau status AI… (Enter kirim, Shift+Enter baris baru)"
            value={input}
            onChange={handleInput}
            onKeyDown={handleKey}
            rows={1}
            disabled={loading}
            autoFocus
          />
          <button className="chat-send" onClick={send} disabled={loading || !input.trim()} title="Kirim">
            <svg
              width="16"
              height="16"
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M14 8 2 2l2.5 6L2 14l12-6z" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}
