/* ============================================================
   INDIC LEAGUE NEWS — Mock login screen
   No backend; "Continue" just sets a fake user in localStorage.
   ============================================================ */

function Login({ onLoggedIn, onBack }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

  const submit = (e) => {
    if (e) e.preventDefault();
    if (!validEmail) {
      setError('Please enter a valid email');
      window.IL_Sounds && window.IL_Sounds.error();
      window.IL_Util && window.IL_Util.Haptics.error();
      return;
    }
    if (password.length < 4) {
      setError('Password must be at least 4 characters');
      window.IL_Sounds && window.IL_Sounds.error();
      window.IL_Util && window.IL_Util.Haptics.error();
      return;
    }
    setError(null);
    setLoading(true);
    window.IL_Sounds && window.IL_Sounds.tap();
    setTimeout(() => {
      const name = email.split('@')[0].replace(/[._-]/g, ' ');
      const user = {
        name: name.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
        email,
        joined: new Date().toISOString(),
      };
      window.IL_Util.Storage.set(window.IL_KEYS.authed, true);
      window.IL_Util.Storage.set(window.IL_KEYS.user, user);
      window.IL_Sounds && window.IL_Sounds.success();
      window.IL_Util && window.IL_Util.Haptics.success();
      onLoggedIn(user);
    }, 500);
  };

  const continueAsGuest = () => {
    window.IL_Sounds && window.IL_Sounds.tap();
    onLoggedIn(null);
  };

  const socialLogin = (provider) => {
    setLoading(true);
    window.IL_Sounds && window.IL_Sounds.tap();
    setTimeout(() => {
      const fakeUser = {
        name: provider === 'google' ? 'Deepanshu Tomar' : 'Indic Reader',
        email: provider === 'google' ? 'deepanshu@gmail.com' : 'user@icloud.com',
        joined: new Date().toISOString(),
        provider,
      };
      window.IL_Util.Storage.set(window.IL_KEYS.authed, true);
      window.IL_Util.Storage.set(window.IL_KEYS.user, fakeUser);
      window.IL_Sounds && window.IL_Sounds.success();
      window.IL_Util && window.IL_Util.Haptics.success();
      onLoggedIn(fakeUser);
    }, 600);
  };

  return (
    <div className="screen">
      <div className="login">
        <button
          aria-label="Back"
          onClick={onBack}
          style={{
            width: 38, height: 38,
            borderRadius: 10,
            border: '1px solid var(--border-strong)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--text-1)',
            alignSelf: 'flex-start',
          }}
        >
          <Icon name="chevron-left" size={18} stroke={2} />
        </button>

        <div style={{ position: 'relative', marginTop: 16 }}>
          <span style={{ position: 'relative', display: 'inline-block' }}>
            <span className="login-mark">iL<span className="dot" /></span>
          </span>
        </div>
        <div className="login-name-row">INDIC LEAGUE <span>NEWS</span></div>

        <h1 className="login-heading">Welcome <em>back</em>.</h1>
        <p className="login-sub">Pick up where you left off. We saved your perspective and your reading streak.</p>

        <form onSubmit={submit}>
          <input
            className="input"
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => { setEmail(e.target.value); setError(null); }}
            autoComplete="email"
            disabled={loading}
          />
          <div style={{ position: 'relative' }}>
            <input
              className="input"
              type={showPw ? 'text' : 'password'}
              placeholder="Password"
              value={password}
              onChange={(e) => { setPassword(e.target.value); setError(null); }}
              autoComplete="current-password"
              disabled={loading}
              style={{ paddingRight: 50 }}
            />
            <button
              type="button"
              onClick={() => setShowPw(!showPw)}
              aria-label={showPw ? 'Hide password' : 'Show password'}
              style={{
                position: 'absolute', right: 16, top: 16,
                color: 'var(--text-3)',
              }}
            >
              <Icon name={showPw ? 'eye-off' : 'eye'} size={20} stroke={1.6} />
            </button>
          </div>

          {error && (
            <div style={{
              padding: '8px 0', color: '#C03B2D',
              fontSize: 13, fontWeight: 500, fontFamily: 'var(--font-ui)',
            }}>
              {error}
            </div>
          )}

          <div style={{ textAlign: 'right', margin: '6px 0 14px' }}>
            <a
              href="#"
              onClick={(e) => {
                e.preventDefault();
                window.IL_Sounds && window.IL_Sounds.tap();
              }}
              style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-2)' }}
            >
              Forgot password?
            </a>
          </div>

          <button type="submit" className="btn" disabled={loading}>
            {loading ? 'Signing in…' : 'Sign in'}
            {!loading && <Icon name="arrow-right" size={18} stroke={2.2} color="#fff" />}
          </button>
        </form>

        <div className="or-divider">OR</div>

        <div className="social-row">
          <button className="social-btn" onClick={() => socialLogin('google')} disabled={loading}>
            <Icon name="google" size={18} />
            Google
          </button>
          <button className="social-btn" onClick={() => socialLogin('apple')} disabled={loading}>
            <Icon name="apple" size={18} />
            Apple
          </button>
        </div>

        <button
          type="button"
          className="btn btn-ghost"
          onClick={continueAsGuest}
        >
          Continue without an account →
        </button>

        <div className="login-foot">
          New to Indic League? <a href="#" onClick={(e) => { e.preventDefault(); onBack && onBack(); }}>Create account</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
