// app.jsx — router shell + global state

const { useState, useEffect, useMemo, useCallback } = React;

// Production defaults: a fresh visitor is logged out and not yet enrolled.
// The auth flows (login → logged_in, signup → logged_in + enrolled) update this in-memory.
const APP_DEFAULTS = {
  authState: "logged_out",   // logged_out | logged_in
  enrollment: "not_enrolled", // enrolled  | not_enrolled | expired
};

// Minimal state hook with the same `setTweak(key, value)` / `setTweak({k1: v1, ...})` API
// the existing pages call. No persistence, no postMessage, no panel.
function useAppState(defaults) {
  const [state, setState] = useState(defaults);
  const set = useCallback((keyOrObj, value) => {
    setState((prev) => {
      if (typeof keyOrObj === "string") return { ...prev, [keyOrObj]: value };
      if (keyOrObj && typeof keyOrObj === "object") return { ...prev, ...keyOrObj };
      return prev;
    });
  }, []);
  return [state, set];
}

function App() {
  const [t, setTweak] = useAppState(APP_DEFAULTS);

  // Hash router. /, /preview, /preview/:c/:ch, /login, /signup,
  // /payment/success, /payment/failed, /dashboard, /dashboard/live, ...
  const [route, setRoute] = useState(() => window.location.hash.replace(/^#/, "") || "/");
  useEffect(() => {
    const onHash = () => setRoute(window.location.hash.replace(/^#/, "") || "/");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const go = (path) => {
    window.location.hash = path;
    requestAnimationFrame(() => window.scrollTo({ top: 0, behavior: "instant" }));
  };

  const isLoggedIn = t.authState === "logged_in";
  const enrollment = t.enrollment;

  const ctx = { go, t, setTweak, isLoggedIn, enrollment };

  const path = route.split("?")[0];
  const parts = path.split("/").filter(Boolean);

  let page = null;
  if (path === "/")                         page = <LandingPage {...ctx} />;
  else if (path === "/preview")             page = <PreviewListPage {...ctx} />;
  else if (path.startsWith("/preview/"))    page = <PreviewViewerPage {...ctx} parts={parts} />;
  else if (path === "/login")               page = <LoginPage {...ctx} />;
  else if (path === "/signup")              page = <SignupPage {...ctx} />;
  else if (path === "/payment/success")     page = <PaymentSuccessPage {...ctx} />;
  else if (path === "/payment/failed")      page = <PaymentFailedPage {...ctx} />;
  else if (path === "/dashboard")           page = <DashboardHome {...ctx} />;
  else if (path === "/dashboard/live")      page = <DashboardLive {...ctx} />;
  else if (path === "/dashboard/recordings")page = <DashboardRecordings {...ctx} />;
  else if (path.startsWith("/dashboard/recordings/")) page = <DashboardRecordingPlayer {...ctx} parts={parts}/>;
  else if (path === "/dashboard/profile")   page = <DashboardProfile {...ctx} />;
  else if (path === "/admin")               page = <AdminDashboard {...ctx} />;
  else if (path === "/admin/students")      page = <AdminStudents {...ctx} />;
  else if (path === "/admin/batches")       page = <AdminBatches {...ctx} />;
  else if (path === "/admin/recordings")    page = <AdminRecordings {...ctx} />;
  else if (path === "/admin/payments")      page = <AdminPayments {...ctx} />;
  else if (path === "/privacy")             page = <PrivacyPage {...ctx} />;
  else if (path === "/terms")               page = <TermsPage {...ctx} />;
  else if (path === "/refund")              page = <RefundPage {...ctx} />;
  else                                       page = <NotFound {...ctx} />;

  return (
    <div className="app">
      <div key={route} className="page-anim" style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        {page}
      </div>
    </div>
  );
}

const NotFound = ({ go }) => (
  <div className="container section center col" style={{ alignItems: "center", textAlign: "center" }}>
    <div className="eyebrow">404</div>
    <h2 style={{ marginTop: 12 }}>Page not found</h2>
    <p className="muted" style={{ marginTop: 12, maxWidth: 420 }}>The page you're looking for doesn't exist.</p>
    <button className="btn btn-primary" style={{ marginTop: 24 }} onClick={() => go("/")}>← Back to home</button>
  </div>
);

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