// screens-auth.jsx — sign in / sign up

function AuthScreen({ app }) {
  const [mode, setMode] = React.useState(() => new URLSearchParams(window.location.search).has('recovery') ? 'recovery' : 'signin'); // 'signin' | 'signup' | 'reset' | 'recovery'
  const [email, setEmail] = React.useState('jordan@lasso.io');
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [name, setName] = React.useState('');
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  const submit = async () => {
    const e = {};
    if (mode !== 'recovery' && (!email || !email.includes('@'))) e.email = 'Enter a valid email';
    if (mode !== 'reset' && !password) e.password = 'Required';
    if (mode === 'signup') {
      if (!name) e.name = 'Required';
      if (password && password !== confirm) e.confirm = 'Passwords don\'t match';
    }
    if (mode === 'recovery' && password !== confirm) e.confirm = 'Passwords don\'t match';
    setErrors(e);
    if (Object.keys(e).length) return;
    setLoading(true);
    try {
      if (mode === 'reset') {
        await window.LassoCustomer.requestPasswordReset(email);
        app.toast('Check your inbox for a secure password-reset link.', 'success');
        setMode('signin');
        return;
      }
      if (mode === 'recovery') {
        await window.LassoCustomer.updatePassword(password);
        window.history.replaceState({}, '', window.location.pathname);
        app.setAuthed(true);
        app.toast('Password updated. You are signed in.', 'success');
        app.nav('home');
        return;
      }
      if(mode === 'signup') {
        const result=await window.LassoCustomer.signUp(name, email, password);
        if(result.confirmationRequired){ app.toast('Check your email to confirm your account, then sign in.', 'info'); return; }
      } else {
        await window.LassoCustomer.signIn(email, password, name || email.split('@')[0]);
      }
      app.setAuthed(true);
      app.toast(mode === 'signup' ? 'Welcome aboard, ' + name.split(' ')[0] : 'Welcome back', 'success');
      app.nav(app.redirectAfterAuth || 'home');
      app.setRedirectAfterAuth(null);
    } catch(error) {
      setErrors({ form: error.message || 'Could not authenticate your account.' });
    } finally { setLoading(false); }
  };

  return (
    <Screen>
      <div data-customer-auth-entry="" style={{ padding: '20px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <button onClick={() => app.nav('home')} style={{
          width: 40, height: 40, borderRadius: 14, border: '1.5px solid var(--soft-line)',
          background: 'var(--bg-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><Ico.chevL c="var(--fg-primary)" s={20}/></button>
        <Wordmark size={18}/>
        <div style={{ width: 40 }}/>
      </div>

      <div style={{ padding: '24px 20px 0', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <Eyebrow color="var(--brand-orange)">{mode === 'signup' ? 'Round up' : 'Saddle up'}</Eyebrow>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 30, lineHeight: 1.0, letterSpacing: '-0.01em', marginTop: 8 }}>
          {mode === 'signin' ? 'Welcome back, partner.' : mode === 'signup' ? 'Make it your trail.' : mode === 'reset' ? 'Reset your password.' : 'Choose a new password.'}
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--warm-stone)', marginTop: 8 }}>
          {mode === 'signin' && 'Sign in to keep track of your orders.'}
          {mode === 'signup' && 'Two minutes. Then we eat.'}
          {mode === 'reset' && 'We\'ll send a secure reset link to your inbox.'}
          {mode === 'recovery' && 'Use a new password you have not used elsewhere.'}
        </div>

        {/* OAuth */}
        {(mode === 'signin' || mode === 'signup') && <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 22 }}>
          <button onClick={() => app.toast('Google sign-in is not configured yet. Use email and password.', 'info')} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            height: 50, borderRadius: 16, border: '1.5px solid var(--soft-line)',
            background: 'var(--bg-surface)', cursor: 'pointer',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--fg-primary)',
          }}>
            <Ico.google s={20}/>
            Continue with Google
          </button>
          <button onClick={() => app.toast('Magic-link sign-in is not configured yet. Use email and password.', 'info')} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            height: 50, borderRadius: 16, border: '1.5px solid var(--soft-line)',
            background: 'var(--bg-surface)', cursor: 'pointer',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--fg-primary)',
          }}>
            <Ico.email c="var(--fg-primary)" s={18}/>
            Email me a magic link
          </button>
        </div>}

        {/* Divider */}
        {(mode === 'signin' || mode === 'signup') && <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0' }}>
          <div style={{ flex: 1, height: 1, background: 'var(--soft-line)' }}/>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 10, letterSpacing: '0.18em', color: 'var(--warm-stone)', textTransform: 'uppercase' }}>or</div>
          <div style={{ flex: 1, height: 1, background: 'var(--soft-line)' }}/>
        </div>}

        {/* Form */}
        <div {...(mode === 'signup' ? { 'data-customer-signup-form': '' } : { 'data-customer-login-form': '' })} style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: (mode === 'reset' || mode === 'recovery') ? 24 : 0 }}>
          {mode === 'signup' && (
            <Input label="Full name" placeholder="Jordan Mason" value={name} onChange={setName} error={errors.name}/>
          )}
          {mode !== 'recovery' && <Input label="Email" type="email" placeholder="you@lasso.io" value={email} onChange={setEmail} icon={<Ico.email c="var(--warm-stone)" s={18}/>} error={errors.email}/>}
          {mode !== 'reset' && (
            <Input label="Password" type="password" placeholder="••••••••" value={password} onChange={setPassword} icon={<Ico.lock c="var(--warm-stone)" s={18}/>} error={errors.password}/>
          )}
          {(mode === 'signup' || mode === 'recovery') && (
            <Input label="Confirm password" type="password" placeholder="••••••••" value={confirm} onChange={setConfirm} icon={<Ico.lock c="var(--warm-stone)" s={18}/>} error={errors.confirm}/>
          )}

          {mode === 'signin' && (
            <div style={{ textAlign: 'right' }}>
              <span onClick={() => setMode('reset')} style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12, color: 'var(--brand-orange)', cursor: 'pointer' }}>
                Forgot password?
              </span>
            </div>
          )}
        </div>

        <div style={{ marginTop: 20 }}>
          <Button kind="accent" full size="lg" onClick={submit} disabled={loading}>
            {loading ? 'One moment…' : mode === 'signup' ? 'Create account' : mode === 'reset' ? 'Send reset link' : mode === 'recovery' ? 'Update password' : 'Sign in'}
          </Button>
        </div>
        {errors.form && <div role="alert" style={{ marginTop: 10, color: 'var(--danger-red)', fontFamily: 'var(--font-body)', fontSize: 12 }}>{errors.form}</div>}

        <div style={{ marginTop: 16, textAlign: 'center', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--warm-stone)' }}>
          {mode === 'signin' && (
            <>New here? <span onClick={() => setMode('signup')} style={{ fontWeight: 700, color: 'var(--brand-orange)', cursor: 'pointer' }}>Create account</span></>
          )}
          {mode === 'signup' && (
            <>Already on the trail? <span onClick={() => setMode('signin')} style={{ fontWeight: 700, color: 'var(--brand-orange)', cursor: 'pointer' }}>Sign in</span></>
          )}
          {(mode === 'reset' || mode === 'recovery') && (
            <span onClick={() => setMode('signin')} style={{ fontWeight: 700, color: 'var(--brand-orange)', cursor: 'pointer' }}>Use a password instead</span>
          )}
        </div>

        <div style={{ marginTop: 'auto', padding: '20px 0', fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--warm-stone)', textAlign: 'center', lineHeight: 1.5 }}>
          By continuing you agree to Lasso's <u>Terms</u> &amp; <u>Privacy</u>.
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { AuthScreen });
