/* global React, ReactDOM, Nav, Hero, HomeBody, Nosotros, Productos, Servicios, Contacto, Footer */
// ====================================================================
// App shell: tab routing + page transitions.
// ====================================================================

function App() {
  const [tab, setTab] = React.useState(() => {
    const h = (window.location.hash || "").replace("#", "");
    return ["inicio", "nosotros", "productos", "servicios", "contacto"].includes(h) ? h : "inicio";
  });
  const [anim, setAnim] = React.useState(0);

  const go = React.useCallback((id) => {
    setTab((prev) => {
      if (prev !== id) {
        window.scrollTo({ top: 0, behavior: "auto" });
        setAnim((a) => a + 1);
      }
      return id;
    });
    window.history.replaceState(null, "", "#" + id);
  }, []);

  React.useEffect(() => {
    const onHash = () => {
      const h = (window.location.hash || "").replace("#", "");
      if (["inicio", "nosotros", "productos", "servicios", "contacto"].includes(h)) {
        setTab(h); setAnim((a) => a + 1);
      }
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  let page;
  if (tab === "inicio") page = <><Hero go={go} /><HomeBody go={go} /></>;
  else if (tab === "nosotros") page = <Nosotros go={go} />;
  else if (tab === "productos") page = <Productos go={go} />;
  else if (tab === "servicios") page = <Servicios go={go} />;
  else page = <Contacto go={go} />;

  return (
    <div className="app">
      <Nav tab={tab} go={go} />
      <main key={anim} className="page-enter">
        {page}
      </main>
      <Footer go={go} />
    </div>
  );
}

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