
// AIChat.jsx — floating AI chat widget.
// System prompt lives in config.js (window.BLD_CONFIG.GEMINI_SYSTEM_PROMPT).
// When the AI has collected all info and outputs [LEAD_CONFIRMED]{json}[/LEAD_CONFIRMED],
// the frontend strips the marker and auto-submits the lead to Supabase ai_leads.

function AIChat({ t, lang }) {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [unread, setUnread] = React.useState(0);
  const [leadSaved, setLeadSaved] = React.useState(false);
  const endRef = React.useRef(null);
  const inputRef = React.useRef(null);

  const scrollToBottom = () => {
    if (endRef.current) endRef.current.parentElement.scrollTop = endRef.current.offsetTop;
  };

  React.useEffect(() => {
    if (open) {
      setUnread(0);
      setTimeout(() => { inputRef.current?.focus(); scrollToBottom(); }, 100);
    }
  }, [open, messages]);

  const sendMessage = async (text) => {
    if (!text.trim() || loading) return;
    const userMsg = { role: 'user', content: text };
    setMessages(m => [...m, userMsg]);
    setInput('');
    setLoading(true);

    try {
      const raw = await window.bldAI.complete({ history: messages, userMessage: text });
      const { text: displayText, lead } = window.bldDB.parseLeadFromReply(raw);

      setMessages(m => [...m, { role: 'assistant', content: displayText, leadConfirmed: !!lead }]);
      if (!open) setUnread(u => u + 1);

      if (lead && !leadSaved) {
        try {
          await window.bldDB.submitAILead({ ...lead, lang });
          setLeadSaved(true);
        } catch (err) {
          console.error('[BLD lead save]', err);
          setMessages(m => [...m, {
            role: 'assistant',
            content: lang === 'uk' ? '⚠️ Заявку не вдалося зберегти. Напишіть нам на email — передамо вручну.' :
                     lang === 'ru' ? '⚠️ Заявку не удалось сохранить. Напишите нам на email — передадим вручную.' :
                     '⚠️ Could not save your application. Please email us and we\'ll handle it manually.',
          }]);
        }
      }
    } catch (err) {
      console.error('[BLD AI]', err);
      setMessages(m => [...m, { role: 'assistant', content: t.chat.errorMsg }]);
    }
    setLoading(false);
  };

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(input); }
  };

  const scrollToForm = () => {
    const el = document.getElementById('form');
    if (el) el.scrollIntoView({ behavior: 'smooth' });
    setOpen(false);
  };

  const successLabel =
    lang === 'uk' ? '✓ Заявку збережено' :
    lang === 'ru' ? '✓ Заявка сохранена' :
    '✓ Application saved';

  return (
    <>
      {/* Floating button */}
      <div className="aichat-fab-wrap" style={{ position: 'fixed', bottom: 28, right: 28, zIndex: 1000 }}>
        {!open && (
          <button onClick={() => setOpen(true)} style={{
            width: 56, height: 56, borderRadius: '50%', border: 'none',
            background: 'linear-gradient(135deg, #3b82f6, #2563eb)',
            color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 8px 32px rgba(59,130,246,0.5)',
            transition: 'transform 0.2s', position: 'relative',
          }}
            onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.08)'}
            onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
            </svg>
            {unread > 0 && (
              <div style={{ position: 'absolute', top: -4, right: -4, width: 18, height: 18, borderRadius: '50%', background: '#e11d48', fontSize: 10, fontWeight: 800, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{unread}</div>
            )}
          </button>
        )}
      </div>

      {/* Chat panel */}
      {open && (
        <div className="aichat-panel" style={{
          position: 'fixed', bottom: 28, right: 28, zIndex: 1000,
          width: 380, maxWidth: 'calc(100vw - 32px)',
          background: '#151925', border: '1px solid #1e293b',
          borderRadius: 20, boxShadow: '0 24px 80px rgba(0,0,0,0.7)',
          display: 'flex', flexDirection: 'column',
          animation: 'slideUp 0.25s ease', overflow: 'hidden',
        }}>
          {/* Header */}
          <div style={{ background: 'linear-gradient(135deg, #1a1f2e, #151925)', borderBottom: '1px solid #1e293b', padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 10, background: '#3b82f620', border: '1px solid #3b82f640', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ fontSize: 14, fontWeight: 900, color: '#3b82f6' }}>B</span>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#e2e8f0' }}>{t.chat.title}</div>
              <div style={{ fontSize: 11, color: '#10b981', display: 'flex', alignItems: 'center', gap: 4 }}>
                <div style={{ width: 5, height: 5, borderRadius: '50%', background: '#10b981' }}/> BLD AI
              </div>
            </div>
            {leadSaved && (
              <span style={{ fontSize: 11, color: '#10b981', fontWeight: 700, background: '#10b98115', border: '1px solid #10b98130', borderRadius: 6, padding: '3px 8px' }}>{successLabel}</span>
            )}
            <button onClick={() => setOpen(false)} style={{ background: 'transparent', border: 'none', color: '#475569', cursor: 'pointer', padding: 6, borderRadius: 6, display: 'flex', lineHeight: 0 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>

          {/* Messages */}
          <div className="aichat-messages" style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 8px', minHeight: 300, maxHeight: 380, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {messages.length === 0 && (
              <div>
                <div style={{ background: '#1a1f2e', borderRadius: '4px 14px 14px 14px', padding: '12px 14px', marginBottom: 12 }}>
                  <span style={{ fontSize: 11, color: '#3b82f6', fontWeight: 700, display: 'block', marginBottom: 4 }}>BLD</span>
                  <span style={{ fontSize: 13, color: '#cbd5e1', lineHeight: 1.6 }}>
                    {lang === 'uk' ? 'Привіт! Я допоможу відповісти на питання про BLD. Що вас цікавить?' :
                     lang === 'ru' ? 'Привет! Я помогу ответить на вопросы о BLD. Что вас интересует?' :
                     'Hi! I can answer questions about BLD. What would you like to know?'}
                  </span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {t.chat.suggestions.map((s, i) => (
                    <button key={i} onClick={() => sendMessage(s)} style={{
                      background: '#1a1f2e', border: '1px solid #1e293b', borderRadius: 8,
                      padding: '8px 12px', fontSize: 12, color: '#94a3b8', cursor: 'pointer',
                      textAlign: 'left', transition: 'border-color 0.15s',
                      fontFamily: "'DM Sans', sans-serif",
                    }}
                      onMouseEnter={e => e.target.style.borderColor='#3b82f6'}
                      onMouseLeave={e => e.target.style.borderColor='#1e293b'}
                    >{s}</button>
                  ))}
                </div>
              </div>
            )}

            {messages.map((msg, i) => {
              const isUser = msg.role === 'user';
              const hasFormRef = /заявк|apply|form|пілот|pilot|пилот/i.test(msg.content);
              return (
                <div key={i} style={{ display: 'flex', justifyContent: isUser ? 'flex-end' : 'flex-start' }}>
                  <div style={{
                    background: isUser ? '#1d4ed8' : '#1a1f2e',
                    borderRadius: isUser ? '14px 4px 14px 14px' : '4px 14px 14px 14px',
                    padding: '10px 14px', maxWidth: '85%',
                  }}>
                    {!isUser && <span style={{ fontSize: 10, color: '#3b82f6', fontWeight: 700, display: 'block', marginBottom: 4 }}>BLD</span>}
                    <p style={{ fontSize: 13, color: '#e2e8f0', lineHeight: 1.6, margin: 0, whiteSpace: 'pre-wrap' }}>{msg.content}</p>
                    {/* Lead confirmed banner */}
                    {msg.leadConfirmed && (
                      <div style={{ marginTop: 10, background: '#10b98115', border: '1px solid #10b98130', borderRadius: 8, padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 6 }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
                        <span style={{ fontSize: 11, color: '#10b981', fontWeight: 700 }}>{successLabel}</span>
                      </div>
                    )}
                    {!isUser && !msg.leadConfirmed && hasFormRef && (
                      <button onClick={scrollToForm} style={{
                        marginTop: 8, background: '#3b82f620', border: '1px solid #3b82f640',
                        borderRadius: 6, padding: '5px 10px', fontSize: 11, color: '#3b82f6',
                        cursor: 'pointer', fontWeight: 700, fontFamily: "'DM Sans', sans-serif",
                      }}>
                        {lang === 'uk' ? '→ Залишити заявку' : lang === 'ru' ? '→ Оставить заявку' : '→ Apply for pilot'}
                      </button>
                    )}
                  </div>
                </div>
              );
            })}

            {loading && (
              <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                <div style={{ background: '#1a1f2e', borderRadius: '4px 14px 14px 14px', padding: '12px 16px' }}>
                  <span style={{ fontSize: 11, color: '#3b82f6', fontWeight: 700, display: 'block', marginBottom: 6 }}>BLD</span>
                  <div style={{ display: 'flex', gap: 4 }}>
                    {[0,1,2].map(d => (
                      <div key={d} style={{ width: 6, height: 6, borderRadius: '50%', background: '#3b82f6', animation: `bounce 1.2s ${d*0.2}s infinite` }}/>
                    ))}
                  </div>
                </div>
              </div>
            )}
            <div ref={endRef}/>
          </div>

          {/* Input — disabled after lead saved */}
          <div style={{ padding: '8px 12px 14px', borderTop: '1px solid #1e293b' }}>
            {leadSaved ? (
              <div style={{ textAlign: 'center', padding: '10px 0', fontSize: 12, color: '#10b981', fontWeight: 600 }}>
                {lang === 'uk' ? 'Заявку отримано. Зв\'яжемось з вами на email.' :
                 lang === 'ru' ? 'Заявка получена. Свяжемся с вами по email.' :
                 'Application received. We\'ll reach out by email.'}
              </div>
            ) : (
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}>
                <textarea
                  ref={inputRef}
                  rows={1}
                  value={input}
                  onChange={e => setInput(e.target.value)}
                  onKeyDown={handleKey}
                  placeholder={t.chat.placeholder}
                  style={{
                    flex: 1, background: '#1a1f2e', border: '1px solid #1e293b',
                    borderRadius: 10, padding: '10px 12px', color: '#e2e8f0',
                    fontSize: 13, resize: 'none', outline: 'none',
                    fontFamily: "'DM Sans', sans-serif", lineHeight: 1.5,
                    maxHeight: 100, overflow: 'auto',
                  }}
                  onFocus={e => e.target.style.borderColor='#3b82f6'}
                  onBlur={e => e.target.style.borderColor='#1e293b'}
                />
                <button onClick={() => sendMessage(input)} disabled={loading || !input.trim()} style={{
                  width: 36, height: 36, borderRadius: 10, border: 'none',
                  background: input.trim() && !loading ? '#3b82f6' : '#1e293b',
                  color: '#fff', cursor: input.trim() && !loading ? 'pointer' : 'default',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0, transition: 'background 0.15s',
                }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { AIChat });
