/* AI Assistant */
(function () {
  const { useState, useRef, useEffect } = React;
  const Icon = window.Icon;
  const D = window.YEIDA;

  const ANSWERS = [
    { match: ['construction', 'start', 'build'], reply: "To start construction on Plot B-47:\n\n1. Ensure possession is granted (✓ done for your plot)\n2. Prepare your architect-stamped building plan\n3. Upload required documents in the Construction module\n4. Submit for YEIDA scrutiny\n\nYour application is currently at Step 4 — Authority Review. Estimated decision: 12 Jun 2026.", action: ['construction', 'Open Construction'] },
    { match: ['document', 'required', 'papers'], reply: "For building plan approval you'll need:\n\n• Approved Building Plan (architect-stamped)\n• Structural Stability Certificate\n• Architect Registration (COA)\n• Soil Test Report\n• Indemnity Bond\n• Possession Certificate copy\n\n5 of 6 are already uploaded. The Soil Test Report is still pending.", action: ['documents', 'View Documents'] },
    { match: ['notice', 'latest', 'update'], reply: "Here are the latest notices:\n\n📌 Revised Annual Lease Rent rates FY 2026-27 (01 Jun)\n📌 Construction guidelines — FAR & setback (24 May)\n• Water supply augmentation, Sector 18 & 20 (18 May)\n\nThe lease rent revision affects your next due on 30 Jun.", action: ['notices', 'Open Notices'] },
    { match: ['transfer', 'sell', 'ownership'], reply: "To transfer Plot B-47:\n\n1. Pass the eligibility check (5-year lock-in — ✓ you're eligible)\n2. Pay transfer charges (~₹2.02 L incl. fees & GST)\n3. Submit the transfer application with transferee KYC\n4. Authority review & approval\n\nWould you like me to open the Transfer module?", action: ['transfer', 'Start Transfer'] },
    { match: ['payment', 'pending', 'due', 'pay'], reply: "You have 3 outstanding dues totalling ₹1,47,585:\n\n• Water Connection Charges — ₹12,400 (Overdue)\n• Annual Lease Rent 2026-27 — ₹38,625 (due 30 Jun)\n• Location Premium 14/16 — ₹96,560 (due 15 Jul)\n\nClear the overdue water charge first to avoid interest.", action: ['payments', 'Pay Dues'] },
    { match: ['map', 'sector', '18', 'plot location'], reply: "Plot B-47 is in Sector 18, a developed residential sector along the Yamuna Expressway. It's an east-facing 300 sq.m plot on a 12 m road in Block B.\n\nI can open the interactive Sector 18 map so you can locate it.", action: ['sectormaps', 'Open Map'] },
  ];
  const fallback = "I can help with construction approvals, payments, documents, transfers, notices and sector maps for your plot. Try one of the suggested questions, or ask me anything about Plot B-47.";

  function reply(text) {
    const t = text.toLowerCase();
    const hit = ANSWERS.find(a => a.match.some(m => t.includes(m)));
    return hit || { reply: fallback };
  }

  function Assistant({ go }) {
    const [msgs, setMsgs] = useState([{ role: 'bot', text: "Hello Rajeev 👋 I'm your YEIDA assistant. Ask me anything about Plot B-47 — construction, payments, documents, transfers or sector maps." }]);
    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]);

    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 }]);
      }, 900);
    };

    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 270px', gap: 18, height: 'calc(100vh - 124px)' }}>
        {/* chat */}
        <div className="card" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div className="row spread" style={{ padding: '16px 22px', borderBottom: '1px solid var(--line)' }}>
            <div className="row gap-3">
              <span style={{ width: 42, height: 42, borderRadius: 12, display: 'grid', placeItems: 'center', background: 'linear-gradient(150deg,var(--blue-500),var(--navy-800))', color: '#fff' }}><Icon name="sparkles" size={21} /></span>
              <div><div style={{ fontWeight: 700, fontSize: 15.5 }}>YEIDA AI Assistant</div><div className="row gap-2" style={{ fontSize: 12, color: 'var(--emerald-700)', fontWeight: 600 }}><span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--emerald-500)' }} />Online · Knowledge base connected</div></div>
            </div>
            <button className="btn btn-outline btn-sm"><Icon name="history" size={15} />History</button>
          </div>

          <div ref={scroller} style={{ flex: 1, overflowY: 'auto', padding: '24px 26px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            {msgs.length === 1 && (
              <div className="anim-fade-up" style={{ textAlign: 'center', padding: '20px 0 8px' }}>
                <div style={{ width: 60, height: 60, borderRadius: 16, margin: '0 auto 14px', display: 'grid', placeItems: 'center', background: 'linear-gradient(150deg,var(--blue-500),var(--navy-800))', color: '#fff', boxShadow: 'var(--sh-glow)' }}><Icon name="sparkles" size={30} /></div>
                <h2 style={{ fontSize: 23 }}>Ask anything about your plot</h2>
                <p className="muted" style={{ fontSize: 14, marginTop: 6 }}>Choose a question below or type your own.</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, maxWidth: 540, margin: '22px auto 0' }}>
                  {D.assistantSuggestions.map(s => (
                    <button key={s} onClick={() => send(s)} className="card-hover" style={{ textAlign: 'left', padding: '13px 15px', borderRadius: 12, border: '1px solid var(--line)', background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10, fontSize: 13.5, fontWeight: 600, color: 'var(--ink-2)' }}>
                      <Icon name="chat" size={16} style={{ color: 'var(--blue-500)', flex: 'none' }} />{s}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {msgs.map((m, i) => <Bubble key={i} m={m} go={go} />)}
            {typing && (
              <div className="row gap-3" style={{ alignItems: 'flex-end' }}>
                <span style={{ width: 32, height: 32, borderRadius: 9, flex: 'none', display: 'grid', placeItems: 'center', background: 'linear-gradient(150deg,var(--blue-500),var(--navy-800))', color: '#fff' }}><Icon name="sparkles" size={16} /></span>
                <div style={{ background: 'var(--bg-2)', borderRadius: '14px 14px 14px 4px', padding: '14px 18px', display: 'flex', gap: 5 }}>
                  {[0, 1, 2].map(i => <span key={i} style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--muted)', animation: `pulseDot 1.2s ${i * 0.2}s infinite` }} />)}
                </div>
              </div>
            )}
          </div>

          <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)' }}>
            <div className="row gap-3" style={{ background: 'var(--bg)', borderRadius: 13, padding: '6px 6px 6px 16px', border: '1.5px solid var(--line)' }}>
              <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send(input)} placeholder="Ask about construction, payments, documents…" style={{ flex: 1, border: 'none', background: 'none', outline: 'none', fontSize: 14.5, color: 'var(--ink)' }} />
              <button className="btn btn-primary btn-sm" style={{ borderRadius: 10 }} onClick={() => send(input)}><Icon name="send" size={17} /></button>
            </div>
            <div className="faint" style={{ fontSize: 11, textAlign: 'center', marginTop: 8 }}>AI responses are informational. Verify critical actions with the Authority.</div>
          </div>
        </div>

        {/* side panel */}
        <div className="col gap-4">
          <div className="card card-pad">
            <h4 style={{ fontSize: 14.5, marginBottom: 12 }}>Smart Suggestions</h4>
            <div className="col gap-2">
              {['What payments are pending?', 'Show Sector 18 map', 'How can I transfer my plot?'].map(s => (
                <button key={s} onClick={() => send(s)} style={{ textAlign: 'left', fontSize: 13, fontWeight: 500, color: 'var(--ink-2)', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line)', background: '#fff', cursor: 'pointer' }} className="card-hover">{s}</button>
              ))}
            </div>
          </div>
          <div className="card card-pad">
            <h4 style={{ fontSize: 14.5, marginBottom: 12 }}>Knowledge Sources</h4>
            <div className="col gap-3">
              {[['Notices & Circulars', 'notices'], ['Document Center', 'documents'], ['Building Byelaws', 'file'], ['Sector Master Plans', 'map']].map(([l, ic]) => (
                <div key={l} className="row gap-3" style={{ fontSize: 13, color: 'var(--muted)' }}><Icon name={ic} size={16} style={{ color: 'var(--blue-500)' }} />{l}</div>
              ))}
            </div>
          </div>
          <div className="card card-pad" style={{ background: 'var(--navy-800)', color: '#fff' }}>
            <Icon name="support" size={22} style={{ color: 'var(--emerald-500)' }} />
            <div style={{ fontWeight: 700, fontSize: 14.5, marginTop: 10 }}>Need a human?</div>
            <p style={{ fontSize: 12.5, color: 'rgba(200,216,240,.8)', marginTop: 4, lineHeight: 1.5 }}>Escalate to a YEIDA support officer for complex queries.</p>
            <button className="btn btn-emerald btn-sm btn-block" style={{ marginTop: 12 }} onClick={() => go('support')}>Talk to an Agent</button>
          </div>
        </div>
      </div>
    );
  }

  function Bubble({ m, go }) {
    const isUser = m.role === 'user';
    return (
      <div className="anim-fade-up row gap-3" style={{ alignItems: 'flex-end', flexDirection: isUser ? 'row-reverse' : 'row' }}>
        <span style={{ width: 32, height: 32, borderRadius: 9, flex: 'none', display: 'grid', placeItems: 'center', background: isUser ? 'var(--bg-2)' : 'linear-gradient(150deg,var(--blue-500),var(--navy-800))', color: isUser ? 'var(--muted)' : '#fff' }}>
          <Icon name={isUser ? 'user' : 'sparkles'} size={16} />
        </span>
        <div style={{ maxWidth: '76%' }}>
          <div style={{ background: isUser ? 'var(--blue-600)' : 'var(--bg-2)', color: isUser ? '#fff' : 'var(--ink)', borderRadius: isUser ? '14px 14px 4px 14px' : '14px 14px 14px 4px', padding: '13px 17px', fontSize: 14, lineHeight: 1.55, whiteSpace: 'pre-wrap' }}>{m.text}</div>
          {m.action && <button className="btn btn-outline btn-sm" style={{ marginTop: 9 }} onClick={() => go(m.action[0])}>{m.action[1]}<Icon name="arrowR" size={15} /></button>}
        </div>
      </div>
    );
  }

  window.Assistant = Assistant;
})();
