const SUGGESTED = [
  '¿Mi seguro de auto cubre granizo?',
  '¿Cuánto me cubre salud en una cirugía?',
  '¿Qué pasa si no pago una cuota?',
  '¿Qué es la UF de cobertura?',
];
const MOCK = [
  { from:'ai', text:'Hola Javier 👋 Soy Holai, tu asistente de seguros. Conozco tus 4 pólizas vigentes. ¿En qué te ayudo?' },
  { from:'me', text:'¿Mi seguro de auto cubre si me roban la radio?' },
  { from:'ai', text:'Tu póliza HDI tiene cobertura de "accesorios no fijos" hasta UF 10 (~$390.000). La radio solo entra si está declarada, y en tu póliza no aparece.' },
  { from:'ai', text:'¿Quieres que te muestre cómo declararla o cotizar una póliza con cobertura extendida?' },
];
function ChatPage({ go }) {
  const [messages, setMessages] = React.useState(MOCK);
  const [draft, setDraft] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(()=>{ if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [messages, typing]);
  const send = (text) => {
    const v = (text ?? draft).trim(); if (!v) return;
    setMessages(m => [...m, {from:'me', text: v}]); setDraft(''); setTyping(true);
    setTimeout(()=>{ setTyping(false); setMessages(m=>[...m, {from:'ai', text: reply(v)}]); }, 1300);
  };
  return (
    <div className="app-shell">
      <Sidebar route="chat" go={go}/>
      <div style={{display:'flex', flexDirection:'column', height:'100vh', background:'var(--bg)'}}>
        <div className="chat-topbar" style={{padding:'20px 40px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <div className="hstack">
            <div style={{width: 44, height: 44, borderRadius:'50%', background:'var(--accent)', color:'#fff', display:'grid', placeItems:'center'}}><I.sparkle size={20}/></div>
            <div>
              <div style={{fontSize: 20, fontWeight: 800, letterSpacing:'-0.02em'}}>Holai</div>
              <div className="mono muted" style={{fontSize: 10, letterSpacing:'0.08em'}}>CONECTADO A 4 PÓLIZAS · EN LÍNEA</div>
            </div>
          </div>
          <div className="chip accent"><I.sparkle size={12}/> Holai Plus</div>
        </div>
        <div ref={ref} className="chat-body" style={{flex: 1, overflowY:'auto', padding:'32px 40px'}}>
          <div style={{maxWidth: 780, margin:'0 auto', display:'flex', flexDirection:'column', gap: 14}}>
            {messages.map((m, i)=>(
              <div key={i} style={{display:'flex', alignItems:'flex-start', gap: 10, flexDirection: m.from==='me'?'row-reverse':'row'}}>
                {m.from==='ai' && <div style={{width: 32, height: 32, borderRadius:'50%', background:'var(--accent)', color:'#fff', display:'grid', placeItems:'center', flexShrink: 0}}><I.sparkle size={14}/></div>}
                <div className={`bubble ${m.from==='me'?'me':'ai'}`}>{m.text}</div>
              </div>
            ))}
            {typing && (
              <div style={{display:'flex', alignItems:'flex-start', gap: 10}}>
                <div style={{width: 32, height: 32, borderRadius:'50%', background:'var(--accent)', color:'#fff', display:'grid', placeItems:'center'}}><I.sparkle size={14}/></div>
                <div className="bubble ai" style={{padding:'14px 20px'}}><div className="typing"><span></span><span></span><span></span></div></div>
              </div>
            )}
            {messages.length <= 4 && !typing && (
              <div style={{marginTop: 12}}>
                <div className="eyebrow" style={{marginBottom: 10}}>Sugerencias</div>
                <div style={{display:'flex', flexWrap:'wrap', gap: 8}}>
                  {SUGGESTED.map(s => <button key={s} className="chip" style={{cursor:'pointer', border:'1.5px solid var(--line)', background:'var(--card)', fontWeight: 500, color:'var(--ink-2)'}} onClick={()=>send(s)}>{s}</button>)}
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="chat-footer" style={{padding:'20px 40px 32px', borderTop:'1px solid var(--line)'}}>
          <div style={{maxWidth: 780, margin:'0 auto', background:'var(--bg-warm)', borderRadius: 999, padding: 6, display:'flex', alignItems:'center', gap: 8}}>
            <button className="btn btn-ghost btn-sm" style={{padding: 10}}><I.attach size={16}/></button>
            <input className="field" style={{border: 0, background:'transparent', padding:'10px 6px'}} placeholder="Pregúntame lo que quieras…" value={draft} onChange={(e)=>setDraft(e.target.value)} onKeyDown={(e)=>{if(e.key==='Enter') send();}}/>
            <button className="btn btn-accent btn-sm" style={{padding: 10}} onClick={()=>send()}><I.send size={16}/></button>
          </div>
          <div className="mono muted" style={{textAlign:'center', fontSize: 10, marginTop: 10, letterSpacing:'0.08em'}}>LA IA PUEDE EQUIVOCARSE · CONSULTÁ LA PÓLIZA OFICIAL</div>
        </div>
      </div>
    </div>
  );
}
function reply(q) {
  q=q.toLowerCase();
  if (q.includes('granizo')) return 'Sí. Tu póliza HDI cubre granizo bajo "fenómenos climáticos". Deducible: UF 5 (~$195.000).';
  if (q.includes('cirug')) return 'Tu plan Cruz Blanca cubre hasta 85% en prestadores en convenio. Tope anual: UF 3.000.';
  if (q.includes('cuota')) return 'Tienes 30 días de gracia. Después queda suspendida. Si pagas en 60 días se reactiva; después de eso, se cancela.';
  if (q.includes('uf')) return 'La UF es una unidad reajustable por inflación. Hoy: $38.940. Las pólizas la usan para mantener coberturas estables.';
  return 'Revisé tus pólizas. Puedo explicarte cualquier cláusula, comparar con el mercado o detectar vacíos. ¿Qué quieres profundizar?';
}
window.ChatPage = ChatPage;
