// screen-login.jsx — magic-link sign in. Matches the Midnight Indigo look.

function LoginScreen({ theme }) {
  const [email, setEmail] = React.useState('');
  const [code, setCode] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const valid = /\S+@\S+\.\S+/.test(email);

  const submit = async () => {
    if (!valid || busy) return;
    setBusy(true); setErr('');
    const { error } = await SBAuth.signIn(email);
    setBusy(false);
    if (error) setErr(error.message); else setSent(true);
  };

  const verify = async () => {
    if (code.length < 6 || busy) return;
    setBusy(true); setErr('');
    const { error } = await SBAuth.verifyCode(email, code);
    setBusy(false);
    if (error) setErr(error.message);
    // on success, the auth listener in phone-app swaps straight to the app
  };

  const field = {
    width: '100%', padding: '14px 16px', borderRadius: 14,
    background: theme.surface, color: theme.text,
    border: `0.5px solid ${theme.borderStrong}`,
    fontSize: 16, fontFamily: 'inherit', outline: 'none', letterSpacing: -0.2,
  };

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center',
      padding: '0 28px', position: 'relative', zIndex: 5,
    }}>
      <div style={{ marginBottom: 28 }}>
        <img src="apple-touch-icon.png" alt="Sharp Sales" style={{
          width: 64, height: 64, borderRadius: 16, marginBottom: 20, display: 'block',
          boxShadow: '0 8px 24px rgba(95,90,240,0.45)',
        }} />
        <div style={{
          fontSize: 30, fontWeight: 700, color: theme.text, letterSpacing: -0.6,
          ...(theme.titleFade ? {
            background: 'linear-gradient(95deg, rgba(255,255,255,0.45) 0%, #FFFFFF 40%)',
            WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent',
          } : {}),
        }}>Your day, sorted.</div>
        <div style={{ fontSize: 15, color: theme.textMute, marginTop: 6, letterSpacing: -0.1 }}>
          Sign in to your tracker.
        </div>
      </div>

      {sent ? (
        <React.Fragment>
          <div style={{ fontSize: 14, color: theme.textMute, marginBottom: 10, lineHeight: 1.45 }}>
            We emailed a 6-digit code to <strong style={{ color: theme.text }}>{email}</strong>.
            Type it in below, no need to leave the app.
          </div>
          <input
            type="text" inputMode="numeric" autoComplete="one-time-code" maxLength={10}
            placeholder="Enter code" value={code}
            onChange={e => setCode(e.target.value.replace(/\D/g, ''))}
            onKeyDown={e => { if (e.key === 'Enter') verify(); }}
            style={{ ...field, letterSpacing: 8, textAlign: 'center', fontSize: 22, fontWeight: 600 }}
          />
          {err && <div style={{ color: theme.red, fontSize: 13, marginTop: 8 }}>{err}</div>}
          <button onClick={verify} disabled={code.length < 6 || busy} style={{
            marginTop: 12, width: '100%', padding: '15px 16px', borderRadius: 14, border: 'none',
            cursor: code.length >= 6 && !busy ? 'pointer' : 'default',
            background: code.length >= 6 ? (theme.accentGrad || theme.blue) : theme.chip,
            color: code.length >= 6 ? '#fff' : theme.textDim,
            fontFamily: 'inherit', fontSize: 16, fontWeight: 600, letterSpacing: -0.2,
            boxShadow: code.length >= 6 ? '0 8px 20px rgba(95,90,240,0.40)' : 'none',
          }}>{busy ? 'Verifying…' : 'Verify & sign in'}</button>
          <button onClick={() => { setSent(false); setCode(''); setErr(''); }} style={{
            border: 'none', background: 'transparent', color: theme.blue, display: 'block',
            fontFamily: 'inherit', fontSize: 14, fontWeight: 600, padding: 0, cursor: 'pointer',
            margin: '16px auto 0',
          }}>Use a different email</button>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <input
            type="email" inputMode="email" autoCapitalize="none" autoCorrect="off"
            placeholder="you@email.com" value={email}
            onChange={e => setEmail(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') submit(); }}
            style={field}
          />
          {err && <div style={{ color: theme.red, fontSize: 13, marginTop: 8 }}>{err}</div>}
          <button onClick={submit} disabled={!valid || busy} style={{
            marginTop: 12, width: '100%', padding: '15px 16px', borderRadius: 14,
            border: 'none', cursor: valid && !busy ? 'pointer' : 'default',
            background: valid ? (theme.accentGrad || theme.blue) : theme.chip,
            color: valid ? '#fff' : theme.textDim,
            fontFamily: 'inherit', fontSize: 16, fontWeight: 600, letterSpacing: -0.2,
            boxShadow: valid ? '0 8px 20px rgba(95,90,240,0.40)' : 'none',
          }}>{busy ? 'Sending…' : 'Email me a code'}</button>
          <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 14, textAlign: 'center' }}>
            No password. We email you a 6-digit code.
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

window.LoginScreen = LoginScreen;
