/* =========================================================================
 *  Python Tutor — /account (signed-in status page)
 *  -----------------------------------------------------------------------
 *  Per web_builder_instructions.md §5:
 *    - Not signed in → "Sign in with Google" CTA.
 *    - Signed in     → photo + email + name + checkAllowlist() result.
 *        - allowed                        → green "you're all set"
 *        - reason: pending_allowlist_…   → amber "pending approval"
 *        - error                          → red error message
 *    - Sign-out button at the bottom.
 *
 *  We never write to Firestore from here — the apps own all teaching
 *  data (per §1 / §12 in the contract). This page is read-only status.
 * =======================================================================*/

const { useState, useEffect, useCallback } = React;

function PythonTutorAccount({ onNavigate }) {
  const [user, setUser] = useState(null);
  // gateState: 'idle' | 'loading' | 'allowed' | 'pending' | 'error'
  const [gateState, setGateState] = useState("idle");
  const [gateRole, setGateRole] = useState(null);
  const [gateError, setGateError] = useState("");
  const [signingIn, setSigningIn] = useState(false);

  useEffect(() => {
    const off = window.PYTHON_TUTOR_AUTH.onUserChange((u) => setUser(u));
    return () => { try { off && off(); } catch {} };
  }, []);

  // Re-run the gate check whenever the signed-in user changes. Reset the
  // gate state if they sign out so we don't show stale "you're all set"
  // copy underneath the sign-in CTA.
  useEffect(() => {
    if (!user) { setGateState("idle"); setGateRole(null); setGateError(""); return; }
    let cancelled = false;
    setGateState("loading");
    setGateError("");
    window.PYTHON_TUTOR_FUNCTIONS.checkAllowlist()
      .then((res) => {
        if (cancelled) return;
        if (res && res.allowed) {
          setGateRole(res.role || "allowlist");
          setGateState("allowed");
        } else if (res && res.reason === "pending_allowlist_approval") {
          setGateState("pending");
        } else {
          setGateState("error");
          setGateError("Unknown response from allowlist check.");
        }
      })
      .catch((err) => {
        if (cancelled) return;
        setGateError((err && (err.message || err.code)) || String(err));
        setGateState("error");
      });
    return () => { cancelled = true; };
  }, [user && user.uid]);

  const onSignIn = useCallback(async () => {
    setSigningIn(true);
    try {
      await window.PYTHON_TUTOR_AUTH.signInWithGoogle();
    } catch (err) {
      // The redirect fallback never throws here; this branch is the
      // genuine "popup closed by user" / blocked case. The auth state
      // listener takes care of everything else.
      console.warn("[python-tutor] sign-in failed:", err);
    } finally {
      setSigningIn(false);
    }
  }, []);

  const onSignOut = useCallback(async () => {
    await window.PYTHON_TUTOR_AUTH.signOut();
  }, []);

  return (
    <div className="pt-page">
      <Topbar onNavigate={onNavigate} />
      <main className="pt-main">
        {!user ? (
          <SignInCTA onSignIn={onSignIn} signingIn={signingIn} />
        ) : (
          <AccountPanel
            user={user}
            gateState={gateState}
            gateRole={gateRole}
            gateError={gateError}
            onSignOut={onSignOut}
          />
        )}
      </main>
      <Footer />
    </div>
  );
}

function SignInCTA({ onSignIn, signingIn }) {
  return (
    <section className="pt-soon">
      <div className="ct-eyebrow">Your Python Tutor account</div>
      <h1 className="pt-soon-h1">Sign in to check your access.</h1>
      <p className="pt-soon-sub">
        Sign in with the same Google account you'll use in the Python
        Tutor desktop and Android apps. We'll show you whether your
        account is on the allowlist.
      </p>
      <div className="pt-soon-cta">
        <button
          className="ct-btn ct-btn-primary ct-btn-lg"
          onClick={onSignIn}
          disabled={signingIn}
        >
          {signingIn ? "Opening Google sign-in…" : "Sign in with Google"}
        </button>
      </div>
    </section>
  );
}

function AccountPanel({ user, gateState, gateRole, gateError, onSignOut }) {
  return (
    <section className="pt-soon">
      <div className="ct-eyebrow">Your Python Tutor account</div>

      {/* Identity card. Uses .pt-feature for the framed look — no new
          design tokens, just reuse what styles-python.css already has. */}
      <div className="pt-feature" style={{ width: "100%", maxWidth: 560, marginTop: 8 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          {user.photoURL ? (
            <img
              src={user.photoURL}
              alt=""
              referrerPolicy="no-referrer"
              style={{
                width: 56, height: 56, borderRadius: "50%",
                border: "1px solid var(--ct-border)",
              }}
            />
          ) : (
            <div
              aria-hidden="true"
              style={{
                width: 56, height: 56, borderRadius: "50%",
                background: "var(--ct-bg-elev-2)",
                border: "1px solid var(--ct-border)",
                display: "grid", placeItems: "center",
                color: "var(--ct-fg-dim)", fontWeight: 600,
              }}
            >
              {(user.name || user.email || "?").slice(0, 1).toUpperCase()}
            </div>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: "var(--ct-fg)" }}>
              {user.name || "Signed in"}
            </div>
            <div className="ct-mono" style={{
              fontSize: 13, color: "var(--ct-fg-dim)",
              overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
            }}>
              {user.email}
            </div>
          </div>
        </div>
      </div>

      <GateBadge gateState={gateState} gateRole={gateRole} gateError={gateError} />

      <div className="pt-soon-cta">
        <button className="ct-btn ct-btn-lg" onClick={onSignOut}>
          Sign out
        </button>
      </div>
    </section>
  );
}

function GateBadge({ gateState, gateRole, gateError }) {
  if (gateState === "loading" || gateState === "idle") {
    return (
      <div className="pt-feature" style={{ width: "100%", maxWidth: 560 }}>
        <div className="pt-feature-eyebrow ct-eyebrow">Status</div>
        <div className="pt-feature-body">Checking your access…</div>
      </div>
    );
  }
  if (gateState === "allowed") {
    return (
      <div
        className="pt-feature"
        style={{ width: "100%", maxWidth: 560, borderColor: "var(--ct-good)" }}
      >
        <div className="pt-feature-eyebrow ct-eyebrow" style={{ color: "var(--ct-good)" }}>
          {gateRole === "owner" ? "Owner" : "You're all set"}
        </div>
        <div className="pt-feature-title" style={{ color: "var(--ct-fg)" }}>
          <CheckIcon /> Access granted
        </div>
        <div className="pt-feature-body">
          Open the Python Tutor desktop app or Android app and sign in with
          this Google account.
        </div>
      </div>
    );
  }
  if (gateState === "pending") {
    return (
      <div
        className="pt-feature"
        style={{ width: "100%", maxWidth: 560, borderColor: "var(--ct-warn)" }}
      >
        <div className="pt-feature-eyebrow ct-eyebrow" style={{ color: "var(--ct-warn)" }}>
          Pending approval
        </div>
        <div className="pt-feature-title" style={{ color: "var(--ct-fg)" }}>
          <WarnIcon /> Your email isn't on the allowlist yet
        </div>
        <div className="pt-feature-body">
          Contact Seth at{" "}
          <a className="ct-mono" href="mailto:sethbenricks@gmail.com" style={{ color: "var(--ct-accent)" }}>
            sethbenricks@gmail.com
          </a>
          {" "}to request access. Once your account is added, refresh this page.
        </div>
      </div>
    );
  }
  // error
  return (
    <div
      className="pt-feature"
      style={{ width: "100%", maxWidth: 560, borderColor: "var(--ct-danger)" }}
    >
      <div className="pt-feature-eyebrow ct-eyebrow" style={{ color: "var(--ct-danger)" }}>
        Allowlist check failed
      </div>
      <div className="pt-feature-body" style={{ color: "var(--ct-danger)" }}>
        {gateError || "Couldn't reach the allowlist server."}
      </div>
    </div>
  );
}

// ----- Tiny inline icons + shared bits ----------------------------------
function CheckIcon() {
  return (
    <svg width={18} height={18} viewBox="0 0 24 24" fill="none"
         stroke="var(--ct-good)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"
         style={{ verticalAlign: "-3px", marginRight: 6 }}>
      <polyline points="5 12 10 17 19 7"/>
    </svg>
  );
}

function WarnIcon() {
  return (
    <svg width={18} height={18} viewBox="0 0 24 24" fill="none"
         stroke="var(--ct-warn)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"
         style={{ verticalAlign: "-3px", marginRight: 6 }}>
      <path d="M12 3 L22 20 L2 20 Z"/>
      <line x1="12" y1="10" x2="12" y2="14"/>
      <circle cx="12" cy="17" r="0.8" fill="var(--ct-warn)" stroke="none"/>
    </svg>
  );
}

function Topbar({ onNavigate }) {
  // PyBrand from brandmark.jsx — the new ">_" mark, replacing the prior
  // inline P-glyph so the topbar matches the brandmark.jsx logo.
  return (
    <header className="pt-topbar">
      <button className="pt-brand-btn" onClick={() => onNavigate("home")}>
        <window.PyBrand size={20} />
      </button>
    </header>
  );
}

function Footer() {
  return (
    <footer className="pt-footer">
      <div className="ct-mono ct-dim pt-footer-line">
        Part of the CTWCAD family. Built by Seth Ricks.
      </div>
    </footer>
  );
}

window.PythonTutorAccount = PythonTutorAccount;
