// Login + Forgot password screens
const { useState } = React;

function LoginScreen({ onLogin, onShowReset }) {
  const [email, setEmail] = useState("alex.morgan@witness.example");
  const [password, setPassword] = useState("••••••••");
  const [error, setError] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    setError("");
    if (!email || !password) {
      setError("Email and password are required.");
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      onLogin();
    }, 600);
  };

  return (
    <div className="login-shell">
      <div className="login-side">
        <div className="brand-large">
          <span className="mark">W</span>
          <span>Witness for the Prosecution</span>
        </div>
        <div>
          <div className="quote">
            Staff portal &mdash;<br/>
            policies, training and<br/>
            day-to-day documents,<br/>
            in one place.
          </div>
          <div style={{marginTop: 24, display: 'flex', gap: 6, flexWrap: 'wrap'}}>
            <span className="tag">Policies</span>
            <span className="tag">Handbooks</span>
            <span className="tag">H&amp;S</span>
            <span className="tag">Training</span>
            <span className="tag">Forms</span>
          </div>
        </div>
        <div className="footer">v3.2.1 &middot; Internal use only</div>
      </div>

      <div className="login-form-wrap">
        <form className="login-form" onSubmit={submit}>
          <h1>Sign in</h1>
          <p className="sub">Use your work email to continue</p>

          {error && <div className="error">{error}</div>}

          <div className="field">
            <label>Email address</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="name@witness.example"
              autoFocus
            />
          </div>

          <div className="field">
            <div className="row">
              <label>Password</label>
              <button type="button" className="link" onClick={onShowReset}>
                Forgot password?
              </button>
            </div>
            <div style={{position: 'relative'}}>
              <input
                type={showPw ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                style={{paddingRight: 36}}
              />
              <button
                type="button"
                onClick={() => setShowPw(s => !s)}
                style={{
                  position: 'absolute', right: 4, top: 4,
                  width: 32, height: 32,
                  border: 'none', background: 'none', padding: 0,
                  color: 'var(--ink-3)',
                }}
                aria-label="Toggle password visibility"
              >
                <I.Eye/>
              </button>
            </div>
          </div>

          <button type="submit" className="primary" disabled={loading}>
            {loading ? "Signing in…" : "Sign in"}
          </button>

          <div style={{
            marginTop: 24,
            paddingTop: 16,
            borderTop: '1px dashed var(--line)',
            fontFamily: 'var(--font-mono)',
            fontSize: 11,
            textTransform: 'uppercase',
            letterSpacing: '0.06em',
            color: 'var(--ink-3)',
            textAlign: 'center',
          }}>
            Trouble signing in? Contact <span style={{color: 'var(--ink)'}}>Admin</span>
          </div>
        </form>
      </div>
    </div>
  );
}

function ResetScreen({ onBack, onComplete }) {
  const [step, setStep] = useState(1); // 1: email, 2: code, 3: new pw, 4: success
  const [email, setEmail] = useState("");
  const [code, setCode] = useState("");
  const [pw, setPw] = useState("");
  const [pw2, setPw2] = useState("");
  const [err, setErr] = useState("");

  const next = (e) => {
    e?.preventDefault();
    setErr("");
    if (step === 1) {
      if (!email.includes("@")) return setErr("Enter a valid email address.");
      setStep(2);
    } else if (step === 2) {
      if (code.length < 4) return setErr("Enter the 6-digit code we emailed you.");
      setStep(3);
    } else if (step === 3) {
      if (pw.length < 8) return setErr("Password must be at least 8 characters.");
      if (pw !== pw2) return setErr("Passwords do not match.");
      setStep(4);
    } else if (step === 4) {
      onComplete();
    }
  };

  return (
    <div className="login-shell">
      <div className="login-side">
        <div className="brand-large">
          <span className="mark">W</span>
          <span>Witness for the Prosecution</span>
        </div>
        <div>
          <div className="quote">Reset your password.</div>
          <div className="muted" style={{marginTop: 16}}>
            Step {step === 4 ? "✓" : `${step} of 3`}
          </div>
          <div style={{display: 'flex', gap: 6, marginTop: 12}}>
            {[1,2,3].map(n => (
              <div key={n} style={{
                flex: 1,
                height: 4,
                background: n <= step ? 'var(--ink)' : 'var(--line)',
              }}/>
            ))}
          </div>
        </div>
        <div className="footer">Secure &middot; Encrypted in transit</div>
      </div>

      <div className="login-form-wrap">
        <form className="login-form" onSubmit={next}>
          <button type="button" onClick={onBack} className="link" style={{marginBottom: 16, fontFamily: 'var(--font-mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)', background: 'none', border: 'none', padding: 0, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6}}>
            <I.ArrowLeft/> Back to sign in
          </button>

          {step === 1 && (
            <>
              <h1>Reset password</h1>
              <p className="sub">We'll email you a one-time code</p>
              {err && <div className="error">{err}</div>}
              <div className="field">
                <label>Email address</label>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="name@witness.example" autoFocus/>
              </div>
              <button type="submit" className="primary">Send code</button>
            </>
          )}

          {step === 2 && (
            <>
              <h1>Enter code</h1>
              <p className="sub">Sent to {email || "your email"}</p>
              {err && <div className="error">{err}</div>}
              <div className="field">
                <label>6-digit code</label>
                <input
                  type="text"
                  value={code}
                  onChange={e => setCode(e.target.value.replace(/\D/g,'').slice(0,6))}
                  placeholder="••••••"
                  style={{fontFamily: 'var(--font-mono)', fontSize: 18, letterSpacing: '0.4em', textAlign: 'center'}}
                  autoFocus
                />
              </div>
              <button type="submit" className="primary">Verify code</button>
              <div style={{marginTop: 16, textAlign: 'center'}}>
                <button type="button" className="link" style={{background: 'none', border: 'none', textDecoration: 'underline', fontFamily: 'var(--font-mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)', cursor: 'pointer'}}>
                  Resend code
                </button>
              </div>
            </>
          )}

          {step === 3 && (
            <>
              <h1>New password</h1>
              <p className="sub">At least 8 characters</p>
              {err && <div className="error">{err}</div>}
              <div className="field">
                <label>New password</label>
                <input type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" autoFocus/>
              </div>
              <div className="field">
                <label>Confirm new password</label>
                <input type="password" value={pw2} onChange={e => setPw2(e.target.value)} placeholder="••••••••"/>
              </div>
              <button type="submit" className="primary">Update password</button>
            </>
          )}

          {step === 4 && (
            <>
              <h1>Password updated</h1>
              <p className="sub">You can now sign in with your new password</p>
              <div style={{
                border: '1px solid var(--line)',
                padding: 24,
                textAlign: 'center',
                marginBottom: 20,
              }}>
                <div style={{
                  width: 48, height: 48,
                  border: '2px solid var(--ink)',
                  borderRadius: '50%',
                  display: 'inline-grid',
                  placeItems: 'center',
                  marginBottom: 12,
                }}>
                  <I.Check width="20" height="20"/>
                </div>
                <div className="muted">All set</div>
              </div>
              <button type="submit" className="primary">Continue to sign in</button>
            </>
          )}
        </form>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
window.ResetScreen = ResetScreen;
