// feedback-vendedora.jsx — FAB + modal de feedback para beta-testers
// Monta un botón flotante en TODAS las pantallas de la vendedora.
// Submit: POST directo a Supabase tabla beta_feedback.

(function () {
  const SUPABASE_TABLE = 'beta_feedback';
  const MAX_CHARS = 1000;

  const TIPOS = [
    { value: 'bug',        label: '🐛 Bug',        placeholder: 'Describí qué pasó y en qué pantalla ocurrió...' },
    { value: 'sugerencia', label: '💡 Sugerencia',  placeholder: 'Contame qué mejorarías o qué te gustaría tener...' },
    { value: 'duda',       label: '❓ Duda',        placeholder: '¿Qué no te quedó claro o no sabés cómo hacer?' },
    { value: 'elogio',     label: '❤️ Elogio',     placeholder: '¿Qué te gustó? Tu feedback positivo nos ayuda a saber qué mantener.' },
  ];

  const SEVERIDADES = [
    { value: 'baja',    label: 'Baja' },
    { value: 'media',   label: 'Media' },
    { value: 'alta',    label: 'Alta' },
    { value: 'critica', label: 'Crítica' },
  ];

  // ── helpers ───────────────────────────────────────────────────────────────

  function getVendedoraAuth() {
    // 1. Preferimos el objeto completo cacheado por App
    try {
      const raw = localStorage.getItem('inova-vend');
      if (raw) {
        const v = JSON.parse(raw);
        if (v && v.id) return v;
      }
    } catch {}
    return null;
  }

  // ── FeedbackModal ─────────────────────────────────────────────────────────

  function FeedbackModal({ screen, vendedora, onClose }) {
    const T = window.T;
    const [tipo, setTipo] = React.useState('bug');
    const [severidad, setSeveridad] = React.useState('media');
    const [mensaje, setMensaje] = React.useState('');
    const [estado, setEstado] = React.useState('idle'); // idle | sending | ok | err | err404
    const overlayRef = React.useRef(null);

    // Focus trap: enfocar el primer input al abrir
    const firstFocusRef = React.useRef(null);
    React.useEffect(() => {
      if (firstFocusRef.current) firstFocusRef.current.focus();
    }, []);

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

    // Bloquear scroll del body mientras está abierto
    React.useEffect(() => {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }, []);

    const currentPlaceholder = TIPOS.find(t => t.value === tipo)?.placeholder || '';
    const charsLeft = MAX_CHARS - mensaje.length;
    const canSubmit = mensaje.trim().length > 0 && estado === 'idle';

    const handleSubmit = async () => {
      if (!canSubmit) return;
      setEstado('sending');

      const vend = vendedora || getVendedoraAuth();
      const payload = {
        vendedora_id:     vend?.id     || null,
        vendedora_nombre: vend?.nombre || null,
        vendedora_cedula: vend?.cedula || null,
        tipo,
        severidad:        tipo === 'bug' ? severidad : 'baja',
        mensaje:          mensaje.trim().slice(0, MAX_CHARS),
        pantalla:         screen || 'desconocida',
        url:              window.location.pathname + (window.location.hash || ''),
        user_agent:       navigator.userAgent,
      };

      try {
        const sb = await window.getSupabase();
        const { error, status } = await sb
          .from(SUPABASE_TABLE)
          .insert([payload]);

        if (error) {
          if (status === 404 || (error.code && error.code === '42P01')) {
            setEstado('err404');
          } else {
            setEstado('err');
          }
        } else {
          setEstado('ok');
          // Cierra el modal a los 2.5 s para que lean el toast
          setTimeout(() => onClose(), 2500);
        }
      } catch (e) {
        // 404 puede venir también como network error con status 0 cuando la tabla no existe
        if (e?.status === 404 || String(e).includes('does not exist') || String(e?.message).includes('does not exist')) {
          setEstado('err404');
        } else {
          setEstado('err');
        }
      }
    };

    // ── Overlay click fuera → cerrar ───────────────────────────────────────
    const handleOverlayClick = (e) => {
      if (e.target === overlayRef.current) onClose();
    };

    return (
      <div
        ref={overlayRef}
        role="dialog"
        aria-modal="true"
        aria-label="Enviar feedback"
        onClick={handleOverlayClick}
        style={{
          position: 'fixed',
          inset: 0,
          background: 'rgba(20,15,10,0.55)',
          zIndex: 9990,
          display: 'flex',
          alignItems: 'flex-end',
          justifyContent: 'center',
          transition: 'opacity .2s ease',
        }}
      >
        {/* Drawer panel */}
        <div
          style={{
            background: T?.paper || '#faf9f7',
            borderRadius: '22px 22px 0 0',
            width: '100%',
            maxWidth: 480,
            maxHeight: '92vh',
            overflowY: 'auto',
            padding: '0 0 env(safe-area-inset-bottom, 16px)',
            boxShadow: '0 -8px 40px rgba(0,0,0,0.18)',
            animation: 'feedbackSlideUp .25s cubic-bezier(.2,.9,.3,1) forwards',
          }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Handle bar */}
          <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
            <div style={{
              width: 36, height: 4, borderRadius: 2,
              background: T?.hairlineStrong || '#c8c2b8',
            }} />
          </div>

          <div style={{ padding: '8px 20px 24px' }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
              <div>
                <div style={{
                  fontFamily: T?.serif || 'Georgia,serif',
                  fontSize: 20, fontWeight: 400,
                  color: T?.ink || '#1a1612',
                  letterSpacing: -0.3,
                }}>Enviar feedback</div>
                {screen && (
                  <div style={{
                    fontFamily: T?.mono || 'monospace',
                    fontSize: 10, letterSpacing: 1,
                    textTransform: 'uppercase',
                    color: T?.inkMute || '#888',
                    marginTop: 2,
                  }}>pantalla: {screen}</div>
                )}
              </div>
              <button
                onClick={onClose}
                aria-label="Cerrar"
                style={{
                  background: T?.paperDeep || '#ede8e0',
                  border: 'none',
                  borderRadius: '50%',
                  width: 32, height: 32,
                  cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 18, color: T?.inkSoft || '#555',
                  flexShrink: 0,
                }}>×</button>
            </div>

            {/* Success toast */}
            {estado === 'ok' && (
              <div style={{
                background: T?.okSoft || '#e8f5ed',
                border: `1px solid ${T?.ok || 'oklch(0.58 0.12 155)'}`,
                borderRadius: 14,
                padding: '14px 16px',
                marginBottom: 12,
                color: T?.ink || '#1a1612',
                fontSize: 14,
                textAlign: 'center',
              }}>
                ¡Gracias! Ya leemos tu feedback 💌
              </div>
            )}

            {/* Error: tabla no existe */}
            {estado === 'err404' && (
              <div style={{
                background: T?.warnSoft || '#fff8e6',
                border: `1px solid ${T?.warn || '#d4a017'}`,
                borderRadius: 14,
                padding: '14px 16px',
                marginBottom: 12,
                color: T?.ink || '#1a1612',
                fontSize: 14,
              }}>
                Estamos preparando el sistema de feedback, intenta en unos minutos.
              </div>
            )}

            {/* Error: otro */}
            {estado === 'err' && (
              <div style={{
                background: T?.dangerSoft || '#fde8e8',
                border: `1px solid ${T?.danger || 'oklch(0.55 0.16 25)'}`,
                borderRadius: 14,
                padding: '14px 16px',
                marginBottom: 12,
                color: T?.ink || '#1a1612',
                fontSize: 14,
              }}>
                Algo falló, intentá de nuevo o avisame por WhatsApp.
                <button
                  onClick={() => setEstado('idle')}
                  style={{
                    display: 'block', marginTop: 8,
                    background: 'none', border: 'none',
                    color: T?.accent || '#b05c2e',
                    fontWeight: 600, fontSize: 13,
                    cursor: 'pointer', padding: 0, fontFamily: T?.sans || 'inherit',
                  }}
                >Reintentar</button>
              </div>
            )}

            {estado !== 'ok' && (
              <>
                {/* Tipo */}
                <div style={{ marginBottom: 14 }}>
                  <div style={{
                    fontSize: 11, letterSpacing: 1.1, textTransform: 'uppercase',
                    color: T?.inkMute || '#888', marginBottom: 8,
                    fontFamily: T?.mono || 'monospace',
                  }}>Tipo</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                    {TIPOS.map(t => (
                      <button
                        key={t.value}
                        ref={t.value === 'bug' ? firstFocusRef : null}
                        onClick={() => setTipo(t.value)}
                        style={{
                          padding: '10px 12px',
                          borderRadius: 12,
                          border: `1.5px solid ${tipo === t.value ? (T?.accent || '#b05c2e') : (T?.hairline || '#ddd')}`,
                          background: tipo === t.value ? (T?.accentSoft || '#fceee6') : (T?.paper || '#faf9f7'),
                          color: tipo === t.value ? (T?.accentInk || '#7a3520') : (T?.ink || '#1a1612'),
                          fontSize: 13,
                          fontWeight: tipo === t.value ? 600 : 400,
                          cursor: 'pointer',
                          textAlign: 'left',
                          fontFamily: T?.sans || 'inherit',
                          transition: 'all .15s',
                        }}
                      >{t.label}</button>
                    ))}
                  </div>
                </div>

                {/* Severidad (solo si tipo=bug) */}
                {tipo === 'bug' && (
                  <div style={{ marginBottom: 14 }}>
                    <div style={{
                      fontSize: 11, letterSpacing: 1.1, textTransform: 'uppercase',
                      color: T?.inkMute || '#888', marginBottom: 8,
                      fontFamily: T?.mono || 'monospace',
                    }}>Severidad</div>
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                      {SEVERIDADES.map(s => (
                        <button
                          key={s.value}
                          onClick={() => setSeveridad(s.value)}
                          style={{
                            padding: '7px 14px',
                            borderRadius: 20,
                            border: `1.5px solid ${severidad === s.value ? (T?.accent || '#b05c2e') : (T?.hairline || '#ddd')}`,
                            background: severidad === s.value ? (T?.accent || '#b05c2e') : (T?.paper || '#faf9f7'),
                            color: severidad === s.value ? '#fff' : (T?.inkSoft || '#555'),
                            fontSize: 12,
                            fontWeight: severidad === s.value ? 600 : 400,
                            cursor: 'pointer',
                            fontFamily: T?.sans || 'inherit',
                            transition: 'all .15s',
                          }}
                        >{s.label}</button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Mensaje */}
                <div style={{ marginBottom: 14 }}>
                  <div style={{
                    fontSize: 11, letterSpacing: 1.1, textTransform: 'uppercase',
                    color: T?.inkMute || '#888', marginBottom: 8,
                    fontFamily: T?.mono || 'monospace',
                  }}>Mensaje</div>
                  <textarea
                    value={mensaje}
                    onChange={(e) => setMensaje(e.target.value.slice(0, MAX_CHARS))}
                    placeholder={currentPlaceholder}
                    rows={4}
                    style={{
                      width: '100%',
                      padding: '12px 14px',
                      borderRadius: 12,
                      border: `1.5px solid ${T?.hairline || '#ddd'}`,
                      background: T?.paperDeep || '#ede8e0',
                      color: T?.ink || '#1a1612',
                      fontSize: 14,
                      lineHeight: 1.5,
                      resize: 'vertical',
                      minHeight: 100,
                      fontFamily: T?.sans || 'inherit',
                      outline: 'none',
                      boxSizing: 'border-box',
                    }}
                    onFocus={(e) => {
                      e.target.style.borderColor = T?.accent || '#b05c2e';
                    }}
                    onBlur={(e) => {
                      e.target.style.borderColor = T?.hairline || '#ddd';
                    }}
                  />
                  <div style={{
                    textAlign: 'right', fontSize: 11, marginTop: 4,
                    color: charsLeft < 100 ? (T?.warn || '#d4a017') : (T?.inkMute || '#888'),
                    fontFamily: T?.mono || 'monospace',
                  }}>{charsLeft} caracteres restantes</div>
                </div>

                {/* Botones */}
                <div style={{ display: 'flex', gap: 10 }}>
                  <button
                    onClick={onClose}
                    style={{
                      flex: '0 0 auto',
                      padding: '12px 18px',
                      borderRadius: 14,
                      border: `1.5px solid ${T?.hairline || '#ddd'}`,
                      background: T?.paper || '#faf9f7',
                      color: T?.inkSoft || '#555',
                      fontSize: 14,
                      fontWeight: 500,
                      cursor: 'pointer',
                      fontFamily: T?.sans || 'inherit',
                    }}
                  >Cancelar</button>
                  <button
                    onClick={handleSubmit}
                    disabled={!canSubmit}
                    style={{
                      flex: 1,
                      padding: '12px 18px',
                      borderRadius: 14,
                      border: 'none',
                      background: canSubmit
                        ? (T?.accent || '#b05c2e')
                        : (T?.hairline || '#ddd'),
                      color: canSubmit ? '#fff' : (T?.inkMute || '#888'),
                      fontSize: 14,
                      fontWeight: 600,
                      cursor: canSubmit ? 'pointer' : 'not-allowed',
                      fontFamily: T?.sans || 'inherit',
                      transition: 'background .15s',
                    }}
                  >
                    {estado === 'sending' ? 'Enviando…' : 'Enviar'}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ── FeedbackFAB ───────────────────────────────────────────────────────────

  function FeedbackFAB({ screen, vendedora }) {
    const T = window.T;
    const [open, setOpen] = React.useState(false);
    const isOrderFlowScreen = screen === 'new' || screen === 'confirm';

    // No renderizar si no hay vendedora logueada
    const vend = vendedora || getVendedoraAuth();
    if (!vend || isOrderFlowScreen) return null;

    return (
      <>
        {/* CSS animation (inyectado una sola vez) */}
        <style>{`
          @keyframes feedbackSlideUp {
            from { transform: translateY(100%); opacity: 0; }
            to   { transform: translateY(0);    opacity: 1; }
          }
          @keyframes feedbackFabPop {
            0%   { transform: scale(0.7); opacity: 0; }
            70%  { transform: scale(1.08); }
            100% { transform: scale(1); opacity: 1; }
          }
          .feedback-fab {
            animation: feedbackFabPop .3s cubic-bezier(.2,.9,.3,1) forwards;
          }
          .feedback-fab:active {
            transform: scale(0.94) !important;
          }
        `}</style>

        {/* FAB */}
        <button
          className="feedback-fab"
          aria-label="Enviar feedback"
          onClick={() => setOpen(true)}
          style={{
            position: 'fixed',
            bottom: 88,          // encima de tab bar (≈80px) con 8px de margen
            right: 16,
            width: 52,
            height: 52,
            borderRadius: '50%',
            border: 'none',
            background: T?.accent || '#b05c2e',
            color: '#fff',
            fontSize: 22,
            cursor: 'pointer',
            boxShadow: '0 4px 18px rgba(0,0,0,0.22)',
            zIndex: 9980,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            transition: 'transform .15s, box-shadow .15s',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.boxShadow = '0 6px 24px rgba(0,0,0,0.30)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.boxShadow = '0 4px 18px rgba(0,0,0,0.22)';
          }}
        >
          💬
        </button>

        {/* Modal (drawer bottom) */}
        {open && (
          <FeedbackModal
            screen={screen}
            vendedora={vend}
            onClose={() => setOpen(false)}
          />
        )}
      </>
    );
  }

  Object.assign(window, { FeedbackVendedora: FeedbackModal, FeedbackFAB });
})();
