"use client";
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { useMap } from "@react-hookz/web";
import { motion, LayoutGroup } from "motion/react";
import { forwardRef, useId, useContext, createContext, useState, useRef, useCallback, useMemo } from "react";
import { ExperimentalIcon } from "./Icon.js";
import { ExperimentalMenuTriggerContext } from "./shared.js";
import { useCSSState } from "./tailwind/useCSSState.js";
import { useCSSPropsPolyfill } from "./tailwind/useCSSPropsPolyfill.js";
import { splitProps } from "../utils/splitProps.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";
import { CaretDownInteractive } from "../icons/CaretDownInteractive.js";
const HIGHLIGHT_TRANSITION_DURATION = 200;
const ExperimentalNavLinkRoot = forwardRef(
  ({
    variant,
    hideLabel,
    iconBefore,
    iconAfter: passedIconAfter,
    current = false,
    highlightOnInteraction: passedHighlightOnInteraction,
    className,
    style,
    children,
    ...props
  }, forwardedRef) => {
    const uniqueId = useId();
    const isMenuTrigger = useContext(ExperimentalMenuTriggerContext) !== null;
    const groupContext = useContext(ExperimentalNavLinkGroupContext);
    const [stateWhenNoGroupHighlight, setStateWhenNoGroupHighlight] = useState("none");
    const [stateRef, state] = useCSSState(
      {
        open: void 0
      },
      (state2) => {
        const navLinkState = state2.pointer !== "idle" ? "hover" : state2.open ? "open" : "none";
        if (highlightOnInteraction === "group") {
          groupContext == null ? void 0 : groupContext.setNavLinkState(uniqueId, navLinkState);
        } else {
          setStateWhenNoGroupHighlight(navLinkState);
        }
      }
    );
    const [propsPolyfillStateRef, propsPolyfillAttributes] = useCSSPropsPolyfill(
      "nav-link",
      { variant, hideLabel },
      { ref: stateRef }
    );
    const { rootProps, nestedProps } = splitProps(props);
    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) === uniqueId || !(groupContext == null ? void 0 : groupContext.highlightedNavLinkId) && ((groupContext == null ? void 0 : groupContext.justExitedNavLinkId) === uniqueId || !(groupContext == null ? void 0 : groupContext.justExitedNavLinkId) && current));
    if (highlightedInGroup && (groupContext == null ? void 0 : groupContext.justExitedNavLinkId) === uniqueId) {
      highlightedInGroup = "just-exited";
    }
    const highlighted = (() => {
      if (highlightOnInteraction === "group") {
        return highlightedInGroup;
      } else {
        return highlightOnInteraction && (stateWhenNoGroupHighlight === "hover" || stateWhenNoGroupHighlight === "open") || current;
      }
    })();
    return /* @__PURE__ */ jsx(
      "span",
      {
        ref: propsPolyfillStateRef,
        "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 --: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-nested-open/nav-link-ref:state-open
          -:has-nested-focus-visible/nav-link-ref:state-focus
          -:has-nested-hover/nav-link-ref:has-nested-enabled/nav-link-ref:state-hover
          -:has-nested-active/nav-link-ref:has-nested-enabled/nav-link-ref:state-active`,
          className
        ]),
        ...state.forwardedAttributes,
        ...getCSSPropsAttributes("nav-link", { variant, hideLabel }, style),
        ...propsPolyfillAttributes,
        ...rootProps,
        children: /* @__PURE__ */ jsx(
          ButtonOrLink,
          {
            ref: forwardedRef,
            selected: props.href !== void 0 ? current : void 0,
            className: `
            nested/nav-link-ref 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))]
            @state-active/nav-link:transition-none
            @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:@state-hover/nav-link:text-white
            @prop-variant-primary/nav-link:@state-active/nav-link: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:@state-hover/nav-link:text-white
            @prop-variant-secondary/nav-link:@state-active/nav-link:text-space-700
            +:nested-icon:default-size-[1em] ${/* This is the default, but it prevents an ancestor from overriding it accidentally */
            ""}
          `,
            ...nestedProps,
            children: ({ target }) => {
              const iconAfter = passedIconAfter !== void 0 ? passedIconAfter : target === "_blank" ? /* @__PURE__ */ jsx(ArrowUpRightInteractive, {}) : isMenuTrigger ? /* @__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))]
                    @state-focus/nav-link: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 @prop-hide-label-true/nav-link:sr-only", 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 uniqueId = useId();
  const navLinksStateById = useMap();
  const [justExitedNavLinkId, setJustExitedNavLinkId] = useState(null);
  const justExitedNavLinkTimeout = useRef();
  const highlightedNavLinkId = (() => {
    let highlightedNavLinkId2 = null;
    for (const [id, state] of navLinksStateById) {
      if (state === "open") {
        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 === "open") && state === "none") {
        setJustExitedNavLinkId(id);
        justExitedNavLinkTimeout.current = 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(LayoutGroup, { id: uniqueId, children: /* @__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
};
