// Botón flotante (FAB) que abre un panel para enviar feedback al backend.
// Solo se monta cuando el usuario está autenticado (en la app, no en landing/auth).

function FeedbackButton({ backend, token }) {
  const [open, setOpen] = React.useState(false);
  const [category, setCategory] = React.useState('sugerencia');
  const [message, setMessage] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState('');

  // Cerrar con tecla Escape
  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [open]);

  // Resetear estado cuando se cierra
  React.useEffect(() => {
    if (!open) {
      const t = setTimeout(() => {
        setSent(false);
        setError('');
      }, 200);
      return () => clearTimeout(t);
    }
  }, [open]);

  const submit = async (e) => {
    e.preventDefault();
    if (!message.trim()) return;
    setSending(true);
    setError('');
    try {
      const r = await fetch(`${backend}/api/feedback`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({
          category,
          message: message.trim(),
          url: window.location.href,
        }),
      });

      // Parsear como texto primero, así si el backend devuelve HTML (ruta no existe)
      // damos un mensaje útil en vez del crash de JSON.parse.
      const raw = await r.text();
      let data;
      try { data = JSON.parse(raw); }
      catch {
        throw new Error(
          r.status === 404
            ? 'Endpoint no disponible. Reiniciá el backend.'
            : `Respuesta inválida del servidor (HTTP ${r.status}).`
        );
      }
      if (!r.ok) throw new Error(data.error || `Error ${r.status}`);

      setSent(true);
      setMessage('');
      setTimeout(() => { setOpen(false); }, 2500);
    } catch (err) {
      setError(err.message || 'No se pudo enviar. Probá de nuevo.');
    } finally {
      setSending(false);
    }
  };

  const categories = [
    { id: 'sugerencia', label: '💡 Sugerencia' },
    { id: 'bug',        label: '🐛 Reportar bug' },
    { id: 'pregunta',   label: '❓ Pregunta' },
    { id: 'otro',       label: '✍️ Otro' },
  ];

  return (
    <>
      {/* Panel popup */}
      {open && (
        <div
          style={{
            position: 'fixed', bottom: 86, right: 20, zIndex: 99,
            width: 320, maxWidth: 'calc(100vw - 40px)',
            background: 'var(--panel)', border: '1px solid var(--border-strong)',
            borderRadius: 14, boxShadow: '0 24px 60px rgba(0, 0, 0, 0.5)',
            padding: 18, animation: 'feedbackSlideIn 0.22s cubic-bezier(0.4, 0, 0.2, 1)',
          }}>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: -0.2 }}>
              {sent ? '¡Gracias!' : 'Tu feedback'}
            </div>
            <button
              type="button"
              onClick={() => setOpen(false)}
              style={{
                width: 26, height: 26, borderRadius: 6,
                color: 'var(--text-faint)', display: 'grid', placeItems: 'center',
              }}
              onMouseEnter={e => e.currentTarget.style.color = 'var(--text)'}
              onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}
            >
              <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
                <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/>
              </svg>
            </button>
          </div>

          {sent ? (
            <div style={{ padding: '20px 8px', textAlign: 'center' }}>
              <div style={{
                width: 52, height: 52, borderRadius: '50%',
                background: 'rgba(0, 194, 117, 0.12)', color: 'var(--accent)',
                display: 'grid', placeItems: 'center', margin: '0 auto 12px',
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                  <path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div style={{ fontSize: 13.5, color: 'var(--text-dim)', lineHeight: 1.5 }}>
                Tu feedback fue recibido.<br/>Lo revisamos pronto.
              </div>
            </div>
          ) : (
            <form onSubmit={submit}>
              {/* Categorías como pills */}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginBottom: 10 }}>
                {categories.map(c => {
                  const active = category === c.id;
                  return (
                    <button
                      key={c.id}
                      type="button"
                      onClick={() => setCategory(c.id)}
                      style={{
                        padding: '5px 10px', fontSize: 11.5, fontWeight: 500,
                        borderRadius: 7,
                        background: active ? 'var(--accent)' : 'var(--panel-2)',
                        color: active ? '#fff' : 'var(--text-dim)',
                        border: `1px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
                        transition: 'all 0.12s',
                      }}>
                      {c.label}
                    </button>
                  );
                })}
              </div>

              {/* Textarea */}
              <textarea
                value={message}
                onChange={e => setMessage(e.target.value)}
                placeholder="Contame qué te gustaría ver, qué encontraste roto, o cualquier idea que tengas…"
                maxLength={2000}
                rows={5}
                autoFocus
                style={{
                  width: '100%', resize: 'vertical', minHeight: 90, maxHeight: 200,
                  padding: '10px 12px', boxSizing: 'border-box',
                  background: 'var(--panel-2)', border: '1px solid var(--border)',
                  borderRadius: 9, color: 'var(--text)', fontSize: 13,
                  outline: 'none', fontFamily: 'inherit', lineHeight: 1.5,
                }}
              />

              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                marginTop: 4, fontSize: 10.5, color: 'var(--text-faint)',
              }}>
                <span>{message.length} / 2000</span>
                {error && <span style={{ color: 'var(--red)' }}>{error}</span>}
              </div>

              <button
                type="submit"
                disabled={!message.trim() || sending}
                style={{
                  width: '100%', marginTop: 10, padding: '10px 0',
                  borderRadius: 10, fontSize: 13.5, fontWeight: 700,
                  background: 'var(--accent)', color: '#fff', border: 'none',
                  opacity: !message.trim() || sending ? 0.5 : 1,
                  cursor: !message.trim() || sending ? 'default' : 'pointer',
                  transition: 'opacity 0.15s',
                }}>
                {sending ? 'Enviando…' : 'Enviar feedback →'}
              </button>
            </form>
          )}
        </div>
      )}

      {/* Botón flotante */}
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        title="Enviar feedback"
        aria-label="Enviar feedback"
        style={{
          position: 'fixed', bottom: 22, right: 20, zIndex: 100,
          width: 50, height: 50, borderRadius: '50%',
          background: 'var(--accent)', color: '#fff',
          display: 'grid', placeItems: 'center',
          boxShadow: open
            ? '0 4px 12px rgba(0, 194, 117, 0.25)'
            : '0 8px 24px rgba(0, 194, 117, 0.4)',
          border: 'none', cursor: 'pointer',
          transition: 'transform 0.18s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.18s',
        }}
        onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.08)'}
        onMouseLeave={e => e.currentTarget.style.transform = 'none'}
      >
        {open ? (
          <svg width="20" height="20" viewBox="0 0 14 14" fill="none">
            <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
          </svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <path
              d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"
              stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
            />
          </svg>
        )}
      </button>
    </>
  );
}

Object.assign(window, { FeedbackButton });
