/* global React, I */

const { useState: auUseState, useEffect: auUseEffect, useRef: auUseRef } = React;

/**
 * Auth — login / signup / 2FA / forgot / reset.
 * Stateless: parent owns "current screen". onAuthed() is called when sign-in completes.
 *
 * Currently no backend wired — all submissions simulate a 600-900ms delay.
 * Hook real auth in by replacing the body of the submit handlers.
 */
function AuthFlow({ onAuthed }) {
  const [screen, setScreen] = auUseState('login'); // login | signup | 2fa | forgot | reset
  const [email, setEmail] = auUseState('');

  return (
    <div className="auth-root">
      <div className="auth-gradient" />

      {/* Brand bar */}
      <div className="auth-top">
        <div className="auth-brand">
          <div className="auth-mark"><div className="auth-mark-l">L</div></div>
          <div className="auth-brand-name">Lynxe</div>
        </div>
      </div>

      {/* Centered card */}
      <div className="auth-stage">
        <div key={screen} className="auth-card auth-anim">
          {screen === 'login'   && <Login    onAuthed={onAuthed} setScreen={setScreen} email={email} setEmail={setEmail} />}
          {screen === 'signup'  && <Signup   onAuthed={onAuthed} setScreen={setScreen} email={email} setEmail={setEmail} />}
          {screen === '2fa'     && <TwoFA    onAuthed={onAuthed} setScreen={setScreen} email={email} />}
          {screen === 'forgot'  && <Forgot   setScreen={setScreen} email={email} setEmail={setEmail} />}
          {screen === 'reset'   && <Reset    setScreen={setScreen} email={email} />}
        </div>
      </div>

      {/* Footer */}
      <div className="auth-foot">
        <div className="dim auth-foot-text">
          <a href="#" className="auth-link" onClick={(e) => e.preventDefault()}>Terms</a>
          <span className="auth-foot-sep">·</span>
          <a href="#" className="auth-link" onClick={(e) => e.preventDefault()}>Privacy</a>
          <span className="auth-foot-sep">·</span>
          <a href="#" className="auth-link" onClick={(e) => e.preventDefault()}>Contact</a>
        </div>
      </div>
    </div>
  );
}

/* ============== GOOGLE BUTTON ============== */

function GoogleButton({ onClick, label }) {
  return (
    <button className="auth-google" onClick={onClick}>
      <svg width="14" height="14" viewBox="0 0 18 18" aria-hidden="true">
        <path fill="#4285F4" d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.614z"/>
        <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z"/>
        <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"/>
        <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"/>
      </svg>
      <span>{label || 'Continue with Google'}</span>
    </button>
  );
}

/* ============== LOGIN ============== */

function Login({ onAuthed, setScreen, email, setEmail }) {
  const [password, setPassword] = auUseState('');
  const [showPass, setShowPass] = auUseState(false);
  const [remember, setRemember] = auUseState(true);
  const [busy, setBusy] = auUseState(false);
  const [err, setErr] = auUseState('');

  const submit = (e) => {
    e?.preventDefault();
    if (!email || !password) { setErr('Enter your email and password.'); return; }
    setErr('');
    setBusy(true);
    // Simulated: half the time go to 2FA, half the time direct sign-in
    setTimeout(() => {
      setBusy(false);
      // Always show 2FA so user can see that flow exists. Hook your own logic later.
      setScreen('2fa');
    }, 700);
  };

  const handleGoogle = () => {
    setBusy(true);
    setTimeout(() => { setBusy(false); onAuthed && onAuthed(); }, 600);
  };

  return (
    <>
      <h1 className="auth-h1">Sign in to Lynxe</h1>
      <p className="auth-sub">Welcome back. Enter your credentials to continue.</p>

      <GoogleButton onClick={handleGoogle} />

      <div className="auth-divider"><span>or</span></div>

      <form className="auth-form" onSubmit={submit}>
        <div className="auth-field">
          <label className="auth-label">Email</label>
          <input
            className="auth-input"
            type="email"
            autoComplete="email"
            autoFocus
            placeholder="you@school.edu"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <div className="auth-field">
          <div className="auth-field-row">
            <label className="auth-label">Password</label>
            <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); setScreen('forgot'); }}>
              Forgot password?
            </a>
          </div>
          <div className="auth-input-wrap">
            <input
              className="auth-input"
              type={showPass ? 'text' : 'password'}
              autoComplete="current-password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <button type="button" className="auth-eye" onClick={() => setShowPass(s => !s)} tabIndex={-1}>
              {showPass ? <I.X size={12} /> : <I.Search size={12} />}
            </button>
          </div>
        </div>

        <label className="auth-check">
          <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
          <span className="auth-check-box">{remember && <I.Check size={9} strokeWidth={3} />}</span>
          <span className="auth-check-label">Remember me on this device</span>
        </label>

        {err && <div className="auth-err">{err}</div>}

        <button type="submit" className="auth-submit" disabled={busy}>
          {busy ? <span className="auth-spin" /> : 'Continue'}
          {!busy && <I.ArrowRight size={11} />}
        </button>
      </form>

      <div className="auth-altline dim">
        Don't have an account?{' '}
        <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); setScreen('signup'); }}>
          Sign up
        </a>
      </div>
    </>
  );
}

/* ============== SIGNUP ============== */

function Signup({ onAuthed, setScreen, email, setEmail }) {
  const [name, setName] = auUseState('');
  const [password, setPassword] = auUseState('');
  const [showPass, setShowPass] = auUseState(false);
  const [busy, setBusy] = auUseState(false);
  const [err, setErr] = auUseState('');

  const submit = (e) => {
    e?.preventDefault();
    if (!name || !email || !password) { setErr('Fill out all fields to continue.'); return; }
    if (password.length < 8) { setErr('Password must be at least 8 characters.'); return; }
    setErr('');
    setBusy(true);
    setTimeout(() => {
      setBusy(false);
      // After signup, send to 2FA setup-style verification (same screen for demo)
      setScreen('2fa');
    }, 700);
  };

  return (
    <>
      <h1 className="auth-h1">Create your account</h1>
      <p className="auth-sub">Free for students — no credit card.</p>

      <GoogleButton onClick={() => onAuthed && onAuthed()} label="Sign up with Google" />

      <div className="auth-divider"><span>or</span></div>

      <form className="auth-form" onSubmit={submit}>
        <div className="auth-field">
          <label className="auth-label">Full name</label>
          <input
            className="auth-input"
            autoComplete="name"
            autoFocus
            placeholder="Alex Kim"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>

        <div className="auth-field">
          <label className="auth-label">Email</label>
          <input
            className="auth-input"
            type="email"
            autoComplete="email"
            placeholder="you@school.edu"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <div className="auth-field">
          <label className="auth-label">Password</label>
          <div className="auth-input-wrap">
            <input
              className="auth-input"
              type={showPass ? 'text' : 'password'}
              autoComplete="new-password"
              placeholder="At least 8 characters"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <button type="button" className="auth-eye" onClick={() => setShowPass(s => !s)} tabIndex={-1}>
              {showPass ? <I.X size={12} /> : <I.Search size={12} />}
            </button>
          </div>
        </div>

        {err && <div className="auth-err">{err}</div>}

        <button type="submit" className="auth-submit" disabled={busy}>
          {busy ? <span className="auth-spin" /> : 'Create account'}
          {!busy && <I.ArrowRight size={11} />}
        </button>

        <div className="auth-fineprint dim">
          By creating an account you agree to our{' '}
          <a href="#" className="auth-link" onClick={(e) => e.preventDefault()}>Terms</a>{' '}and{' '}
          <a href="#" className="auth-link" onClick={(e) => e.preventDefault()}>Privacy Policy</a>.
        </div>
      </form>

      <div className="auth-altline dim">
        Already have an account?{' '}
        <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); setScreen('login'); }}>
          Sign in
        </a>
      </div>
    </>
  );
}

/* ============== TWO-FACTOR ============== */

function TwoFA({ onAuthed, setScreen, email }) {
  const [digits, setDigits] = auUseState(['', '', '', '', '', '']);
  const [busy, setBusy] = auUseState(false);
  const [err, setErr] = auUseState('');
  const [resent, setResent] = auUseState(false);
  const [cooldown, setCooldown] = auUseState(0);
  const inputs = auUseRef([]);

  auUseEffect(() => {
    inputs.current[0]?.focus();
  }, []);

  auUseEffect(() => {
    if (cooldown <= 0) return;
    const t = setTimeout(() => setCooldown(c => c - 1), 1000);
    return () => clearTimeout(t);
  }, [cooldown]);

  const setDigit = (i, v) => {
    const clean = v.replace(/\D/g, '').slice(-1);
    setDigits(d => {
      const n = [...d];
      n[i] = clean;
      return n;
    });
    if (clean && i < 5) inputs.current[i + 1]?.focus();
  };

  const onKeyDown = (i, e) => {
    if (e.key === 'Backspace' && !digits[i] && i > 0) {
      inputs.current[i - 1]?.focus();
    } else if (e.key === 'ArrowLeft' && i > 0) {
      inputs.current[i - 1]?.focus();
    } else if (e.key === 'ArrowRight' && i < 5) {
      inputs.current[i + 1]?.focus();
    }
  };

  const onPaste = (e) => {
    const text = (e.clipboardData?.getData('text') || '').replace(/\D/g, '').slice(0, 6);
    if (!text) return;
    e.preventDefault();
    const next = ['', '', '', '', '', ''];
    for (let i = 0; i < text.length; i++) next[i] = text[i];
    setDigits(next);
    const focusIdx = Math.min(text.length, 5);
    inputs.current[focusIdx]?.focus();
  };

  const code = digits.join('');
  const ready = code.length === 6;

  const submit = (e) => {
    e?.preventDefault();
    if (!ready) { setErr('Enter all six digits.'); return; }
    setErr('');
    setBusy(true);
    setTimeout(() => {
      setBusy(false);
      onAuthed && onAuthed();
    }, 700);
  };

  // Auto-submit when 6 digits filled
  auUseEffect(() => {
    if (ready && !busy) {
      const t = setTimeout(() => submit(), 200);
      return () => clearTimeout(t);
    }
  }, [code]);

  const resend = () => {
    setResent(true);
    setCooldown(30);
    setTimeout(() => setResent(false), 1800);
  };

  return (
    <>
      <button className="auth-backlink" onClick={() => setScreen('login')}>
        <I.ArrowLeft size={11} /> Back
      </button>
      <h1 className="auth-h1">Check your email</h1>
      <p className="auth-sub">
        We sent a 6-digit code to{' '}
        <span style={{ color: 'var(--fg)' }}>{email || 'your email'}</span>.
        Enter it below to continue.
      </p>

      <form className="auth-form" onSubmit={submit}>
        <div className="auth-otp" onPaste={onPaste}>
          {digits.map((d, i) => (
            <input
              key={i}
              ref={(el) => (inputs.current[i] = el)}
              className={`auth-otp-cell ${d ? 'is-filled' : ''}`}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={d}
              onChange={(e) => setDigit(i, e.target.value)}
              onKeyDown={(e) => onKeyDown(i, e)}
            />
          ))}
        </div>

        {err && <div className="auth-err">{err}</div>}

        <button type="submit" className="auth-submit" disabled={busy || !ready}>
          {busy ? <span className="auth-spin" /> : 'Verify'}
          {!busy && <I.ArrowRight size={11} />}
        </button>
      </form>

      <div className="auth-altline dim">
        Didn't get a code?{' '}
        {cooldown > 0 ? (
          <span>Resend in {cooldown}s</span>
        ) : resent ? (
          <span style={{ color: 'var(--ok)' }}>Sent — check your inbox.</span>
        ) : (
          <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); resend(); }}>
            Resend code
          </a>
        )}
      </div>
    </>
  );
}

/* ============== FORGOT PASSWORD ============== */

function Forgot({ setScreen, email, setEmail }) {
  const [busy, setBusy] = auUseState(false);
  const [sent, setSent] = auUseState(false);

  const submit = (e) => {
    e?.preventDefault();
    if (!email) return;
    setBusy(true);
    setTimeout(() => {
      setBusy(false);
      setSent(true);
    }, 600);
  };

  if (sent) {
    return (
      <>
        <div className="auth-success-mark">
          <I.Check size={20} strokeWidth={2.4} />
        </div>
        <h1 className="auth-h1">Check your email</h1>
        <p className="auth-sub">
          If an account exists for{' '}
          <span style={{ color: 'var(--fg)' }}>{email}</span>, we sent a link to reset your password.
          The link expires in 30 minutes.
        </p>
        <div className="auth-stack">
          <button className="auth-submit" onClick={() => setScreen('reset')}>
            Open reset page <I.ArrowRight size={11} />
          </button>
          <button className="auth-submit auth-submit-ghost" onClick={() => setScreen('login')}>
            Back to sign in
          </button>
        </div>
      </>
    );
  }

  return (
    <>
      <button className="auth-backlink" onClick={() => setScreen('login')}>
        <I.ArrowLeft size={11} /> Back to sign in
      </button>
      <h1 className="auth-h1">Reset your password</h1>
      <p className="auth-sub">Enter the email associated with your account and we'll send you a reset link.</p>

      <form className="auth-form" onSubmit={submit}>
        <div className="auth-field">
          <label className="auth-label">Email</label>
          <input
            className="auth-input"
            type="email"
            autoComplete="email"
            autoFocus
            placeholder="you@school.edu"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <button type="submit" className="auth-submit" disabled={busy || !email}>
          {busy ? <span className="auth-spin" /> : 'Send reset link'}
          {!busy && <I.ArrowRight size={11} />}
        </button>
      </form>
    </>
  );
}

/* ============== RESET PASSWORD ============== */

function Reset({ setScreen, email }) {
  const [pw1, setPw1] = auUseState('');
  const [pw2, setPw2] = auUseState('');
  const [busy, setBusy] = auUseState(false);
  const [err, setErr] = auUseState('');
  const [done, setDone] = auUseState(false);

  const submit = (e) => {
    e?.preventDefault();
    if (pw1.length < 8) { setErr('Password must be at least 8 characters.'); return; }
    if (pw1 !== pw2) { setErr('Passwords don\u2019t match.'); return; }
    setErr('');
    setBusy(true);
    setTimeout(() => { setBusy(false); setDone(true); }, 700);
  };

  if (done) {
    return (
      <>
        <div className="auth-success-mark">
          <I.Check size={20} strokeWidth={2.4} />
        </div>
        <h1 className="auth-h1">Password updated</h1>
        <p className="auth-sub">Your password has been changed. Sign in to continue.</p>
        <button className="auth-submit" onClick={() => setScreen('login')}>
          Back to sign in <I.ArrowRight size={11} />
        </button>
      </>
    );
  }

  return (
    <>
      <h1 className="auth-h1">Set a new password</h1>
      <p className="auth-sub">For{' '}<span style={{ color: 'var(--fg)' }}>{email || 'your account'}</span>. Use at least 8 characters.</p>

      <form className="auth-form" onSubmit={submit}>
        <div className="auth-field">
          <label className="auth-label">New password</label>
          <input
            className="auth-input"
            type="password"
            autoComplete="new-password"
            autoFocus
            placeholder="At least 8 characters"
            value={pw1}
            onChange={(e) => setPw1(e.target.value)}
          />
        </div>

        <div className="auth-field">
          <label className="auth-label">Confirm password</label>
          <input
            className="auth-input"
            type="password"
            autoComplete="new-password"
            placeholder="Re-type your new password"
            value={pw2}
            onChange={(e) => setPw2(e.target.value)}
          />
        </div>

        {err && <div className="auth-err">{err}</div>}

        <button type="submit" className="auth-submit" disabled={busy}>
          {busy ? <span className="auth-spin" /> : 'Update password'}
          {!busy && <I.ArrowRight size={11} />}
        </button>
      </form>
    </>
  );
}

window.AuthFlow = AuthFlow;
