// Login / signup. Renders without the app chrome (no sidebar). On successful
// signIn the auth listener fires and App swaps to the routed app automatically.

function LoginScreen() {
  const [mode, setMode] = React.useState('login'); // 'login' | 'signup'
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [info, setInfo] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setInfo(null);
    if (!email || !password) {
      setError('Email and password are required.');
      return;
    }
    if (password.length < 6) {
      setError('Password must be at least 6 characters.');
      return;
    }
    setBusy(true);
    try {
      const fn = mode === 'signup' ? signUp : signIn;
      const { data, error } = await fn(email, password);
      if (error) {
        setError(error.message);
      } else if (mode === 'signup' && !data.session) {
        setInfo('Account created. Check your email for a confirmation link, then sign in.');
        setMode('login');
      }
      // success: auth state listener swaps the screen automatically
    } catch (err) {
      setError(err.message || String(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh', width: '100vw',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--bg)', padding: 24,
      backgroundImage:
        'radial-gradient(circle at 20% 0%, var(--paper) 0%, transparent 40%),' +
        'radial-gradient(circle at 100% 100%, var(--blue-wash) 0%, transparent 40%)',
    }}>
      <form onSubmit={submit} style={{
        width: 380, background: 'white', border: '1px solid var(--line)',
        borderRadius: 14, padding: '28px 28px 22px',
        boxShadow: 'var(--shadow-l)',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 30, height: 30, borderRadius: 7, background: 'var(--ink)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 14, transform: 'rotate(-4deg)' }}>sb</div>
          <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 17, fontWeight: 500 }}>studybuddy</span>
        </div>

        <div>
          <h1 className="display" style={{ margin: 0, fontSize: 24, letterSpacing: '-0.02em' }}>
            {mode === 'login' ? 'Welcome back' : 'Create your account'}
          </h1>
          <div style={{ color: 'var(--ink-mute)', fontSize: 12, marginTop: 4 }}>
            {mode === 'login' ? 'Sign in to access your study guides.' : 'Generate guides from your own files.'}
          </div>
        </div>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-soft)' }}>Email</span>
          <input
            type="email" value={email}
            onChange={(e) => setEmail(e.target.value)}
            autoComplete="email"
            required
            style={inputStyle}
          />
        </label>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-soft)' }}>Password</span>
          <input
            type="password" value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
            required
            minLength={6}
            style={inputStyle}
          />
          {mode === 'signup' && <span style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>Min. 6 characters.</span>}
        </label>

        {error && (
          <div style={{ padding: '8px 10px', background: 'var(--coral-soft)', border: '1px solid var(--coral)', borderRadius: 6, fontSize: 11.5, color: '#8a3a20' }}>
            {error}
          </div>
        )}
        {info && (
          <div style={{ padding: '8px 10px', background: 'var(--blue-wash)', border: '1px solid var(--blue-soft)', borderRadius: 6, fontSize: 11.5, color: 'var(--blue-deep)' }}>
            {info}
          </div>
        )}

        <button type="submit" className="btn blue" disabled={busy} style={{
          justifyContent: 'center', height: 36, fontSize: 13,
          opacity: busy ? 0.7 : 1, cursor: busy ? 'wait' : 'pointer',
        }}>
          {busy ? 'Working…' : mode === 'login' ? 'Sign in' : 'Create account'}
        </button>

        <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--ink-mute)' }}>
          {mode === 'login' ? "Don't have an account? " : 'Already have an account? '}
          <a
            href="#"
            onClick={(e) => { e.preventDefault(); setError(null); setInfo(null); setMode(mode === 'login' ? 'signup' : 'login'); }}
            style={{ color: 'var(--blue-deep)', cursor: 'pointer', fontWeight: 500 }}
          >
            {mode === 'login' ? 'Sign up' : 'Sign in'}
          </a>
        </div>
      </form>
    </div>
  );
}

const inputStyle = {
  height: 34, padding: '0 10px',
  border: '1px solid var(--line)', borderRadius: 6,
  fontSize: 13, fontFamily: 'inherit', color: 'var(--ink)',
  outline: 'none',
  background: 'white',
};

Object.assign(window, { LoginScreen });
