// AuthScreen.option2.jsx — Option 2: Editorial Split-Screen (light, premium)
// Exposed on window as AuthScreenOption2. The active design is chosen by
// AuthScreen.jsx, which acts as a switcher. To force this design, append
// ?auth=2 to the URL (or set window.__AEGIS_AUTH__ = '2').
//
// Visual concept: full-bleed split-pane. Left = bold editorial brand panel
// with animated mesh-gradient blobs over deep navy, oversized display headline
// and a marquee of compliance modules. Right = warm cream form panel with
// thin precise borders, large inputs and a tactile premium feel.

// Wrapped in IIFE so internals don't collide with Option 1.
(function () {

// ── Helpers ────────────────────────────────────────────────────────────────
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;
}

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.';
}

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%)' },
];

// ── Styles ─────────────────────────────────────────────────────────────────
const s = {
  // Full-bleed page split
  shell: { minHeight: '100vh', width: '100%', display: 'grid', gridTemplateColumns: '1fr 1fr', background: '#F8F4EC', fontFamily: "'DM Sans', sans-serif" },

  // ─── LEFT PANE — editorial brand with campus photo ───────────────────
  left: {
    position: 'relative',
    overflow: 'hidden',
    background: '#0A1530',
    color: 'white',
    padding: '56px 56px 48px',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    minHeight: '100vh',
  },
  // Campus photo as the backdrop. Slow Ken Burns pan keeps it feeling alive.
  photo: { position: 'absolute', inset: 0, backgroundImage: 'url("../../assets/login-campus.jpg")',
    backgroundSize: 'cover', backgroundPosition: 'center',
    animation: 'a2kenburns 28s ease-in-out infinite alternate', pointerEvents: 'none' },
  // Vertical gradient overlay so headline + body text stay legible.
  photoOverlay: { position: 'absolute', inset: 0, pointerEvents: 'none',
    background: 'linear-gradient(180deg, rgba(10,21,48,0.55) 0%, rgba(10,21,48,0.72) 45%, rgba(10,21,48,0.92) 100%)' },
  // Subtle teal/amber colour wash that ties the photo back to brand colours.
  blob1: { position: 'absolute', top: '-20%', left: '-20%', width: '70%', height: '70%', borderRadius: '50%',
    background: 'radial-gradient(circle at 35% 35%, rgba(13,148,136,0.35) 0%, rgba(13,148,136,0) 65%)',
    filter: 'blur(80px)', animation: 'a2blob1 16s ease-in-out infinite', pointerEvents: 'none', mixBlendMode: 'screen' },
  blob2: { position: 'absolute', bottom: '-15%', right: '-10%', width: '60%', height: '60%', borderRadius: '50%',
    background: 'radial-gradient(circle at 50% 50%, rgba(232,116,60,0.22) 0%, rgba(232,116,60,0) 65%)',
    filter: 'blur(90px)', animation: 'a2blob2 20s ease-in-out infinite', pointerEvents: 'none', mixBlendMode: 'screen' },
  blob3: { position: 'absolute', top: '35%', right: '20%', width: '45%', height: '45%', borderRadius: '50%',
    background: 'radial-gradient(circle, rgba(99,102,241,0.18) 0%, rgba(99,102,241,0) 60%)',
    filter: 'blur(80px)', animation: 'a2blob3 24s ease-in-out infinite', pointerEvents: 'none', mixBlendMode: 'screen' },
  // Light grain over the photo
  noise: { position: 'absolute', inset: 0, opacity: 0.12, pointerEvents: 'none',
    backgroundImage: 'radial-gradient(rgba(255,255,255,0.5) 0.6px, transparent 0.6px)',
    backgroundSize: '4px 4px' },

  // Brand mark top-left
  brandRow: { position: 'relative', zIndex: 2, display: 'flex', alignItems: 'center', gap: 12 },
  brandLogo: { width: 40, height: 40, objectFit: 'contain' },
  brandWord: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 17, fontWeight: 700, letterSpacing: '0.02em' },
  brandTag: { fontSize: 11, color: 'rgba(255,255,255,0.55)', letterSpacing: '0.18em', textTransform: 'uppercase', marginLeft: 'auto' },

  // Editorial headline block
  hero: { position: 'relative', zIndex: 2, marginTop: 'auto' },
  eyebrow: { display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 12px', borderRadius: 100, background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.14)', fontSize: 11, color: 'rgba(255,255,255,0.85)', letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 24 },
  eyebrowDot: { width: 6, height: 6, borderRadius: '50%', background: '#5EEAD4', boxShadow: '0 0 12px rgba(94,234,212,0.9)', animation: 'a2pulse 2s ease-in-out infinite' },
  headline: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 'clamp(40px, 4.8vw, 64px)', fontWeight: 700, lineHeight: 1.02, letterSpacing: '-0.025em', marginBottom: 18 },
  headlineAccent: { fontStyle: 'italic', background: 'linear-gradient(90deg, #FBBF24 0%, #FB923C 60%, #F472B6 100%)', WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent', color: 'transparent' },
  lede: { fontSize: 16, lineHeight: 1.6, color: 'rgba(255,255,255,0.7)', maxWidth: 480, marginBottom: 32 },

  // Module marquee chips
  moduleRow: { position: 'relative', zIndex: 2, display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 36 },
  moduleChip: { display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 100, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', fontSize: 12, fontWeight: 600, color: 'rgba(255,255,255,0.9)' },
  moduleDot: { width: 6, height: 6, borderRadius: 2 },

  // Bottom testimonial / footer block
  bottomRow: { position: 'relative', zIndex: 2, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24 },
  quote: { maxWidth: 360 },
  quoteText: { fontSize: 13, lineHeight: 1.6, color: 'rgba(255,255,255,0.75)', marginBottom: 10, fontStyle: 'italic' },
  quoteWho: { fontSize: 11, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.05em', textTransform: 'uppercase', fontWeight: 600 },
  stamp: { display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 6, border: '1px dashed rgba(255,255,255,0.25)', fontSize: 10, color: 'rgba(255,255,255,0.6)', letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 700, fontFamily: "'JetBrains Mono', monospace" },

  // ─── RIGHT PANE — form ───────────────────────────────────────────────
  right: { background: '#F8F4EC', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px 48px', minHeight: '100vh' },
  rightFrame: { width: '100%', maxWidth: 460 },
  topNav: { position: 'absolute', top: 24, right: 32, display: 'flex', alignItems: 'center', gap: 18, fontSize: 13, color: '#475569' },
  topNavLink: { color: '#0F172A', fontWeight: 600, textDecoration: 'none', cursor: 'pointer' },
  topNavBtn: { padding: '8px 16px', borderRadius: 8, border: '1px solid #0F172A', background: 'transparent', color: '#0F172A', fontWeight: 600, fontSize: 13, cursor: 'pointer', fontFamily: "'DM Sans', sans-serif" },

  formTitle: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 32, fontWeight: 700, color: '#0A1530', letterSpacing: '-0.015em', marginBottom: 8 },
  formSub: { fontSize: 14, color: '#64748B', marginBottom: 32, lineHeight: 1.55 },

  // Tab pill at top of form
  tabs: { display: 'inline-flex', background: '#FFFFFF', padding: 4, borderRadius: 12, gap: 4, border: '1px solid #E5E0D4', marginBottom: 28, boxShadow: '0 1px 2px rgba(15,23,42,0.04)' },
  tab: { padding: '9px 20px', fontSize: 13, fontWeight: 600, border: 'none', background: 'transparent', color: '#64748B', cursor: 'pointer', borderRadius: 8, fontFamily: "'DM Sans', sans-serif", transition: 'all 200ms' },
  tabActive: { background: '#0A1530', color: 'white' },

  fieldGroup: { marginBottom: 16 },
  fieldLabel: { fontSize: 12, fontWeight: 600, color: '#0A1530', display: 'block', marginBottom: 6, letterSpacing: '0.01em' },
  fieldInput: { width: '100%', height: 50, border: '1px solid #DDD4C0', borderRadius: 12, padding: '0 16px', fontFamily: "'DM Sans', sans-serif", fontSize: 15, color: '#0F172A', outline: 'none', background: '#FFFFFF', boxSizing: 'border-box', transition: 'all 180ms' },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },

  submitBtn: { width: '100%', height: 52, border: 'none', borderRadius: 12, background: '#0A1530', fontSize: 14, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", marginTop: 10, transition: 'all 200ms', letterSpacing: '0.02em', boxShadow: '0 6px 14px rgba(10,21,48,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 },

  errorBox: { background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 10, padding: '11px 14px', fontSize: 13, color: '#B91C1C', marginBottom: 14, lineHeight: 1.5 },
  successBox: { background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: 10, padding: '11px 14px', fontSize: 13, color: '#15803D', marginBottom: 14 },
  pilotBox: { background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 12, padding: '14px 16px', fontSize: 13, color: '#92400E', marginBottom: 18, lineHeight: 1.55 },

  forgotLink: { fontSize: 13, fontWeight: 600, color: '#0A1530', cursor: 'pointer', textDecoration: 'underline', textDecorationColor: '#FBBF24', textUnderlineOffset: 4, transition: 'color 150ms' },

  footer: { marginTop: 28, paddingTop: 20, borderTop: '1px solid #E5E0D4', textAlign: 'center', fontSize: 11, color: '#94A3B8', lineHeight: 1.6 },
  footerLock: { display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 4, fontSize: 11, fontWeight: 600, color: '#64748B' },

  // Subscribe box for frozen account
  subscribeBox: { background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 12, padding: '16px', marginBottom: 14, lineHeight: 1.6 },
  subscribeTitle: { fontSize: 14, fontWeight: 700, color: '#B91C1C', marginBottom: 4 },
  subscribeText: { fontSize: 13, color: '#7F1D1D' },
  subscribeBtn: { width: '100%', height: 44, border: 'none', borderRadius: 10, background: '#DC2626', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", marginTop: 12 },

  // Plan select (register step 2)
  planSelect: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 },
  planOption: { border: '2px solid #E5E0D4', borderRadius: 12, padding: '12px 14px', cursor: 'pointer', transition: 'all 180ms', textAlign: 'center', background: '#FFFFFF' },
  planOptionSelected: { border: '2px solid #0A1530', background: '#FFFBEB' },
  planName: { fontSize: 13, fontWeight: 700, color: '#0F172A', marginBottom: 2 },
  planPrice: { fontSize: 11, color: '#64748B' },

  // Step indicator
  stepRow: { display: 'flex', gap: 6, marginBottom: 20, alignItems: 'center' },
  stepDotActive: { background: '#0A1530', color: 'white' },
  stepDotDone: { background: '#15803D', color: 'white' },
  stepDotIdle: { background: '#E5E0D4', color: '#94A3B8' },
};

// ── 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 {
      // Wait briefly for the Supabase client in case it's still loading
      // (slow CDN on first visit). Falls back to a clear inline diagnostic
      // if the SDK was actually blocked.
      let sb = window.supabaseClient;
      if (!sb && typeof window.aegisEnsureSupabase === 'function') {
        try { sb = await Promise.race([
          window.aegisEnsureSupabase(),
          new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 8000)),
        ]); } catch (_) {}
      }
      if (!sb) {
        const blocked = window.__AEGIS_SDK_BLOCKED__;
        throw new Error(
          blocked
            ? 'Cannot reach AegisComply server. An ad-blocker, VPN, or your network may be blocking it. Try: disable ad-blockers for this site, switch to mobile data, or try a different browser.'
            : 'Connection to AegisComply server is still loading. Please wait 5 seconds and try again.'
        );
      }
      const { data, error: signInError } = await sb.auth.signInWithPassword({
        email: form.email.trim().toLowerCase(),
        password: form.password,
      });
      if (signInError) throw signInError;
      const profile = await fetchUserProfile(data.user.id);
      if (profile.tier === 'frozen') {
        setShowSubscribe(true);
        await sb.auth.signOut();
        return;
      }
      onLogin(profile);
    } catch (err) {
      console.error('[AuthScreen.option2] 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={s.subscribeBox}>
        <div style={s.subscribeTitle}>Your subscription has lapsed</div>
        <div style={s.subscribeText}>
          The account <strong>{form.email}</strong> is currently frozen. To restore access, please contact us to renew your subscription.
        </div>
        <button style={s.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', marginTop: 8 }}>
        Plans from <strong style={{ color: '#0A1530' }}>RM 289/month</strong>
      </div>
      <button style={{ ...s.submitBtn, background: 'transparent', color: '#0A1530', border: '1px solid #DDD4C0', marginTop: 14, boxShadow: 'none' }} onClick={() => setShowSubscribe(false)}>
        ← Back to Login
      </button>
    </div>
  );

  return (
    <form onSubmit={handleSubmit}>
      {error && <div style={s.errorBox}>{error}</div>}
      {info && <div style={s.successBox}>{info}</div>}
      <div style={s.fieldGroup}>
        <label style={s.fieldLabel}>Work Email</label>
        <input className="a2-input" style={s.fieldInput} type="email" placeholder="you@company.com.my" value={form.email} onChange={e => set('email', e.target.value)} autoComplete="email"/>
      </div>
      <div style={s.fieldGroup}>
        <label style={s.fieldLabel}>Password</label>
        <input className="a2-input" style={s.fieldInput} type="password" placeholder="Enter your password" value={form.password} onChange={e => set('password', e.target.value)} autoComplete="current-password"/>
        <div className="a2-link" style={{ ...s.forgotLink, marginTop: 10, display: 'inline-block' }} onClick={handleForgotPassword}>Forgot password?</div>
      </div>
      <button type="submit" className="a2-submit" style={{ ...s.submitBtn, opacity: loading ? 0.55 : 1, cursor: loading ? 'not-allowed' : 'pointer' }} disabled={loading}>
        {loading ? 'Signing in…' : <>Sign In <span style={{ fontSize: 16 }}>→</span></>}
      </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.');
        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;
        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;
        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.option2] Profile insert failed:', profileError);
          }
        }
        if (!signUpData.session) {
          setNeedsConfirmation(true);
          setLoading(false);
          return;
        }
        const profile = await fetchUserProfile(newUserId);
        setLoading(false);
        setStep(3);
        setTimeout(() => onLogin(profile), 1500);
      } catch (err) {
        console.error('[AuthScreen.option2] Register error:', err);
        setError(friendlyAuthError(err));
        setLoading(false);
      }
    }
  };

  if (needsConfirmation) return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{ width: 60, height: 60, borderRadius: '50%', background: '#FFFBEB', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', border: '1px solid #FDE68A' }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#92400E" strokeWidth="2.2" 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: 20, fontWeight: 700, color: '#0A1530', marginBottom: 8 }}>Confirm Your Email</div>
      <div style={{ fontSize: 14, color: '#64748B', marginBottom: 4 }}>We've sent a confirmation link to:</div>
      <div style={{ fontSize: 14, fontWeight: 600, color: '#0A1530', marginBottom: 18 }}>{form.email}</div>
      <div style={{ fontSize: 13, color: '#94A3B8', marginBottom: 22, lineHeight: 1.6 }}>
        Click the link in the email to activate your account, then return here to sign in.
      </div>
      <button style={s.submitBtn} onClick={onSwitchToLogin}>Back to Sign In →</button>
    </div>
  );

  if (step === 3) return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{ width: 60, height: 60, borderRadius: '50%', background: '#F0FDF4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', border: '1px solid #BBF7D0' }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#15803D" strokeWidth="2.2" 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: 20, fontWeight: 700, color: '#0A1530', marginBottom: 8 }}>Account Created</div>
      <div style={{ fontSize: 14, color: '#64748B', marginBottom: 6 }}>Welcome, <strong>{form.name}</strong>. Your 14-day pilot starts now.</div>
      <div style={{ fontSize: 13, color: '#94A3B8' }}>Signing you in…</div>
    </div>
  );

  return (
    <div>
      <div style={s.stepRow}>
        {['Company Details', 'Select Plan'].map((label, i) => {
          const dotStyle = step > i + 1 ? s.stepDotDone : step === i + 1 ? s.stepDotActive : s.stepDotIdle;
          return (
            <React.Fragment key={i}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0, ...dotStyle }}>
                  {step > i + 1 ? '✓' : i + 1}
                </div>
                <span style={{ fontSize: 12, fontWeight: 600, color: step === i + 1 ? '#0A1530' : '#94A3B8' }}>{label}</span>
              </div>
              {i === 0 && <div style={{ flex: 1, height: 1, background: step > 1 ? '#0A1530' : '#E5E0D4' }}/>}
            </React.Fragment>
          );
        })}
      </div>

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

      {step === 1 && (
        <>
          <div style={s.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={s.fieldGroup}>
            <label style={s.fieldLabel}>Company Name *</label>
            <input className="a2-input" style={s.fieldInput} placeholder="e.g. Petronas Chemicals Bhd" value={form.company} onChange={e => set('company', e.target.value)}/>
          </div>
          <div style={s.grid2}>
            <div style={s.fieldGroup}>
              <label style={s.fieldLabel}>Your Name *</label>
              <input className="a2-input" style={s.fieldInput} placeholder="Full name" value={form.name} onChange={e => set('name', e.target.value)}/>
            </div>
            <div style={s.fieldGroup}>
              <label style={s.fieldLabel}>Phone</label>
              <input className="a2-input" style={s.fieldInput} placeholder="+60 12-xxx xxxx" value={form.phone} onChange={e => set('phone', e.target.value)}/>
            </div>
          </div>
          <div style={s.fieldGroup}>
            <label style={s.fieldLabel}>Work Email *</label>
            <input className="a2-input" style={s.fieldInput} type="email" placeholder="you@company.com.my" value={form.email} onChange={e => set('email', e.target.value)}/>
          </div>
          <div style={s.fieldGroup}>
            <label style={s.fieldLabel}>Password * <span style={{ color: '#94A3B8', fontWeight: 400 }}>(min 8 characters)</span></label>
            <input className="a2-input" style={s.fieldInput} type="password" placeholder="Create a strong password" value={form.password} onChange={e => set('password', e.target.value)}/>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#0A1530', marginBottom: 12 }}>What plan would you like after the pilot?</div>
          <div style={s.planSelect}>
            {PLANS.map(p => (
              <div key={p.id} style={{ ...s.planOption, ...(form.plan === p.id ? s.planOptionSelected : {}) }} onClick={() => set('plan', p.id)}>
                <div style={s.planName}>{p.name}</div>
                <div style={{ ...s.planPrice, color: form.plan === p.id ? '#0A1530' : '#64748B', fontWeight: 600 }}>{p.price}</div>
                <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>{p.desc}</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 10, lineHeight: 1.55 }}>
            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="a2-submit"
        style={{ ...s.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: 12 }}>
          <span style={{ fontSize: 12, color: '#0A1530', cursor: 'pointer', fontWeight: 600 }} onClick={() => setStep(1)}>← Back</span>
        </div>
      )}
    </div>
  );
}

// ── Global keyframes + focus styles (injected once per mount) ───────────────
const A2_KEYFRAMES = `
  @keyframes a2kenburns { 0% { transform: scale(1.04) translate(0,0); } 100% { transform: scale(1.12) translate(-1.5%, -1%); } }
  @keyframes a2blob1 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(6vw, 4vh) scale(1.1); } }
  @keyframes a2blob2 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(-5vw, -3vh) scale(1.15); } }
  @keyframes a2blob3 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(3vw, -4vh) scale(0.9); } }
  @keyframes a2pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.45; } }
  @keyframes a2fadeUp { 0% { opacity: 0; transform: translateY(16px); } 100% { opacity: 1; transform: translateY(0); } }
  .a2-fade-up { animation: a2fadeUp 640ms cubic-bezier(0.16, 1, 0.3, 1) both; }
  .a2-fade-up.d1 { animation-delay: 80ms; }
  .a2-fade-up.d2 { animation-delay: 160ms; }
  .a2-fade-up.d3 { animation-delay: 240ms; }
  .a2-fade-up.d4 { animation-delay: 320ms; }
  /* Input focus ring */
  .a2-input:focus { border-color: #0A1530 !important; background: #FFFFFF !important; box-shadow: 0 0 0 4px rgba(10,21,48,0.08) !important; }
  .a2-input::placeholder { color: #B6AC95; }
  /* Submit button hover */
  .a2-submit:hover { transform: translateY(-1px); box-shadow: 0 12px 22px rgba(10,21,48,0.28) !important; }
  .a2-submit:active { transform: translateY(0); }
  /* Forgot link hover */
  .a2-link:hover { color: #B45309 !important; }
  /* Mobile: stack the split */
  @media (max-width: 980px) {
    .a2-shell { grid-template-columns: 1fr !important; }
    .a2-left { min-height: auto !important; padding: 40px 28px 36px !important; }
    .a2-right { padding: 32px 24px !important; min-height: auto !important; }
    .a2-topnav { display: none !important; }
    .a2-headline { font-size: 36px !important; }
  }
`;

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

  const modules = [
    { label: 'Equipment Calibration', color: '#5EEAD4' },
    { label: 'PPE Tracking',          color: '#FBBF24' },
    { label: 'Compliance Audits',     color: '#F472B6' },
    { label: 'QR Workflows',          color: '#A5B4FC' },
    { label: 'PDF Reports',           color: '#FB923C' },
  ];

  return (
    <div className="a2-shell" style={s.shell}>
      <style>{A2_KEYFRAMES}</style>

      {/* ─── LEFT — Editorial brand panel ─────────────────────────────── */}
      <div className="a2-left" style={s.left}>
        <div style={s.photo}/>
        <div style={s.photoOverlay}/>
        <div style={s.blob1}/>
        <div style={s.blob2}/>
        <div style={s.blob3}/>
        <div style={s.noise}/>

        <div style={s.brandRow} className="a2-fade-up">
          <img src="../../assets/logo-aegisfeld.png" style={s.brandLogo} alt="AegisComply" onError={e => { e.target.style.display = 'none'; }}/>
          <div style={s.brandWord}>AegisComply</div>
          <div style={s.brandTag}>Industrial · Compliance · Suite</div>
        </div>

        <div style={s.hero}>
          <div style={s.eyebrow} className="a2-fade-up d1">
            <span style={s.eyebrowDot}/>
            Live across 12 sites in Malaysia
          </div>
          <div style={s.headline} className="a2-fade-up d2 a2-headline">
            Compliance,<br/>
            <span style={s.headlineAccent}>on the ground.</span>
          </div>
          <div style={s.lede} className="a2-fade-up d3">
            One workspace for calibration, PPE, audits and field reports — built for Malaysian industrial safety officers. PDPA-compliant. Always inspection-ready.
          </div>

          <div style={s.moduleRow} className="a2-fade-up d4">
            {modules.map((m, i) => (
              <div key={i} style={s.moduleChip}>
                <span style={{ ...s.moduleDot, background: m.color }}/>
                {m.label}
              </div>
            ))}
          </div>
        </div>

        <div style={s.bottomRow}>
          <div style={s.quote}>
            <div style={s.quoteText}>"We cut our audit prep from three days to about forty minutes. The QR flow alone justifies the subscription."</div>
            <div style={s.quoteWho}>— Pilot Customer · Chemical Plant, Pasir Gudang</div>
          </div>
          <div style={s.stamp}>ISO-Ready · DOSH-Aligned</div>
        </div>
      </div>

      {/* ─── RIGHT — Form panel ──────────────────────────────────────── */}
      <div className="a2-right" style={s.right}>
        <div className="a2-topnav" style={s.topNav}>
          <span>New to AegisComply?</span>
          <button className="a2-submit" style={s.topNavBtn} onClick={() => setTab(tab === 'login' ? 'register' : 'login')}>
            {tab === 'login' ? 'Start free pilot' : 'Sign in instead'}
          </button>
        </div>

        <div style={s.rightFrame} className="a2-fade-up d1">
          <div style={s.tabs}>
            <button style={{ ...s.tab, ...(tab === 'login' ? s.tabActive : {}) }} onClick={() => setTab('login')}>Sign In</button>
            <button style={{ ...s.tab, ...(tab === 'register' ? s.tabActive : {}) }} onClick={() => setTab('register')}>Create Account</button>
          </div>

          <div style={s.formTitle}>
            {tab === 'login' ? 'Welcome back.' : 'Start your 14-day pilot.'}
          </div>
          <div style={s.formSub}>
            {tab === 'login'
              ? 'Sign in to your AegisComply workspace.'
              : 'Full access. No credit card. Cancel anytime.'}
          </div>

          {tab === 'login'
            ? <LoginForm onLogin={onLogin}/>
            : <RegisterForm onLogin={onLogin} onSwitchToLogin={() => setTab('login')}/>
          }

          <div style={s.footer}>
            <div style={s.footerLock}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
              PDPA-compliant · Singapore-hosted database
            </div>
            By continuing, you agree to our Terms of Service and Privacy Policy.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreenOption2 });

})();
