// ── Auth — custom Clerk forms (sign in / sign up / reset) ──────────
// Uses clerk-js from the CDN (window.__clerk) directly, with a gorgeous,
// responsive split layout in the PaintMini home aesthetic.

function Auth({ navigate, initialMode = 'signup', onAuth }) {
  // mode: 'signin' | 'signup' | 'forgot'
  // phase: which step within the mode
  const [mode, setMode] = useState(initialMode === 'signin' ? 'signin' : 'signup');
  const [phase, setPhase] = useState('form');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [code, setCode] = useState('');
  const [secondStrategy, setSecondStrategy] = useState('totp');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  const clerk = () => window.__clerk;

  function switchMode(m) {
    setMode(m); setPhase('form'); setError(null); setCode(''); setPassword(''); setNewPassword('');
  }

  function errMsg(err) {
    return err?.errors?.[0]?.longMessage || err?.errors?.[0]?.message || err?.message || 'Something went wrong. Try again.';
  }

  async function done() {
    try {
      const { user } = await Api.me();
      if (onAuth) onAuth(user); else navigate('studio');
    } catch {
      navigate('studio');
    }
  }

  // ── Sign in ──────────────────────────────────────────────────────
  async function submitSignIn(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      if (!c) throw new Error('Auth is still loading — one moment.');
      const si = await c.client.signIn.create({ identifier: email, password });
      if (si.status === 'complete') { await c.setActive({ session: si.createdSessionId }); return done(); }
      if (si.status === 'needs_first_factor') {
        const f = (si.supportedFirstFactors || []).find(x => x.strategy === 'email_code');
        if (f?.emailAddressId) {
          await c.client.signIn.prepareFirstFactor({ strategy: 'email_code', emailAddressId: f.emailAddressId });
          setSecondStrategy('email_code'); setPhase('verify'); return;
        }
        throw new Error('This account needs a verification method that isn’t available here.');
      }
      if (si.status === 'needs_second_factor') {
        const factors = si.supportedSecondFactors || [];
        const totp = factors.find(f => f.strategy === 'totp');
        const phone = factors.find(f => f.strategy === 'phone_code');
        if (phone && !totp) { await si.prepareSecondFactor({ strategy: 'phone_code', phoneNumberId: phone.phoneNumberId }); setSecondStrategy('phone_code'); }
        else setSecondStrategy('totp');
        setPhase('two-factor'); return;
      }
      throw new Error('Sign-in needs additional steps: ' + si.status);
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  async function verifySignInCode(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      const res = await c.client.signIn.attemptFirstFactor({ strategy: 'email_code', code });
      if (res.status === 'complete') { await c.setActive({ session: res.createdSessionId }); return done(); }
      throw new Error('Verification incomplete: ' + res.status);
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  async function verifySecondFactor(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      const res = await c.client.signIn.attemptSecondFactor({ strategy: secondStrategy, code });
      if (res.status === 'complete') { await c.setActive({ session: res.createdSessionId }); return done(); }
      throw new Error('Two-factor incomplete: ' + res.status);
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  // ── Sign up ──────────────────────────────────────────────────────
  async function submitSignUp(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      if (!c) throw new Error('Auth is still loading — one moment.');
      const first = name.split(' ')[0] || undefined;
      const last = name.split(' ').slice(1).join(' ') || undefined;
      const su = await c.client.signUp.create({ emailAddress: email, password, firstName: first, lastName: last });
      if (su.status === 'complete') { await c.setActive({ session: su.createdSessionId }); return done(); }
      await su.prepareEmailAddressVerification({ strategy: 'email_code' });
      setPhase('verify');
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  async function verifySignUpCode(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      const res = await c.client.signUp.attemptEmailAddressVerification({ code });
      if (res.status === 'complete') { await c.setActive({ session: res.createdSessionId }); return done(); }
      throw new Error('Verification incomplete: ' + res.status);
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  // ── Forgot / reset password ──────────────────────────────────────
  async function requestReset(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      if (!c) throw new Error('Auth is still loading — one moment.');
      await c.client.signIn.create({ strategy: 'reset_password_email_code', identifier: email });
      setPhase('reset');
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  async function submitReset(e) {
    e.preventDefault(); setError(null); setBusy(true);
    try {
      const c = clerk();
      const res = await c.client.signIn.attemptFirstFactor({ strategy: 'reset_password_email_code', code, password: newPassword });
      if (res.status === 'complete') { await c.setActive({ session: res.createdSessionId }); return done(); }
      throw new Error('Reset needs additional steps: ' + res.status);
    } catch (err) { setError(errMsg(err)); } finally { setBusy(false); }
  }

  async function resend() {
    setError(null);
    try {
      const c = clerk();
      if (mode === 'signup') await c.client.signUp.prepareEmailAddressVerification({ strategy: 'email_code' });
      else if (mode === 'forgot') await c.client.signIn.create({ strategy: 'reset_password_email_code', identifier: email });
      else if (mode === 'signin') {
        const f = (c.client.signIn.supportedFirstFactors || []).find(x => x.strategy === 'email_code');
        if (f?.emailAddressId) await c.client.signIn.prepareFirstFactor({ strategy: 'email_code', emailAddressId: f.emailAddressId });
      }
    } catch (err) { setError(errMsg(err)); }
  }

  // ── Copy per screen ──────────────────────────────────────────────
  const isSignUp = mode === 'signup';
  const heads = {
    'signin-form':   { eb: 'sign in',        h: 'Welcome back.',        p: 'Pick up where you left off — every design is saved.' },
    'signup-form':   { eb: 'create account', h: 'Set up your studio.',  p: 'Free forever. One free credit to render your first scheme.' },
    'forgot-form':   { eb: 'password reset',  h: 'Forgot password?',    p: 'Enter your email and we’ll send a 6-digit code to reset it.' },
    'verify':        { eb: 'email code',     h: 'Check your inbox.',    p: <>We sent a 6-digit code to <b>{email}</b>. Enter it below to continue.</> },
    'two-factor':    { eb: 'two-factor',     h: 'One more step.',       p: secondStrategy === 'phone_code' ? 'Enter the code we texted to your phone.' : 'Enter the current code from your authenticator app.' },
    'reset':         { eb: 'reset · code',   h: 'Set a new password.',  p: <>Code sent to <b>{email}</b>. Enter it with your new password.</> },
  };
  const key = phase === 'form' ? `${mode}-form` : phase;
  const copy = heads[key] || heads['signin-form'];

  const codeInput = (val, set) => (
    <div className="auth-field">
      <label>Verification code</label>
      <input className="input auth-code" inputMode="numeric" autoComplete="one-time-code" placeholder="123456"
        value={val} onChange={e => set(e.target.value)} maxLength={6} required autoFocus />
    </div>
  );

  return (
    <div className="auth" data-screen-label="auth">
      <style>{`
        .auth { min-height: 100vh; display: grid; grid-template-columns: 1.02fr 1fr; background: var(--bg); }
        .auth-brand {
          position: relative; overflow: hidden; color: var(--sidebar-ink);
          padding: clamp(40px, 5vw, 64px);
          display: flex; flex-direction: column; justify-content: space-between;
          background: linear-gradient(158deg, #24513E 0%, var(--sidebar) 52%, #10231A 100%);
        }
        .auth-brand::after { content:''; position:absolute; inset:0; pointer-events:none;
          background: radial-gradient(58% 52% at 74% 24%, rgba(242,140,56,0.16), transparent 62%); }
        .auth-brand > * { position: relative; z-index: 1; }
        .auth-eyebrow { font-family: var(--mono); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; font-weight: 600; color: var(--brand-bright); }
        .auth-brand h1 { font-family: var(--serif); font-weight: 800; letter-spacing: -0.03em; line-height: 0.98; font-size: clamp(40px, 4.6vw, 66px); margin: 20px 0 18px; }
        .auth-brand h1 em { font-style: normal; color: var(--brand-bright); }
        .auth-brand p.lede { font-size: 16px; line-height: 1.6; max-width: 440px; color: var(--sidebar-ink-2); }
        .auth-feats { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; max-width: 460px; margin-top: 30px; }
        .auth-feat { padding: 14px 15px; border-radius: 12px; background: rgba(250,248,245,0.05); border: 1px solid var(--sidebar-line); }
        .auth-feat .t { display: flex; align-items: center; gap: 8px; font-family: var(--serif); font-weight: 700; font-size: 15px; }
        .auth-feat .t span.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--brand); flex: none; }
        .auth-feat .d { font-size: 12px; line-height: 1.5; color: var(--sidebar-ink-2); margin-top: 5px; }

        .auth-panel { display: flex; flex-direction: column; padding: clamp(24px, 4vw, 44px); }
        .auth-top { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
        .auth-top .switch { font-size: 13px; color: var(--ink-2); }
        .auth-top .switch a { color: var(--brand-deep); font-weight: 700; cursor: pointer; }
        .auth-body { flex: 1; display: flex; flex-direction: column; justify-content: center; padding: 28px 0; }
        .auth-form { width: 100%; max-width: 400px; margin: 0 auto; }
        .auth-form h2 { font-family: var(--serif); font-weight: 800; letter-spacing: -0.02em; line-height: 1.02; font-size: clamp(34px, 4vw, 46px); color: var(--primary-deep); margin: 12px 0 8px; }
        .auth-form p.sub { font-size: 14.5px; color: var(--ink-2); line-height: 1.55; margin: 0 0 26px; }
        .auth-field { margin-bottom: 16px; }
        .auth-form .input { width: 100%; display: block; }
        .auth-field label { display: block; font-size: 12.5px; font-weight: 600; color: var(--ink-2); margin-bottom: 7px; }
        .auth-field .row { display: flex; align-items: baseline; justify-content: space-between; }
        .auth-field .row a { font-size: 12px; color: var(--brand-deep); font-weight: 700; cursor: pointer; }
        .auth-code { letter-spacing: 0.4em; font-family: var(--mono); font-size: 18px; text-align: center; }
        .auth-err { padding: 10px 14px; border-radius: 10px; background: rgba(192,57,43,0.08); border: 1px solid rgba(192,57,43,0.3); color: var(--crimson); font-size: 13px; margin-bottom: 16px; }
        .auth-sub-link { text-align: center; margin-top: 20px; font-size: 13px; color: var(--ink-3); }
        .auth-sub-link a { color: var(--brand-deep); font-weight: 700; cursor: pointer; }
        .auth-verify-links { display: flex; justify-content: space-between; margin-top: 16px; font-size: 12.5px; }
        .auth-verify-links a { color: var(--brand-deep); font-weight: 600; cursor: pointer; }
        @media (max-width: 900px) { .auth { grid-template-columns: 1fr; } .auth-brand { display: none; } }
      `}</style>

      {/* Brand panel (desktop) */}
      <aside className="auth-brand">
        <a href="#" onClick={(e) => { e.preventDefault(); navigate('home'); }}>
          <img className="pm-logo pm-logo--dark" src="/assets/logo-new.png" alt="PaintMini" style={{ height: 30 }} />
        </a>
        <div>
          <div className="auth-eyebrow">Plan the paint job before you open a pot</div>
          <h1>See it painted<br /><em>before</em> you<br />pick up a brush.</h1>
          <p className="lede">Upload a primed mini, choose the paints on your shelf, and render a finished scheme with a full step-by-step guide.</p>
          <div className="auth-feats">
            {[
              ['Painted preview', 'Rendered on your exact sculpt'],
              ['Step-by-step', 'A technique-aware painting guide'],
              ['Your shelf', 'Built from paints you already own'],
              ['Printable PDF', 'A clean sheet for the workbench'],
            ].map(([t, d]) => (
              <div className="auth-feat" key={t}>
                <div className="t"><span className="dot" />{t}</div>
                <div className="d">{d}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="auth-eyebrow" style={{ color: 'var(--sidebar-ink-3)' }}>New painters get 1 free credit · no card required</div>
      </aside>

      {/* Form panel */}
      <div className="auth-panel">
        <div className="auth-top">
          <a href="#" onClick={(e) => { e.preventDefault(); navigate('home'); }} style={{ display: 'flex' }}>
            <img className="pm-logo" src="/assets/logo-new.png" alt="PaintMini" style={{ height: 26 }} />
          </a>
          <div className="switch">
            {mode === 'signup'
              ? <>Have an account? <a onClick={() => switchMode('signin')}>Sign in →</a></>
              : <>New here? <a onClick={() => switchMode('signup')}>Create account →</a></>}
          </div>
        </div>

        <div className="auth-body">
          <div className="auth-form">
            <div className="auth-eyebrow" style={{ color: 'var(--brand-deep)' }}>{copy.eb}</div>
            <h2>{copy.h}</h2>
            <p className="sub">{copy.p}</p>

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

            {/* ── SIGN IN — credentials ── */}
            {mode === 'signin' && phase === 'form' && (
              <form onSubmit={submitSignIn}>
                <div className="auth-field">
                  <label>Email</label>
                  <input className="input" type="email" autoComplete="email" placeholder="painter@studio.com" value={email} onChange={e => setEmail(e.target.value)} required />
                </div>
                <div className="auth-field">
                  <div className="row"><label>Password</label><a onClick={() => switchMode('forgot')}>Forgot?</a></div>
                  <input className="input" type="password" autoComplete="current-password" placeholder="••••••••" value={password} onChange={e => setPassword(e.target.value)} required minLength={8} />
                </div>
                <button type="submit" className="btn btn-gold" style={{ width: '100%', height: 50, marginTop: 6 }} disabled={busy}>{busy ? 'Signing in…' : 'Sign in ↦'}</button>
                <div className="auth-sub-link">No account? <a onClick={() => switchMode('signup')}>Create one free</a></div>
              </form>
            )}

            {/* ── SIGN UP — form ── */}
            {mode === 'signup' && phase === 'form' && (
              <form onSubmit={submitSignUp}>
                <div className="auth-field">
                  <label>Your name</label>
                  <input className="input" autoComplete="name" placeholder="Edith Marsh" value={name} onChange={e => setName(e.target.value)} />
                </div>
                <div className="auth-field">
                  <label>Email</label>
                  <input className="input" type="email" autoComplete="email" placeholder="painter@studio.com" value={email} onChange={e => setEmail(e.target.value)} required />
                </div>
                <div className="auth-field">
                  <label>Password</label>
                  <input className="input" type="password" autoComplete="new-password" placeholder="At least 8 characters" value={password} onChange={e => setPassword(e.target.value)} required minLength={8} />
                </div>
                <button type="submit" className="btn btn-gold" style={{ width: '100%', height: 50, marginTop: 6 }} disabled={busy}>{busy ? 'Creating…' : 'Create account ↦'}</button>
                <div className="auth-sub-link">By continuing you agree to the terms & privacy policy.</div>
              </form>
            )}

            {/* ── FORGOT — request ── */}
            {mode === 'forgot' && phase === 'form' && (
              <form onSubmit={requestReset}>
                <div className="auth-field">
                  <label>Email</label>
                  <input className="input" type="email" autoComplete="email" placeholder="painter@studio.com" value={email} onChange={e => setEmail(e.target.value)} required />
                </div>
                <button type="submit" className="btn btn-gold" style={{ width: '100%', height: 50, marginTop: 6 }} disabled={busy}>{busy ? 'Sending…' : 'Send reset code'}</button>
                <div className="auth-sub-link"><a onClick={() => switchMode('signin')}>← Back to sign in</a></div>
              </form>
            )}

            {/* ── VERIFY (signup email OR signin email-code) ── */}
            {phase === 'verify' && (
              <form onSubmit={mode === 'signup' ? verifySignUpCode : verifySignInCode}>
                {codeInput(code, setCode)}
                <button type="submit" className="btn btn-gold" style={{ width: '100%', height: 50, marginTop: 6 }} disabled={busy}>{busy ? 'Verifying…' : 'Verify ↦'}</button>
                <div className="auth-verify-links">
                  <a onClick={() => switchMode(mode)}>← Start over</a>
                  <a onClick={resend}>Resend code</a>
                </div>
              </form>
            )}

            {/* ── TWO-FACTOR ── */}
            {phase === 'two-factor' && (
              <form onSubmit={verifySecondFactor}>
                <div className="auth-field">
                  <label>{secondStrategy === 'phone_code' ? 'SMS code' : 'Authenticator code'}</label>
                  <input className="input auth-code" inputMode="numeric" autoComplete="one-time-code" placeholder="123456" value={code} onChange={e => setCode(e.target.value)} maxLength={8} required autoFocus />
                </div>
                <button type="submit" className="btn btn-gold" style={{ width: '100%', height: 50, marginTop: 6 }} disabled={busy}>{busy ? 'Verifying…' : 'Verify ↦'}</button>
                <div className="auth-verify-links"><a onClick={() => switchMode('signin')}>← Back to sign in</a></div>
              </form>
            )}

            {/* ── RESET (code + new password) ── */}
            {phase === 'reset' && (
              <form onSubmit={submitReset}>
                {codeInput(code, setCode)}
                <div className="auth-field">
                  <label>New password</label>
                  <input className="input" type="password" autoComplete="new-password" placeholder="At least 8 characters" value={newPassword} onChange={e => setNewPassword(e.target.value)} required minLength={8} />
                </div>
                <button type="submit" className="btn btn-gold" style={{ width: '100%', height: 50, marginTop: 6 }} disabled={busy}>{busy ? 'Resetting…' : 'Reset & sign in ↦'}</button>
                <div className="auth-verify-links">
                  <a onClick={() => switchMode('forgot')}>← Different email</a>
                  <a onClick={resend}>Resend code</a>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Auth });
