// ActionMinutes — root app: pathname-based router, real API, JWT auth
const { useState: useStateA, useEffect: useEffectA, useCallback: useCallbackA } = React;

const PRODUCT_NAME = "ActionMinutes";

// Routes that require a valid JWT
const AUTH_REQUIRED_PATHS = ["/setup", "/home", "/jobs", "/minutes"];
// Routes that must NOT have a JWT (redirect to /home if already authed)
const ANON_ONLY_PATHS = ["/", "/start"];

function isPathAuthRequired(path) {
  return AUTH_REQUIRED_PATHS.some((p) => path.startsWith(p));
}

function AMApp() {
  const [path, setPath] = useStateA(window.location.pathname + window.location.search);
  const [user, setUser] = useStateA({ name: "", email: "", jurisdiction: "", role: "" });
  const [appState, setAppState] = useStateA({
    boardId: null,
    boardName: "",
    generationId: null,
    credits: { used: 0, total: 3, remaining: 3, resetsOn: "next month" },
    isStaff: false,
    actor: null,
    actorAccount: null,
  });
  const [authChecked, setAuthChecked] = useStateA(false);

  const navigate = useCallbackA((to) => {
    window.history.pushState(null, "", to);
    setPath(to);
    window.scrollTo(0, 0);
  }, []);

  // Handle browser back/forward
  useEffectA(() => {
    const onPop = () => setPath(window.location.pathname + window.location.search);
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Bootstrap: check auth on load
  useEffectA(() => {
    const token = AM_API.getToken();
    const currentPath = window.location.pathname;

    if (!token) {
      setAuthChecked(true);
      if (isPathAuthRequired(currentPath)) {
        navigate("/start");
      }
      return;
    }

    // Validate token by hitting /me
    AM_API.auth.me().then((me) => {
      setUser({ name: me.name || "", email: me.email || "", jurisdiction: me.jurisdiction || "", role: me.role || "" });
      setAppState((s) => ({
        ...s,
        isStaff: !!me.isStaff,
        actor: me.actor || null,
        actorAccount: me.actorAccount || null,
        credits: me.credits || s.credits,
      }));
      setAuthChecked(true);
      // If on an anon-only path with a valid token, redirect to /home
      if (ANON_ONLY_PATHS.includes(currentPath)) {
        navigate("/home");
      }
    }).catch(() => {
      AM_API.clearToken();
      setAuthChecked(true);
      if (isPathAuthRequired(currentPath)) {
        navigate("/start");
      }
    });
  }, []);

  if (!authChecked) {
    return (
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <span className="am-spin" style={{ width: 36, height: 36, borderColor: "rgba(3,149,255,0.2)", borderTopColor: "var(--pi-blue)", display: "inline-block" }}></span>
      </div>
    );
  }

  const pathname = path.split("?")[0];
  const name = PRODUCT_NAME;

  // Screens that show the AppBar
  const hasAppBar = (
    pathname.startsWith("/setup") ||
    pathname.startsWith("/jobs") ||
    pathname.startsWith("/minutes") ||
    pathname === "/home"
  );

  // Which screens get the BrowserStrip
  const isEmailView = false; // No email-simulation views in real app

  const token = AM_API.getToken();
  const credits = appState.credits || { used: 0, total: 3, remaining: 3, resetsOn: "next month" };

  const commonProps = {
    name,
    navigate,
    user,
    setUser,
    appState,
    setAppState,
    isStaff: appState.actor === "staff",
  };

  const handleExitStaff = () => {
    // Clear and reload to return to own session
    AM_API.clearToken();
    window.location.href = "/start";
  };

  let page = null;

  if (pathname === "/" || pathname === "") {
    page = <LandingPage {...commonProps} />;
  } else if (pathname === "/start") {
    page = <SignupPage {...commonProps} />;
  } else if (pathname === "/verify") {
    page = <VerifyPage {...commonProps} />;
  } else if (pathname === "/setup/board") {
    page = <BoardPickPage {...commonProps} />;
  } else if (pathname === "/setup/sources") {
    page = <InterviewPage {...commonProps} />;
  } else if (pathname === "/setup/equation") {
    page = <EquationPage {...commonProps} />;
  } else if (pathname.startsWith("/jobs/")) {
    const genId = pathname.split("/")[2];
    const state = genId ? { ...appState, generationId: genId } : appState;
    page = <ProcessingPage {...commonProps} appState={state} />;
  } else if (pathname.startsWith("/minutes/")) {
    const genId = pathname.split("/")[2];
    const state = genId ? { ...appState, generationId: genId } : appState;
    page = <MinutesPage {...commonProps} appState={state} />;
  } else if (pathname === "/home") {
    page = <DashboardPage {...commonProps} />;
  } else {
    // 404 — redirect to home or landing
    page = (
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 16 }}>
        <AMIcon name="file-question" size={40} color="var(--pi-gray-400)" />
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18, color: "var(--fg-2)" }}>Page not found</div>
        <button className="pi-btn pi-btn-primary" onClick={() => navigate(token ? "/home" : "/")}>
          {token ? "Go to dashboard" : "Go to home"}
        </button>
      </div>
    );
  }

  return (
    <React.Fragment>
      <div className="am-viewport">
        <div className="am-screen" key={pathname}>
          {hasAppBar && (
            <AppBar
              name={name}
              used={credits.used}
              allowance={credits.total}
              resetLabel={credits.resetsOn}
              onHome={() => navigate("/home")}
              user={user}
              isStaff={appState.actor === "staff"}
              actorAccount={appState.actorAccount}
              onExitStaff={handleExitStaff}
            />
          )}
          <AMErrorBoundary>
            {page}
          </AMErrorBoundary>
        </div>
      </div>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<AMApp />);
