/* Floating AI Assistant — global launcher + compact chat panel, on every app page */
(function () {
  const { useState, useRef, useEffect } = React;
  const Icon = window.Icon;
  const D = window.YEIDA;

  // lightweight reply engine (shares the spirit of the full-page assistant)
  function reply(text) {
    const t = text.toLowerCase();
    const A = [
      { m: ['construction', 'build', 'start'], r: "Your construction is at Step 4 — Authority Review. Next action: upload the pending Soil Test Report. Want me to open the Construction module?", a: ['construction', 'Open Construction'] },
      { m: ['payment', 'due', 'pay', 'challan'], r: "You have ₹1,47,585 across 3 dues. Authority records and challans are on your Payments page.", a: ['payments', 'Open Payments'] },
      { m: ['document', 'paper', 'lease', 'atl'], r: "Lease Deed: Completed. ATL: Pending — that's your next paperwork item. All documents live in the Document Center.", a: ['documents', 'Document Center'] },
      { m: ['sell', 'transfer'], r: "To sell Plot B-47 you're eligible (7 years held). Estimated transfer cost ≈ ₹2.02 L. Shall I open the Transfer module?", a: ['transfer', 'Start Transfer'] },
      { m: ['plan', 'design', 'tour', 'sample'], r: "I've matched 3 plans to your 300 sq.m east-facing plot, with 3D walkthroughs. Open Sample Plans?", a: ['sampleplans', 'View Plans'] },
      { m: ['map', 'sector', 'location'], r: "Plot B-47 is in Sector 18, Block B — an east-facing 300 sq.m plot. I can open the interactive map.", a: ['sectormaps', 'Open Map'] },
    ];
    const hit = A.find(x => x.m.some(k => t.includes(k)));
    return hit ? { reply: hit.r, action: hit.a } : { reply: "I can help with your plot status, authority paperwork, payments, construction, sample plans and transfers. What would you like to know?" };
  }

  function FloatingAssistant({ go }) {
    const [open, setOpen] = useState(false);
    const [msgs, setMsgs] = useState([{ role: 'bot', text: "Hi Rajeev 👋 Quick help on your plot — payments, paperwork, construction or plans. Ask away, or open the full assistant." }]);
    const [input, setInput] = useState('');
    const [typing, setTyping] = useState(false);
    const scroller = useRef(null);
    useEffect(() => { if (scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight; }, [msgs, typing, open]);

    const send = (text) => {
      if (!text.trim()) return;
      setMsgs(m => [...m, { role: 'user', text }]); setInput(''); setTyping(true);
      setTimeout(() => { const r = reply(text); setTyping(false); setMsgs(m => [...m, { role: 'bot', text: r.reply, action: r.action }]); }, 800);
    };

    const quick = ['What payments are pending?', 'What is my ATL status?', 'Show sample plans'];

    return (
      <div style={{ position: 'fixed', right: 26, bottom: 26, zIndex: 800, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 14 }}>
        {open && (
          <div className="anim-pop card" style={{ width: 360, maxWidth: 'calc(100vw - 52px)', height: 480, maxHeight: 'calc(100vh - 120px)', display: 'flex', flexDirection: 'column', overflow: 'hidden', boxShadow: 'var(--sh-lg)' }}>
            {/* header */}
            <div className="row spread" style={{ padding: '14px 16px', background: 'linear-gradient(120deg,#103263,#0b2548)', color: '#fff' }}>
              <div className="row gap-3">
                <span style={{ width: 36, height: 36, borderRadius: 10, display: 'grid', placeItems: 'center', background: 'rgba(255,255,255,.14)' }}><Icon name="sparkles" size={19} /></span>
                <div><div style={{ fontWeight: 700, fontSize: 14.5 }}>YEIDA Assistant</div><div className="row gap-2" style={{ fontSize: 11.5, color: '#9ff0cd' }}><span style={{ width: 6, height: 6, borderRadius: 99, background: 'var(--emerald-500)' }} />Online</div></div>
              </div>
              <div className="row gap-1">
                <button onClick={() => { setOpen(false); go('assistant'); }} title="Open full assistant" style={{ width: 30, height: 30, borderRadius: 8, border: 'none', background: 'rgba(255,255,255,.12)', color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center' }}><Icon name="expand" size={15} /></button>
                <button onClick={() => setOpen(false)} style={{ width: 30, height: 30, borderRadius: 8, border: 'none', background: 'rgba(255,255,255,.12)', color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center' }}><Icon name="x" size={16} /></button>
              </div>
            </div>
            {/* messages */}
            <div ref={scroller} style={{ flex: 1, overflowY: 'auto', padding: '16px', display: 'flex', flexDirection: 'column', gap: 12, background: 'var(--bg)' }}>
              {msgs.map((m, i) => (
                <div key={i} className="row" style={{ alignItems: 'flex-end', gap: 8, flexDirection: m.role === 'user' ? 'row-reverse' : 'row' }}>
                  {m.role === 'bot' && <span style={{ width: 26, height: 26, borderRadius: 7, flex: 'none', display: 'grid', placeItems: 'center', background: 'linear-gradient(150deg,var(--blue-500),var(--navy-800))', color: '#fff' }}><Icon name="sparkles" size={13} /></span>}
                  <div style={{ maxWidth: '80%' }}>
                    <div style={{ background: m.role === 'user' ? 'var(--blue-600)' : '#fff', color: m.role === 'user' ? '#fff' : 'var(--ink)', border: m.role === 'user' ? 'none' : '1px solid var(--line)', borderRadius: m.role === 'user' ? '12px 12px 4px 12px' : '12px 12px 12px 4px', padding: '10px 13px', fontSize: 13, lineHeight: 1.5 }}>{m.text}</div>
                    {m.action && <button className="btn btn-outline btn-sm" style={{ marginTop: 7 }} onClick={() => { setOpen(false); go(m.action[0]); }}>{m.action[1]}<Icon name="arrowR" size={14} /></button>}
                  </div>
                </div>
              ))}
              {typing && <div className="row gap-2" style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: '12px 12px 12px 4px', padding: '11px 14px', alignSelf: 'flex-start' }}>{[0, 1, 2].map(i => <span key={i} style={{ width: 6, height: 6, borderRadius: 99, background: 'var(--muted)', animation: `pulseDot 1.2s ${i * 0.2}s infinite` }} />)}</div>}
              {msgs.length === 1 && (
                <div className="col gap-2" style={{ marginTop: 4 }}>
                  {quick.map(q => <button key={q} onClick={() => send(q)} style={{ textAlign: 'left', fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', padding: '9px 12px', borderRadius: 10, border: '1px solid var(--line)', background: '#fff', cursor: 'pointer' }}>{q}</button>)}
                </div>
              )}
            </div>
            {/* input */}
            <div style={{ padding: 12, borderTop: '1px solid var(--line)', background: '#fff' }}>
              <div className="row gap-2" style={{ background: 'var(--bg)', borderRadius: 11, padding: '5px 5px 5px 14px', border: '1.5px solid var(--line)' }}>
                <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send(input)} placeholder="Ask anything…" style={{ flex: 1, border: 'none', background: 'none', outline: 'none', fontSize: 13.5 }} />
                <button className="btn btn-primary btn-sm" style={{ borderRadius: 9, padding: '8px 10px' }} onClick={() => send(input)}><Icon name="send" size={15} /></button>
              </div>
            </div>
          </div>
        )}
        {/* launcher */}
        <button onClick={() => setOpen(o => !o)} style={{ width: 58, height: 58, borderRadius: 99, border: 'none', cursor: 'pointer', background: open ? 'var(--navy-800)' : 'linear-gradient(150deg,var(--blue-500),var(--navy-800))', color: '#fff', boxShadow: '0 16px 36px -10px rgba(11,37,72,.6)', display: 'grid', placeItems: 'center', transition: 'transform .15s' }} title="AI Assistant">
          <Icon name={open ? 'chevD' : 'sparkles'} size={26} />
          {!open && <span style={{ position: 'absolute', top: 4, right: 4, width: 12, height: 12, borderRadius: 99, background: 'var(--emerald-500)', border: '2px solid #fff' }} />}
        </button>
      </div>
    );
  }

  window.FloatingAssistant = FloatingAssistant;
})();
