const { useState, useEffect, useRef } = React;
const AMNA_GREETING = "Hi, I'm AMNA, the TRUVIS AI Advisor. Tell me what financial activity you want to license in the UAE. I'll tell you which regulator and licence path fits — ADGM (Abu Dhabi Global Market) FSRA, DIFC (Dubai International Financial Centre) DFSA, CBUAE (Central Bank of the UAE), or a fintech RegLab route — and then connect you with an advisor.";
const CONSENT_KEY = 'amna_consent_accepted';
const AmnaLauncher = () => {
  const [open, setOpen] = useState(false);
  const [consented, setConsented] = useState(false);
  const [consentChecked, setConsentChecked] = useState(false);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [streaming, setStreaming] = useState(false);
  const [handedOff, setHandedOff] = useState(false);
  const scrollRef = useRef(null);
  const textareaRef = useRef(null);
  useEffect(() => {
    try { if (localStorage.getItem(CONSENT_KEY) === '1') setConsented(true); } catch (_) {}
  }, []);
  useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [messages]);
  useEffect(() => { if (open && consented && textareaRef.current) setTimeout(() => textareaRef.current.focus(), 100); }, [open, consented]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);
  const acceptConsent = () => {
    try { localStorage.setItem(CONSENT_KEY, '1'); } catch (_) {}
    setConsented(true);
  };
  const appendToLast = (chunk) => {
    if (!chunk) return;
    setMessages(prev => { const c=[...prev]; const l={...c[c.length-1]}; l.content=(l.content||'')+chunk; c[c.length-1]=l; return c; });
  };
  const replaceLast = (content) => {
    setMessages(prev => { const c=[...prev]; const last=c[c.length-1]; if (last && last.role==='assistant') c[c.length-1]={ role:'assistant', content }; return c; });
  };
  const send = async () => {
    const text = input.trim(); if (!text || streaming || handedOff) return;
    setInput(''); const next = [...messages, { role: 'user', content: text }];
    setMessages(next); setStreaming(true); setMessages([...next, { role: 'assistant', content: '' }]);
    let gotToken = false;
    try {
      // The advisor backend is stateful — it anchors the conversation on a cookie
      // it sets on its response (relayed by /api/amna/chat). We send only the new
      // message; the cookie carries continuity. Same-origin fetch sends/stores it.
      const res = await fetch('/api/amna/chat', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message: text }) });
      if (!res.ok || !res.body) throw new Error('bad response');
      const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = '';
      while (true) {
        const { done, value } = await reader.read(); if (done) break;
        buf += decoder.decode(value, { stream: true }); const lines = buf.split('\n'); buf = lines.pop() || '';
        for (const line of lines) {
          if (!line.startsWith('data: ')) continue;
          let evt; try { evt = JSON.parse(line.slice(6)); } catch (_) { continue; }
          switch (evt.type) {
            case 'token': {
              const chunk = typeof evt.payload === 'string' ? evt.payload : '';
              if (chunk) { gotToken = true; appendToLast(chunk); }
              break;
            }
            case 'handed_off':
              setHandedOff(true);
              break;
            case 'rate_limited':
              replaceLast('I need to pause for a moment — please try again shortly.'); gotToken = true;
              break;
            case 'error':
              if (!gotToken) replaceLast('Sorry, something went wrong. Please try again.');
              break;
            default:
              // qualified / tool_call / truncation_warning / listing_suggestion — ignore in UI
              break;
          }
        }
      }
      if (!gotToken) replaceLast('Sorry, I could not process that. Please try again.');
    } catch (_) { replaceLast('Sorry, I could not process that. Please try again.'); }
    finally { setStreaming(false); }
  };
  const onKeyDown = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } };
  const all = messages.length === 0 ? [{ role: 'assistant', content: AMNA_GREETING }] : messages;
  return (
    <>
      {!open && (
        <button onClick={() => setOpen(true)} aria-label="Chat with AMNA — TRUVIS AI Advisor"
          style={{ position:'fixed', bottom:24, right:24, zIndex:400, display:'flex', alignItems:'center', gap:10, padding:'12px 18px', borderRadius:999, border:'none', cursor:'pointer', background:'#023059', color:'#fff', boxShadow:'0 4px 20px rgba(0,0,0,0.25)', outline:'2px solid #10b981', outlineOffset:0, fontSize:14, fontWeight:500, whiteSpace:'nowrap', fontFamily:'inherit' }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}>
            <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>
          Hi, I'm AMNA — ask me anything
        </button>
      )}
      {open && (
        <div role="dialog" aria-modal="true" aria-label="Chat with AMNA — TRUVIS AI Advisor" style={{ position:'fixed', bottom:24, right:24, zIndex:500, width:360, maxWidth:'calc(100vw - 24px)', height:520, maxHeight:'calc(100dvh - 80px)', display:'flex', flexDirection:'column', background:'#fff', borderRadius:16, boxShadow:'0 8px 40px rgba(0,0,0,0.2)', border:'1px solid #e5e7eb', overflow:'hidden' }}>
          {/* Header */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'12px 16px', background:'#023059', color:'#fff', flexShrink:0 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:32, height:32, borderRadius:'50%', background:'#10b981', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <span style={{ fontSize:12, fontWeight:700, color:'#fff' }}>A</span>
              </div>
              <div>
                <p style={{ fontSize:14, fontWeight:600, lineHeight:1.2, margin:0 }}>AMNA</p>
                <p style={{ fontSize:11, opacity:0.6, lineHeight:1.2, margin:0 }}>TRUVIS AI Advisor</p>
              </div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="Close chat" style={{ background:'none', border:'none', cursor:'pointer', color:'#fff', opacity:0.6, padding:4, lineHeight:1 }}>
              <svg width="18" height="18" 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>

          {/* Consent gate */}
          {!consented ? (
            <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'24px 20px', gap:20, background:'#f9fafb', textAlign:'center' }}>
              <div style={{ width:52, height:52, borderRadius:'50%', background:'#e0f2fe', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#023059" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                </svg>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                <p style={{ fontSize:15, fontWeight:600, color:'#023059', margin:0 }}>Before we start</p>
                <p style={{ fontSize:13, lineHeight:1.6, color:'#374151', margin:0 }}>
                  Please agree to our{' '}
                  <a href="/privacy" target="_blank" rel="noopener noreferrer" style={{ color:'#10b981', fontWeight:500 }}>Privacy Policy</a>
                  {' '}so TRUVIS can use your details to help with your licensing question.
                </p>
              </div>
              <label style={{ display:'flex', alignItems:'flex-start', gap:10, cursor:'pointer', textAlign:'left' }}>
                <input
                  type="checkbox"
                  checked={consentChecked}
                  onChange={e => setConsentChecked(e.target.checked)}
                  style={{ marginTop:2, width:16, height:16, accentColor:'#10b981', cursor:'pointer', flexShrink:0 }}
                  aria-label="I agree to the Privacy Policy and am happy for TRUVIS to use my details for this question"
                />
                <span style={{ fontSize:13, lineHeight:1.55, color:'#374151' }}>
                  I agree, and I'm happy for TRUVIS to use my details for this question.
                </span>
              </label>
              <button
                onClick={acceptConsent}
                disabled={!consentChecked}
                style={{ width:'100%', padding:'10px 0', borderRadius:10, border:'none', cursor:consentChecked?'pointer':'not-allowed', background:consentChecked?'#10b981':'#d1d5db', color:'#fff', fontSize:14, fontWeight:600, fontFamily:'inherit', transition:'background 0.15s' }}
              >
                Accept &amp; Chat
              </button>
            </div>
          ) : (
            <>
              {/* Messages */}
              <div ref={scrollRef} aria-live="polite" aria-label="Conversation" style={{ flex:1, overflowY:'auto', padding:16, display:'flex', flexDirection:'column', gap:12, background:'#f9fafb' }}>
                {all.map((msg, i) => (
                  <div key={i} style={{ display:'flex', justifyContent:msg.role==='user'?'flex-end':'flex-start' }}>
                    <div style={{ maxWidth:'80%', padding:'10px 14px', fontSize:14, lineHeight:1.55, borderRadius:msg.role==='user'?'16px 16px 4px 16px':'16px 16px 16px 4px', background:msg.role==='user'?'#023059':'#fff', color:msg.role==='user'?'#fff':'#1f2937', border:msg.role==='assistant'?'1px solid #e5e7eb':'none' }}>
                      {msg.content || (streaming && i===all.length-1 ? '…' : '')}
                    </div>
                  </div>
                ))}
              </div>
              {/* Input — or hand-off confirmation */}
              {handedOff ? (
                <div style={{ display:'flex', alignItems:'flex-start', gap:10, padding:'14px 16px', borderTop:'1px solid #e5e7eb', background:'rgba(16,185,129,0.05)', flexShrink:0 }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0, marginTop:2}} aria-hidden="true">
                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/>
                  </svg>
                  <p style={{ fontSize:13, lineHeight:1.55, color:'#374151', margin:0 }}>
                    You're all set. A TRUVIS advisor will contact you soon to help with your licence.
                  </p>
                </div>
              ) : (
                <div style={{ display:'flex', gap:8, padding:'10px 12px', borderTop:'1px solid #e5e7eb', background:'#fff', flexShrink:0 }}>
                  <label htmlFor="amna-licensing-input" style={{ position:'absolute', width:1, height:1, padding:0, margin:-1, overflow:'hidden', clip:'rect(0,0,0,0)', whiteSpace:'nowrap', border:0 }}>Message AMNA</label>
                  <textarea id="amna-licensing-input" ref={textareaRef} value={input} onChange={e => setInput(e.target.value)} onKeyDown={onKeyDown} disabled={streaming} placeholder="Ask about FSRA, DFSA, CBUAE, RegLab, or your licence path…" rows={1} style={{ flex:1, resize:'none', border:'1px solid #d1d5db', borderRadius:12, padding:'8px 12px', fontSize:14, outline:'none', maxHeight:96, overflowY:'auto', opacity:streaming?0.5:1, fontFamily:'inherit' }} />
                  <button onClick={send} disabled={!input.trim()||streaming} aria-label="Send message" style={{ width:36, height:36, borderRadius:10, background:'#10b981', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, opacity:(!input.trim()||streaming)?0.4:1, transition:'opacity 0.15s' }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <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>
      )}
    </>
  );
};
window.AmnaLauncher = AmnaLauncher;
