// WeWire applicant — email sign-in (OTP + magic link).

function ScreenAuthEmail({ onSent, onBack, mode }) {
  const [email, setEmail] = React.useState(() => WWAuth.getEmail() || '');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const submit = async (e) => {
    e?.preventDefault();
    setError('');
    const trimmed = email.trim();
    if (!/.+@.+\..+/.test(trimmed)) {
      setError('Enter a valid email address.');
      return;
    }
    setLoading(true);
    try {
      const res = await WWAuth.requestCode(trimmed);
      onSent(trimmed, res);
    } catch (err) {
      const msg = err.message || 'Something went wrong.';
      if (/failed to fetch/i.test(msg)) {
        setError('Could not reach the server. Check your connection and try again.');
      } else if (/RESEND|email|send/i.test(msg)) {
        setError(msg);
      } else {
        setError(msg);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Screen footer={
      <Btn variant="primary" full onClick={submit} disabled={loading || !email.trim()} icon="arrow">
        {loading ? 'Sending…' : 'Send sign-in code'}
      </Btn>
    }>
      <TopBar title="" onBack={onBack} />
      <div style={{ marginTop: 20, width: 56, height: 56, borderRadius: 16, background: WW.orangeSoft,
        display: 'grid', placeItems: 'center', color: WW.orangeDeep }}>
        <Icon name="user" size={28} />
      </div>
      <Eyebrow style={{ marginTop: 22 }}>
        {mode === 'resume' ? 'Welcome back' : 'Sign in to apply'}
      </Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 28, letterSpacing: '-0.02em', margin: '10px 0 12px' }}>
        {mode === 'resume' ? 'Continue your application' : 'Enter your email'}
      </h1>
      <p style={{ fontSize: 15, color: WW.muted, lineHeight: 1.55, marginBottom: 22 }}>
        We'll send a 6-digit code so you can save progress and pick up on any device — today or weeks from now.
      </p>
      <Field label="Email address" hint="Personal or student — we'll send your sign-in code here.">
        <TextInput type="email" value={email} onChange={(e) => setEmail(e.target.value)}
          placeholder="you@example.com" autoComplete="email" onKeyDown={(e) => e.key === 'Enter' && submit()} />
      </Field>
      {error && (
        <Card pad={14} style={{ background: WW.redSoft, border: 'none', marginTop: 4 }}>
          <div style={{ fontSize: 13, color: WW.red, lineHeight: 1.45 }}>{error}</div>
        </Card>
      )}
      <Card pad={16} style={{ background: WW.sand, border: 'none', marginTop: 16 }}>
        <div style={{ fontSize: 13, color: WW.muted, lineHeight: 1.5 }}>
          Your application is tied to this email. Close the tab anytime — your place is saved after each step.
        </div>
      </Card>
    </Screen>
  );
}

function ScreenAuthVerify({ email, devHint, onVerified, onBack, onResend }) {
  const [code, setCode] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [resent, setResent] = React.useState(false);
  const [dev, setDev] = React.useState(devHint);

  const submit = async () => {
    setError('');
    if (code.trim().length < 6) {
      setError('Enter the 6-digit code from your email.');
      return;
    }
    setLoading(true);
    try {
      const data = await WWAuth.verifyCode(email, code.trim());
      await WWAuth.flushSession();
      onVerified(data.session);
    } catch (err) {
      setError(err.message || 'Verification failed.');
    } finally {
      setLoading(false);
    }
  };

  const resend = async () => {
    setError('');
    setResent(false);
    setLoading(true);
    try {
      const res = await WWAuth.requestCode(email);
      if (res.dev) setDev(res.dev);
      setResent(true);
      setCode('');
    } catch (err) {
      setError(err.message || 'Could not resend.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Screen footer={
      <Btn variant="primary" full onClick={submit} disabled={loading || code.trim().length < 6} icon="check">
        {loading ? 'Verifying…' : 'Verify & continue'}
      </Btn>
    }>
      <TopBar title="" onBack={onBack} />
      <Eyebrow style={{ marginTop: 24 }}>Check your inbox</Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 28, letterSpacing: '-0.02em', margin: '10px 0 12px' }}>
        Enter your code
      </h1>
      <p style={{ fontSize: 15, color: WW.muted, lineHeight: 1.55 }}>
        We sent a 6-digit code to <b style={{ color: WW.ink }}>{email}</b>. It expires in 15 minutes.
      </p>

      {dev && (
        <Card pad={16} style={{ background: WW.blueSoft, border: 'none', marginTop: 18 }}>
          <Eyebrow color={WW.blue} style={{ fontSize: 10 }}>Dev preview</Eyebrow>
          <div style={{ fontSize: 14, color: WW.ink, marginTop: 8, lineHeight: 1.5 }}>
            Code: <b style={{ fontFamily: 'ui-monospace, monospace', letterSpacing: '0.2em' }}>{dev.code}</b>
          </div>
          <div style={{ fontSize: 12, color: WW.muted, marginTop: 8 }}>
            Also printed in the terminal where <code>npm start</code> is running.
          </div>
        </Card>
      )}

      <Field label="6-digit code">
        <TextInput value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
          placeholder="000000" inputMode="numeric" autoComplete="one-time-code"
          style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, letterSpacing: '0.35em', textAlign: 'center' }}
          onKeyDown={(e) => e.key === 'Enter' && submit()} />
      </Field>

      {error && (
        <Card pad={14} style={{ background: WW.redSoft, border: 'none' }}>
          <div style={{ fontSize: 13, color: WW.red }}>{error}</div>
        </Card>
      )}

      {resent && (
        <div style={{ fontSize: 13, color: WW.green, fontWeight: 600, marginTop: 8 }}>New code sent.</div>
      )}

      <div style={{ textAlign: 'center', marginTop: 20, fontSize: 14, color: WW.muted }}>
        Didn't get it?{' '}
        <button type="button" onClick={resend} disabled={loading}
          style={{ background: 'none', border: 'none', color: WW.orange, fontWeight: 700, cursor: 'pointer', fontSize: 14 }}>
          Resend code
        </button>
      </div>
    </Screen>
  );
}

function ScreenAuthLoading({ message }) {
  return (
    <div style={{ minHeight: '100%', height: '100%', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', background: WW.cream, padding: 32 }}>
      <div style={{ width: 48, height: 48, borderRadius: '50%', border: `3px solid ${WW.sand}`,
        borderTopColor: WW.orange, animation: 'ww-spin 0.8s linear infinite' }} />
      <p style={{ marginTop: 20, fontSize: 15, color: WW.muted }}>{message || 'Loading your application…'}</p>
      <style>{'@keyframes ww-spin { to { transform: rotate(360deg); } }'}</style>
    </div>
  );
}

Object.assign(window, { ScreenAuthEmail, ScreenAuthVerify, ScreenAuthLoading });
