// Jai Mahal Audio Tour — Root App
// Handles routing via URL hash (?stop=N or #welcome / #closing).
// This is what the QR codes will deep-link into.

const { useState, useEffect } = React;

function readRoute() {
  const url = new URL(window.location.href);
  const q = url.searchParams.get("stop");
  const hash = url.hash.replace("#", "");
  if (q) {
    if (q === "welcome") return { view: "welcome" };
    if (q === "end" || q === "closing") return { view: "closing" };
    const n = parseInt(q, 10);
    if (n >= 1 && n <= 5) return { view: "checkpoint", ch: n };
  }
  if (hash === "closing" || hash === "end") return { view: "closing" };
  if (hash.startsWith("stop-")) {
    const n = parseInt(hash.replace("stop-", ""), 10);
    if (n >= 1 && n <= 5) return { view: "checkpoint", ch: n };
  }
  return { view: "welcome" };
}

function writeRoute(state) {
  const url = new URL(window.location.href);
  url.searchParams.delete("stop");
  if (state.view === "welcome") {
    window.history.replaceState({}, "", url.pathname);
  } else if (state.view === "closing") {
    url.searchParams.set("stop", "end");
    window.history.replaceState({}, "", url.pathname + url.search);
  } else {
    url.searchParams.set("stop", String(state.ch));
    window.history.replaceState({}, "", url.pathname + url.search);
  }
}

function App() {
  const [route, setRoute] = useState(() => readRoute());

  useEffect(() => writeRoute(route), [route]);

  // Scroll-to-top on route change
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route.view, route.ch]);

  const goHome = () => setRoute({ view: "welcome" });
  const goCh = (n) => {
    if (n < 1) return goHome();
    if (n > 5) return setRoute({ view: "closing" });
    setRoute({ view: "checkpoint", ch: n });
  };
  const goClosing = () => setRoute({ view: "closing" });

  return (
    <div className="app-root">
      {route.view === "welcome" && (
        <WelcomeScreen onBegin={() => goCh(1)} onSelectChapter={(n) => goCh(n)} />
      )}
      {route.view === "checkpoint" && (
        <CheckpointScreen
          chId={route.ch}
          onHome={goHome}
          onPrev={() => goCh(route.ch - 1)}
          onNext={() => goCh(route.ch + 1)}
          onComplete={goClosing}
        />
      )}
      {route.view === "closing" && <ClosingScreen onHome={goHome} />}
    </div>
  );
}

window.App = App;
