/* Trepa't — App / router con hash + idioma persistente */
function App() {
  const PAGES = {
    home: window.Home,
    empezar: window.Empezar,
    actividades: window.Actividades,
    tarifas: window.Tarifas,
    servicios: window.Servicios,
    centros: window.Centros,
    team: window.Team,
    nosotros: window.Nosotros,
    contacto: window.Contacto,
  };

  const parse = (hash) => {
    const raw = (hash || "").replace(/^#/, "");
    if (raw.indexOf("actividad/") === 0) {
      const slug = raw.slice("actividad/".length);
      if (window.TPT_ACT_BY_SLUG[slug]) return { page: "actividad", slug: slug };
      return { page: "actividades", slug: null };
    }
    return { page: PAGES[raw] ? raw : "home", slug: null };
  };

  const [route, setRoute] = React.useState(() => parse(location.hash));
  const [lang, setLang] = React.useState(() => {
    const saved = localStorage.getItem("tpt-lang");
    return window.TPT_I18N[saved] ? saved : "ES";
  });

  React.useEffect(() => {
    localStorage.setItem("tpt-lang", lang);
    document.documentElement.lang = window.TPT_I18N[lang].code;
  }, [lang]);

  const go = React.useCallback((id) => {
    const next = parse("#" + id);
    const hash = "#" + (next.page === "actividad" ? "actividad/" + next.slug : next.page);
    if (location.hash !== hash) history.pushState(null, "", hash);
    setRoute(next);
    window.scrollTo({ top: 0, behavior: "auto" });
  }, []);

  React.useEffect(() => {
    const onHash = () => { setRoute(parse(location.hash)); window.scrollTo({ top: 0, behavior: "auto" }); };
    window.addEventListener("popstate", onHash);
    window.addEventListener("hashchange", onHash);
    return () => { window.removeEventListener("popstate", onHash); window.removeEventListener("hashchange", onHash); };
  }, []);

  React.useEffect(() => {
    const run = () => window.lucide && window.lucide.createIcons();
    run();
    const t = setInterval(run, 250);
    setTimeout(() => clearInterval(t), 1500);
    return () => clearInterval(t);
  }, [route, lang]);

  const isDetail = route.page === "actividad";
  const Page = isDetail ? window.Actividad : (PAGES[route.page] || window.Home);
  const navPage = isDetail ? "actividades" : route.page;

  return (
    <div className="site-page">
      <window.Nav page={navPage} lang={lang} setLang={setLang} go={go} />
      <div className="site-main">
        <Page key={route.page + (route.slug || "") + lang} lang={lang} go={go} slug={route.slug} />
      </div>
      <window.Footer lang={lang} go={go} />
    </div>
  );
}

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