// Floating support widget — collects a problem + email, sends to /api/support.
// Admins get an email so they resolve same-day.
function SupportChat() {
  const [open, setOpen] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [state, setState] = React.useState('idle'); // idle | sending | sent | error
  const [err, setErr] = React.useState('');

  const send = async (e) => {
    if (e) e.preventDefault();
    const m = msg.trim();
    const em = email.trim().toLowerCase();
    if (m.length < 3) { setState('error'); setErr('Cuéntanos un poco más el problema.'); return; }
    if (!em || em.indexOf('@') === -1) { setState('error'); setErr('Pon un email válido para responderte.'); return; }
    setState('sending'); setErr('');
    try {
      let page = '/';
      try { page = window.location.pathname + window.location.search; } catch (e2) {}
      const r = await fetch('/api/support', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: m, email: em, page }),
      });
      if (!r.ok) {
        const d = await r.json().catch(() => ({}));
        setState('error'); setErr((d && d.error) || 'No se pudo enviar. Inténtalo de nuevo.');
        return;
      }
      setState('sent');
    } catch (e3) {
      setState('error'); setErr('No se pudo enviar. Inténtalo de nuevo.');
    }
  };

  const accent = 'var(--pl-accent, #7c3aed)';

  return (
    <div style={{ position: 'fixed', right: 20, bottom: 20, zIndex: 9999, fontFamily: "'Manrope',-apple-system,Segoe UI,sans-serif" }}>
      {/* Panel */}
      {open && (
        <div style={{
          width: 340, maxWidth: 'calc(100vw - 40px)',
          background: '#fff', borderRadius: 18, overflow: 'hidden',
          boxShadow: '0 24px 60px -16px rgba(15,23,42,.35)', border: '1px solid #ede9fe',
          marginBottom: 14,
        }}>
          <div style={{ background: accent, color: '#fff', padding: '16px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontWeight: 800, fontSize: 15.5 }}>¿Algún problema? 👋</div>
              <div style={{ fontSize: 12, opacity: .9 }}>Te lo resolvemos HOY mismo</div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="Cerrar"
              style={{ background: 'rgba(255,255,255,.2)', border: 'none', color: '#fff', width: 28, height: 28, borderRadius: 8, cursor: 'pointer', fontSize: 16, lineHeight: 1 }}>×</button>
          </div>

          <div style={{ padding: 18 }}>
            {state === 'sent' ? (
              <div style={{ textAlign: 'center', padding: '10px 4px' }}>
                <div style={{ fontSize: 40, marginBottom: 8 }}>🙌</div>
                <div style={{ fontWeight: 800, fontSize: 16, color: '#0f172a', marginBottom: 6 }}>¡Recibido!</div>
                <div style={{ fontSize: 13.5, color: '#475569', lineHeight: 1.5 }}>
                  Te escribimos <strong>hoy mismo</strong> a <strong>{email.trim().toLowerCase()}</strong>. Gracias por avisar 💜
                </div>
                <button onClick={() => { setOpen(false); setState('idle'); setMsg(''); setEmail(''); }}
                  style={{ marginTop: 16, background: accent, color: '#fff', border: 'none', borderRadius: 10, padding: '10px 18px', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>Cerrar</button>
              </div>
            ) : (
              <form onSubmit={send}>
                <div style={{ background: '#f5f3ff', borderRadius: 12, padding: '10px 12px', fontSize: 13.5, color: '#3730a3', marginBottom: 12, lineHeight: 1.5 }}>
                  Cuéntame qué te pasa y déjame tu email. Lo reviso y te respondo el mismo día.
                </div>
                <textarea
                  value={msg}
                  onChange={(e) => { setMsg(e.target.value); if (state === 'error') setState('idle'); }}
                  placeholder="Ej: me da error al pagar / no puedo entrar..."
                  rows={3}
                  style={{ width: '100%', boxSizing: 'border-box', borderRadius: 10, border: '1px solid #e2e8f0', padding: '10px 12px', fontSize: 14, resize: 'vertical', outline: 'none', fontFamily: 'inherit' }}
                />
                <input
                  type="email" inputMode="email" autoComplete="email"
                  value={email}
                  onChange={(e) => { setEmail(e.target.value); if (state === 'error') setState('idle'); }}
                  placeholder="tu@email.com"
                  style={{ width: '100%', boxSizing: 'border-box', borderRadius: 10, border: '1px solid #e2e8f0', padding: '10px 12px', fontSize: 14, marginTop: 8, outline: 'none' }}
                />
                {state === 'error' && <div style={{ color: '#dc2626', fontSize: 12.5, fontWeight: 600, marginTop: 8 }}>{err}</div>}
                <button type="submit" disabled={state === 'sending'}
                  style={{ width: '100%', marginTop: 12, background: accent, color: '#fff', border: 'none', borderRadius: 12, padding: '13px', fontWeight: 800, fontSize: 14.5, cursor: 'pointer', opacity: state === 'sending' ? .6 : 1 }}>
                  {state === 'sending' ? 'Enviando…' : 'Enviar y que me resuelvan hoy'}
                </button>
              </form>
            )}
          </div>
        </div>
      )}

      {/* Bubble */}
      <button onClick={() => setOpen(!open)} aria-label="Soporte"
        style={{
          marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8,
          background: accent, color: '#fff', border: 'none', borderRadius: 999,
          padding: open ? '14px' : '14px 20px', boxShadow: '0 12px 30px -8px rgba(124,58,237,.55)',
          cursor: 'pointer', fontWeight: 800, fontSize: 14.5, float: 'right',
        }}>
        <span style={{ fontSize: 18 }}>{open ? '×' : '💬'}</span>
        {!open && <span>¿Ayuda?</span>}
      </button>
    </div>
  );
}

window.SupportChat = SupportChat;
