// Chatbot.jsx — floating AI assistant for the Elle Lee site.
// Uses window.claude.complete (Haiku 4.5, free for visitors).

const SYSTEM_PROMPT_EN = `You are Elle Lee's AI receptionist on her real-estate website.
About Elle:
- New York City real-estate advisor, REBNY member.
- Specializes in: New Development, international relocation (corporate transferees, students, families), buyers/sellers/renters.
- Works in Korean and English, both fluently.
- Markets: covers ALL of New York State. Strongest expertise in Manhattan (UWS, UES, Chelsea, Tribeca, West Village, Flatiron, FiDi), Queens (LIC), and Brooklyn (Downtown, Williamsburg, Brooklyn Heights), but happy to source anywhere in NY State on request.
- Contact: ellelee.nestseekers@gmail.com · Instagram @milim.elle · TikTok @ellemlee · KakaoTalk @ANGELML
- Replies personally within 24 hours.

Your job:
- Be warm, unhurried, and concise. Match Elle's editorial, gentle voice.
- Answer common questions about her services, neighborhoods she covers, the rental/sale process, what to expect.
- If asked about a SPECIFIC listing/price/availability, say you don't have live unit data and offer to forward the inquiry — point them to the Book a viewing button or her email.
- If asked anything outside real estate (e.g. legal advice, finance, jokes), politely redirect.
- 2-4 sentences per reply, no marketing fluff, no exclamation points.
- If the user writes Korean, reply in Korean. If English, reply in English.
- Never make up information. If unsure, say so and offer to connect them with Elle directly.`;

const STARTERS_EN = [
  'What areas do you cover?',
  'How does international relocation work?',
  'Do you handle student rentals?',
  'How do I book a viewing?',
];
const STARTERS_KR = [
  '어떤 동네를 다루시나요?',
  '해외 이주 절차는 어떻게 되나요?',
  '유학생 임대도 가능한가요?',
  '투어 예약은 어떻게 하나요?',
];

const Chatbot = ({ lang = 'EN', onContact }) => {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const bodyRef = React.useRef(null);
  const inputRef = React.useRef(null);

  const isKR = lang === 'KR';
  const greeting = isKR
    ? '안녕하세요. 엘 리의 AI 어시스턴트입니다. 매물, 동네, 이주 절차 — 무엇이든 편하게 물어보세요.'
    : 'Hi — I\u2019m Elle\u2019s AI assistant. Ask me about neighborhoods, the relocation process, or anything else. I\u2019ll pass along the rest.';

  // Seed greeting + reset on language change
  React.useEffect(() => {
    setMessages([{ role: 'assistant', content: greeting }]);
  }, [lang]);

  // Auto-scroll to bottom on new message
  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, busy]);

  // Focus input on open
  React.useEffect(() => {
    if (open && inputRef.current) setTimeout(() => inputRef.current?.focus(), 80);
  }, [open]);

  const send = async (text) => {
    const value = (text ?? input).trim();
    if (!value || busy) return;
    setInput('');
    const next = [...messages, { role: 'user', content: value }];
    setMessages(next);
    setBusy(true);
    try {
      const reply = await window.claude.complete({
        messages: [
          { role: 'user', content: `${SYSTEM_PROMPT_EN}\n\nConversation so far:\n${next.map(m => `${m.role === 'user' ? 'Visitor' : 'You'}: ${m.content}`).join('\n')}\n\nYou:` },
        ],
      });
      setMessages([...next, { role: 'assistant', content: reply.trim() }]);
    } catch (err) {
      setMessages([
        ...next,
        {
          role: 'assistant',
          content: isKR
            ? '죄송합니다, 연결에 문제가 있습니다. ellelee.nestseekers@gmail.com 으로 직접 연락 주시면 24시간 안에 답장 드립니다.'
            : 'I\u2019m having trouble connecting just now. Please email ellelee.nestseekers@gmail.com — Elle replies within 24 hours.',
        },
      ]);
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      {!open && (
        <button
          className="ms-chat-launcher"
          onClick={() => setOpen(true)}
          aria-label={isKR ? '엘 리에게 문의하기' : 'Ask Elle\u2019s assistant'}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
          </svg>
          <span className="ms-chat-launcher-label">{isKR ? '어시스턴트' : 'Ask Elle'}</span>
        </button>
      )}
      {open && (
        <aside className="ms-chat-panel" role="dialog" aria-label={isKR ? 'AI 어시스턴트' : 'AI assistant'}>
          <header className="ms-chat-head">
            <div className="ms-chat-head-info">
              <span className="ms-chat-head-name">Elle Lee</span>
              <span className="ms-chat-head-sub">{isKR ? 'AI 어시스턴트 · 시범 운영' : 'AI assistant · beta'}</span>
            </div>
            <button className="ms-chat-close" onClick={() => setOpen(false)} aria-label={isKR ? '닫기' : 'Close'}>×</button>
          </header>
          <div className="ms-chat-body" ref={bodyRef}>
            {messages.map((m, i) => (
              <div key={i} className={`ms-chat-msg ${m.role === 'user' ? 'user' : 'bot'}`}>{m.content}</div>
            ))}
            {busy && (
              <div className="ms-chat-msg typing" aria-label={isKR ? '답변 작성 중' : 'Typing'}>
                <span /><span /><span />
              </div>
            )}
            {messages.length <= 1 && !busy && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 6 }}>
                {(isKR ? STARTERS_KR : STARTERS_EN).map((s) => (
                  <button
                    key={s}
                    className="chip-outline"
                    style={{ fontSize: 11, padding: '6px 12px' }}
                    onClick={() => send(s)}
                  >
                    {s}
                  </button>
                ))}
              </div>
            )}
          </div>
          <form
            className="ms-chat-foot"
            onSubmit={(e) => { e.preventDefault(); send(); }}
          >
            <input
              ref={inputRef}
              className="ms-chat-input"
              placeholder={isKR ? '메시지를 입력하세요…' : 'Type your question…'}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              aria-label={isKR ? '질문' : 'Your question'}
              disabled={busy}
            />
            <button className="ms-chat-send" type="submit" disabled={busy || !input.trim()}>
              {isKR ? '보내기' : 'Send'}
            </button>
          </form>
        </aside>
      )}
    </>
  );
};

window.Chatbot = Chatbot;
