/* ── ROUTER / APP ──────────────────────────────────────────────────── */

const MARKETING_PATHS = ["/", "/login", "/pricing", "/get-started"];

// If we landed on /_kredoo/index.html (because the .htaccess rewrite didn't
// fire, or someone followed an old hash link), promote the hash route to a
// clean pathname so the browser URL never shows the /_kredoo/ internals.
(function cleanInternalUrl() {
  if (!/\/_kredoo\/(index\.html)?$/i.test(window.location.pathname)) return;
  const h = window.location.hash.replace(/^#/, "");
  const target = (h && /^\/(login|pricing|get-started)$/.test(h)) ? h : "/";
  window.history.replaceState(null, "", target);
})();

function getInitialRoute() {
  const p = (window.location.pathname || "/").replace(/\/$/, "") || "/";
  if (MARKETING_PATHS.includes(p)) return p;
  // Fallback for legacy hash links (#/login, #/pricing…)
  const h = window.location.hash.replace(/^#/, "");
  if (h && MARKETING_PATHS.includes(h)) return h;
  return "/";
}

function usePathRoute() {
  const [path, setPath] = useState(getInitialRoute);
  useEffect(() => {
    const on = () => {
      setPath(getInitialRoute());
      window.scrollTo(0, 0);
    };
    window.addEventListener("popstate", on);
    window.addEventListener("kr-route", on);
    return () => {
      window.removeEventListener("popstate", on);
      window.removeEventListener("kr-route", on);
    };
  }, []);
  return path;
}

function useMarketingLinkInterceptor() {
  useEffect(() => {
    const onClick = (e) => {
      if (e.defaultPrevented) return;
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
      const a = e.target.closest && e.target.closest("a");
      if (!a) return;
      const href = a.getAttribute("href");
      if (!href || a.target === "_blank" || a.hasAttribute("download")) return;
      // Only intercept in-marketing-site nav (full reload for /dashboard, /home, etc.)
      if (!MARKETING_PATHS.includes(href)) return;
      e.preventDefault();
      if (window.location.pathname !== href) {
        window.history.pushState(null, "", href);
        window.dispatchEvent(new Event("kr-route"));
      }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);
}

function App() {
  const route = usePathRoute();
  useMarketingLinkInterceptor();

  let page;
  if (route === "/login") page = <LoginPage />;
  else if (route === "/get-started") page = <GetStartedPage />;
  else if (route === "/pricing") page = <PricingPage />;
  else page = <LandingPage />;

  return (
    <div data-screen-label={
      route === "/login" ? "02 Login" :
      route === "/get-started" ? "03 Get Started" :
      route === "/pricing" ? "04 Pricing" :
      "01 Landing"
    }>
      {page}
    </div>
  );
}

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