// ============================================================
// AUTH MODAL — single-column gradient card with acid-green palette.
// Supports three modes: login | signup | apply (Elite application).
// No Google sign-in. Mouse-tilt 3D + traveling light beams + corner glow.
// ============================================================

const AuthModal = ({ mode = 'login', onClose, onSuccess, onSwitch }) => {
  const isLogin   = mode === 'login';
  const isSignup  = mode === 'signup';
  const isApply   = mode === 'apply';

  const [data, setData] = React.useState({
    name: '', email: '', password: '',
    phone: '', experience: '',
  });
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [successMode, setSuccessMode] = React.useState(null);
  const [showPassword, setShowPassword] = React.useState(false);
  const [focused, setFocused] = React.useState(null);
  const [remember, setRemember] = React.useState(false);
  // Marketing & terms consent
  const [marketing, setMarketing]     = React.useState(false); // optional in both flows
  const [terms, setTerms]             = React.useState(false); // required in signup

  // 3D mouse tilt
  const cardRef = React.useRef(null);
  const [rot, setRot] = React.useState({ x: 0, y: 0 });
  const onMouseMove = (e) => {
    const el = cardRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const x = e.clientX - r.left - r.width / 2;
    const y = e.clientY - r.top - r.height / 2;
    setRot({ x: -(y / r.height) * 10, y: (x / r.width) * 10 });
  };
  const onMouseLeave = () => setRot({ x: 0, y: 0 });

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  React.useEffect(() => {
    setError('');
    setShowPassword(false);
    setSuccessMode(null);
    setSubmitted(false);
    // Reset consent state when modal switches mode
    setMarketing(false);
    setTerms(false);
  }, [mode]);

  const noBackend = !window.sb;

  // After login/signup succeeds, hand the marketing preference to Brevo.
  // Safe to call without secrets configured — the edge function falls
  // back to a DB-only update.
  const syncMarketing = async (src) => {
    if (!window.sb) return;
    if (!marketing) return; // nothing to do
    try {
      await window.sb.functions.invoke('brevo-sync', {
        body: {
          action: 'subscribe',
          source: src, // 'signup' | 'login'
          tags: [
            'Free Member',
            'Marketing Accepted',
            'Not Elite',
            src === 'signup' ? 'Website Signup' : 'Website Login Opt-in',
          ],
        },
      });
    } catch (e) {
      // Don't block the user flow if Brevo is down — log and move on.
      console.warn('[brevo-sync] failed:', e);
    }
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    if (noBackend) { setError('Backend not configured. Edit config.js with your Supabase credentials.'); return; }
    if (!data.email || !data.password) { setError('Email și parolă sunt necesare.'); return; }
    setBusy(true);
    const { error } = await window.sb.auth.signInWithPassword({ email: data.email, password: data.password });
    if (error) { setBusy(false); setError(error.message); return; }
    // After successful login, fire-and-forget the marketing sync if the user opted in.
    await syncMarketing('login');
    setBusy(false);
    setSuccessMode('login_success');
  };

  const handleSignup = async (e) => {
    e.preventDefault();
    setError('');
    if (noBackend) { setError('Backend not configured. Edit config.js with your Supabase credentials.'); return; }
    if (!terms) { setError('Trebuie să accepți Termenii și Condițiile.'); return; }
    if (!data.email || !data.password) { setError('Email și parolă sunt necesare.'); return; }
    if (data.password.length < 6) { setError('Parola trebuie să aibă cel puțin 6 caractere.'); return; }
    setBusy(true);
    const nowIso = new Date().toISOString();
    const { error } = await window.sb.auth.signUp({
      email: data.email,
      password: data.password,
      options: {
        data: {
          name: data.name || data.email.split('@')[0],
          // Picked up by the handle_new_user trigger to seed profiles.*
          marketing_consent:    !!marketing,
          marketing_consent_at: marketing ? nowIso : null,
          terms_accepted_at:    nowIso,
        },
      },
    });
    if (error) { setBusy(false); setError(error.message); return; }
    // Subscribe to Brevo only if the user opted in.
    await syncMarketing('signup');
    setBusy(false);
    setSuccessMode('signup_success');
  };

  const continueAfterSuccess = () => {
    const m = successMode === 'signup_success' ? 'signup' : 'login';
    setSuccessMode(null);
    onSuccess?.(m);
  };

  const canSubmitApply = data.name.trim() && data.phone.trim();

  const handleApply = async (e) => {
    e.preventDefault();
    setError('');
    if (!canSubmitApply) { setError('Completează toate câmpurile.'); return; }
    if (noBackend) { setError('Backend not configured. Edit config.js with your Supabase credentials.'); return; }
    setBusy(true);
    const { data: sessionData } = await window.sb.auth.getSession();
    const uid = sessionData?.session?.user?.id ?? null;
    const { error } = await window.sb.from('elite_applications').insert({
      user_id: uid,
      name: data.name.trim(),
      phone: data.phone.trim(),
      trading_experience: '—',
    });
    setBusy(false);
    if (error) { setError(error.message); return; }
    setSubmitted(true);
  };

  const headers = {
    login:  { eyebrow: 'WELCOME BACK',       title: 'Bine ai revenit',  sub: 'Sign in to continue to Tyrone Trading' },
    signup: { eyebrow: 'CREATE ACCOUNT',     title: 'Creează cont free', sub: 'Acces la materialele gratuite ale comunității' },
    apply:  { eyebrow: 'ELITE · APPLICATION', title: 'Aplică pentru Elite', sub: 'Completează cele 2 câmpuri — te contactăm în maxim 24h' },
  };
  const h = headers[mode] || headers.login;

  const cardStyle = {
    transform: `perspective(1500px) rotateX(${rot.x}deg) rotateY(${rot.y}deg)`,
    transition: 'transform 0.3s cubic-bezier(0.22, 1, 0.36, 1)',
  };

  return (
    <div className="amx-overlay" onClick={onClose}>
      {/* atmosphere */}
      <div className="amx-atmos">
        <div className="amx-gradient" />
        <div className="amx-noise" />
        <div className="amx-blob amx-blob-top" />
        <div className="amx-blob amx-blob-bot" />
        <div className="amx-spot amx-spot-tl" />
        <div className="amx-spot amx-spot-br" />
      </div>

      <button className="amx-close" onClick={onClose} aria-label="Close"><Icon name="x" size={18}/></button>

      <div
        ref={cardRef}
        className="amx-card-wrap"
        style={cardStyle}
        onMouseMove={onMouseMove}
        onMouseLeave={onMouseLeave}
        onClick={(e) => e.stopPropagation()}>

        {/* Traveling light beams on 4 edges */}
        <div className="amx-beams">
          <span className="amx-beam amx-beam-top" />
          <span className="amx-beam amx-beam-right" />
          <span className="amx-beam amx-beam-bottom" />
          <span className="amx-beam amx-beam-left" />
          <span className="amx-dot amx-dot-tl" />
          <span className="amx-dot amx-dot-tr" />
          <span className="amx-dot amx-dot-br" />
          <span className="amx-dot amx-dot-bl" />
        </div>

        <div className="amx-card">
          <div className="amx-grid-pattern" />

          {/* Header (no brand logo — keeps the modal compact) */}
          <div className="amx-head">
            <div className="amx-eyebrow"><span className="dot" />{h.eyebrow}</div>
            <h1 className="amx-title">{h.title}</h1>
            <p className="amx-sub">{h.sub}</p>
          </div>

          {/* Success states */}
          {successMode && (
            <div className="amx-success">
              <div className="amx-success-icon"><Icon name="check" size={28} stroke={2.5}/></div>
              <h3>{successMode === 'signup_success' ? 'Cont creat' : 'Conectat cu succes'}</h3>
              <p>
                {successMode === 'signup_success'
                  ? 'Contul tău a fost creat cu succes. Acces deblocat la materialele free.'
                  : 'Te-ai conectat cu succes.'}
              </p>
              <button type="button" className="amx-btn-primary" onClick={continueAfterSuccess}>
                Continuă <span className="amx-arrow">→</span>
              </button>
            </div>
          )}

          {/* LOGIN */}
          {!successMode && isLogin && (
            <form onSubmit={handleLogin} className="amx-form">
              <div className={`amx-field ${focused === 'email' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="mail" size={16}/></span>
                <input
                  type="email"
                  required
                  placeholder="Email address"
                  value={data.email}
                  onChange={e => setData({...data, email: e.target.value})}
                  onFocus={() => setFocused('email')}
                  onBlur={() => setFocused(null)}
                  autoFocus
                />
              </div>

              <div className={`amx-field ${focused === 'password' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="lock" size={16}/></span>
                <input
                  type={showPassword ? 'text' : 'password'}
                  required
                  placeholder="Password"
                  value={data.password}
                  onChange={e => setData({...data, password: e.target.value})}
                  onFocus={() => setFocused('password')}
                  onBlur={() => setFocused(null)}
                />
                <button type="button" className="amx-eye" onClick={() => setShowPassword(!showPassword)} aria-label="Toggle password">
                  <Icon name="eye" size={16}/>
                </button>
              </div>

              <div className="amx-row">
                <label className="amx-check">
                  <input type="checkbox" checked={remember} onChange={() => setRemember(!remember)} />
                  <span className="amx-check-box">
                    {remember && (
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                    )}
                  </span>
                  <span>Remember me</span>
                </label>
                <a href="#" className="amx-link" onClick={(e) => e.preventDefault()}>Forgot password?</a>
              </div>

              {/* Optional marketing opt-in (login flow) */}
              <label className="amx-check amx-check-block">
                <input type="checkbox" checked={marketing} onChange={() => setMarketing(!marketing)} />
                <span className="amx-check-box amx-check-box-sm">
                  {marketing && (
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  )}
                </span>
                <span className="amx-check-text">
                  Primește alerte când apar reduceri mari la prop firms + materiale gratuite pentru trading.
                </span>
              </label>

              {error && <div className="amx-error">{error}</div>}

              <button type="submit" disabled={busy} className="amx-btn-primary">
                {busy ? <span className="amx-spinner" /> : <>Sign In <span className="amx-arrow">→</span></>}
              </button>

              <p className="amx-bottom">
                Nu ai cont?{' '}
                <a href="#" onClick={(e) => { e.preventDefault(); onSwitch('signup'); }}>Creează cont gratuit</a>
              </p>
              <p className="amx-bottom amx-bottom-sm">
                Vrei Elite?{' '}
                <a href="#" onClick={(e) => { e.preventDefault(); onSwitch('apply'); }}>Aplică acum</a>
              </p>
            </form>
          )}

          {/* SIGNUP */}
          {!successMode && isSignup && (
            <form onSubmit={handleSignup} className="amx-form">
              <div className={`amx-field ${focused === 'name' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="user" size={16}/></span>
                <input
                  type="text"
                  placeholder="Numele tău"
                  value={data.name}
                  onChange={e => setData({...data, name: e.target.value})}
                  onFocus={() => setFocused('name')}
                  onBlur={() => setFocused(null)}
                  autoFocus
                />
              </div>

              <div className={`amx-field ${focused === 'email' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="mail" size={16}/></span>
                <input
                  type="email"
                  required
                  placeholder="Email address"
                  value={data.email}
                  onChange={e => setData({...data, email: e.target.value})}
                  onFocus={() => setFocused('email')}
                  onBlur={() => setFocused(null)}
                />
              </div>

              <div className={`amx-field ${focused === 'password' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="lock" size={16}/></span>
                <input
                  type={showPassword ? 'text' : 'password'}
                  required
                  placeholder="Password (min. 6 caractere)"
                  value={data.password}
                  onChange={e => setData({...data, password: e.target.value})}
                  onFocus={() => setFocused('password')}
                  onBlur={() => setFocused(null)}
                />
                <button type="button" className="amx-eye" onClick={() => setShowPassword(!showPassword)} aria-label="Toggle password">
                  <Icon name="eye" size={16}/>
                </button>
              </div>

              {/* Consent — marketing (optional) + terms (required) */}
              <label className="amx-check amx-check-block">
                <input type="checkbox" checked={marketing} onChange={() => setMarketing(!marketing)} />
                <span className="amx-check-box amx-check-box-sm">
                  {marketing && (
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  )}
                </span>
                <span className="amx-check-text">
                  Vreau să primesc emailuri cu materiale gratuite, promoții Apex/Tradeify/FundedNext, update-uri despre prop firms și oferte pentru Elite Plan.
                </span>
              </label>

              <label className="amx-check amx-check-block">
                <input type="checkbox" checked={terms} onChange={() => setTerms(!terms)} />
                <span className="amx-check-box amx-check-box-sm">
                  {terms && (
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  )}
                </span>
                <span className="amx-check-text">
                  Sunt de acord cu{' '}
                  <a href="#terms" className="amx-inline-link" onClick={(e)=>e.stopPropagation()} target="_blank" rel="noopener">Termenii și Condițiile</a>
                  {' '}și{' '}
                  <a href="#privacy" className="amx-inline-link" onClick={(e)=>e.stopPropagation()} target="_blank" rel="noopener">Politica de Confidențialitate</a>.
                </span>
              </label>

              {error && <div className="amx-error">{error}</div>}

              <button
                type="submit"
                disabled={busy || !terms}
                className={`amx-btn-primary ${!terms ? 'is-disabled' : ''}`}>
                {busy ? <span className="amx-spinner" /> : <>Creează cont <span className="amx-arrow">→</span></>}
              </button>

              <p className="amx-bottom">
                Ai deja cont?{' '}
                <a href="#" onClick={(e) => { e.preventDefault(); onSwitch('login'); }}>Login</a>
              </p>
            </form>
          )}

          {/* ELITE APPLY */}
          {!successMode && isApply && !submitted && (
            <form onSubmit={handleApply} className="amx-form">
              <div className={`amx-field ${focused === 'name' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="user" size={16}/></span>
                <input
                  type="text"
                  required
                  placeholder="Nume complet"
                  value={data.name}
                  onChange={e => setData({...data, name: e.target.value})}
                  onFocus={() => setFocused('name')}
                  onBlur={() => setFocused(null)}
                  autoFocus
                />
              </div>

              <div className={`amx-field ${focused === 'phone' ? 'is-focused' : ''}`}>
                <span className="amx-field-icon"><Icon name="phone" size={16}/></span>
                <input
                  type="tel"
                  required
                  placeholder="07xx xxx xxx"
                  value={data.phone}
                  onChange={e => setData({...data, phone: e.target.value})}
                  onFocus={() => setFocused('phone')}
                  onBlur={() => setFocused(null)}
                />
              </div>

              {error && <div className="amx-error">{error}</div>}

              <button
                type="submit"
                disabled={!canSubmitApply || busy}
                className="amx-btn-primary"
                style={{ opacity: (canSubmitApply && !busy) ? 1 : 0.5 }}>
                {busy ? <span className="amx-spinner" /> : <>Trimite aplicație <span className="amx-arrow">→</span></>}
              </button>

              <p className="amx-bottom">
                Ai deja cont?{' '}
                <a href="#" onClick={(e) => { e.preventDefault(); onSwitch('login'); }}>Login</a>
              </p>
            </form>
          )}

          {/* APPLY SUCCESS */}
          {isApply && submitted && (
            <div className="amx-success">
              <div className="amx-success-icon"><Icon name="check" size={28} stroke={2.5}/></div>
              <h3>Aplicare trimisă</h3>
              <p>Aplicația ta a fost trimisă cu succes. Te vom contacta în maxim 24 de ore.</p>
              <button type="button" className="amx-btn-primary" onClick={onClose}>
                Continue <span className="amx-arrow">→</span>
              </button>
            </div>
          )}
        </div>
      </div>

      <style>{`
        /* ============================================================
           AUTH MODAL — gradient card with acid-green palette
           ============================================================ */
        .amx-overlay {
          position: fixed; inset: 0; z-index: 100;
          display: grid; place-items: center;
          padding: 24px;
          overflow: hidden;
          background: #000;
          animation: amx-fade-in 0.3s ease;
        }
        @keyframes amx-fade-in { from { opacity: 0; } to { opacity: 1; } }

        .amx-atmos {
          position: absolute; inset: 0;
          pointer-events: none;
          overflow: hidden;
        }
        .amx-gradient {
          position: absolute; inset: 0;
          background: linear-gradient(180deg,
            rgba(183, 255, 26, 0.04) 0%,
            rgba(143, 224, 0, 0.02) 30%,
            #000 100%);
        }
        .amx-noise {
          position: absolute; inset: 0;
          opacity: 0.04;
          mix-blend-mode: soft-light;
          background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
          background-size: 200px 200px;
        }
        .amx-blob {
          position: absolute; left: 50%;
          transform: translateX(-50%);
          width: 120vh; height: 60vh;
          filter: blur(100px);
          opacity: 0.18;
        }
        .amx-blob-top {
          top: 0;
          background: radial-gradient(ellipse at top, rgba(183, 255, 26, 0.18) 0%, transparent 70%);
          border-radius: 0 0 50% 50%;
          animation: amx-blob-pulse 10s ease-in-out infinite;
        }
        .amx-blob-bot {
          bottom: 0;
          width: 90vh; height: 90vh;
          background: radial-gradient(ellipse at bottom, rgba(79, 231, 213, 0.10) 0%, transparent 70%);
          border-radius: 50% 50% 0 0;
          animation: amx-blob-pulse 8s ease-in-out infinite 1s;
        }
        @keyframes amx-blob-pulse {
          0%, 100% { opacity: 0.12; transform: translateX(-50%) scale(1); }
          50%      { opacity: 0.20; transform: translateX(-50%) scale(1.04); }
        }
        .amx-spot {
          position: absolute; width: 400px; height: 400px;
          background: rgba(255, 255, 255, 0.02);
          border-radius: 50%;
          filter: blur(100px);
          opacity: 0.2;
          animation: amx-spot-pulse 6s ease-in-out infinite;
        }
        .amx-spot-tl { left: 20%; top: 20%; }
        .amx-spot-br { right: 20%; bottom: 20%; animation-delay: 1.5s; }
        @keyframes amx-spot-pulse {
          0%, 100% { opacity: 0.12; }
          50%      { opacity: 0.22; }
        }

        .amx-close {
          position: fixed; top: 22px; right: 22px;
          z-index: 110;
          width: 40px; height: 40px;
          border-radius: 50%;
          display: grid; place-items: center;
          background: rgba(255,255,255,0.06);
          border: 1px solid rgba(255,255,255,0.14);
          color: #fff;
          cursor: pointer;
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
          transition: background 0.2s, border-color 0.2s, transform 0.2s;
        }
        .amx-close:hover { background: rgba(255,255,255,0.14); border-color: rgba(255,255,255,0.30); transform: scale(1.05); }

        .amx-card-wrap {
          position: relative; z-index: 5;
          width: 100%; max-width: 400px;
          animation: amx-rise 0.5s cubic-bezier(0.22, 1, 0.36, 1);
          transform-style: preserve-3d;
        }
        @keyframes amx-rise {
          from { opacity: 0; transform: translateY(20px); }
          to   { opacity: 1; transform: translateY(0); }
        }

        /* Traveling light beams */
        .amx-beams {
          position: absolute; inset: -2px;
          border-radius: 22px;
          overflow: hidden;
          pointer-events: none;
        }
        .amx-beam {
          position: absolute;
          opacity: 0.7;
          filter: blur(2px);
        }
        .amx-beam-top {
          top: 0; left: -50%;
          height: 3px; width: 50%;
          background: linear-gradient(90deg, transparent, var(--acid, #B7FF1A), transparent);
          animation: amx-beam-h 3.5s ease-in-out infinite;
        }
        .amx-beam-right {
          top: -50%; right: 0;
          width: 3px; height: 50%;
          background: linear-gradient(180deg, transparent, var(--acid, #B7FF1A), transparent);
          animation: amx-beam-v 3.5s ease-in-out infinite 0.7s;
        }
        .amx-beam-bottom {
          bottom: 0; right: -50%;
          height: 3px; width: 50%;
          background: linear-gradient(90deg, transparent, var(--acid, #B7FF1A), transparent);
          animation: amx-beam-h-rev 3.5s ease-in-out infinite 1.4s;
        }
        .amx-beam-left {
          bottom: -50%; left: 0;
          width: 3px; height: 50%;
          background: linear-gradient(180deg, transparent, var(--acid, #B7FF1A), transparent);
          animation: amx-beam-v-rev 3.5s ease-in-out infinite 2.1s;
        }
        @keyframes amx-beam-h {
          0% { left: -50%; opacity: 0.3; }
          50% { opacity: 0.9; }
          100% { left: 100%; opacity: 0.3; }
        }
        @keyframes amx-beam-h-rev {
          0% { right: -50%; opacity: 0.3; }
          50% { opacity: 0.9; }
          100% { right: 100%; opacity: 0.3; }
        }
        @keyframes amx-beam-v {
          0% { top: -50%; opacity: 0.3; }
          50% { opacity: 0.9; }
          100% { top: 100%; opacity: 0.3; }
        }
        @keyframes amx-beam-v-rev {
          0% { bottom: -50%; opacity: 0.3; }
          50% { opacity: 0.9; }
          100% { bottom: 100%; opacity: 0.3; }
        }
        .amx-dot {
          position: absolute;
          width: 6px; height: 6px;
          border-radius: 50%;
          background: var(--acid, #B7FF1A);
          box-shadow: 0 0 8px var(--acid, #B7FF1A);
          opacity: 0.6;
          animation: amx-dot-pulse 2.2s ease-in-out infinite;
        }
        .amx-dot-tl { top: -3px; left: -3px; }
        .amx-dot-tr { top: -3px; right: -3px; animation-delay: 0.5s; }
        .amx-dot-br { bottom: -3px; right: -3px; animation-delay: 1s; }
        .amx-dot-bl { bottom: -3px; left: -3px; animation-delay: 1.5s; }
        @keyframes amx-dot-pulse {
          0%, 100% { opacity: 0.3; transform: scale(1); }
          50%      { opacity: 1; transform: scale(1.3); }
        }

        /* The card itself */
        .amx-card {
          position: relative;
          padding: 28px 26px 26px;
          border-radius: 22px;
          background: rgba(0, 0, 0, 0.55);
          backdrop-filter: blur(28px) saturate(140%);
          -webkit-backdrop-filter: blur(28px) saturate(140%);
          border: 1px solid rgba(255, 255, 255, 0.06);
          box-shadow:
            0 40px 100px rgba(0, 0, 0, 0.65),
            inset 0 1px 0 rgba(255, 255, 255, 0.06),
            0 0 30px rgba(183, 255, 26, 0.08);
          overflow: hidden;
          isolation: isolate;
        }
        .amx-grid-pattern {
          position: absolute; inset: 0;
          pointer-events: none;
          opacity: 0.03;
          background-image:
            linear-gradient(135deg, rgba(255,255,255,1) 0.5px, transparent 0.5px),
            linear-gradient(45deg, rgba(255,255,255,1) 0.5px, transparent 0.5px);
          background-size: 30px 30px;
        }

        /* Header */
        .amx-head {
          position: relative; z-index: 1;
          text-align: center;
          margin-bottom: 22px;
        }
        .amx-logo {
          position: relative;
          margin: 0 auto 14px;
          width: 44px; height: 44px;
          border-radius: 50%;
          border: 1px solid rgba(255,255,255,0.12);
          background: linear-gradient(180deg, rgba(255,255,255,0.06), rgba(0,0,0,0.4));
          display: grid; place-items: center;
          overflow: hidden;
        }
        .amx-logo-shine {
          position: absolute; inset: 0;
          background: radial-gradient(circle at 30% 20%, rgba(255,255,255,0.20), transparent 60%);
        }
        .amx-logo > * { position: relative; z-index: 1; }
        .amx-eyebrow {
          display: inline-flex; align-items: center; gap: 8px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          color: rgba(255, 255, 255, 0.55);
        }
        .amx-eyebrow .dot {
          width: 6px; height: 6px; border-radius: 50%;
          background: var(--acid, #B7FF1A);
          box-shadow: 0 0 8px var(--acid, #B7FF1A);
        }
        .amx-title {
          margin: 10px 0 6px;
          font-size: 22px;
          font-weight: 700;
          letter-spacing: -0.02em;
          background: linear-gradient(180deg, #ffffff 0%, rgba(255,255,255,0.75) 100%);
          -webkit-background-clip: text; background-clip: text;
          color: transparent;
        }
        .amx-sub {
          font-size: 12.5px;
          color: rgba(255, 255, 255, 0.5);
          line-height: 1.45;
        }

        /* Form */
        .amx-form { position: relative; z-index: 1; display: flex; flex-direction: column; gap: 12px; }
        .amx-field {
          position: relative;
          display: flex; align-items: center;
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid transparent;
          border-radius: 10px;
          transition: border-color 0.25s, background 0.25s, box-shadow 0.25s;
          overflow: hidden;
        }
        .amx-field.is-focused {
          background: rgba(255, 255, 255, 0.08);
          border-color: rgba(183, 255, 26, 0.45);
          box-shadow: 0 0 0 3px rgba(183, 255, 26, 0.12);
        }
        .amx-field-icon {
          position: absolute; left: 12px;
          display: grid; place-items: center;
          color: rgba(255, 255, 255, 0.40);
          transition: color 0.25s;
          pointer-events: none;
        }
        .amx-field.is-focused .amx-field-icon { color: var(--acid, #B7FF1A); }
        .amx-field-icon-top { top: 12px; }
        .amx-field input,
        .amx-field textarea {
          flex: 1;
          background: transparent;
          border: none;
          outline: none;
          color: #fff;
          padding: 11px 14px 11px 40px;
          font: inherit;
          font-size: 14px;
          line-height: 1.4;
          font-family: inherit;
        }
        .amx-field input::placeholder,
        .amx-field textarea::placeholder { color: rgba(255, 255, 255, 0.30); }
        .amx-field textarea { resize: vertical; min-height: 80px; padding-top: 11px; }
        .amx-eye {
          position: absolute; right: 10px;
          background: transparent; border: none;
          color: rgba(255, 255, 255, 0.40);
          cursor: pointer;
          padding: 6px;
          display: grid; place-items: center;
          transition: color 0.2s;
        }
        .amx-eye:hover { color: #fff; }

        .amx-row {
          display: flex; align-items: center; justify-content: space-between;
          padding: 2px 2px 4px;
          font-size: 12px;
        }
        .amx-check {
          display: inline-flex; align-items: center; gap: 8px;
          cursor: pointer;
          color: rgba(255, 255, 255, 0.55);
          user-select: none;
          transition: color 0.2s;
        }
        .amx-check:hover { color: rgba(255,255,255,0.8); }
        .amx-check input { display: none; }
        .amx-check-box {
          width: 16px; height: 16px;
          border-radius: 4px;
          border: 1px solid rgba(255, 255, 255, 0.22);
          background: rgba(255, 255, 255, 0.05);
          display: grid; place-items: center;
          color: #050505;
          transition: background 0.2s, border-color 0.2s;
        }
        .amx-check input:checked + .amx-check-box {
          background: var(--acid, #B7FF1A);
          border-color: var(--acid, #B7FF1A);
        }
        /* Multi-line consent checkbox — full-width, text wraps next to the box */
        .amx-check-block {
          display: grid;
          grid-template-columns: 18px 1fr;
          align-items: flex-start;
          gap: 10px;
          padding: 2px 2px;
          font-size: 12px;
          line-height: 1.45;
          color: rgba(255, 255, 255, 0.62);
        }
        .amx-check-block:hover { color: rgba(255, 255, 255, 0.85); }
        .amx-check-box-sm { width: 18px; height: 18px; margin-top: 1px; }
        .amx-check-text { display: block; }
        .amx-inline-link {
          color: var(--acid, #B7FF1A);
          text-decoration: none;
          border-bottom: 1px dashed rgba(183,255,26,0.4);
          padding-bottom: 1px;
          transition: color 0.2s, border-color 0.2s;
        }
        .amx-inline-link:hover { color: #DCFF7A; border-color: var(--acid, #B7FF1A); }

        /* Disabled / not-yet-consented primary CTA */
        .amx-btn-primary.is-disabled,
        .amx-btn-primary:disabled {
          background: linear-gradient(180deg, rgba(120,120,120,0.55) 0%, rgba(70,70,70,0.55) 100%);
          color: rgba(255,255,255,0.45);
          box-shadow: inset 0 1px 0 rgba(255,255,255,0.08), 0 4px 14px rgba(0,0,0,0.45);
          cursor: not-allowed;
          border-color: rgba(255,255,255,0.06);
        }
        .amx-btn-primary.is-disabled:hover { transform: none; }
        .amx-link {
          color: rgba(255, 255, 255, 0.55);
          text-decoration: none;
          transition: color 0.2s;
        }
        .amx-link:hover { color: var(--acid, #B7FF1A); }

        .amx-error {
          padding: 10px 12px;
          background: rgba(255, 90, 90, 0.08);
          border: 1px solid rgba(255, 90, 90, 0.3);
          border-radius: 10px;
          color: #ff9090;
          font-size: 12.5px;
          line-height: 1.4;
        }

        .amx-btn-primary {
          position: relative;
          margin-top: 6px;
          height: 42px;
          border-radius: 10px;
          background: linear-gradient(180deg, #C8FF35 0%, #A8F00B 100%);
          color: #050505;
          font-weight: 700;
          font-size: 13.5px;
          letter-spacing: 0;
          border: 1px solid rgba(0,0,0,0.18);
          cursor: pointer;
          display: inline-flex; align-items: center; justify-content: center;
          gap: 8px;
          overflow: hidden;
          transition: transform 0.2s, box-shadow 0.3s;
          box-shadow:
            inset 0 1px 0 rgba(255, 255, 255, 0.45),
            0 8px 24px rgba(183, 255, 26, 0.35),
            0 0 30px rgba(183, 255, 26, 0.30);
        }
        .amx-btn-primary:hover:not(:disabled) {
          transform: translateY(-1px);
          box-shadow:
            inset 0 1px 0 rgba(255, 255, 255, 0.55),
            0 12px 32px rgba(183, 255, 26, 0.45),
            0 0 40px rgba(183, 255, 26, 0.45);
        }
        .amx-btn-primary:disabled { cursor: not-allowed; }
        .amx-arrow { transition: transform 0.25s ease; font-weight: 800; }
        .amx-btn-primary:hover:not(:disabled) .amx-arrow { transform: translateX(3px); }

        .amx-spinner {
          width: 16px; height: 16px;
          border: 2px solid rgba(5, 5, 5, 0.25);
          border-top-color: rgba(5, 5, 5, 0.85);
          border-radius: 50%;
          animation: amx-spin 0.7s linear infinite;
        }
        @keyframes amx-spin { to { transform: rotate(360deg); } }

        .amx-bottom {
          text-align: center;
          margin-top: 10px;
          font-size: 12px;
          color: rgba(255, 255, 255, 0.55);
        }
        .amx-bottom a {
          color: #ffffff;
          text-decoration: none;
          font-weight: 600;
          position: relative;
          transition: color 0.2s;
        }
        .amx-bottom a:hover { color: var(--acid, #B7FF1A); }
        .amx-bottom-sm { margin-top: 4px; font-size: 11.5px; opacity: 0.85; }

        /* Success */
        .amx-success {
          position: relative; z-index: 1;
          text-align: center;
          padding: 14px 6px 6px;
        }
        .amx-success-icon {
          width: 72px; height: 72px; border-radius: 50%;
          background: rgba(183, 255, 26, 0.10);
          border: 1px solid rgba(183, 255, 26, 0.40);
          color: var(--acid, #B7FF1A);
          display: grid; place-items: center;
          margin: 0 auto 20px;
          box-shadow: 0 0 40px rgba(183, 255, 26, 0.30);
          animation: amx-success-pulse 2s ease-in-out infinite;
        }
        @keyframes amx-success-pulse {
          0%, 100% { box-shadow: 0 0 40px rgba(183, 255, 26, 0.30); }
          50%      { box-shadow: 0 0 60px rgba(183, 255, 26, 0.50); }
        }
        .amx-success h3 {
          font-size: 20px;
          margin: 0;
          letter-spacing: -0.01em;
        }
        .amx-success p {
          margin-top: 12px;
          font-size: 13.5px;
          line-height: 1.55;
          color: rgba(255, 255, 255, 0.55);
        }
        .amx-success .amx-btn-primary {
          margin-top: 22px;
          width: 100%;
        }

        @media (max-width: 480px) {
          .amx-card-wrap { max-width: none; }
          .amx-card { padding: 24px 20px; }
          .amx-title { font-size: 20px; }
          .amx-close { top: 14px; right: 14px; }
        }
        @media (prefers-reduced-motion: reduce) {
          .amx-blob, .amx-spot, .amx-beam, .amx-dot, .amx-success-icon { animation: none; }
          .amx-card-wrap { transform: none !important; }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { AuthModal });
