// Auth modal — Login / Register / Reset / Profile
function AuthModal({ open, onClose, user, setUser, onNavigate }) {
  const P = window.POP;
  const [mode, setMode] = React.useState('login'); // login | register | reset
  const [form, setForm] = React.useState({ email: '', password: '', name: '', phone: '', accept: false });
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [emailSent, setEmailSent] = React.useState(false);
  const [orders, setOrders] = React.useState([]);

  React.useEffect(() => {
    if (open) {
      setMode(user ? 'profile' : 'login');
      setLoading(false);
      setError('');
      setEmailSent(false);
    }
  }, [open, user]);

  // Cargar últimos 3 pedidos al ver el perfil
  React.useEffect(() => {
    if (user?.id && window.sb) {
      window.sb.from('orders').select('id, status, total, created_at, order_items(id)')
        .eq('user_id', user.id).order('created_at', { ascending: false }).limit(3)
        .then(({ data }) => { if (data) setOrders(data); });
    }
  }, [user?.id]);

  if (!open) return null;

  const setField = (k) => (e) => setForm({ ...form, [k]: e.target?.type === 'checkbox' ? e.target.checked : e.target.value });

  const submit = async (e) => {
    e?.preventDefault?.();
    setError('');

    if (!window.sb) {
      setError('Servicio no disponible. Configura Supabase en config.js.');
      return;
    }

    setLoading(true);
    try {
      if (mode === 'login') {
        const { data, error: err } = await window.sb.auth.signInWithPassword({ email: form.email, password: form.password });
        if (err) throw err;
        const { data: profile } = await window.sb.from('profiles').select('*').eq('id', data.user.id).single();
        setUser({
          id: data.user.id,
          email: data.user.email,
          name: profile?.name || data.user.email.split('@')[0],
          avatar: (profile?.name || data.user.email)[0].toUpperCase(),
          points: profile?.points || 0,
          level: profile?.level || 'MAGIC CELL Basic',
        });

      } else if (mode === 'register') {
        if (!form.accept) { setError('Debes aceptar los términos para continuar.'); setLoading(false); return; }
        const { data, error: err } = await window.sb.auth.signUp({
          email: form.email,
          password: form.password,
          options: { data: { name: form.name, phone: form.phone } },
        });
        if (err) throw err;
        if (data.session) {
          setUser({
            id: data.user.id,
            email: data.user.email,
            name: form.name || data.user.email.split('@')[0],
            avatar: (form.name || data.user.email)[0].toUpperCase(),
            points: 0,
            level: 'MAGIC CELL Basic',
          });
        } else {
          setEmailSent(true);
        }

      } else if (mode === 'reset') {
        const cfg = window.VOLTIO_CONFIG || {};
        const { error: err } = await window.sb.auth.resetPasswordForEmail(form.email, {
          redirectTo: cfg.appUrl || window.location.origin,
        });
        if (err) throw err;
        setEmailSent(true);
      }
    } catch (err) {
      setError(err.message || 'Error inesperado. Inténtalo de nuevo.');
    } finally {
      setLoading(false);
    }
  };

  const logout = async () => {
    if (window.sb) await window.sb.auth.signOut();
    setUser(null);
    setMode('login');
  };

  const fmtDate = (d) => new Date(d).toLocaleDateString('es-MX', { day: 'numeric', month: 'short' });
  const fmtAmt = (n) => Number(n).toLocaleString('es-MX');

  const ErrorBox = ({ msg }) => msg ? (
    <div className="pop-bounce-in" style={{ padding: '10px 14px', background: P.red, color: P.card,
      border: `2px solid ${P.ink}`, borderRadius: 8, fontSize: 12, fontWeight: 600 }}>
      ✗ {msg}
    </div>
  ) : null;

  return (
    <>
      <div onClick={onClose} className="pop-overlay-in" style={{
        position: 'fixed', inset: 0, background: 'rgba(26,20,16,0.65)', zIndex: 200, backdropFilter: 'blur(4px)',
      }}></div>
      {/* Outer div owns the position — inner div owns the animation,
          so scale() in @keyframes never clobbers translate(-50%,-50%) */}
      <div style={{
        position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        width: 'min(440px, calc(100vw - 32px))', maxHeight: 'calc(100vh - 32px)',
        zIndex: 201,
      }}>
      <div className="pop-bounce-in" style={{
        background: P.bg,
        border: `3px solid ${P.ink}`, borderRadius: 20, boxShadow: `8px 8px 0 ${P.ink}`,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        maxHeight: 'calc(100vh - 32px)',
      }}>
        {/* Header */}
        <div style={{
          padding: '18px 22px', background: P.yellow, borderBottom: `3px solid ${P.ink}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'relative', overflow: 'hidden',
        }}>
          <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.4, pointerEvents: 'none' }}></div>
          <div style={{ position: 'relative' }}>
            <div style={{ fontFamily: P.display, fontSize: 24, letterSpacing: -1 }}>
              {user ? '👋 ¡HOLA!' : mode === 'login' ? '⚡ INICIA SESIÓN' : mode === 'register' ? '🎉 CREA TU CUENTA' : '🔑 RECUPERAR'}
            </div>
            <div style={{ fontSize: 11, fontWeight: 600, marginTop: 2, position: 'relative' }}>
              {user ? 'Tu cuenta MAGIC CELL'
                : mode === 'login' ? 'Bienvenido de vuelta'
                : mode === 'register' ? 'Y llévate $50.000 de regalo'
                : 'Te enviaremos un email'}
            </div>
          </div>
          <button onClick={onClose} className="pop-press" style={{
            width: 36, height: 36, borderRadius: 10, background: P.card, border: `2px solid ${P.ink}`,
            boxShadow: `2px 2px 0 ${P.ink}`, fontFamily: P.display, fontSize: 14, position: 'relative', cursor: 'pointer',
          }}>✕</button>
        </div>

        {/* Body */}
        <div style={{ padding: '24px 22px', overflowY: 'auto', flex: 1 }}>

          {/* Profile view */}
          {user && (
            <div className="pop-page-in" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14,
                background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, boxShadow: `3px 3px 0 ${P.ink}` }}>
                <div style={{ width: 56, height: 56, borderRadius: '50%', background: P.pink, border: `2px solid ${P.ink}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: P.display, fontSize: 24, boxShadow: `2px 2px 0 ${P.ink}` }}>{user.avatar}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: P.display, fontSize: 18, letterSpacing: -0.5, lineHeight: 1.1 }}>{user.name}</div>
                  <div style={{ fontSize: 12, color: P.dim, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.email}</div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                    <PopBadge color={P.purple} fg={P.ink}>⭐ {user.level}</PopBadge>
                    <PopBadge color={P.green} fg={P.card}>{user.points} pts</PopBadge>
                  </div>
                </div>
              </div>

              {/* Historial de pedidos */}
              <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: 14, boxShadow: `3px 3px 0 ${P.ink}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                  <div style={{ fontFamily: P.display, fontSize: 12, letterSpacing: 0.5 }}>📦 MIS PEDIDOS</div>
                  <button onClick={() => onNavigate?.('orders')} style={{
                    background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
                    fontFamily: P.display, fontSize: 11, color: P.blue, letterSpacing: 0.5, textDecoration: 'underline',
                  }}>Ver todos →</button>
                </div>
                {orders.length === 0 ? (
                  <div style={{ fontSize: 12, color: P.dim, textAlign: 'center', padding: '10px 0' }}>
                    Aún no tienes pedidos.{' '}
                    <button onClick={() => onNavigate?.('listing')} style={{
                      background: 'transparent', border: 'none', cursor: 'pointer', color: P.ink,
                      fontSize: 12, fontWeight: 700, textDecoration: 'underline', padding: 0,
                    }}>¡Empezar a comprar!</button>
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {orders.map(o => {
                      const statusLabel = { pending: '🕐 Pendiente', paid: '✅ Pagado', shipped: '🚚 En camino', delivered: '🏠 Entregado', cancelled: '✗ Cancelado' }[o.status] || o.status;
                      const statusColor = { paid: P.green, shipped: P.blue, delivered: P.green, cancelled: P.red }[o.status] || P.dim;
                      const itemCount   = o.order_items?.length || 0;
                      return (
                        <div key={o.id} onClick={() => onNavigate?.('orders')} className="pop-press" style={{
                          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                          fontSize: 12, padding: '8px 10px', borderRadius: 10, cursor: 'pointer',
                          background: P.cream, border: `1.5px solid ${P.line2}`,
                        }}>
                          <div>
                            <div>
                              <span style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, color: P.dim }}>#{o.id.slice(0, 8).toUpperCase()}</span>
                              {itemCount > 0 && <span style={{ fontSize: 10, color: P.dim, marginLeft: 6 }}>· {itemCount} item{itemCount !== 1 ? 's' : ''}</span>}
                            </div>
                            <div style={{ fontWeight: 600, color: statusColor, marginTop: 2 }}>{statusLabel}</div>
                          </div>
                          <div style={{ textAlign: 'right' }}>
                            <div style={{ color: P.dim, fontSize: 10 }}>{fmtDate(o.created_at)}</div>
                            <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: -0.5, marginTop: 2 }}>${fmtAmt(o.total)}</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {[['📍', 'Direcciones'], ['💳', 'Métodos pago'], ['🎟', 'Cupones'], ['⚙️', 'Configuración']].map(([e, t]) => (
                  <div key={t} onClick={onClose} className="pop-press" style={{
                    padding: '12px 10px', background: P.card, border: `2px solid ${P.ink}`, borderRadius: 10,
                    boxShadow: `2px 2px 0 ${P.ink}`, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
                  }}>
                    <span style={{ fontSize: 20 }}>{e}</span>
                    <div style={{ fontSize: 12, fontWeight: 700 }}>{t}</div>
                  </div>
                ))}
              </div>

              <div style={{ background: P.purple, border: `2px solid ${P.ink}`, borderRadius: 12,
                padding: '12px 14px', boxShadow: `3px 3px 0 ${P.ink}`, display: 'flex', alignItems: 'center', gap: 10 }}>
                <StarBurst size={48} fill={P.yellow} text={'PRO'} />
                <div style={{ flex: 1, fontSize: 11, fontWeight: 600 }}>¡Hazte MAGIC CELL PRO y ahorra más!</div>
                <PopButton variant="dark" size="sm">VER</PopButton>
              </div>

              <PopButton variant="secondary" size="md" full onClick={logout}>Cerrar sesión</PopButton>
            </div>
          )}

          {/* Email confirmación enviado */}
          {!user && emailSent && (
            <div className="pop-page-in" style={{ display: 'flex', flexDirection: 'column', gap: 16, textAlign: 'center' }}>
              <div style={{ fontSize: 64 }}>📧</div>
              <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -1 }}>
                {mode === 'register' ? '¡Revisa tu email!' : 'Enlace enviado'}
              </div>
              <div style={{ fontSize: 13, color: P.ink2, lineHeight: 1.6 }}>
                {mode === 'register'
                  ? `Enviamos un enlace de confirmación a ${form.email}. Actívalo y luego inicia sesión.`
                  : `Enviamos instrucciones a ${form.email} para restablecer tu contraseña.`}
              </div>
              <PopButton variant="dark" size="md" full onClick={() => { setEmailSent(false); setMode('login'); }}>
                Ir al login →
              </PopButton>
            </div>
          )}

          {/* Login */}
          {!user && !emailSent && mode === 'login' && (
            <form onSubmit={submit} className="pop-page-in" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <PopButton variant="secondary" size="md" icon={<span>🔵</span>}>Google</PopButton>
                <PopButton variant="secondary" size="md" icon={<span>🍎</span>}>Apple</PopButton>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11, color: P.dim, letterSpacing: 1,
                textTransform: 'uppercase', margin: '4px 0' }}>
                <div style={{ flex: 1, height: 2, background: P.line2 }}></div>
                <span>o con email</span>
                <div style={{ flex: 1, height: 2, background: P.line2 }}></div>
              </div>
              <AuthField label="EMAIL" type="email" value={form.email} onChange={setField('email')} placeholder="tu@correo.com" />
              <AuthField label="CONTRASEÑA" type="password" value={form.password} onChange={setField('password')} placeholder="••••••••" />
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12 }}>
                <label style={{ display: 'flex', gap: 6, alignItems: 'center', cursor: 'pointer' }}>
                  <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: P.ink }} />
                  Recordarme
                </label>
                <button type="button" onClick={() => setMode('reset')} style={{
                  background: 'transparent', border: 'none', color: P.blue, fontSize: 12, fontWeight: 600,
                  cursor: 'pointer', padding: 0, textDecoration: 'underline',
                }}>¿Olvidaste tu contraseña?</button>
              </div>
              <ErrorBox msg={error} />
              <PopButton variant="dark" size="lg" full onClick={submit}>
                {loading ? '⚡ Entrando...' : 'INICIAR SESIÓN →'}
              </PopButton>
              <div style={{ fontSize: 13, textAlign: 'center', color: P.ink2, marginTop: 4 }}>
                ¿Aún no tienes cuenta?{' '}
                <button type="button" onClick={() => setMode('register')} style={{
                  background: 'transparent', border: 'none', color: P.ink, fontWeight: 700,
                  cursor: 'pointer', padding: 0, textDecoration: 'underline', fontSize: 13,
                }}>Regístrate gratis</button>
              </div>
            </form>
          )}

          {/* Register */}
          {!user && !emailSent && mode === 'register' && (
            <form onSubmit={submit} className="pop-page-in" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ background: P.green, color: P.card, border: `2px solid ${P.ink}`, borderRadius: 12,
                padding: '10px 14px', boxShadow: `3px 3px 0 ${P.ink}`,
                display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, fontWeight: 600 }}>
                <span style={{ fontSize: 20 }}>🎁</span>
                <span>¡Bienvenido! Te damos <strong style={{ color: P.yellow }}>$50.000</strong> al registrarte.</span>
              </div>
              <AuthField label="NOMBRE COMPLETO" value={form.name} onChange={setField('name')} placeholder="Ana Martínez" />
              <AuthField label="EMAIL" type="email" value={form.email} onChange={setField('email')} placeholder="tu@correo.com" />
              <AuthField label="TELÉFONO" value={form.phone} onChange={setField('phone')} placeholder="+52 55 ..." />
              <AuthField label="CONTRASEÑA (mínimo 6 caracteres)" type="password" value={form.password} onChange={setField('password')} placeholder="••••••••" />
              <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontSize: 12, lineHeight: 1.5 }}>
                <input type="checkbox" checked={form.accept} onChange={setField('accept')}
                  style={{ width: 18, height: 18, accentColor: P.ink, flexShrink: 0, marginTop: 1 }} />
                <span>Acepto los <span style={{ textDecoration: 'underline', fontWeight: 700 }}>términos</span> y la <span style={{ textDecoration: 'underline', fontWeight: 700 }}>política de privacidad</span>.</span>
              </label>
              <ErrorBox msg={error} />
              <PopButton variant="dark" size="lg" full onClick={submit}>
                {loading ? '⚡ Creando cuenta...' : 'CREAR CUENTA →'}
              </PopButton>
              <div style={{ fontSize: 13, textAlign: 'center', color: P.ink2 }}>
                ¿Ya tienes cuenta?{' '}
                <button type="button" onClick={() => setMode('login')} style={{
                  background: 'transparent', border: 'none', color: P.ink, fontWeight: 700,
                  cursor: 'pointer', padding: 0, textDecoration: 'underline', fontSize: 13,
                }}>Inicia sesión</button>
              </div>
            </form>
          )}

          {/* Reset */}
          {!user && !emailSent && mode === 'reset' && (
            <form onSubmit={submit} className="pop-page-in" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ fontSize: 13, color: P.ink2, lineHeight: 1.5 }}>
                Ingresa tu email y te enviaremos un enlace para restablecer tu contraseña.
              </div>
              <AuthField label="EMAIL" type="email" value={form.email} onChange={setField('email')} placeholder="tu@correo.com" />
              <ErrorBox msg={error} />
              <PopButton variant="dark" size="lg" full onClick={submit}>
                {loading ? '⚡ Enviando...' : 'ENVIAR ENLACE →'}
              </PopButton>
              <div style={{ fontSize: 13, textAlign: 'center' }}>
                <button type="button" onClick={() => setMode('login')} style={{
                  background: 'transparent', border: 'none', color: P.ink, fontWeight: 700,
                  cursor: 'pointer', padding: 0, textDecoration: 'underline', fontSize: 13,
                }}>← Volver al login</button>
              </div>
            </form>
          )}
        </div>
      </div>
      </div>
    </>
  );
}

function AuthField({ label, type = 'text', value, onChange, placeholder }) {
  const P = window.POP;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{ fontFamily: P.display, fontSize: 11, letterSpacing: 1 }}>{label}</label>
      <input type={type} value={value} onChange={onChange} placeholder={placeholder}
        style={{
          padding: '12px 14px', border: `2px solid ${P.ink}`, borderRadius: 10,
          fontFamily: P.font, fontSize: 14, outline: 'none', background: P.card,
          boxShadow: `inset 2px 2px 0 ${P.line2}`, width: '100%',
        }} />
    </div>
  );
}

window.AuthModal = AuthModal;
