"use client"; import { useState, useEffect, useRef } from "react"; export function ChatPanel() { const [messages, setMessages] = useState>([]); const [input, setInput] = useState(""); const [loading, setLoading] = useState(false); const [ticker, setTicker] = useState("AAPL"); const scrollRef = useRef(null); useEffect(() => { const saved = localStorage.getItem("atlas_active_ticker"); if (saved) setTicker(saved); const handler = (e: Event) => { const detail = (e as CustomEvent).detail; if (detail) setTicker(detail); }; window.addEventListener("atlas-ticker-change", handler); return () => window.removeEventListener("atlas-ticker-change", handler); }, []); useEffect(() => { scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" }); }, [messages]); async function handleSend() { if (!input.trim() || loading) return; const userMsg = input.trim(); setInput(""); setMessages((prev) => [...prev, { role: "user", content: userMsg }]); setLoading(true); try { const apiKey = localStorage.getItem("atlas_gemini_key") || ""; const res = await fetch("/api/analysis/strategy", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ticker, question: userMsg, api_key: apiKey }), }); if (res.ok) { const data = await res.json(); const text = typeof data === "string" ? data : data.analysis || data.result || JSON.stringify(data); setMessages((prev) => [...prev, { role: "assistant", content: text }]); } else { setMessages((prev) => [ ...prev, { role: "assistant", content: "Settings에서 Gemini API Key를 설정해주세요." }, ]); } } catch { setMessages((prev) => [...prev, { role: "assistant", content: "연결 오류. 다시 시도해주세요." }]); } setLoading(false); } const suggestions = [ "Is this company undervalued?", "Analyze the financial health", "What are the key risks?", ]; return ( ); }