/* ===== Authentication screens (React) ==================================
   Split-screen auth UI gating the Sectionly dashboard. Talks to window.Auth.
   Exposes <AuthApp> (the gate's signed-out experience) on window.
   ===================================================================== */

/* extra icons used only by auth (others come from window.ICONS in data.js) */
window.ICONS['eye-off'] = '<path d="M3 3l18 18M10.6 10.7a3 3 0 0 0 4 4M9.9 4.6A9.6 9.6 0 0 1 12 4.4c6.5 0 10 7.6 10 7.6a17 17 0 0 1-2.2 3.2M6.1 6.2A17 17 0 0 0 2 12s3.5 7.6 10 7.6a9.3 9.3 0 0 0 3.9-.8"/>';
window.ICONS['key'] = '<circle cx="8" cy="14" r="4.5"/><path d="M11.5 11.5 20 3M17 6l2.5 2.5M14.5 8.5 17 11"/>';
window.ICONS['send'] = '<path d="M21 3 10.5 13.5M21 3l-6.5 18-4-8-8-4L21 3Z"/>';
window.ICONS['shield-check'] = '<path d="M12 3l8 3v5c0 5-3.4 8.5-8 10-4.6-1.5-8-5-8-10V6l8-3Z"/><path d="M9 11.5 11 13.5 15 9.5"/>';

/* ---- Google "G" logo (multi-color, not a stroke icon) ---- */
function GoogleG({ size }) {
  size = size || 19;
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#4285F4" d="M45.1 24.5c0-1.6-.1-2.7-.4-3.9H24v7.1h12.1c-.2 1.8-1.6 4.6-4.5 6.5l6.6 5.1c4-3.7 6.9-9.1 6.9-14.8z" />
      <path fill="#34A853" d="M24 46c5.9 0 10.9-1.9 14.5-5.3l-6.6-5.1c-1.8 1.2-4.2 2-7.9 2-6 0-11.1-4-12.9-9.6l-6.8 5.3C7.5 40.9 15.1 46 24 46z" />
      <path fill="#FBBC05" d="M11.1 28c-.5-1.4-.7-2.9-.7-4.5s.3-3.1.7-4.5l-6.8-5.3C2.6 16.5 2 20.2 2 24s.6 7.5 2.3 10.3L11.1 28z" />
      <path fill="#EA4335" d="M24 9.9c3.3 0 5.6 1.4 6.9 2.6l5.8-5.7C33.9 3.4 29.9 2 24 2 15.1 2 7.5 7.1 4.3 14.2l6.8 5.3C12.9 13.9 18 9.9 24 9.9z" />
    </svg>
  );
}
function GoogleWordmark() {
  const cols = [['G', '#4285F4'], ['o', '#EA4335'], ['o', '#FBBC05'], ['g', '#4285F4'], ['l', '#34A853'], ['e', '#EA4335']];
  return (
    <span style={{ fontFamily: 'Inter, Roboto, Arial, sans-serif', fontWeight: 500, fontSize: 17, letterSpacing: '-.5px' }}>
      {cols.map(([c, col], i) => <span key={i} style={{ color: col }}>{c}</span>)}
    </span>
  );
}

/* ---- shared field with leading icon + optional show/hide ---- */
function AuthInput({ icon, type, value, onChange, placeholder, autoComplete, state, onBlur, onKeyDown, inputRef, name }) {
  const [show, setShow] = useState(false);
  const isPw = type === 'password';
  const realType = isPw ? (show ? 'text' : 'password') : type;
  return (
    <div className={'auth-input' + (isPw ? ' has-toggle' : '') + (state === 'err' ? ' err' : state === 'ok' ? ' ok' : '')}>
      <span className="ai-lead"><Icon name={icon} size={17} /></span>
      <input ref={inputRef} type={realType} value={value} name={name}
        onChange={e => onChange(e.target.value)} onBlur={onBlur} onKeyDown={onKeyDown}
        placeholder={placeholder} autoComplete={autoComplete} />
      {isPw &&
        <button type="button" className="auth-eye" tabIndex={-1} onClick={() => setShow(s => !s)}
          aria-label={show ? 'Hide password' : 'Show password'}>
          <Icon name={show ? 'eye-off' : 'eye'} size={18} />
        </button>}
    </div>
  );
}

function Alert({ children }) {
  if (!children) return null;
  return <div className="auth-alert"><Icon name="shield" size={17} /><span>{children}</span></div>;
}

function SubmitBtn({ busy, children, disabled }) {
  return (
    <button type="submit" className="auth-submit" disabled={busy || disabled}>
      {busy ? <span className="spin" /> : children}
    </button>
  );
}

/* ---- left brand panel ---- */
function BrandPanel() {
  return (
    <div className="auth-brand">
      <div className="auth-brand-logo">
        <img src={window.assetUrl('app/assets/sectionly-logo.png')} alt="Sectionly" />
      </div>
      <div className="auth-brand-body">
        <div className="auth-brand-eyebrow">Section Templates Dashboard</div>
        <h1>Ship beautiful pages, section by section.</h1>
        <p>Your library of production-ready frontend sections — browse, customize and copy clean HTML &amp; React in seconds.</p>
        <ul className="auth-feats">
          <li><span className="af-ico"><Icon name="library" size={16} /></span> 120+ curated, responsive sections</li>
          <li><span className="af-ico"><Icon name="copy" size={16} /></span> Copy-paste HTML &amp; React, no lock-in</li>
          <li><span className="af-ico"><Icon name="heart" size={16} /></span> Favorites &amp; collections that sync</li>
        </ul>
      </div>
      <div className="auth-brand-foot">© {new Date().getFullYear()} Sectionly · Crafted for frontend developers</div>
    </div>
  );
}

/* ====================================================================
   Sign in
   ==================================================================== */
function SignInScreen({ ctx }) {
  const [email, setEmail] = useState(ctx.email || '');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [touched, setTouched] = useState({});
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const emailBad = touched.email && !window.Auth.validEmail(email.trim().toLowerCase());

  const submit = (e) => {
    e.preventDefault();
    setErr('');
    setBusy(true);
    window.Auth.signIn({ email, password, remember })
      .then(u => ctx.onAuthed(u))
      .catch(ex => {
        setBusy(false);
        if (ex && ex.needVerify) { ctx.go('verify', { email: ex.email, devCode: ex.verifyCode, name: '' }); return; }
        setErr(ex.message || 'Could not sign in.');
      });
  };

  return (
    <form className="auth-card" onSubmit={submit} noValidate>
      <div className="auth-card-logo"><img src={window.assetUrl('app/assets/sectionly-logo.png')} alt="Sectionly" /></div>
      <div className="auth-head">
        <h2>Welcome back</h2>
        <p>Sign in to your Sectionly account to continue.</p>
      </div>
      <div className="auth-form">
        <Alert>{err}</Alert>
        <GoogleButton ctx={ctx} setErr={setErr} remember={remember} />
        <div className="auth-divider">or sign in with email</div>
        <div className="auth-field">
          <label>Email</label>
          <AuthInput icon="mail" type="email" value={email} onChange={setEmail} placeholder="you@company.com"
            autoComplete="email" state={emailBad ? 'err' : ''} onBlur={() => setTouched(t => ({ ...t, email: true }))} />
          {emailBad && <span className="auth-fielderr"><Icon name="shield" size={13} /> Enter a valid email address.</span>}
        </div>
        <div className="auth-field">
          <div className="auth-optrow">
            <label>Password</label>
            <button type="button" className="auth-link" onClick={() => ctx.go('forgot', { email })}>Forgot password?</button>
          </div>
          <AuthInput icon="lock" type="password" value={password} onChange={setPassword} placeholder="Enter your password" autoComplete="current-password" />
        </div>
        <label className="auth-check">
          <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} />
          <span className="ac-box"><Icon name="check" size={12} /></span>
          Keep me signed in
        </label>
        <SubmitBtn busy={busy} disabled={!email || !password}>Sign in</SubmitBtn>
        <div className="auth-note">
          <Icon name="key" size={16} />
          <span>Demo account — email <b>ashraf@sectionly.app</b>, password <b>password123</b>. Or create your own below.</span>
        </div>
      </div>
      <div className="auth-foot">
        Don’t have an account? <button type="button" className="auth-link" onClick={() => ctx.go('signup', { email })}>Sign up free</button>
      </div>
    </form>
  );
}

/* ====================================================================
   Sign up
   ==================================================================== */
function passwordChecks(pw) {
  return {
    len: pw.length >= 8,
    alpha: /[a-zA-Z]/.test(pw),
    num: /[0-9]/.test(pw)
  };
}
function SignUpScreen({ ctx }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState(ctx.email || '');
  const [password, setPassword] = useState('');
  const [touched, setTouched] = useState({});
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const checks = passwordChecks(password);
  const pwOk = checks.len && checks.alpha && checks.num;
  const emailBad = touched.email && !window.Auth.validEmail(email.trim().toLowerCase());
  const canSubmit = name.trim() && window.Auth.validEmail(email.trim().toLowerCase()) && pwOk;

  const submit = (e) => {
    e.preventDefault();
    setErr('');
    setBusy(true);
    window.Auth.signUp({ name, email, password })
      .then(res => {
        setBusy(false);
        // local mode returns { user, verifyCode }; server mode signs in directly
        if (res && res.verifyCode != null) ctx.go('verify', { email: email.trim().toLowerCase(), name: name.trim(), devCode: res.verifyCode });
        else if (res && (res.verified === false)) ctx.go('verify', { email: email.trim().toLowerCase(), name: name.trim(), devCode: null });
        else ctx.onAuthed(res);
      })
      .catch(ex => { setBusy(false); setErr(ex.message || 'Could not create your account.'); });
  };

  const rules = [['len', 'At least 8 characters'], ['alpha', 'Contains a letter'], ['num', 'Contains a number']];

  return (
    <form className="auth-card" onSubmit={submit} noValidate>
      <div className="auth-card-logo"><img src={window.assetUrl('app/assets/sectionly-logo.png')} alt="Sectionly" /></div>
      <div className="auth-head">
        <h2>Create your account</h2>
        <p>Start building with the Sectionly library — free, no card required.</p>
      </div>
      <div className="auth-form">
        <Alert>{err}</Alert>
        <GoogleButton ctx={ctx} setErr={setErr} label="Sign up with Google" remember={true} />
        <div className="auth-divider">or sign up with email</div>
        <div className="auth-field">
          <label>Full name</label>
          <AuthInput icon="user" type="text" value={name} onChange={setName} placeholder="Jane Doe" autoComplete="name" />
        </div>
        <div className="auth-field">
          <label>Email</label>
          <AuthInput icon="mail" type="email" value={email} onChange={setEmail} placeholder="you@company.com"
            autoComplete="email" state={emailBad ? 'err' : ''} onBlur={() => setTouched(t => ({ ...t, email: true }))} />
          {emailBad && <span className="auth-fielderr"><Icon name="shield" size={13} /> Enter a valid email address.</span>}
        </div>
        <div className="auth-field">
          <label>Password</label>
          <AuthInput icon="lock" type="password" value={password} onChange={setPassword} placeholder="Create a password" autoComplete="new-password" />
          {password.length > 0 &&
            <div className="auth-rules">
              {rules.map(([k, lbl]) =>
                <div key={k} className={'auth-rule' + (checks[k] ? ' met' : '')}>
                  <span className="ar-tick"><Icon name="check" size={11} /></span>{lbl}
                </div>)}
            </div>}
        </div>
        <SubmitBtn busy={busy} disabled={!canSubmit}>Create account</SubmitBtn>
        <p className="auth-hint" style={{ textAlign: 'center' }}>
          By creating an account you agree to our Terms &amp; Privacy Policy.
        </p>
      </div>
      <div className="auth-foot">
        Already have an account? <button type="button" className="auth-link" onClick={() => ctx.go('signin', { email })}>Sign in</button>
      </div>
    </form>
  );
}

/* ---- Google chooser trigger button + modal ---- */
function GoogleButton({ ctx, setErr, label, remember }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button type="button" className="auth-google" onClick={() => setOpen(true)}>
        <GoogleG size={19} /> {label || 'Continue with Google'}
      </button>
      {open && <GoogleChooser onClose={() => setOpen(false)}
        onPick={(acct) => {
          setOpen(false);
          window.Auth.signInGoogle(acct, remember)
            .then(u => ctx.onAuthed(u))
            .catch(ex => setErr && setErr(ex.message || 'Google sign-in failed.'));
        }} />}
    </>
  );
}

const DEMO_GOOGLE = [
  { name: 'Ashraf Hossain', email: 'ashraf.hossain@gmail.com', color: '#7c4dff' },
  { name: 'Maya Chen', email: 'maya.chen@gmail.com', color: '#1a9d5a' }
];
function GoogleChooser({ onClose, onPick }) {
  const [other, setOther] = useState(false);
  const [oName, setOName] = useState('');
  const [oEmail, setOEmail] = useState('');
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  const otherOk = oName.trim() && window.Auth.validEmail(oEmail.trim().toLowerCase());
  return (
    <div className="gc-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="gc-modal" role="dialog" aria-modal="true">
        <div className="gc-head">
          <div className="gc-glogo"><GoogleWordmark /></div>
          <h3>Choose an account</h3>
          <p>to continue to <b>Sectionly</b></p>
        </div>
        {!other ? (
          <>
            <div className="gc-list">
              {DEMO_GOOGLE.map(a =>
                <button key={a.email} className="gc-acct" onClick={() => onPick(a)}>
                  <span className="gc-ava" style={{ background: a.color }}>{initials(a.name)}</span>
                  <span className="gc-acct-meta"><b>{a.name}</b><span>{a.email}</span></span>
                </button>)}
            </div>
            <button className="gc-other" onClick={() => setOther(true)}>
              <span className="gc-ava"><Icon name="user" size={18} /></span>
              <span>Use another account</span>
            </button>
          </>
        ) : (
          <div style={{ padding: '18px 24px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div className="auth-field">
              <label style={{ fontSize: 13, fontWeight: 600 }}>Name</label>
              <AuthInput icon="user" type="text" value={oName} onChange={setOName} placeholder="Your name" />
            </div>
            <div className="auth-field">
              <label style={{ fontSize: 13, fontWeight: 600 }}>Email</label>
              <AuthInput icon="mail" type="email" value={oEmail} onChange={setOEmail} placeholder="you@gmail.com" />
            </div>
            <button className="auth-submit" disabled={!otherOk}
              onClick={() => onPick({ name: oName.trim(), email: oEmail.trim().toLowerCase(), color: '#4285F4' })}>Continue</button>
          </div>
        )}
        <div className="gc-foot">
          To continue, Google will share your name and email address with Sectionly. This is a simulated chooser for the demo.
        </div>
      </div>
    </div>
  );
}

/* ====================================================================
   Verify email
   ==================================================================== */
function VerifyScreen({ ctx }) {
  const len = 6;
  const [digits, setDigits] = useState(Array(len).fill(''));
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const [devCode, setDevCode] = useState(ctx.devCode || null);
  const refs = useRef([]);

  useEffect(() => { if (refs.current[0]) refs.current[0].focus(); }, []);

  const setAt = (i, v) => {
    v = v.replace(/\D/g, '');
    setDigits(prev => {
      const next = prev.slice();
      if (v.length > 1) { // paste
        for (let k = 0; k < len; k++) next[k] = v[k] || '';
        return next;
      }
      next[i] = v;
      return next;
    });
    if (v && i < len - 1 && refs.current[i + 1]) refs.current[i + 1].focus();
  };
  const onKey = (i, e) => {
    if (e.key === 'Backspace' && !digits[i] && i > 0) refs.current[i - 1].focus();
  };

  const code = digits.join('');
  const submit = (e) => {
    e && e.preventDefault();
    setErr(''); setBusy(true);
    window.Auth.verifyEmail(ctx.email, code)
      .then(u => ctx.onAuthed(u))
      .catch(ex => { setBusy(false); setErr(ex.message || 'That code is not correct.'); });
  };
  useEffect(() => { if (code.length === len) submit(); /* auto-submit */ }, [code]);

  const resend = () => {
    setErr('');
    window.Auth.resendVerification(ctx.email).then(res => {
      if (res && res.verifyCode) setDevCode(res.verifyCode);
    });
  };

  return (
    <form className="auth-card" onSubmit={submit} noValidate>
      <button type="button" className="auth-back" onClick={() => ctx.go('signin', { email: ctx.email })}>
        <Icon name="back" size={16} /> Back to sign in
      </button>
      <div className="auth-bigico"><Icon name="mail" size={28} /></div>
      <div className="auth-head">
        <h2>Verify your email</h2>
        <p>We sent a 6-digit code to <b>{ctx.email}</b>. Enter it below to activate your account.</p>
      </div>
      <div className="auth-form">
        <Alert>{err}</Alert>
        <div className="auth-code">
          {digits.map((d, i) =>
            <input key={i} ref={el => refs.current[i] = el} inputMode="numeric" maxLength={i === 0 ? len : 1}
              className={d ? 'filled' : ''} value={d}
              onChange={e => setAt(i, e.target.value)} onKeyDown={e => onKey(i, e)} />)}
        </div>
        {devCode &&
          <div className="auth-note">
            <Icon name="key" size={16} />
            <span>This is a demo, so no real email is sent. Your verification code is <b>{devCode}</b>.</span>
          </div>}
        <SubmitBtn busy={busy} disabled={code.length !== len}>Verify &amp; continue</SubmitBtn>
        <p className="auth-hint" style={{ textAlign: 'center' }}>
          Didn’t get a code? <button type="button" className="auth-link" onClick={resend}>Resend</button>
        </p>
      </div>
    </form>
  );
}

/* ====================================================================
   Forgot password
   ==================================================================== */
function ForgotScreen({ ctx }) {
  const [email, setEmail] = useState(ctx.email || '');
  const [busy, setBusy] = useState(false);
  const [sent, setSent] = useState(false);
  const [resetToken, setResetToken] = useState(null);
  const [err, setErr] = useState('');

  const submit = (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    window.Auth.requestReset(email)
      .then(res => { setBusy(false); setSent(true); setResetToken(res && res.resetToken); })
      .catch(ex => { setBusy(false); setErr(ex.message || 'Something went wrong.'); });
  };

  if (sent) {
    return (
      <div className="auth-card">
        <button type="button" className="auth-back" onClick={() => ctx.go('signin', { email })}>
          <Icon name="back" size={16} /> Back to sign in
        </button>
        <div className="auth-bigico ok"><Icon name="send" size={26} /></div>
        <div className="auth-head">
          <h2>Check your inbox</h2>
          <p>If an account exists for <b>{email}</b>, we’ve sent a link to reset your password.</p>
        </div>
        <div className="auth-form">
          {resetToken
            ? <>
                <div className="auth-note">
                  <Icon name="key" size={16} />
                  <span>Demo mode — no real email is sent. Continue to set a new password using your reset link.</span>
                </div>
                <button className="auth-submit" onClick={() => ctx.go('reset', { email, resetToken })}>Set a new password</button>
              </>
            : <div className="auth-note">
                <Icon name="mail" size={16} />
                <span>Follow the link in the email to choose a new password. The link expires in 30 minutes.</span>
              </div>}
          <p className="auth-hint" style={{ textAlign: 'center' }}>
            Wrong email? <button type="button" className="auth-link" onClick={() => setSent(false)}>Try again</button>
          </p>
        </div>
      </div>
    );
  }

  return (
    <form className="auth-card" onSubmit={submit} noValidate>
      <button type="button" className="auth-back" onClick={() => ctx.go('signin', { email })}>
        <Icon name="back" size={16} /> Back to sign in
      </button>
      <div className="auth-bigico"><Icon name="lock" size={26} /></div>
      <div className="auth-head">
        <h2>Reset your password</h2>
        <p>Enter the email linked to your account and we’ll send you a reset link.</p>
      </div>
      <div className="auth-form">
        <Alert>{err}</Alert>
        <div className="auth-field">
          <label>Email</label>
          <AuthInput icon="mail" type="email" value={email} onChange={setEmail} placeholder="you@company.com" autoComplete="email" />
        </div>
        <SubmitBtn busy={busy} disabled={!email}>Send reset link</SubmitBtn>
      </div>
    </form>
  );
}

/* ====================================================================
   Reset password (consume token)
   ==================================================================== */
function ResetScreen({ ctx }) {
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [done, setDone] = useState(false);

  const checks = passwordChecks(password);
  const pwOk = checks.len && checks.alpha && checks.num;
  const match = confirm.length > 0 && confirm === password;
  const canSubmit = pwOk && match;

  const submit = (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    window.Auth.resetPassword(ctx.resetToken, password)
      .then(res => { setBusy(false); setDone(true); })
      .catch(ex => { setBusy(false); setErr(ex.message || 'This reset link is invalid or has expired.'); });
  };

  if (done) {
    return (
      <div className="auth-card">
        <div className="auth-bigico ok"><Icon name="shield-check" size={28} /></div>
        <div className="auth-head">
          <h2>Password updated</h2>
          <p>Your password has been changed. You can now sign in with your new password.</p>
        </div>
        <div className="auth-form">
          <button className="auth-submit" onClick={() => ctx.go('signin', { email: ctx.email })}>Back to sign in</button>
        </div>
      </div>
    );
  }

  const rules = [['len', 'At least 8 characters'], ['alpha', 'Contains a letter'], ['num', 'Contains a number']];
  return (
    <form className="auth-card" onSubmit={submit} noValidate>
      <div className="auth-bigico"><Icon name="key" size={26} /></div>
      <div className="auth-head">
        <h2>Choose a new password</h2>
        <p>Pick a strong password you don’t use anywhere else.</p>
      </div>
      <div className="auth-form">
        <Alert>{err}</Alert>
        <div className="auth-field">
          <label>New password</label>
          <AuthInput icon="lock" type="password" value={password} onChange={setPassword} placeholder="New password" autoComplete="new-password" />
          {password.length > 0 &&
            <div className="auth-rules">
              {rules.map(([k, lbl]) =>
                <div key={k} className={'auth-rule' + (checks[k] ? ' met' : '')}>
                  <span className="ar-tick"><Icon name="check" size={11} /></span>{lbl}
                </div>)}
            </div>}
        </div>
        <div className="auth-field">
          <label>Confirm password</label>
          <AuthInput icon="lock" type="password" value={confirm} onChange={setConfirm} placeholder="Re-enter password"
            autoComplete="new-password" state={confirm.length > 0 ? (match ? 'ok' : 'err') : ''} />
          {confirm.length > 0 && !match && <span className="auth-fielderr"><Icon name="shield" size={13} /> Passwords don’t match.</span>}
        </div>
        <SubmitBtn busy={busy} disabled={!canSubmit}>Update password</SubmitBtn>
      </div>
    </form>
  );
}

/* ====================================================================
   AuthApp — the signed-out experience (split layout + screen router)
   ==================================================================== */
function AuthApp({ onAuthed, theme, toggleTheme }) {
  const [screen, setScreen] = useState('signin');
  const [ctxData, setCtxData] = useState({ email: '' });

  const go = useCallback((next, patch) => {
    setCtxData(prev => Object.assign({}, prev, patch || {}));
    setScreen(next);
    const p = document.querySelector('.auth-panel'); if (p) p.scrollTop = 0;
  }, []);

  const ctx = Object.assign({}, ctxData, { go, onAuthed });

  let body;
  if (screen === 'signup') body = <SignUpScreen ctx={ctx} />;
  else if (screen === 'verify') body = <VerifyScreen ctx={ctx} />;
  else if (screen === 'forgot') body = <ForgotScreen ctx={ctx} />;
  else if (screen === 'reset') body = <ResetScreen ctx={ctx} />;
  else body = <SignInScreen ctx={ctx} />;

  return (
    <div className="auth">
      <BrandPanel />
      <div className="auth-panel">
        <button className="auth-theme" onClick={toggleTheme} title="Toggle theme" aria-label="Toggle theme">
          <Icon name={theme === 'light' ? 'moon' : 'sun'} size={18} />
        </button>
        <div key={screen}>{body}</div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthApp, GoogleG, GoogleWordmark });
