/* =========================================================
   RENFECHT — App shell
   Async-loads values.json, mounts with ValuesContext.
   ========================================================= */

const PAGES = {
  home:      HomePage,
  event:     EventPage,
  about:     AboutPage,
  gallery:   GalleryPage,
  register:  RegisterPage,
  champions: ChampionsPage,
  sponsors:  SponsorsPage,
  faq:       FaqPage,
  contact:   ContactPage,
};

function App({ values }) {
  const [page, setPage] = React.useState(() => {
    const h = (window.location.hash || "#home").replace("#", "");
    return PAGES[h] ? h : "home";
  });

  const [tweakValues, setTweak] = useTweaks(DEFAULT_TWEAKS);
  React.useEffect(() => applyTweaksToDOM(tweakValues), []);

  const navigate = (next) => {
    if (next === page) { window.scrollTo({ top: 0, behavior: "smooth" }); return; }
    setPage(next);
    window.location.hash = next;
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  React.useEffect(() => {
    const onHash = () => {
      const h = (window.location.hash || "#home").replace("#", "");
      if (PAGES[h]) setPage(h);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const Page = PAGES[page] || HomePage;

  return (
    <ValuesContext.Provider value={values}>
      <SiteHeader active={page} onNavigate={navigate} tweaks={tweakValues} setTweak={setTweak} />
      <Page onNavigate={navigate} heroVariant={tweakValues.heroVariant} />
      <SiteFooter onNavigate={navigate} />
      <RenfechtTweaksPanel tweaks={tweakValues} setTweak={setTweak} />
    </ValuesContext.Provider>
  );
}

/* ---------- Boot: fetch values.json then mount ---------- */

(async function boot() {
  let values = null;
  try {
    const res = await fetch("values.json");
    if (!res.ok) throw new Error("HTTP " + res.status);
    values = await res.json();
  } catch (err) {
    document.getElementById("app").innerHTML =
      '<div style="padding: 60px; text-align: center; font-family: serif;">' +
        '<h1 style="color: #950606;">Failed to load values.json</h1>' +
        '<p style="color: #555;">' + String(err) + '</p>' +
      '</div>';
    return;
  }
  ReactDOM.createRoot(document.getElementById("app")).render(<App values={values} />);
})();
