const EliaChat = () => {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { role: 'elia', text: '¡Hola! Soy Elia, tu asistente estratégica. ✦ ¿En qué puedo ayudarte hoy?' }
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const scrollRef = React.useRef();

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    if (!input.trim() || loading) return;
    const msg = input.trim();
    setInput('');
    setMessages(prev => [...prev, { role: 'user', text: msg }]);
    setLoading(true);

    try {
      const res = await API.post('/chat', { message: msg });
      setMessages(prev => [...prev, { role: 'elia', text: res.response }]);
    } catch (e) {
      setMessages(prev => [...prev, { role: 'elia', text: 'Lo siento, hubo un error al procesar tu solicitud.' }]);
    } finally {
      setLoading(false);
    }
  };

  const bubble = {
    padding: '10px 14px', borderRadius: 18, fontSize: 13, lineHeight: 1.5,
    maxWidth: '85%', position: 'relative', marginBottom: 8
  };

  return (
    <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 10000 }}>
      {/* Botón flotante */}
      <button onClick={() => setOpen(!open)}
        style={{ width: 56, height: 56, borderRadius: '50%', background: '#1A1F6E', border: 'none', cursor: 'pointer', boxShadow: '0 8px 24px rgba(26,31,110,0.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', transition: 'all .2s' }}
        onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.05)'}
        onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
        {open ? <span style={{ fontSize: 24 }}>✕</span> : <span style={{ fontSize: 24 }}>✦</span>}
      </button>

      {/* Ventana de chat */}
      {open && (
        <div style={{ position: 'absolute', bottom: 70, right: 0, width: 340, height: 480, background: '#fff', borderRadius: 24, boxShadow: '0 12px 40px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', overflow: 'hidden', border: '1px solid #E0E8FF' }}>
          {/* Header */}
          <div style={{ background: '#1A1F6E', padding: '16px 20px', color: '#fff' }}>
            <div style={{ fontSize: 15, fontWeight: 800, fontFamily: 'Nunito, sans-serif' }}>Elia ✨</div>
            <div style={{ fontSize: 11, opacity: 0.8 }}>Asistente Estratégica Nativa</div>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, padding: 20, overflowY: 'auto', display: 'flex', flexDirection: 'column', background: '#F5F9FF' }}>
            {messages.map((m, i) => (
              <div key={i} style={{ ...bubble, 
                alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
                background: m.role === 'user' ? '#1A1F6E' : '#fff',
                color: m.role === 'user' ? '#fff' : '#2A2A3A',
                border: m.role === 'user' ? 'none' : '1px solid #E0E8FF',
                borderBottomRightRadius: m.role === 'user' ? 4 : 18,
                borderBottomLeftRadius: m.role === 'elia' ? 4 : 18,
              }}>
                {m.text.split('\n').map((line, idx) => <div key={idx} style={{ marginBottom: line.startsWith('**') ? 4 : 0 }}>{line}</div>)}
              </div>
            ))}
            {loading && <div style={{ alignSelf: 'flex-start', color: '#9898B0', fontSize: 11 }}>Elia está pensando...</div>}
          </div>

          {/* Input */}
          <div style={{ padding: 14, borderTop: '1px solid #E0E8FF', display: 'flex', gap: 8, background: '#fff' }}>
            <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
              placeholder="Pregúntame algo..."
              style={{ flex: 1, border: '1.5px solid #E0E8FF', borderRadius: 50, padding: '8px 16px', fontSize: 13, outline: 'none' }} />
            <button onClick={send} disabled={!input.trim() || loading}
              style={{ width: 36, height: 36, borderRadius: '50%', background: '#1A1F6E', border: 'none', color: '#fff', cursor: 'pointer', opacity: input.trim() ? 1 : 0.5 }}>
              ➤
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
window.EliaChat = EliaChat;
