// AI Chat — fake but interactive assistant.
function Chat() {
  const D = window.ZD_DATA;
  const suggestions = ['What needs my attention today?', 'When does my insurance renew?', 'Summarize this week\u2019s spending', 'Any packages arriving today?'];
  const greeting = { who:'ai', text:`Hi ${D.user.name.split(' ')[0]} — here\u2019s what\u2019s new across your bills, packages, calendar and tasks this morning. Ask me anything.` };
  const [msgs, setMsgs] = useState([greeting]);
  const [val, setVal] = useState('');
  const [typing, setTyping] = useState(false);
  const endRef = useRef(null);
  useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [msgs, typing]);
  const reset = () => { setMsgs([greeting]); setVal(''); setTyping(false); };
  const answered = msgs.filter(m => m.who === 'ai').length - 1;

  const reply = q => {
    const l = q.toLowerCase();
    if (l.includes('attention') || l.includes('today')) return 'Three things: a reply is waiting for your landlord (flagged high), your AirPods Pro arrive by 9 PM, and Geico ($142) is due in 3 days. Nothing overdue.';
    if (l.includes('insurance') || l.includes('renew')) return 'Your Geico auto policy renews June 9 — $142.00. I can remind you two days before if you\u2019d like.';
    if (l.includes('spend')) return 'Over the last 7 days you spent $335.40 across Amazon, Whole Foods and a credit report. That\u2019s about average for you.';
    if (l.includes('package')) return 'One package is arriving today: AirPods Pro via Amazon Logistics, out for delivery, expected by 9 PM.';
    return 'I\u2019ve noted that. I can pull this from your bills, packages, calendar, tasks or subscriptions — want me to dig into one of those?';
  };
  const send = q => {
    const text = (q ?? val).trim(); if (!text) return;
    setMsgs(m => [...m, { who:'user', text }]); setVal(''); setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs(m => [...m, { who:'ai', text: reply(text) }]); }, 850);
  };

  return (
    <div className="screen-inner chat-screen">
      <div className="card card-pad rise" style={{ display:'flex', flexDirection:'column', flex:1, minHeight:0 }}>
        <div className="section-h">
          <div>
            <div className="t">Zeranda Assistant</div>
            <div className="s">Ask anything about your bills, packages, calendar or tasks</div>
          </div>
          <button className="viewall" onClick={reset}><Icon name="refresh-cw" size={15} /> New chat</button>
        </div>

        <div ref={endRef} className="zd-scroll chat-scroll">
          {msgs.map((m,i) => (
            <div key={i} style={{ display:'flex', gap:11, marginBottom:18, flexDirection: m.who==='user'?'row-reverse':'row' }}>
              {m.who==='ai'
                ? <span className="ic-chip" style={{ background:'var(--gold-100)', width:34, height:34, borderRadius:10, display:'grid', placeItems:'center', flex:'none' }}><Icon name="sparkles" size={17} color="var(--gold-600)" /></span>
                : <div className="avatar" style={{ width:34, height:34, fontSize:13, flex:'none' }}>{D.user.initial}</div>}
              <div style={{ maxWidth:'76%', background: m.who==='user'?'var(--gold-500)':'var(--surface)', color: m.who==='user'?'#fff':'var(--fg-1)',
                border: m.who==='user'?'none':'1px solid var(--border)', padding:'12px 15px', borderRadius:14, fontSize:14.5, lineHeight:1.5 }}>{m.text}</div>
            </div>
          ))}
          {typing && <div style={{ display:'flex', gap:11 }}>
            <span className="ic-chip" style={{ background:'var(--gold-100)', width:34, height:34, borderRadius:10, display:'grid', placeItems:'center' }}><Icon name="sparkles" size={17} color="var(--gold-600)" /></span>
            <div style={{ padding:'14px 16px', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:14, color:'var(--fg-3)' }}>Zeranda is thinking…</div>
          </div>}
        </div>

        <div className="chat-compose">
          {msgs.length <= 1 && <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:12 }}>
            {suggestions.map(s => <button key={s} className="bchip" onClick={() => send(s)} style={{ fontWeight:500 }}>{s}</button>)}
          </div>}
          <div className="search" style={{ borderRadius:'var(--r-md)' }}>
            <Icon name="sparkles" size={17} color="var(--gold-500)" />
            <input placeholder="Ask Zeranda anything…" value={val} onChange={e => setVal(e.target.value)} onKeyDown={e => e.key==='Enter' && send()} />
            <button className="iconbtn" onClick={() => send()} style={{ color:'var(--gold-600)' }}><Icon name="arrow-up" size={18} /></button>
          </div>
        </div>
      </div>
    </div>
  );
}
window.Chat = Chat;
