/* App.jsx — top-level router + tweaks panel */

const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "default",
  "typePair": "grotesque"
}/*EDITMODE-END*/;

const VALID_ROUTES = ["home", "camps", "programs", "gallery", "venice", "mece-choir", "about", "collaboration", "testimonials", "employment", "employment-apply", "promote", "workshop", "register", "volunteer", "shop", "shop-success", "attendance"];

function App() {
  // Split route from any query string (e.g. CR #264 Stripe redirects to
  // /#shop-success?ref=LP-XXXX -- routing must ignore the query, but the
  // ShopSuccessPage component reads it back off window.location.hash).
  const rawHash = (window.location.hash || "#home").slice(1) || "home";
  const rawNoSubmit = rawHash === "submit" ? "promote" : rawHash;
  const initialHash = rawNoSubmit.split("?")[0];
  const [route, setRoute] = useState(VALID_ROUTES.includes(initialHash) ? initialHash : "home");
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];

  useEffect(() => {
    // Only rewrite the hash if the route part actually changed -- preserves
    // any query string the route currently carries (CR #264 shop-success).
    const currentRoutePart = (window.location.hash || "").slice(1).split("?")[0];
    if (currentRoutePart !== route) {
      history.replaceState(null, "", `#${route}`);
    }
    // CR #204: scroll to top on every route change so users land at the top
    // of the new page (footer link clicks were preserving the bottom-of-page
    // scroll position from the previous page).
    window.scrollTo(0, 0);
  }, [route]);

  useEffect(() => {
    const onPop = () => {
      let h = (window.location.hash || "#home").slice(1) || "home";
      if (h === "submit") h = "promote";
      h = h.split("?")[0];
      // Only react to recognised top-level routes. In-page anchors like #sites
      // or #process should fall through so the browser scrolls them into view.
      if (VALID_ROUTES.includes(h)) setRoute(h);
    };
    window.addEventListener("hashchange", onPop);
    return () => window.removeEventListener("hashchange", onPop);
  }, []);

  // Apply tweaks to root
  useEffect(() => {
    const root = document.documentElement;
    root.dataset.palette = tweaks.palette === "default" ? "" : tweaks.palette;
    root.dataset.type = tweaks.typePair;
  }, [tweaks.palette, tweaks.typePair]);

  // CR #268: scope a Love Park red palette to the /shop page only via a
  // root data-page attribute that tokens.css picks up. Includes shop-success
  // so the confirmation screen stays on-brand.
  useEffect(() => {
    const root = document.documentElement;
    if (route === "shop" || route === "shop-success") {
      root.dataset.page = "shop";
    } else {
      delete root.dataset.page;
    }
  }, [route]);

  return (
    <div className="site">
      <Header route={route} setRoute={setRoute} />
      <main>
        {route === "home" && <HomePage setRoute={setRoute} />}
        {route === "camps" && <CampsPage setRoute={setRoute} />}
        {route === "programs" && <ProgramsPage />}
        {route === "gallery" && <GalleryPage />}
        {route === "venice" && <VenicePage />}
        {route === "mece-choir" && <MECEChoirPage />}
        {route === "about" && <AboutPage />}
        {route === "collaboration" && <CollaborationPage />}
        {route === "testimonials" && <TestimonialsPage />}
        {route === "employment" && <EmploymentPage />}
        {route === "employment-apply" && <EmploymentApplicationPage />}
        {route === "promote" && <CenterSubmitPage />}
        {route === "workshop" && <WorkshopPage />}
        {route === "register" && <ParticipantRegistrationPage />}
        {route === "volunteer" && <VolunteerPage />}
        {route === "shop" && <ShopPage />}
        {route === "shop-success" && <ShopSuccessPage />}
        {route === "attendance" && <ParentAttendancePage />}
      </main>
      <Footer setRoute={setRoute} />

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Color palette">
            <window.TweakRadio
              value={tweaks.palette}
              onChange={(v) => setTweak("palette", v)}
              options={[
                { value: "default", label: "Sunlit Terracotta" },
                { value: "plum", label: "Stage Plum" },
                { value: "citrus", label: "Daylight Citrus" },
                { value: "cobalt", label: "Civic Cobalt" },
              ]}
            />
          </window.TweakSection>
          <window.TweakSection title="Typography">
            <window.TweakRadio
              value={tweaks.typePair}
              onChange={(v) => setTweak("typePair", v)}
              options={[
                { value: "grotesque", label: "Bricolage + DM Sans" },
                { value: "condensed", label: "Familjen Grotesk" },
                { value: "editorial", label: "Fraunces + DM Sans" },
                { value: "poster", label: "Anton + DM Sans" },
              ]}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

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