/* =========================================================================
 *  Python Tutor — App shell (client-side router)
 *  -----------------------------------------------------------------------
 *  Three routes: 'home' | 'desktop-signin' | 'account'.
 *
 *  Phase B3 ships all three for real. Routing is pathname-driven (Firebase
 *  Hosting rewrites every path to /index.html), but we ALSO support
 *  hash-style routes (#/desktop-signin) so the file:// preview works for
 *  local dev — the desktop's loopback URL always uses the clean path.
 *
 *  We listen to popstate so back/forward work, and use history.pushState
 *  for in-app navigation. The two stub Coming-Soon panels were removed
 *  in B3; the real components live in desktop-signin.jsx + account.jsx.
 * =======================================================================*/

const { useState, useEffect, useCallback } = React;

function pathToRoute(pathname, hash) {
  // Hash override (used during file:// preview): #/desktop-signin?...
  if (hash && hash.startsWith("#/")) {
    const h = hash.slice(2).split("?")[0].replace(/\/+$/, "");
    if (h === "desktop-signin") return "desktop-signin";
    if (h === "account") return "account";
    if (h === "" || h === "home") return "home";
  }
  const p = (pathname || "/").replace(/\/+$/, "") || "/";
  if (p === "/desktop-signin") return "desktop-signin";
  if (p === "/account") return "account";
  return "home";
}

function routeToPath(route) {
  if (route === "desktop-signin") return "/desktop-signin";
  if (route === "account") return "/account";
  return "/";
}

function App() {
  const [route, setRoute] = useState(() =>
    typeof window !== "undefined"
      ? pathToRoute(window.location.pathname, window.location.hash)
      : "home"
  );

  useEffect(() => {
    const onPop = () => setRoute(pathToRoute(window.location.pathname, window.location.hash));
    window.addEventListener("popstate", onPop);
    window.addEventListener("hashchange", onPop);
    return () => {
      window.removeEventListener("popstate", onPop);
      window.removeEventListener("hashchange", onPop);
    };
  }, []);

  const navigate = useCallback((next) => {
    setRoute(next);
    const path = routeToPath(next);
    // Preserve hash-style routing when the page is already running off a
    // hash URL (file:// preview). On real hosting we use clean paths.
    const usingHash = window.location.hash.startsWith("#/");
    if (usingHash) {
      const targetHash = next === "home" ? "" : "#" + path;
      if (window.location.hash !== targetHash) {
        // history.pushState with just the hash avoids a hashchange storm.
        window.history.pushState({}, "", targetHash || window.location.pathname);
      }
    } else if (window.location.pathname !== path) {
      window.history.pushState({}, "", path);
    }
    // Always scroll back to the top on route change — landing-style sites
    // expect this and the alternative is a confusing mid-page entry.
    window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
  }, []);

  // /desktop-signin must remain reachable to SIGNED_OUT and PENDING
  // users — that's where the desktop app sends people to complete the
  // OAuth handshake. Bypass the AccessGate ONLY here. The page handles
  // its own sign-in UX and won't expose product surfaces.
  if (route === "desktop-signin") {
    return <PythonTutorDesktopSignIn onNavigate={navigate} />;
  }

  // Every other route runs through the AccessGate: SIGNED_OUT users see
  // a "Continue with Google" card, signed-in but unapproved users see
  // a "Pending approval" card, and only allowlisted users see the app.
  const inner = route === "account"
    ? <PythonTutorAccount onNavigate={navigate} />
    : <PythonTutorHome    onNavigate={navigate} />;
  return <AccessGate>{inner}</AccessGate>;
}

window.App = App;
