/* global React, ReactDOM */
// FirstSteps — root app with simple state-based router

const { useState, useEffect, useCallback } = React;

const DEFAULT_LANG = (() => {
  // Site default is English. We still respect an explicit user choice
  // saved in localStorage from a previous visit, but we never auto-pick
  // a language from navigator.language.
  try {
    const saved = localStorage.getItem("fs_lang");
    if (saved && ["en", "es", "ru"].includes(saved)) return saved;
    return "en";
  } catch (e) { return "en"; }
})();

// Every form on the site lives at a single canonical URL: #/apply/form.
// Program / track / form-type context travels in sessionStorage so the URL
// remains identical whether the lead came from a player program, a track,
// or the collaboration page.
const APPLY_CTX_KEY = "fs_apply_ctx";

function writeApplyContext(ctx) {
  try { sessionStorage.setItem(APPLY_CTX_KEY, JSON.stringify(ctx || {})); } catch (e) {}
}
function readApplyContext() {
  try {
    const raw = sessionStorage.getItem(APPLY_CTX_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch (e) { return null; }
}
// Expose for child components that don't get the helpers as props.
window.FS_APPLY_CTX_KEY = APPLY_CTX_KEY;
window.fsReadApplyContext  = readApplyContext;
window.fsWriteApplyContext = writeApplyContext;

function parseHash() {
  const h = (window.location.hash || "").replace(/^#\/?/, "");
  if (!h) return { name: "home" };
  const parts = h.split("/");
  if (parts[0] === "program" && parts[1]) return { name: "program", id: parts[1], track: parts[2] || null };
  // Canonical form URL — #/apply/form. We still accept legacy #/apply/{id}/{track}
  // links (e.g. bookmarks, old emails) and silently migrate their context into
  // sessionStorage, then the route resolves to the unified form.
  if (parts[0] === "apply") {
    if (parts[1] && parts[1] !== "form") {
      writeApplyContext({ type: "player", programId: parts[1], trackId: parts[2] || null });
    }
    return { name: "apply" };
  }
  if (parts[0] === "thanks") return { name: "thanks", id: parts[1] || null, ref: parts[2] || null };
  if (parts[0] === "about")         return { name: "about" };
  if (parts[0] === "partners")      return { name: "partners", id: parts[1] || null };
  if (parts[0] === "collaboration") return { name: "collaboration" };
  return { name: "home" };
}
function routeToHash(r) {
  if (r.name === "home")    return "#/";
  if (r.name === "program") return "#/program/" + r.id + (r.track ? "/" + r.track : "");
  if (r.name === "apply")   return "#/apply/form";
  if (r.name === "thanks")  return "#/thanks/" + (r.id || "_") + (r.ref ? "/" + r.ref : "");
  if (r.name === "about")         return "#/about";
  if (r.name === "partners")      return "#/partners" + (r.id ? "/" + r.id : "");
  if (r.name === "collaboration") return "#/collaboration";
  return "#/";
}

function App() {
  const [lang, setLangState] = useState(DEFAULT_LANG);
  const [route, setRoute] = useState(parseHash());

  const setLang = (l) => {
    setLangState(l);
    try { localStorage.setItem("fs_lang", l); } catch (e) {}
    document.documentElement.setAttribute("lang", l);
  };

  useEffect(() => {
    document.documentElement.setAttribute("lang", lang);
  }, [lang]);

  const navigate = useCallback((r) => {
    // When the destination is the unified form, persist the original context
    // (program/track or collaboration intent) BEFORE the hash change, so the
    // form has everything it needs without the URL revealing it.
    if (r && r.name === "apply") {
      const ctx = {
        type:      r.type      || "player",
        programId: r.id        || null,
        trackId:   r.track     || null,
        returnTo:  r.returnTo  || null,
      };
      writeApplyContext(ctx);
    }
    window.location.hash = routeToHash(r);
    setRoute(typeof r === "object" && r.name === "apply" ? { name: "apply" } : r);
  }, []);

  useEffect(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const onDark = route.name === "thanks";

  let page;
  if (route.name === "program")            page = <ProgramDetail   lang={lang} programId={route.id} trackId={route.track} navigate={navigate} />;
  else if (route.name === "apply")          page = <ApplyPage       lang={lang} navigate={navigate} />;
  else if (route.name === "thanks")         page = <ThankYouPage    lang={lang} refCode={route.ref} navigate={navigate} />;
  else if (route.name === "about")          page = <AboutPage       lang={lang} navigate={navigate} />;
  else if (route.name === "partners")       page = route.id
    ? <ClubDetailPage  lang={lang} clubId={route.id} navigate={navigate} />
    : <PartnersPage    lang={lang} navigate={navigate} />;
  else if (route.name === "collaboration")  page = <CollaborationPage lang={lang} navigate={navigate} />;
  else page = <HomePage lang={lang} navigate={navigate} />;

  return (
    <React.Fragment>
      <Header lang={lang} setLang={setLang} navigate={navigate} onDark={onDark} route={route} />
      {page}
      <Footer lang={lang} navigate={navigate} />
    </React.Fragment>
  );
}

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