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();
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);

  React.useEffect(() => {
    const handle = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', handle);
    return () => window.removeEventListener('resize', handle);
  }, []);

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

  // Prevent body scroll when chat is open on mobile
  React.useEffect(() => {
    if (open && isMobile) {
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = ''; };
    }
  }, [open, isMobile]);

  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 {
      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.6,
    maxWidth: '85%', position: 'relative', marginBottom: 8, wordBreak: 'break-word'
  };

  // ── MOBILE: Fullscreen overlay ──
  if (isMobile) {
    return (
      <>
        {/* Floating button — positioned above bottom nav */}
        {!open && (
          <button onClick={() => setOpen(true)}
            style={{
              position: 'fixed', bottom: 76, right: 14, zIndex: 10000,
              width: 52, height: 52, borderRadius: '50%',
              background: '#1A1F6E', border: '3px solid #fff',
              cursor: 'pointer', boxShadow: '0 6px 20px rgba(26,31,110,0.35)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              overflow: 'hidden', transition: 'transform .2s'
            }}>
            <img src="/icono-elia.png" width="52" height="52"
              style={{ objectFit: 'cover', borderRadius: '50%' }} alt="Elia"
              onError={e => { e.target.style.display='none'; e.target.parentNode.innerHTML='<span style="font-size:20px;color:#fff">✦</span>'; }} />
          </button>
        )}

        {/* Fullscreen chat panel */}
        {open && (
          <div style={{
            position: 'fixed', inset: 0, zIndex: 10001,
            background: '#fff', display: 'flex', flexDirection: 'column',
          }}>
            {/* Header */}
            <div style={{
              background: '#1A1F6E', padding: '14px 16px',
              paddingTop: 'calc(14px + env(safe-area-inset-top))',
              color: '#fff', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0
            }}>
              <img src="/icono-elia.png" width="38" height="38"
                style={{ borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} alt="Elia"
                onError={e => { e.target.style.display='none'; }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 800, fontFamily: 'Nunito, sans-serif' }}>Elia ✨</div>
                <div style={{ fontSize: 11, opacity: 0.8 }}>Asistente Estratégica</div>
              </div>
              <button onClick={() => setOpen(false)}
                style={{
                  background: 'rgba(255,255,255,0.15)', border: 'none', borderRadius: '50%',
                  width: 36, height: 36, cursor: 'pointer', color: '#fff',
                  fontSize: 18, display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}>✕</button>
            </div>

            {/* Messages */}
            <div ref={scrollRef} style={{
              flex: 1, padding: 16, overflowY: 'auto', display: 'flex',
              flexDirection: 'column', background: '#F5F9FF', minHeight: 0
            }}>
              {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}>{line}</div>)}
                </div>
              ))}
              {loading && <div style={{ alignSelf: 'flex-start', color: '#9898B0', fontSize: 12, padding: '8px 0' }}>Elia está pensando…</div>}
            </div>

            {/* Input */}
            <div style={{
              padding: '12px 14px', paddingBottom: 'calc(12px + env(safe-area-inset-bottom))',
              borderTop: '1px solid #E0E8FF', display: 'flex', gap: 8, background: '#fff', flexShrink: 0
            }}>
              <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: '10px 16px', fontSize: 14, outline: 'none', minWidth: 0,
                  fontFamily: 'inherit'
                }} />
              <button onClick={send} disabled={!input.trim() || loading}
                style={{
                  width: 40, height: 40, borderRadius: '50%', background: '#1A1F6E',
                  border: 'none', color: '#fff', cursor: 'pointer',
                  opacity: input.trim() ? 1 : 0.4, flexShrink: 0, fontSize: 16
                }}>➤</button>
            </div>
          </div>
        )}
      </>
    );
  }

  // ── DESKTOP: Floating panel ──
  return (
    <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 10000 }}>
      <button onClick={() => setOpen(!open)}
        style={{
          width: 56, height: 56, borderRadius: '50%', background: '#1A1F6E',
          border: '3px solid #fff', cursor: 'pointer',
          boxShadow: '0 8px 24px rgba(26,31,110,0.35)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          overflow: 'hidden', transition: 'transform .2s'
        }}
        onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.08)'}
        onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
        {open
          ? <span style={{ fontSize: 22, color: '#fff', fontWeight: 700 }}>✕</span>
          : <img src="/icono-elia.png" width="56" height="56"
              style={{ objectFit: 'cover', borderRadius: '50%' }} alt="Elia"
              onError={e => { e.target.style.display='none'; e.target.parentNode.innerHTML='<span style="font-size:24px;color:#fff">✦</span>'; }} />}
      </button>

      {open && (
        <div style={{
          position: 'absolute', bottom: 66, right: 0, width: 360, height: 480,
          background: '#fff', borderRadius: 24,
          boxShadow: '0 12px 40px rgba(0,0,0,0.18)',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
          border: '1px solid #E0E8FF'
        }}>
          {/* Header */}
          <div style={{ background: '#1A1F6E', padding: '14px 18px', color: '#fff', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
            <img src="/icono-elia.png" width="36" height="36"
              style={{ borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} alt="Elia"
              onError={e => { e.target.style.display='none'; }} />
            <div>
              <div style={{ fontSize: 15, fontWeight: 800, fontFamily: 'Nunito, sans-serif' }}>Elia ✨</div>
              <div style={{ fontSize: 11, opacity: 0.8 }}>Asistente Estratégica</div>
            </div>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, padding: 16, overflowY: 'auto', display: 'flex', flexDirection: 'column', background: '#F5F9FF', minHeight: 0 }}>
            {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}>{line}</div>)}
              </div>
            ))}
            {loading && <div style={{ alignSelf: 'flex-start', color: '#9898B0', fontSize: 11, padding: '8px 0' }}>Elia está pensando…</div>}
          </div>

          {/* Input */}
          <div style={{ padding: 12, borderTop: '1px solid #E0E8FF', display: 'flex', gap: 8, background: '#fff', flexShrink: 0 }}>
            <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: '9px 16px', fontSize: 13, outline: 'none', minWidth: 0 }} />
            <button onClick={send} disabled={!input.trim() || loading}
              style={{
                width: 38, height: 38, borderRadius: '50%', background: '#1A1F6E',
                border: 'none', color: '#fff', cursor: 'pointer',
                opacity: input.trim() ? 1 : 0.4, flexShrink: 0, fontSize: 16
              }}>➤</button>
          </div>
        </div>
      )}
    </div>
  );
};
window.EliaChat = EliaChat;
