"use client";
import { jsx } from "react/jsx-runtime";
import { unsafeKeys } from "@edgeandnode/common";
import * as RadixTooltip from "@radix-ui/react-tooltip";
import { forwardRef, useRef, useEffect } from "react";
import { merge, ThemeUIProvider } from "theme-ui";
import { GDSContext } from "./GDSContext.js";
import { theme } from "./theme.js";
import { legacyTheme } from "./theme.legacy.js";
import { normalizePath } from "../utils/normalizePath.js";
import { ButtonOrLink } from "../atoms/ButtonOrLink/ButtonOrLink.js";
const GDSProvider = ({
  clientRouter,
  clientLink: passedClientLink,
  mapButtonOrLinkProps,
  useThemeUI = false,
  children
}) => {
  const clientLink = passedClientLink != null ? passedClientLink : MockClientLink;
  const useRouter = () => {
    if (!clientRouter) return null;
    let appRouter = null;
    let pagesRouter = null;
    let pathname;
    let params;
    let searchParams;
    if ("usePathname" in clientRouter) {
      appRouter = clientRouter.useRouter();
      pathname = clientRouter.usePathname();
      params = clientRouter.useParams();
      searchParams = clientRouter.useSearchParams();
    } else {
      pagesRouter = clientRouter;
      pathname = `${clientRouter.locale ? `/${clientRouter.locale}` : ""}${clientRouter.asPath.split(/[?#]/)[0]}`;
      if (clientRouter.asPath.includes("?")) {
        searchParams = new URLSearchParams(clientRouter.asPath.split("?")[1]);
      } else {
        searchParams = new URLSearchParams();
      }
      params = {};
      Object.entries(clientRouter.query).forEach(([key, value]) => {
        if (!searchParams.has(key) && value !== void 0) {
          params[key] = String(value);
        }
      });
    }
    const basePath = clientRouter.basePath ? normalizePath(clientRouter.basePath) : "";
    const fullPathname = `${basePath}${pathname}`;
    return {
      appRouter,
      pagesRouter,
      pathname,
      basePath,
      fullPathname,
      params,
      searchParams
    };
  };
  let finalTheme = null;
  if (useThemeUI) {
    const { useLegacyTheme = false, extendTheme } = typeof useThemeUI === "boolean" ? {} : useThemeUI;
    finalTheme = useLegacyTheme ? legacyTheme : theme;
    if (extendTheme) {
      finalTheme = merge(finalTheme, extendTheme);
    }
  }
  const isSpaceDown = useRef(false);
  useEffect(() => {
    const addAttribute = () => {
      if (isSpaceDown.current) return;
      isSpaceDown.current = true;
      document.documentElement.setAttribute("data-gds-active", "");
    };
    const removeAttribute = () => {
      if (!isSpaceDown.current) return;
      isSpaceDown.current = false;
      document.documentElement.removeAttribute("data-gds-active");
    };
    const onKeyDown = (event) => {
      if (event.code === "Space") addAttribute();
    };
    const onKeyUp = (event) => {
      if (event.code === "Space") removeAttribute();
    };
    const onWindowBlur = () => {
      removeAttribute();
    };
    const onVisibilityChange = () => {
      if (document.visibilityState === "hidden") removeAttribute();
    };
    window.addEventListener("keydown", onKeyDown);
    window.addEventListener("keyup", onKeyUp);
    window.addEventListener("blur", onWindowBlur);
    document.addEventListener("visibilitychange", onVisibilityChange);
    return () => {
      window.removeEventListener("keydown", onKeyDown);
      window.removeEventListener("keyup", onKeyUp);
      window.removeEventListener("blur", onWindowBlur);
      document.removeEventListener("visibilitychange", onVisibilityChange);
    };
  }, []);
  return /* @__PURE__ */ jsx(MaybeThemeUIProvider, { theme: finalTheme, children: /* @__PURE__ */ jsx(GDSContext.Provider, { value: { isProvided: true, clientLink, useRouter }, children: /* @__PURE__ */ jsx(MaybeButtonOrLinkConfig, { mapButtonOrLinkProps, children: /* @__PURE__ */ jsx(RadixTooltip.Provider, { delayDuration: 300, children }) }) }) });
};
const MaybeThemeUIProvider = ({ theme: theme2, children }) => {
  if (theme2 == null) return children;
  return /* @__PURE__ */ jsx(ThemeUIProvider, { theme: theme2, children });
};
const MaybeButtonOrLinkConfig = ({
  mapButtonOrLinkProps,
  children
}) => {
  if (!mapButtonOrLinkProps) return children;
  return /* @__PURE__ */ jsx(ButtonOrLink.Config, { mapProps: mapButtonOrLinkProps, children });
};
const MockClientLink = forwardRef(
  ({ href: propsHref, as, legacyBehavior, locale, passHref, prefetch, replace, scroll, shallow, ...rest }, ref) => {
    let href;
    if (typeof propsHref === "object") {
      const url = new URL(window.location.href);
      unsafeKeys(propsHref).forEach((key) => {
        if (key === "auth" || key === "slashes" || key === "query") return;
        if (propsHref[key]) url[key] = String(propsHref[key]);
      });
      href = url.toString();
    } else {
      href = propsHref;
    }
    return /* @__PURE__ */ jsx("a", { ref, href, ...rest });
  }
);
MockClientLink.displayName = "MockClientLink";
export {
  GDSProvider,
  MockClientLink
};
