// chatbot-landing.jsx — chatbot de la landing con avatar de abogada

function VictoriaAvatar({ size = 52 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      backgroundImage: 'url(/lexia-avatar.png)',
      backgroundSize: 'cover',
      backgroundPosition: 'center 25%',
      backgroundRepeat: 'no-repeat',
      WebkitBackfaceVisibility: 'hidden',
      transform: 'translateZ(0)',
    }} />
  );
}

function renderRichText(text) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((part, i) => {
    if (part.startsWith('**') && part.endsWith('**')) {
      return <strong key={i}>{part.slice(2, -2)}</strong>;
    }
    return part;
  });
}

function ChatbotLanding() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    {
      role: 'assistant',
      content: '¡Hola! Soy Victoria, tu asistente de Excelencia Legal CR. Puedo contarte todo sobre la plataforma, el precio, cómo registrarte y los beneficios. ¿En qué te puedo ayudar? 😊'
    }
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [contactMode, setContactMode] = React.useState(false);
  const [contactForm, setContactForm] = React.useState({ fullName: '', email: '', mensaje: '' });
  const [contactSending, setContactSending] = React.useState(false);
  const [contactError, setContactError] = React.useState('');
  const bottomRef = React.useRef(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (bottomRef.current) bottomRef.current.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  React.useEffect(() => {
    if (open && inputRef.current) setTimeout(() => inputRef.current.focus(), 120);
  }, [open]);

  async function send(overrideText) {
    const text = (overrideText ?? input).trim();
    if (!text || loading) return;
    setInput('');
    const next = [...messages, { role: 'user', content: text }];
    setMessages(next);
    setLoading(true);

    try {
      const res = await fetch('/api/chat/landing', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: next }),
      });
      const data = await res.json();
      if (data.text) {
        setMessages(prev => [...prev, { role: 'assistant', content: data.text }]);
      } else {
        setMessages(prev => [...prev, { role: 'assistant', content: data.error || 'Error al procesar tu consulta.' }]);
      }
    } catch {
      setMessages(prev => [...prev, { role: 'assistant', content: 'Error de conexión. Intentá de nuevo.' }]);
    } finally {
      setLoading(false);
    }
  }

  function handleKey(e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
  }

  async function sendContact() {
    const fullName = contactForm.fullName.trim();
    const email = contactForm.email.trim();
    const mensaje = contactForm.mensaje.trim();
    if (!fullName || !email || !mensaje) {
      setContactError('Completá todos los campos.');
      return;
    }
    setContactSending(true);
    setContactError('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fullName, email, mensaje, source: 'landing' }),
      });
      const data = await res.json();
      if (!res.ok) {
        setContactError(data.error || 'No se pudo enviar tu mensaje.');
        return;
      }
      setMessages(prev => [...prev, { role: 'assistant', content: `¡Gracias, ${fullName}! Recibimos tu mensaje y te vamos a responder a ${email} lo antes posible. 😊` }]);
      setContactForm({ fullName: '', email: '', mensaje: '' });
      setContactMode(false);
    } catch {
      setContactError('Error de conexión. Intentá de nuevo.');
    } finally {
      setContactSending(false);
    }
  }

  const chatStyle = {
    position: 'fixed', bottom: 96, right: 24, zIndex: 9001,
    width: 'min(380px, calc(100vw - 32px))',
    height: 'min(520px, calc(100dvh - 120px))',
    background: '#fff',
    borderRadius: 18, overflow: 'hidden',
    boxShadow: '0 24px 64px -16px rgba(0,0,0,0.28), 0 0 0 1px rgba(0,0,0,0.06)',
    display: 'flex', flexDirection: 'column',
  };

  const headerStyle = {
    background: '#0A1626', padding: '14px 16px',
    display: 'flex', alignItems: 'center', gap: 10,
    borderBottom: '1px solid rgba(201,168,76,.22)',
  };

  return (
    <div>
      {/* Floating avatar button */}
      <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 9002 }}>
        <button
          onClick={() => setOpen(v => !v)}
          style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: 0,
            display: 'block', position: 'relative',
          }}
          aria-label="Hablar con Victoria"
        >
          <VictoriaAvatar size={56} />
          {!open && (
            <span style={{
              position: 'absolute', top: 4, right: 4,
              background: '#C9A84C', color: '#0A1626',
              borderRadius: '50%', width: 20, height: 20,
              fontSize: 11, fontWeight: 800, display: 'flex',
              alignItems: 'center', justifyContent: 'center',
              border: '2px solid white', lineHeight: 1,
            }}>?</span>
          )}
        </button>
      </div>

      {/* Chat window */}
      {open && (
        <div style={chatStyle}>
          {/* Header */}
          <div style={headerStyle}>
            <div style={{ flexShrink: 0 }}>
              <VictoriaAvatar size={40} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <p style={{ margin: 0, fontSize: 14, fontWeight: 700, color: '#F0EBE0' }}>Victoria</p>
              <p style={{ margin: 0, fontSize: 10.5, color: '#C9A84C', fontFamily: 'monospace', letterSpacing: '.1em', textTransform: 'uppercase' }}>Asesora · Excelencia Legal CR</p>
            </div>
            <button onClick={() => setOpen(false)} style={{ background: 'none', border: 'none', color: '#6A8090', fontSize: 18, cursor: 'pointer', padding: 4 }}>✕</button>
          </div>

          {/* Messages */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '14px 14px', display: 'flex', flexDirection: 'column', gap: 10, background: '#F9F7F2' }}>
            {messages.map((m, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start', alignItems: 'flex-end', gap: 6 }}>
                {m.role === 'assistant' && (
                  <div style={{ flexShrink: 0, marginBottom: 2 }}>
                    <VictoriaAvatar size={26} />
                  </div>
                )}
                <div style={{
                  maxWidth: '80%', padding: '9px 13px',
                  borderRadius: m.role === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                  background: m.role === 'user' ? '#0A1626' : '#fff',
                  color: m.role === 'user' ? '#F0EBE0' : '#17202E',
                  fontSize: 13.5, lineHeight: 1.55, fontWeight: m.role === 'user' ? 500 : 400,
                  boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
                  whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                }}>
                  {renderRichText(m.content)}
                </div>
              </div>
            ))}

            {loading && (
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6 }}>
                <div style={{ flexShrink: 0 }}>
                  <VictoriaAvatar size={26} />
                </div>
                <div style={{ background: '#fff', borderRadius: '14px 14px 14px 4px', padding: '10px 14px', boxShadow: '0 1px 3px rgba(0,0,0,0.08)' }}>
                  <span style={{ display: 'inline-flex', gap: 4 }}>
                    {[0,1,2].map(j => (
                      <span key={j} style={{ width: 7, height: 7, borderRadius: '50%', background: '#C9A84C', display: 'inline-block', animation: `dotBounce 1.2s ${j*0.2}s ease-in-out infinite` }}/>
                    ))}
                  </span>
                </div>
              </div>
            )}
            <div ref={bottomRef}/>
          </div>

          {/* Quick suggestions (only on first open) */}
          {!contactMode && messages.length <= 1 && (
            <div style={{ padding: '8px 12px', borderTop: '1px solid #EDE8D8', background: '#F9F7F2', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {['¿Cuánto cuesta?', '¿Qué incluye?', '¿Cómo me registro?', 'Simulacro gratis'].map(q => (
                <button key={q} onClick={() => send(q)}
                  style={{ fontSize: 12, padding: '5px 10px', borderRadius: 20, border: '1px solid #C9A84C', background: 'transparent', color: '#8A6A20', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500 }}>
                  {q}
                </button>
              ))}
            </div>
          )}

          {!contactMode && (
            <div style={{ padding: '0 12px 8px', borderTop: messages.length <= 1 ? 'none' : '1px solid #EDE8D8', background: '#F9F7F2' }}>
              <button onClick={() => { setContactMode(true); setContactError('') }}
                style={{ marginTop: 8, fontSize: 12, padding: '5px 10px', borderRadius: 20, border: '1px solid #0A1626', background: '#0A1626', color: '#F0EBE0', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500 }}>
                ✉ Contacto
              </button>
            </div>
          )}

          {/* Contact form */}
          {contactMode ? (
            <div style={{ borderTop: '1px solid #EDE8D8', padding: '12px', background: '#fff', display: 'flex', flexDirection: 'column', gap: 8 }}>
              <input
                type="text"
                value={contactForm.fullName}
                onChange={e => setContactForm(p => ({ ...p, fullName: e.target.value }))}
                placeholder="Nombre completo"
                style={{ border: '1px solid #D8D0BC', borderRadius: 10, padding: '9px 12px', fontSize: 13.5, outline: 'none', fontFamily: 'inherit', color: '#17202E', background: '#FAF8F3' }}
              />
              <input
                type="email"
                value={contactForm.email}
                onChange={e => setContactForm(p => ({ ...p, email: e.target.value }))}
                placeholder="Correo electrónico"
                style={{ border: '1px solid #D8D0BC', borderRadius: 10, padding: '9px 12px', fontSize: 13.5, outline: 'none', fontFamily: 'inherit', color: '#17202E', background: '#FAF8F3' }}
              />
              <textarea
                value={contactForm.mensaje}
                onChange={e => setContactForm(p => ({ ...p, mensaje: e.target.value }))}
                placeholder="¿Qué necesitás?"
                rows={3}
                style={{ border: '1px solid #D8D0BC', borderRadius: 10, padding: '9px 12px', fontSize: 13.5, outline: 'none', fontFamily: 'inherit', color: '#17202E', background: '#FAF8F3', resize: 'none' }}
              />
              {contactError && <p style={{ margin: 0, fontSize: 12, color: '#B23A3A' }}>{contactError}</p>}
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={() => { setContactMode(false); setContactError('') }} disabled={contactSending}
                  style={{ flex: 1, padding: '9px 0', borderRadius: 10, border: '1px solid #D8D0BC', background: 'transparent', color: '#6A8090', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13 }}>
                  Cancelar
                </button>
                <button onClick={sendContact} disabled={contactSending}
                  style={{ flex: 1, padding: '9px 0', borderRadius: 10, border: 'none', background: '#0A1626', color: '#F0EBE0', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, opacity: contactSending ? 0.6 : 1 }}>
                  {contactSending ? 'Enviando…' : 'Enviar'}
                </button>
              </div>
            </div>
          ) : (
            /* Input */
            <div style={{ borderTop: '1px solid #EDE8D8', padding: '10px 12px', display: 'flex', gap: 8, background: '#fff' }}>
              <input
                ref={inputRef}
                type="text"
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={handleKey}
                disabled={loading}
                placeholder="Escribí tu pregunta…"
                style={{
                  flex: 1, border: '1px solid #D8D0BC', borderRadius: 10, padding: '9px 12px',
                  fontSize: 13.5, outline: 'none', fontFamily: 'inherit', color: '#17202E', background: '#FAF8F3',
                }}
              />
              <button
                onClick={send}
                disabled={loading || !input.trim()}
                style={{
                  background: input.trim() && !loading ? '#0A1626' : '#D0CCC0',
                  border: 'none', borderRadius: 10, width: 40, height: 40,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  cursor: input.trim() && !loading ? 'pointer' : 'default',
                  transition: 'background .15s', flexShrink: 0, alignSelf: 'flex-end',
                }}
              >
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path d="M2 8L14 2L8 14L7 9L2 8Z" fill={input.trim() && !loading ? '#F0EBE0' : '#9A9488'}/>
                </svg>
              </button>
            </div>
          )}
        </div>
      )}

      <style>{`
        @keyframes chatPulse { 0%{transform:scale(1);opacity:.7} 70%{transform:scale(1.35);opacity:0} 100%{opacity:0} }
        @keyframes dotBounce { 0%,80%,100%{transform:translateY(0)} 40%{transform:translateY(-6px)} }
      `}</style>
    </div>
  );
}

const _chatRoot = document.createElement('div');
document.body.appendChild(_chatRoot);
ReactDOM.createRoot(_chatRoot).render(<ChatbotLanding />);
