// App shell — router + state
const { useState, useEffect, useMemo } = React;

function App() {
  const [path, setPath] = useState(() => window.location.hash.replace(/^#/, "") || "/");
  const [device, setDevice] = useState("desktop");
  const [signedIn, setSignedIn] = useState(false);
  const [buyOpen, setBuyOpen] = useState(null);
  const [successFor, setSuccessFor] = useState(null);

  function nav(to) {
    window.location.hash = to;
    setPath(to);
    window.scrollTo({ top: 0, behavior: "instant" });
  }

  useEffect(() => {
    const onHash = () => setPath(window.location.hash.replace(/^#/, "") || "/");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  function onBuy(modId) {
    if (!signedIn) {
      nav("/auth/sign-in");
      // stash intent
      window.__pendingBuy = modId;
      return;
    }
    setBuyOpen(modId);
  }
  function confirmBuy() {
    const id = buyOpen;
    setBuyOpen(null);
    setSuccessFor(id);
    nav("/success");
  }
  function handleSignIn() {
    setSignedIn(true);
    if (window.__pendingBuy) {
      const id = window.__pendingBuy;
      window.__pendingBuy = null;
      nav("/library");
      setTimeout(() => setBuyOpen(id), 300);
    } else {
      nav("/library");
    }
  }
  function handleSignOut() {
    setSignedIn(false);
    nav("/");
  }
  function handleReset() {
    setSignedIn(false);
    setBuyOpen(null);
    setSuccessFor(null);
    window.__pendingBuy = null;
    nav("/");
  }

  const isMobile = device === "mobile";

  // Pick screen
  let Screen = null;
  if (path === "/" || path === "") Screen = <LandingScreen nav={nav} device={device} />;
  else if (path === "/catalog") Screen = <CatalogScreen nav={nav} signedIn={signedIn} />;
  else if (path.startsWith("/m/")) Screen = <ModuleScreen nav={nav} moduleId={path.slice(3)} signedIn={signedIn} onBuy={onBuy} />;
  else if (path.startsWith("/v/")) Screen = <VideoScreen nav={nav} videoId={path.slice(3)} onBuy={onBuy} />;
  else if (path === "/auth/sign-in") Screen = <AuthScreen nav={nav} onSignIn={handleSignIn} />;
  else if (path === "/library") Screen = signedIn ? <LibraryScreen nav={nav} /> : <AuthScreen nav={nav} onSignIn={handleSignIn} />;
  else if (path === "/account") Screen = signedIn ? <AccountScreen nav={nav} onSignOut={handleSignOut} onReset={handleReset} /> : <AuthScreen nav={nav} onSignIn={handleSignIn} />;
  else if (path === "/success") Screen = <SuccessScreen nav={nav} moduleId={successFor} />;
  else Screen = <div className="container section"><p>Page not found. <a onClick={() => nav("/")}>Go home</a></p></div>;

  const innerContent = (
    <div className={`app-inner ${isMobile ? "is-mobile-view" : ""}`}>
      <SiteHeader path={path} device={device} signedIn={signedIn} nav={nav} setSignedIn={setSignedIn} />
      <main>{Screen}</main>
      <SiteFooter device={device} />
    </div>
  );

  return (
    <div className="app-viewport">
      <PreviewBar path={path} device={device} setDevice={setDevice} signedIn={signedIn} setSignedIn={setSignedIn} onReset={handleReset} />
      <div className={`device-wrap ${isMobile ? "is-mobile" : ""}`}>
        {isMobile ? (
          <div className="device-mobile">{innerContent}</div>
        ) : (
          <div className="device-desktop">{innerContent}</div>
        )}
      </div>
      {buyOpen && <BuyModal moduleId={buyOpen} onCancel={() => setBuyOpen(null)} onConfirm={confirmBuy} />}
    </div>
  );
}

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