// AuthScreen.option1.jsx — Option 1: Aurora Glass (dark theme)
// Exposed on window as AuthScreenOption1. The active design is chosen by
// AuthScreen.jsx, which acts as a switcher. To force this design, append
// ?auth=1 to the URL.

// Wrapped in IIFE so internal identifiers (LoginForm, RegisterForm,
// authStyles, AUTH_KEYFRAMES, etc.) do not collide with Option 2's.
(function () {

// ── Supabase client (initialised in config.js, exposed on window) ──────────
// window.supabaseClient — created by config.js after Supabase SDK loads

// ── Helper: fetch user profile from public.users after auth ───────────────
async function fetchUserProfile(userId) {
  const sb = window.supabaseClient;
  if (!sb) throw new Error('Supabase client not initialised');
  const { data, error } = await sb.from('users').select('*').eq('id', userId).single();
  if (error) throw error;
  return data;
}

// ── Map Supabase auth errors to friendly messages ─────────────────────────
function friendlyAuthError(err) {
  const msg = (err?.message || '').toLowerCase();
  if (msg.includes('invalid login credentials')) return 'Incorrect email or password.';
  if (msg.includes('email not confirmed'))       return 'Please check your email and confirm your account first.';
  if (msg.includes('user already registered'))   return 'An account with this email already exists. Please sign in.';
  if (msg.includes('password should be'))        return 'Password must be at least 8 characters.';
  if (msg.includes('rate limit'))                return 'Too many attempts. Please wait a moment and try again.';
  if (msg.includes('network'))                   return 'Connection problem. Check your internet and try again.';
  return err?.message || 'Something went wrong. Please try again.';
}

// ── Styles ─────────────────────────────────────────────────────────────────
const authStyles = {
  // ─── Aurora background shell ─────────────────────────────────────────
  shell: {
    minHeight: '100vh',
    background: '#040B19',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '40px 24px',
    position: 'relative',
    overflow: 'hidden',
  },
  // Large drifting gradient orbs — the "aurora"
  aurora1: { position: 'absolute', top: '-15%',  left: '-10%', width: '60vw', height: '60vw', borderRadius: '50%',
    background: 'radial-gradient(circle at 40% 40%, rgba(13,148,136,0.55), rgba(13,148,136,0) 65%)',
    filter: 'blur(80px)', animation: 'aegisAurora1 18s ease-in-out infinite', pointerEvents: 'none' },
  aurora2: { position: 'absolute', bottom: '-25%', right: '-10%', width: '65vw', height: '65vw', borderRadius: '50%',
    background: 'radial-gradient(circle at 60% 60%, rgba(14,165,233,0.45), rgba(14,165,233,0) 60%)',
    filter: 'blur(90px)', animation: 'aegisAurora2 22s ease-in-out infinite', pointerEvents: 'none' },
  aurora3: { position: 'absolute', top: '20%', right: '15%', width: '38vw', height: '38vw', borderRadius: '50%',
    background: 'radial-gradient(circle, rgba(94,234,212,0.35), rgba(94,234,212,0) 65%)',
    filter: 'blur(70px)', animation: 'aegisAurora3 26s ease-in-out infinite', pointerEvents: 'none' },
  // Subtle dot-grid overlay (texture)
  grid: { position: 'absolute', inset: 0, opacity: 0.4, pointerEvents: 'none',
    backgroundImage: 'radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)',
    backgroundSize: '28px 28px' },
  // Floating geometric chips
  chip: { position: 'absolute', borderRadius: 12, border: '1px solid rgba(94,234,212,0.18)', background: 'rgba(13,148,136,0.06)', backdropFilter: 'blur(10px)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(94,234,212,0.8)', pointerEvents: 'none', boxShadow: '0 8px 32px rgba(0,0,0,0.25)' },

  // ─── Glass card ──────────────────────────────────────────────────────
  card: {
    position: 'relative',
    zIndex: 5,
    width: '100%',
    maxWidth: 460,
    borderRadius: 24,
    background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(255,255,255,0.12)',
    boxShadow: '0 32px 80px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.04) inset',
    backdropFilter: 'blur(28px) saturate(180%)',
    WebkitBackdropFilter: 'blur(28px) saturate(180%)',
    overflow: 'hidden',
  },
  // Top portion inside the card (logo + welcome + tabs)
  header: { padding: '36px 36px 22px', textAlign: 'center', position: 'relative' },
  // Logo with soft glow behind it
  logoWrap: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', position: 'relative', marginBottom: 18 },
  logoGlow: { position: 'absolute', inset: -12, borderRadius: '50%', background: 'radial-gradient(circle, rgba(94,234,212,0.35), rgba(94,234,212,0) 70%)', filter: 'blur(12px)', pointerEvents: 'none' },
  logo: { width: 56, height: 56, objectFit: 'contain', position: 'relative', zIndex: 2 },
  // Welcome text — display sized with gradient accent
  welcome: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 28, fontWeight: 700, letterSpacing: '-0.5px', lineHeight: 1.15, color: 'white', marginBottom: 6 },
  welcomeAccent: { background: 'linear-gradient(90deg, #5EEAD4 0%, #67E8F9 100%)', WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent', color: 'transparent' },
  welcomeSub: { fontSize: 13, color: 'rgba(255,255,255,0.55)', marginBottom: 22, lineHeight: 1.5 },
  // Tabs
  tabs: { display: 'inline-flex', background: 'rgba(255,255,255,0.06)', borderRadius: 10, padding: 3, gap: 3, border: '1px solid rgba(255,255,255,0.08)' },
  tab: { padding: '8px 18px', fontSize: 13, fontWeight: 600, border: 'none', background: 'transparent', color: 'rgba(255,255,255,0.55)', cursor: 'pointer', borderRadius: 8, fontFamily: "'DM Sans',sans-serif", transition: 'all 200ms' },
  tabActive: { background: 'linear-gradient(135deg, rgba(255,255,255,0.95), rgba(255,255,255,0.85))', color: '#0B1F3A', boxShadow: '0 2px 8px rgba(0,0,0,0.25)' },
  body: { padding: '8px 36px 28px' },
  fieldGroup: { marginBottom: 14 },
  fieldLabel: { fontSize: 11, fontWeight: 600, color: 'rgba(255,255,255,0.7)', display: 'block', marginBottom: 6, letterSpacing: '0.04em', textTransform: 'uppercase' },
  fieldInput: { width: '100%', height: 44, border: '1px solid rgba(255,255,255,0.12)', borderRadius: 10, padding: '0 14px', fontFamily: "'DM Sans',sans-serif", fontSize: 14, color: 'white', outline: 'none', background: 'rgba(255,255,255,0.04)', boxSizing: 'border-box', transition: 'all 180ms' },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
  submitBtn: { width: '100%', height: 48, border: 'none', borderRadius: 10, background: 'linear-gradient(135deg, #0D9488 0%, #14B8A6 100%)', fontSize: 14, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", marginTop: 8, transition: 'all 200ms', letterSpacing: '0.04em', boxShadow: '0 8px 20px rgba(13,148,136,0.35), 0 0 0 1px rgba(255,255,255,0.08) inset' },
  errorBox: { background: 'rgba(220,38,38,0.12)', border: '1px solid rgba(220,38,38,0.3)', borderRadius: 10, padding: '10px 14px', fontSize: 12, color: '#FCA5A5', marginBottom: 12, lineHeight: 1.5 },
  successBox: { background: 'rgba(22,163,74,0.12)', border: '1px solid rgba(22,163,74,0.3)', borderRadius: 10, padding: '10px 14px', fontSize: 12, color: '#86EFAC', marginBottom: 12 },
  pilotBox: { background: 'rgba(13,148,136,0.12)', border: '1px solid rgba(94,234,212,0.25)', borderRadius: 10, padding: '12px 16px', fontSize: 12, color: '#5EEAD4', marginBottom: 16, lineHeight: 1.6 },
  footer: { padding: '16px 36px 22px', borderTop: '1px solid rgba(255,255,255,0.06)', textAlign: 'center', fontSize: 11, color: 'rgba(255,255,255,0.35)', lineHeight: 1.6 },
  subscribeBox: { background: 'rgba(220,38,38,0.1)', border: '1px solid rgba(220,38,38,0.25)', borderRadius: 10, padding: '14px 16px', marginBottom: 16, lineHeight: 1.6 },
  subscribeTitle: { fontSize: 13, fontWeight: 700, color: '#FCA5A5', marginBottom: 4 },
  subscribeText: { fontSize: 12, color: 'rgba(252,165,165,0.8)' },
  subscribeBtn: { width: '100%', height: 40, border: 'none', borderRadius: 10, background: 'linear-gradient(135deg, #DC2626, #B91C1C)', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", marginTop: 10 },
  planSelect: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 },
  planOption: { border: '2px solid rgba(255,255,255,0.08)', borderRadius: 10, padding: '10px 12px', cursor: 'pointer', transition: 'all 180ms', textAlign: 'center', background: 'rgba(255,255,255,0.03)' },
  planOptionSelected: { border: '2px solid #5EEAD4', background: 'rgba(13,148,136,0.18)' },
  planName: { fontSize: 13, fontWeight: 700, color: 'white', marginBottom: 2 },
  planPrice: { fontSize: 11, color: 'rgba(255,255,255,0.6)' },
  // Forgot link + sign-in helpers
  forgotLink: { fontSize: 12, fontWeight: 600, color: '#5EEAD4', cursor: 'pointer', textDecoration: 'none', transition: 'color 150ms' },
};

const PLANS = [
  { id: 'pilot',     name: '14-Day Pilot',     price: 'Free',      desc: 'Full access, no card' },
  { id: 'monthly',   name: '🛡️ AegisFlex',     price: 'RM 289/mo', desc: 'Cancel anytime' },
  { id: 'half_year', name: '⚡ AegisPro',      price: 'RM 259/mo', desc: 'RM 1,554 / 6 months (save 10%)' },
  { id: 'yearly',    name: '👑 AegisElite',    price: 'RM 189/mo', desc: 'RM 2,268/yr (launch promo, save 35%)' },
];

// ── Login Form ──────────────────────────────────────────────────────────────
function LoginForm({ onLogin }) {
  const [form, setForm] = React.useState({ email: '', password: '' });
  const [error, setError] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [showSubscribe, setShowSubscribe] = React.useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(''); setInfo('');
    if (!form.email || !form.password) { setError('Please enter your email and password.'); return; }

    setLoading(true);
    try {
      const sb = window.supabaseClient;
      if (!sb) throw new Error('Supabase not initialised — check console.');

      const { data, error: signInError } = await sb.auth.signInWithPassword({
        email: form.email.trim().toLowerCase(),
        password: form.password,
      });
      if (signInError) throw signInError;

      // Fetch profile from public.users
      const profile = await fetchUserProfile(data.user.id);

      // Frozen tier — block login at app level (App.jsx already handles read-only banner)
      if (profile.tier === 'frozen') {
        setShowSubscribe(true);
        await sb.auth.signOut(); // sign out so they need to re-auth after subscribing
        return;
      }

      onLogin(profile);
    } catch (err) {
      console.error('[AuthScreen] Login error:', err);
      setError(friendlyAuthError(err));
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPassword = async () => {
    setError(''); setInfo('');
    if (!form.email) { setError('Enter your email above first, then click "Forgot password".'); return; }
    try {
      const sb = window.supabaseClient;
      const { error: resetError } = await sb.auth.resetPasswordForEmail(form.email.trim().toLowerCase());
      if (resetError) throw resetError;
      setInfo('Password reset link sent. Check your email.');
    } catch (err) {
      setError(friendlyAuthError(err));
    }
  };

  if (showSubscribe) return (
    <div>
      <div style={authStyles.subscribeBox}>
        <div style={authStyles.subscribeTitle}>Your subscription has lapsed</div>
        <div style={authStyles.subscribeText}>
          The account <strong>{form.email}</strong> is currently frozen. To restore access, please contact us to renew your subscription.
        </div>
        <button style={authStyles.subscribeBtn} onClick={() => window.open('mailto:billing@aegiscomply.my?subject=Subscription Renewal — ' + form.email, '_blank')}>
          Contact Us to Renew →
        </button>
      </div>
      <div style={{ textAlign: 'center', fontSize: 12, color: '#94A3B8' }}>
        Plans from <strong style={{ color: '#0D9488' }}>RM 289/month</strong>. Email: billing@aegiscomply.my
      </div>
      <button style={{ ...authStyles.submitBtn, background: 'transparent', color: '#64748B', border: '1px solid #E2E8F0', marginTop: 12 }} onClick={() => setShowSubscribe(false)}>
        ← Back to Login
      </button>
    </div>
  );

  return (
    <form onSubmit={handleSubmit}>
      {error && <div style={authStyles.errorBox}>{error}</div>}
      {info && <div style={authStyles.successBox}>{info}</div>}
      <div style={authStyles.fieldGroup}>
        <label style={authStyles.fieldLabel}>Work Email</label>
        <input className="aegis-input" style={authStyles.fieldInput} type="email" placeholder="you@company.com.my" value={form.email} onChange={e => set('email', e.target.value)} autoComplete="email"/>
      </div>
      <div style={authStyles.fieldGroup}>
        <label style={authStyles.fieldLabel}>Password</label>
        <input className="aegis-input" style={authStyles.fieldInput} type="password" placeholder="Enter your password" value={form.password} onChange={e => set('password', e.target.value)} autoComplete="current-password"/>
        <div className="aegis-link" style={{ ...authStyles.forgotLink, marginTop: 8, display: 'block', textAlign: 'right' }} onClick={handleForgotPassword}>Forgot password?</div>
      </div>
      <button type="submit" className="aegis-submit" style={{ ...authStyles.submitBtn, opacity: loading ? 0.5 : 1, cursor: loading ? 'not-allowed' : 'pointer' }} disabled={loading}>
        {loading ? 'Signing in…' : 'Sign In →'}
      </button>
    </form>
  );
}

// ── Register Form ───────────────────────────────────────────────────────────
function RegisterForm({ onLogin, onSwitchToLogin }) {
  const [form, setForm] = React.useState({ company: '', name: '', email: '', phone: '', password: '', plan: 'pilot' });
  const [step, setStep] = React.useState(1);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [needsConfirmation, setNeedsConfirmation] = React.useState(false);
  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setError(''); };
  const valid1 = form.company && form.name && form.email && form.password && form.password.length >= 8;

  const handleNext = async () => {
    setError('');

    if (step === 1) {
      if (!valid1) { setError('Please fill in all fields. Password must be at least 8 characters.'); return; }
      setStep(2);
      return;
    }

    if (step === 2) {
      setLoading(true);
      try {
        const sb = window.supabaseClient;
        if (!sb) throw new Error('Supabase not initialised — check console.');

        // 1. Create Supabase Auth account
        const { data: signUpData, error: signUpError } = await sb.auth.signUp({
          email: form.email.trim().toLowerCase(),
          password: form.password,
          options: {
            data: {
              name: form.name,
              company: form.company,
              phone: form.phone,
            },
          },
        });
        if (signUpError) throw signUpError;

        // Detect "email already registered" — Supabase returns a fake user with empty identities
        if (signUpData.user && Array.isArray(signUpData.user.identities) && signUpData.user.identities.length === 0) {
          throw new Error('An account with this email already exists. Please sign in instead.');
        }

        const newUserId = signUpData.user?.id;

        // 2. If we got a user ID, insert profile row into public.users
        if (newUserId) {
          const { error: profileError } = await sb.from('users').insert({
            id:        newUserId,
            email:     form.email.trim().toLowerCase(),
            name:      form.name,
            phone:     form.phone || null,
            whatsapp:  form.phone || null,
            company:   form.company,
            role:      'Safety Officer',
            tier:      'pilot',
            pilot_used: true,
            created_by: 'self',
          });
          if (profileError && !/duplicate key/i.test(profileError.message)) {
            console.warn('[AuthScreen] Profile insert failed:', profileError);
            // don't block — the trigger or admin can create the profile later
          }
        }

        // 3. If no active session → email confirmation is required
        if (!signUpData.session) {
          setNeedsConfirmation(true);
          setLoading(false);
          return;
        }

        // 4. We have a session — log in immediately
        const profile = await fetchUserProfile(newUserId);
        setLoading(false);
        setStep(3);
        setTimeout(() => onLogin(profile), 1500);
      } catch (err) {
        console.error('[AuthScreen] Register error:', err);
        setError(friendlyAuthError(err));
        setLoading(false);
      }
    }
  };

  if (needsConfirmation) return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#F0FDFA', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#0D9488" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
      </div>
      <div style={{ fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 17, fontWeight: 700, color: '#0F172A', marginBottom: 6 }}>Confirm Your Email</div>
      <div style={{ fontSize: 13, color: '#64748B', marginBottom: 4 }}>We've sent a confirmation link to:</div>
      <div style={{ fontSize: 13, fontWeight: 600, color: '#0D9488', marginBottom: 16 }}>{form.email}</div>
      <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 18, lineHeight: 1.6 }}>
        Click the link in the email to activate your account, then return here to sign in.
      </div>
      <button style={{ ...authStyles.submitBtn, marginTop: 0 }} onClick={onSwitchToLogin}>
        Back to Sign In →
      </button>
    </div>
  );

  if (step === 3) return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#F0FDF4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
      </div>
      <div style={{ fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 17, fontWeight: 700, color: '#0F172A', marginBottom: 6 }}>Account Created!</div>
      <div style={{ fontSize: 13, color: '#64748B', marginBottom: 4 }}>Welcome, <strong>{form.name}</strong>. Your 14-day pilot starts now.</div>
      <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 18 }}>Signing you in…</div>
    </div>
  );

  return (
    <div>
      {/* Step indicator */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 18, alignItems: 'center' }}>
        {['Company Details', 'Select Plan'].map((s, i) => (
          <React.Fragment key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: step > i + 1 ? '#16A34A' : step === i + 1 ? '#0D9488' : '#E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: step >= i + 1 ? 'white' : '#94A3B8', flexShrink: 0 }}>
                {step > i + 1 ? '✓' : i + 1}
              </div>
              <span style={{ fontSize: 11, fontWeight: 600, color: step === i + 1 ? '#0F172A' : '#94A3B8' }}>{s}</span>
            </div>
            {i === 0 && <div style={{ flex: 1, height: 1, background: step > 1 ? '#0D9488' : '#E2E8F0' }}/>}
          </React.Fragment>
        ))}
      </div>

      {error && <div style={authStyles.errorBox}>{error}</div>}

      {step === 1 && (
        <>
          <div style={authStyles.pilotBox}>
            <strong>14-Day Free Pilot</strong> — Full system access, no credit card. Starts immediately on registration. Each email address can only be used once.
          </div>
          <div style={authStyles.fieldGroup}>
            <label style={authStyles.fieldLabel}>Company Name *</label>
            <input className="aegis-input" style={authStyles.fieldInput} placeholder="e.g. Petronas Chemicals Bhd" value={form.company} onChange={e => set('company', e.target.value)}/>
          </div>
          <div style={authStyles.grid2}>
            <div style={authStyles.fieldGroup}>
              <label style={authStyles.fieldLabel}>Your Name *</label>
              <input className="aegis-input" style={authStyles.fieldInput} placeholder="Full name" value={form.name} onChange={e => set('name', e.target.value)}/>
            </div>
            <div style={authStyles.fieldGroup}>
              <label style={authStyles.fieldLabel}>Phone</label>
              <input className="aegis-input" style={authStyles.fieldInput} placeholder="+60 12-xxx xxxx" value={form.phone} onChange={e => set('phone', e.target.value)}/>
            </div>
          </div>
          <div style={authStyles.fieldGroup}>
            <label style={authStyles.fieldLabel}>Work Email *</label>
            <input className="aegis-input" style={authStyles.fieldInput} type="email" placeholder="you@company.com.my" value={form.email} onChange={e => set('email', e.target.value)}/>
          </div>
          <div style={authStyles.fieldGroup}>
            <label style={authStyles.fieldLabel}>Password * <span style={{ color: 'rgba(255,255,255,0.4)', fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>(min 8 characters)</span></label>
            <input className="aegis-input" style={authStyles.fieldInput} type="password" placeholder="Create a strong password" value={form.password} onChange={e => set('password', e.target.value)}/>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'rgba(255,255,255,0.85)', marginBottom: 12 }}>What plan would you like after the pilot?</div>
          <div style={authStyles.planSelect}>
            {PLANS.map(p => (
              <div key={p.id} style={{ ...authStyles.planOption, ...(form.plan === p.id ? authStyles.planOptionSelected : {}) }} onClick={() => set('plan', p.id)}>
                <div style={authStyles.planName}>{p.name}</div>
                <div style={{ ...authStyles.planPrice, color: form.plan === p.id ? '#5EEAD4' : 'rgba(255,255,255,0.55)', fontWeight: 600 }}>{p.price}</div>
                <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', marginTop: 2 }}>{p.desc}</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', marginBottom: 10, lineHeight: 1.6 }}>
            You will not be charged during the 14-day pilot. After the trial, you will be contacted to arrange payment based on your selected plan.
          </div>
        </>
      )}

      <button
        className="aegis-submit"
        style={{ ...authStyles.submitBtn, opacity: ((step === 1 && !valid1) || loading) ? 0.5 : 1, cursor: ((step === 1 && !valid1) || loading) ? 'not-allowed' : 'pointer' }}
        disabled={(step === 1 && !valid1) || loading}
        onClick={handleNext}
      >
        {loading ? 'Creating account…' : step === 1 ? 'Continue →' : 'Create Account & Start Pilot'}
      </button>
      {step === 2 && (
        <div style={{ textAlign: 'center', marginTop: 10 }}>
          <span style={{ fontSize: 12, color: '#0D9488', cursor: 'pointer' }} onClick={() => setStep(1)}>← Back</span>
        </div>
      )}
    </div>
  );
}

// ── Global keyframes + focus styles (injected once) ─────────────────────────
const AUTH_KEYFRAMES = `
  @keyframes aegisAurora1 { 0%,100% { transform: translate(0,0) scale(1) rotate(0deg); } 50% { transform: translate(8vw, 5vh) scale(1.15) rotate(15deg); } }
  @keyframes aegisAurora2 { 0%,100% { transform: translate(0,0) scale(1) rotate(0deg); } 50% { transform: translate(-6vw, -4vh) scale(1.1) rotate(-12deg); } }
  @keyframes aegisAurora3 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(-4vw, 6vh) scale(0.9); } }
  @keyframes aegisFloatChip1 { 0%,100% { transform: translateY(0) rotate(0deg); } 50% { transform: translateY(-14px) rotate(8deg); } }
  @keyframes aegisFloatChip2 { 0%,100% { transform: translateY(0) rotate(0deg); } 50% { transform: translateY(12px) rotate(-6deg); } }
  @keyframes aegisFadeUp { 0% { opacity: 0; transform: translateY(14px); } 100% { opacity: 1; transform: translateY(0); } }
  @keyframes aegisGlowPulse { 0%,100% { opacity: 0.7; } 50% { opacity: 1; } }
  .aegis-fade-up { animation: aegisFadeUp 580ms cubic-bezier(0.16, 1, 0.3, 1) both; }
  .aegis-fade-up.d1 { animation-delay: 80ms; }
  .aegis-fade-up.d2 { animation-delay: 160ms; }
  .aegis-fade-up.d3 { animation-delay: 240ms; }
  /* Input focus glow */
  .aegis-input:focus { border-color: rgba(94,234,212,0.6) !important; background: rgba(255,255,255,0.06) !important; box-shadow: 0 0 0 3px rgba(94,234,212,0.18) !important; }
  .aegis-input::placeholder { color: rgba(255,255,255,0.32); }
  /* Submit button hover */
  .aegis-submit:hover { transform: translateY(-1px); box-shadow: 0 12px 28px rgba(13,148,136,0.5), 0 0 0 1px rgba(255,255,255,0.12) inset !important; }
  .aegis-submit:active { transform: translateY(0); }
  /* Forgot link hover */
  .aegis-link:hover { color: #67E8F9 !important; }
  /* Logo glow pulse */
  .aegis-logo-glow { animation: aegisGlowPulse 4s ease-in-out infinite; }
  /* Chip floats */
  .aegis-chip-1 { animation: aegisFloatChip1 9s ease-in-out infinite; }
  .aegis-chip-2 { animation: aegisFloatChip2 11s ease-in-out infinite; }
  @media (max-width: 720px) {
    .aegis-chip { display: none !important; }
  }
`;

// ── Auth Shell ──────────────────────────────────────────────────────────────
function AuthScreenOption1({ onLogin }) {
  const [tab, setTab] = React.useState('login');

  return (
    <div style={authStyles.shell}>
      <style>{AUTH_KEYFRAMES}</style>

      {/* Aurora gradient orbs */}
      <div style={authStyles.aurora1}/>
      <div style={authStyles.aurora2}/>
      <div style={authStyles.aurora3}/>
      {/* Dot-grid texture */}
      <div style={authStyles.grid}/>

      {/* Floating decorative chips (hidden on mobile) */}
      <div className="aegis-chip aegis-chip-1" style={{ ...authStyles.chip, top: '14%', left: '8%', width: 64, height: 64 }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
      </div>
      <div className="aegis-chip aegis-chip-2" style={{ ...authStyles.chip, bottom: '18%', right: '10%', width: 72, height: 72 }}>
        <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
      </div>
      <div className="aegis-chip aegis-chip-1" style={{ ...authStyles.chip, top: '22%', right: '14%', width: 52, height: 52, animationDelay: '2s' }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      </div>
      <div className="aegis-chip aegis-chip-2" style={{ ...authStyles.chip, bottom: '14%', left: '12%', width: 56, height: 56, animationDelay: '3s' }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/></svg>
      </div>

      {/* ─── Glass card ─────────────────────────────────────────────── */}
      <div style={authStyles.card} className="aegis-fade-up">
        <div style={authStyles.header}>
          <div style={authStyles.logoWrap} className="aegis-fade-up d1">
            <div style={authStyles.logoGlow} className="aegis-logo-glow"/>
            <img src="../../assets/logo-aegisfeld.png"
              style={authStyles.logo}
              alt="AegisComply"
              onError={e => { e.target.style.display = 'none'; }}
            />
          </div>
          <div style={authStyles.welcome} className="aegis-fade-up d2">
            {tab === 'login'
              ? <>Welcome <span style={authStyles.welcomeAccent}>back.</span></>
              : <>Start your <span style={authStyles.welcomeAccent}>14-day pilot.</span></>}
          </div>
          <div style={authStyles.welcomeSub} className="aegis-fade-up d3">
            {tab === 'login'
              ? 'Sign in to your AegisComply workspace.'
              : 'Full access. No credit card. Cancel anytime.'}
          </div>
          <div style={authStyles.tabs}>
            <button style={{ ...authStyles.tab, ...(tab === 'login' ? authStyles.tabActive : {}) }} onClick={() => setTab('login')}>Sign In</button>
            <button style={{ ...authStyles.tab, ...(tab === 'register' ? authStyles.tabActive : {}) }} onClick={() => setTab('register')}>Create Account</button>
          </div>
        </div>
        <div style={authStyles.body}>
          {tab === 'login'
            ? <LoginForm onLogin={onLogin}/>
            : <RegisterForm onLogin={onLogin} onSwitchToLogin={() => setTab('login')}/>
          }
        </div>
        <div style={authStyles.footer}>
          🔒 PDPA-compliant · Singapore-hosted database<br/>
          By continuing, you agree to our Terms of Service and Privacy Policy.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreenOption1 });

})();
