// Admin sign-in screen. Same Firebase Auth as the client portal — the
// admin gate is the custom claim, not a separate identity system. We
// deliberately don't expose account creation here; admins are minted by
// the bootstrap script or by an existing admin via the makeAdmin call.

const AdminAuth = ({ onSignedIn }) => {
  const [mode, setMode] = React.useState("email"); // "email" | "loading"
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState(null);

  const submit = async (e) => {
    e && e.preventDefault();
    setError(null);
    setMode("loading");
    try {
      await window.fb.signInWithEmailAndPassword(window.fb.auth, email.trim(), password);
      if (onSignedIn) onSignedIn();
    } catch (err) {
      setError(prettyAuthError(err));
      setMode("email");
    }
  };

  const google = async () => {
    setError(null);
    setMode("loading");
    try {
      const provider = new window.fb.GoogleAuthProvider();
      provider.setCustomParameters({ prompt: "select_account" });
      await window.fb.signInWithPopup(window.fb.auth, provider);
      if (onSignedIn) onSignedIn();
    } catch (err) {
      setError(prettyAuthError(err));
      setMode("email");
    }
  };

  const reset = async () => {
    setError(null);
    if (!email.trim()) { setError("Type your email above first."); return; }
    try {
      await window.fb.sendPasswordResetEmail(window.fb.auth, email.trim());
      setError("Password reset email sent.");
    } catch (err) {
      setError(prettyAuthError(err));
    }
  };

  return (
    <div className="auth-shell">
      <div className="auth-card">
        <div className="auth-brand">
          <span className="auth-brand-mark">S</span>
          <div>
            <div className="auth-brand-name">SPAND STUDIO</div>
            <div className="auth-brand-sub">ADMINISTRATOR PORTAL</div>
          </div>
        </div>

        <h1>Sign in</h1>
        <p className="auth-lede">
          Restricted area. Studio admins only.
        </p>

        <form onSubmit={submit} className="auth-form">
          <label>
            <span>Email</span>
            <input
              type="email"
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={mode === "loading"}
              required
            />
          </label>
          <label>
            <span>Password</span>
            <input
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={mode === "loading"}
              required
            />
          </label>

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

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

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

          <button
            type="button"
            className="btn ghost lg"
            onClick={google}
            disabled={mode === "loading"}
          >
            <Icon name="google" size={15} /> Continue with Google
          </button>

          <button
            type="button"
            className="auth-link"
            onClick={reset}
            disabled={mode === "loading"}
          >
            Forgot password?
          </button>
        </form>

        <div className="auth-foot">
          New admins are minted from the studio's command line. If you need
          access, message Jackson.
        </div>
      </div>
    </div>
  );
};

const prettyAuthError = (err) => {
  const code = (err && err.code) || "";
  if (code === "auth/invalid-credential" || code === "auth/wrong-password" || code === "auth/user-not-found") {
    return "That email and password don't match.";
  }
  if (code === "auth/too-many-requests") {
    return "Too many tries. Try again in a few minutes.";
  }
  if (code === "auth/popup-closed-by-user") {
    return "Google sign-in was cancelled.";
  }
  return (err && err.message) || "Sign-in failed.";
};

window.AdminAuth = AdminAuth;
