// Page bootstrap shared by every page: the language, <html lang>, hash
// scrolling under the sticky nav, and the React root. Loaded after the modules
// and before each page's inline script.

// Height of the sticky nav plus breathing room, so a hash target is not hidden
// under it.

(function (NUON) {
  const HASH_SCROLL_OFFSET = 90;

  function readLang() {
    return new URLSearchParams(window.location.search).get("lang") === "en" ? "en" : "es";
  }

  function scrollToHash() {
    const id = window.location.hash.replace(/^#/, "");
    if (!id) return;
    const el = document.getElementById(id);
    if (!el) return;
    requestAnimationFrame(() => {
      const top = window.scrollY + el.getBoundingClientRect().top - HASH_SCROLL_OFFSET;
      window.scrollTo({ top, behavior: "smooth" });
    });
  }

  // `?lang=en` opens the page in English; anything else is Spanish. The choice
  // is written back to the URL, only when it is not the default, so a link
  // copied from an English page stays English. <html lang> follows it for
  // assistive technology and hyphenation.
  function usePageLang() {
    const [lang, setLang] = React.useState(readLang);
    React.useEffect(() => {
      document.documentElement.lang = lang;
      const url = new URL(window.location.href);
      if (lang === "en") url.searchParams.set("lang", "en");
      else url.searchParams.delete("lang");
      window.history.replaceState({}, "", url.toString());
    }, [lang]);
    React.useEffect(() => {
      scrollToHash();
      window.addEventListener("hashchange", scrollToHash);
      return () => window.removeEventListener("hashchange", scrollToHash);
    }, []);
    return [lang, setLang];
  }

  function mountPage(Page) {
    ReactDOM.createRoot(document.getElementById("root")).render(<Page />);
  }
  Object.assign(NUON, { usePageLang, mountPage });
})((window.NUON ??= {}));
