// chatbot.jsx — AI 상담 챗봇 풀스크린
// window.claude.complete 사용 (프로토타입). 단지/세금/대출/청약 질의 응답.

function ChatbotPage() {
  const isMobile = useIsMobile();
  const [messages, setMessages] = useState([
    { who: 'ai', text: '안녕하세요! 우리집사기 AI 상담입니다 🏠\n매수 타이밍·대출 한도·세금·청약 무엇이든 물어보세요.' },
  ]);
  const [input, setInput] = useState('');
  const [busy, setBusy] = useState(false);
  const scrollRef = React.useRef(null);

  useEffect(() => { document.title = 'AI 챗봇 — 우리집사기'; window.UJTrack.track('view_chatbot', {}); }, []);
  useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [messages]);

  const suggestions = ['대치 은마 지금 사도 될까?', '연소득 8천이면 대출 얼마까지?', '취득세 얼마 나와?', 'GTX-A 수혜 단지 알려줘'];

  const send = async (text) => {
    const q = (text || input).trim();
    if (!q || busy) return;
    setMessages(m => [...m, { who: 'user', text: q }, { who: 'ai', text: '…', pending: true }]);
    setInput(''); setBusy(true);
    window.UJTrack.track('chatbot_ask', { q });
    try {
      const sys = '당신은 한국 부동산 매수 상담 AI "우리집사기"입니다. 국토부 실거래가·금리·학군·GTX 등 12개 요인 기반으로 친절하고 간결하게(3~5문장) 답하세요. 마지막에 "※ 투자 자문이 아닌 정보 제공입니다"를 붙이세요. 질문: ';
      let answer = '';
      if (window.claude && window.claude.complete) {
        answer = await window.claude.complete(sys + q);
      }
      if (!answer) answer = '죄송해요, 지금은 답변을 받지 못했어요. 잠시 후 다시 시도해주세요.\n※ 투자 자문이 아닌 정보 제공입니다.';
      setMessages(m => [...m.slice(0, -1), { who: 'ai', text: answer }]);
    } catch (e) {
      setMessages(m => [...m.slice(0, -1), { who: 'ai', text: '오류가 발생했어요. 잠시 후 다시 시도해주세요.' }]);
    } finally { setBusy(false); }
  };

  return (
    <div style={{ padding: isMobile ? 12 : 20, display: 'flex', flexDirection: 'column', height: isMobile ? 'calc(100vh - 180px)' : 'calc(100vh - 160px)' }}>
      <PageHead title="AI 상담 챗봇" sub="claude · 매수·대출·세금·청약" />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.card, border: '1px solid ' + T.line, borderRadius: 8, overflow: 'hidden', minHeight: 0 }}>
        <div ref={scrollRef} className="uj-scroll" style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {messages.map((m, i) => (
            <div key={i} style={{ maxWidth: '86%', alignSelf: m.who === 'user' ? 'flex-end' : 'flex-start',
              background: m.who === 'user' ? T.hot : T.cardLo, color: m.who === 'user' ? T.bg : T.fg,
              border: m.who === 'user' ? 'none' : '1px solid ' + T.line, borderRadius: 10, padding: '10px 14px',
              fontSize: 14, lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
              {m.pending ? <span className="uj-blink">● ● ●</span> : m.text}
            </div>
          ))}
        </div>
        {messages.length <= 1 && (
          <div style={{ padding: '0 16px 8px', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {suggestions.map(s => (
              <button key={s} onClick={() => send(s)} style={{ padding: '6px 12px', borderRadius: 999, background: T.cardLo, color: T.fgDim, border: '1px solid ' + T.line, fontSize: 12, cursor: 'pointer', fontFamily: T.font }}>{s}</button>
            ))}
          </div>
        )}
        <div style={{ borderTop: '1px solid ' + T.line, padding: 12, display: 'flex', gap: 8 }}>
          <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()}
            placeholder="질문을 입력하세요…" disabled={busy}
            style={{ flex: 1, padding: '12px 14px', borderRadius: 6, background: T.cardLo, color: T.fg, border: '1px solid ' + T.line, fontSize: 14, outline: 'none', fontFamily: T.font }} />
          <button onClick={() => send()} disabled={busy || !input.trim()}
            style={{ padding: '0 20px', borderRadius: 6, background: busy || !input.trim() ? T.cardLo : T.hot, color: busy || !input.trim() ? T.fgMuted : T.bg, border: 'none', fontSize: 14, fontWeight: 700, cursor: busy ? 'wait' : 'pointer', fontFamily: T.font }}>전송</button>
        </div>
      </div>
      <div style={{ fontSize: 10, color: T.fgFaint, fontFamily: T.mono, marginTop: 8, textAlign: 'center' }}>
        ※ AI 답변은 참고용 정보이며 투자 자문이 아닙니다.
      </div>
    </div>
  );
}

Object.assign(window, { ChatbotPage });
