// LandAI — combined site shell. Keeps clean URLs in sync with the active page.
const { useState, useEffect } = React;

const ROUTES = {
  mobile: "/",
  store: "/data-store",
  api: "/api",
  about: "/about",
  contact: "/contact",
};

function pageFromPath(pathname) {
  const p = String(pathname || "").toLowerCase();
  if (p === "/api" || p === "/api/") return "api";
  if (p.includes("data-store") || p.includes("datastore")) return "store";
  if (p.includes("about")) return "about";
  if (p.includes("contact")) return "contact";
  return "mobile";
}

function Site() {
  const [page, setPage] = useState(() => pageFromPath(window.location.pathname));

  useEffect(() => {
    const setRoute = (p, replace = false) => {
      const next = ROUTES[p] ? p : "mobile";
      setPage(next);
      const url = ROUTES[next];
      if (window.location.pathname !== url) {
        window.history[replace ? "replaceState" : "pushState"]({ page: next }, "", url);
      }
      window.scrollTo(0, 0);
    };

    window.__landaiNav = (p) => setRoute(p);

    const current = pageFromPath(window.location.pathname);
    if (/\/(Landing|Features|DataStore|About|Contact)\.html$/i.test(window.location.pathname)) {
      setRoute(current, true);
    }

    const onPopState = () => setPage(pageFromPath(window.location.pathname));
    window.addEventListener("popstate", onPopState);
    return () => {
      delete window.__landaiNav;
      window.removeEventListener("popstate", onPopState);
    };
  }, []);

  const Features = window.Features;
  const DataStore = window.DataStore;
  const ApiPage = window.ApiPage;
  const Contact = window.Contact;
  const About = window.About;
  if (page === "store") return <DataStore />;
  if (page === "api") return <ApiPage />;
  if (page === "contact") return <Contact />;
  if (page === "about") return <About />;
  return <Features />;
}

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