"use client";
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { useMap } from "@react-hookz/web";
import { motion } from "motion/react";
import { forwardRef, useRef, useId, useContext, createContext, useState, useCallback, useMemo } from "react";
import { ExperimentalIcon } from "./Icon.js";
import { ExperimentalMegaMenuTriggerContext } from "./shared.js";
import { useStyleObserver } from "./hooks/useStyleObserver.js";
import { CaretDownInteractive } from "../icons/CaretDownInteractive.js";
import { useCSSPropsPolyfill } from "./tailwind/useCSSPropsPolyfill.js";
import { getCSSPropsAttributes } from "./tailwind/cssProps.js";
import { classNames } from "../utils/classNames.js";
import { ButtonOrLink } from "../atoms/ButtonOrLink/ButtonOrLink.js";
import { ArrowUpRightInteractive } from "../icons/ArrowUpRightInteractive.js";
const HIGHLIGHT_TRANSITION_DURATION = 200;
function isNavLinkState(value) {
  return typeof value === "string" && ["none", "hover", "expanded"].includes(value);
}
const ExperimentalNavLinkRoot = forwardRef(
  ({
    variant,
    iconBefore,
    iconAfter: passedIconAfter,
    current = false,
    highlightOnInteraction: passedHighlightOnInteraction,
    className,
    style,
    children,
    ...props
  }, ref) => {
    const { polyfillAttributes, polyfillElement } = useCSSPropsPolyfill("nav-link", { variant });
    const wrapperRef = useRef(null);
    const id = useId();
    const isMegaMenuTrigger = useContext(ExperimentalMegaMenuTriggerContext) !== null;
    const groupContext = useContext(ExperimentalNavLinkGroupContext);
    const [stateWhenNoGroupHighlight, setStateWhenNoGroupHighlight] = useState("none");
    let highlightOnInteraction = passedHighlightOnInteraction ?? (groupContext == null ? void 0 : groupContext.highlightOnInteraction) ?? false;
    if (highlightOnInteraction && (groupContext == null ? void 0 : groupContext.highlightOnInteraction)) {
      highlightOnInteraction = "group";
    }
    let highlightedInGroup = highlightOnInteraction === "group" && ((groupContext == null ? void 0 : groupContext.highlightedNavLinkId) === id || !(groupContext == null ? void 0 : groupContext.highlightedNavLinkId) && ((groupContext == null ? void 0 : groupContext.justExitedNavLinkId) === id || !(groupContext == null ? void 0 : groupContext.justExitedNavLinkId) && current));
    if (highlightedInGroup && (groupContext == null ? void 0 : groupContext.justExitedNavLinkId) === id) {
      highlightedInGroup = "just-exited";
    }
    const highlighted = (() => {
      if (highlightOnInteraction === "group") {
        return highlightedInGroup;
      } else {
        return highlightOnInteraction && (stateWhenNoGroupHighlight === "hover" || stateWhenNoGroupHighlight === "expanded") || current;
      }
    })();
    const onStyleChange = useCallback(
      (values) => {
        const state = values["--gds-nav-link-state"];
        if (!isNavLinkState(state)) return;
        if (highlightOnInteraction === "group") {
          groupContext == null ? void 0 : groupContext.setNavLinkState(id, state);
        } else {
          setStateWhenNoGroupHighlight(state);
        }
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [id, highlightOnInteraction, groupContext == null ? void 0 : groupContext.setNavLinkState]
    );
    useStyleObserver(wrapperRef, ["--gds-nav-link-state"], onStyleChange);
    return /* @__PURE__ */ jsxs(
      "span",
      {
        ref: wrapperRef,
        "data-current": current || void 0,
        "data-highlight-on-interaction": highlightOnInteraction || void 0,
        "data-highlighted": highlighted || void 0,
        className: classNames([
          `group/nav-link gds-nav-link flex [--gds-nav-link-state:none]
          --:text-p16 -:size-max -:max-w-full -:text-[0] -:leading-0 -:[--gds-font-weight:0]
          -:[--gds-nav-link-offset-x:theme(spacing.2)]
          -:[--gds-nav-link-offset-y:theme(spacing.1)]
          -:[--gds-nav-link-padding-x:0px] -:[--gds-nav-link-padding-y:0px]
          has-clickable-hover:[--gds-nav-link-state:hover]
          has-clickable-[[aria-expanded=true]]:[--gds-nav-link-state:expanded]`,
          className
        ]),
        ...getCSSPropsAttributes("nav-link", { variant }, style),
        ...polyfillAttributes,
        children: [
          polyfillElement,
          /* @__PURE__ */ jsx(
            ButtonOrLink,
            {
              ref,
              selected: props.href !== void 0 ? current : void 0,
              className: `
            flex min-h-[1lh] ${/* Ensure consistent height between icon-only and other nav links */
              ""}
            grow items-center justify-center gap-1 px-[var(--gds-nav-link-padding-x)] py-[var(--gds-nav-link-padding-y)]
            text-[max(var(--default-font-size)-1em*9999,1em)]
            leading-[max(var(--default-line-height)-1lh*9999,1lh)]
            transition
            outline-none
            [font-weight:max(var(--default-font-weight)-var(--gds-font-weight)*9999,var(--gds-font-weight))]
            hover:text-white
            active:transition-none
            group-data-[highlighted=true]/nav-link:text-white
            +:nested-icon:default-size-[1em] ${/* This is the default, but it prevents an ancestor from overriding it accidentally */
              ""}
            @prop-variant-primary/nav-link:text-space-200
            @prop-variant-primary/nav-link:[--default-font-size:theme(fontSize.16)]
            @prop-variant-primary/nav-link:[--default-font-weight:theme(fontWeight.medium)]
            @prop-variant-primary/nav-link:[--default-line-height:theme(lineHeight.6)]
            +:@prop-variant-primary/nav-link:active:text-space-500
            @prop-variant-secondary/nav-link:text-space-500
            @prop-variant-secondary/nav-link:[--default-font-size:theme(fontSize.14)]
            @prop-variant-secondary/nav-link:[--default-font-weight:theme(fontWeight.regular)]
            @prop-variant-secondary/nav-link:[--default-line-height:theme(lineHeight.5)]
            +:@prop-variant-secondary/nav-link:active:text-space-700
          `,
              ...props,
              children: ({ href, target }) => {
                const iconAfter = passedIconAfter !== void 0 ? passedIconAfter : href !== void 0 && target === "_blank" ? /* @__PURE__ */ jsx(ArrowUpRightInteractive, {}) : isMegaMenuTrigger ? /* @__PURE__ */ jsx(CaretDownInteractive, {}) : void 0;
                return /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: `
                    absolute rounded-8 transition
                    -:inset-x-[min(0px,var(--gds-nav-link-padding-x)-var(--gds-nav-link-offset-x))]
                    -:inset-y-[min(0px,var(--gds-nav-link-padding-y)-var(--gds-nav-link-offset-y))]
                    in-clickable-focus-visible:outline-focus
                  `,
                      children: /* @__PURE__ */ jsx(
                        "span",
                        {
                          className: `
                      absolute inset-0 rounded-[inherit] transition-[opacity,visibility] pointer-events-none
                      group-[:not([data-current],[data-highlight-on-interaction])]/nav-link:invisible
                      group-data-[highlight-on-interaction=group]/nav-link:group-not-has-[.gds-nav-link:is([data-current],[data-highlighted=true])]/nav-link-group:opacity-0
                    `,
                          children: /* @__PURE__ */ jsx(
                            motion.span,
                            {
                              layoutId: highlightedInGroup ? "gds-nav-link-highlight" : void 0,
                              transition: highlightedInGroup ? { duration: HIGHLIGHT_TRANSITION_DURATION / 1e3 } : void 0,
                              className: `
                        nested/nav-link-highlight absolute inset-0 rounded-[inherit] bg-white/10 transition-opacity
                        group-not-data-[highlighted]/nav-link:opacity-0
                      `
                            },
                            highlightedInGroup ? "gds-nav-link-highlight" : void 0
                          )
                        }
                      )
                    }
                  ),
                  iconBefore ? /* @__PURE__ */ jsx(ExperimentalIcon, { alt: "", className: "size-max", children: iconBefore }) : null,
                  children ? /* @__PURE__ */ jsx("span", { className: "truncate", children }) : null,
                  iconAfter ? /* @__PURE__ */ jsx(ExperimentalIcon, { alt: "", className: "size-max", children: iconAfter }) : null
                ] });
              }
            }
          )
        ]
      }
    );
  }
);
ExperimentalNavLinkRoot.displayName = "ExperimentalNavLink";
const ExperimentalNavLinkGroupContext = createContext(null);
const ExperimentalNavLinkGroup = ({
  highlightOnInteraction = false,
  className,
  children,
  ...props
}) => {
  const navLinksStateById = useMap();
  const [justExitedNavLinkId, setJustExitedNavLinkId] = useState(null);
  const justExitedNavLinkTimeout = useRef();
  const highlightedNavLinkId = (() => {
    let highlightedNavLinkId2 = null;
    for (const [id, state] of navLinksStateById) {
      if (state === "expanded") {
        highlightedNavLinkId2 = id;
        break;
      }
      if (state === "hover" && !highlightedNavLinkId2) {
        highlightedNavLinkId2 = id;
      }
    }
    return highlightedNavLinkId2;
  })();
  const setNavLinkState = useCallback(
    (id, state) => {
      const previousState = navLinksStateById.get(id);
      navLinksStateById.set(id, state);
      clearTimeout(justExitedNavLinkTimeout.current);
      if ((previousState === "hover" || previousState === "expanded") && state === "none") {
        setJustExitedNavLinkId(id);
        justExitedNavLinkTimeout.current = window.setTimeout(() => {
          setJustExitedNavLinkId(null);
        }, HIGHLIGHT_TRANSITION_DURATION);
      } else {
        setJustExitedNavLinkId(null);
      }
    },
    [navLinksStateById]
  );
  const contextValue = useMemo(() => {
    return {
      highlightOnInteraction,
      highlightedNavLinkId,
      justExitedNavLinkId,
      setNavLinkState
    };
  }, [highlightOnInteraction, highlightedNavLinkId, justExitedNavLinkId, setNavLinkState]);
  return /* @__PURE__ */ jsx(ExperimentalNavLinkGroupContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx("div", { className: classNames(["group/nav-link-group", className]), ...props, children }) });
};
ExperimentalNavLinkGroup.displayName = "ExperimentalNavLink.Group";
export {
  ExperimentalNavLinkGroup,
  ExperimentalNavLinkRoot
};
