import { jsxs, jsx } from 'react/jsx-runtime';
import { forwardRef, useState, useEffect, useRef, useId, useCallback, useLayoutEffect, useMemo } from 'react';
import { S as SvgClose } from './close-DZj38AEh.js';
import { c as cx } from './index-De1g9FRV.js';
import { T as Text } from './Text-J5YtSSXY.js';
import { u as useDialogContext, D as DialogCancelButton } from './DialogCancelButton-CbtQcf2J.js';
import { c as childrenToString } from './childrenToString-Bz9MqbHb.js';
import { useTrackingId } from './useTrackingId.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { D as DialogContext } from './DialogContext-DBgtApl9.js';
import { d as drillDownStyles, D as DrillDownContext } from './DrillDown.module-D1Bf9_yP.js';
import { u as useDrillDownContextState, a as useDialogTransitionStates, b as useKeyboardFocusables, c as useInitialFocus } from './useInitialFocus-BUxEDMEG.js';
import { a as ToastProvider, b as ToasterPopover, c as ToasterContent } from './Toaster-Bq42x6Gx.js';
import { u as useDialogScrollLock } from './useDialogScrollLock-BW-aVboo.js';
import { r as registerLayer, u as unregisterLayer, a as useOnClickOutside } from './useOnClickOutside-Zw5vzxSq.js';

import './Dialog.css';const dialog = "_dialog_1ac4h_1";
const closing = "_closing_1ac4h_32";
const container = "_container_1ac4h_39";
const header = "_header_1ac4h_53";
const title = "_title_1ac4h_64";
const content = "_content_1ac4h_76";
const sticky = "_sticky_1ac4h_83";
const footer = "_footer_1ac4h_90";
const large = "_large_1ac4h_103";
const fullscreen = "_fullscreen_1ac4h_103";
const xlarge = "_xlarge_1ac4h_107";
const styles = {
	"open-dialog": "_open-dialog_1ac4h_1",
	"open-backdrop": "_open-backdrop_1ac4h_1",
	"close-dialog": "_close-dialog_1ac4h_1",
	"close-backdrop": "_close-backdrop_1ac4h_1",
	dialog: dialog,
	closing: closing,
	container: container,
	header: header,
	title: title,
	"close-container": "_close-container_1ac4h_68",
	content: content,
	sticky: sticky,
	footer: footer,
	large: large,
	fullscreen: fullscreen,
	xlarge: xlarge
};

const DialogHeader = forwardRef(
  (props, ref) => {
    const { children, className, ...rest } = props;
    const { headerRef } = useDialogContext();
    const data = {
      children: childrenToString(props.children)
    };
    const trackingId = useTrackingId({
      name: "Dialog",
      data,
      hasOverride: !!props["data-tracking-id"]
    });
    const headerClassNames = cx(className, styles["header"]);
    return /* @__PURE__ */ jsxs(
      "header",
      {
        className: headerClassNames,
        "data-anv": "dialog-header",
        "data-tracking-id": trackingId,
        ref: useMergeRefs([ref, headerRef]),
        ...rest,
        children: [
          /* @__PURE__ */ jsx(Text, { variant: "headline", el: "h1", className: styles["title"], children }),
          /* @__PURE__ */ jsx("span", { className: styles["close-container"], children: /* @__PURE__ */ jsx(
            DialogCancelButton,
            {
              className: styles["close-button"],
              size: "small",
              appearance: "ghost",
              "aria-label": "Close dialog",
              icon: SvgClose
            }
          ) })
        ]
      }
    );
  }
);
DialogHeader.displayName = "DialogHeader";

const DialogFooter = forwardRef(
  (props, ref) => {
    const { children, className, sticky = false, ...rest } = props;
    const footerClassNames = cx(styles["footer"], className, {
      [styles["sticky"]]: sticky
    });
    return /* @__PURE__ */ jsx(
      "footer",
      {
        className: footerClassNames,
        "data-anv": "dialog-footer",
        ref,
        ...rest,
        children
      }
    );
  }
);
DialogFooter.displayName = "DialogFooter";

const DialogContent = forwardRef(
  (props, ref) => {
    const { children, className, sticky = false, ...rest } = props;
    const { headerRef } = useDialogContext();
    const [headerHeight, setHeaderHeight] = useState(0);
    useEffect(() => {
      const headerElement = headerRef?.current;
      if (!sticky || !headerElement) return;
      const updateHeight = () => {
        setHeaderHeight(headerElement.offsetHeight || 0);
      };
      updateHeight();
      const resizeObserver = new ResizeObserver(updateHeight);
      resizeObserver.observe(headerElement);
      return () => resizeObserver.disconnect();
    }, [sticky, headerRef]);
    const contentClassNames = cx(styles["content"], className, {
      [styles["sticky"]]: sticky
    });
    const stickyStyle = sticky ? { top: `${headerHeight}px` } : void 0;
    return /* @__PURE__ */ jsx(
      "div",
      {
        className: contentClassNames,
        "data-anv": "dialog-content",
        ref,
        style: { ...stickyStyle, ...rest.style },
        ...rest,
        children
      }
    );
  }
);
DialogContent.displayName = "DialogContent";

const Dialog = Object.assign(
  forwardRef(function DialogInner(props, ref) {
    const {
      className,
      open = false,
      children,
      onClose,
      onKeyDown,
      fullScreen = false,
      disableCloseOnEscape = false,
      onClickOutside,
      disableCloseOnClickOutside = false,
      size,
      enableScrollChaining,
      onOpenAnimationStart,
      onOpenAnimationComplete,
      onCloseAnimationStart,
      onCloseAnimationComplete,
      initialFocusResolver,
      defaultDrillDownIndex,
      onDrillDownContextChange,
      ...rest
    } = props;
    const elRef = useRef(null);
    const contentRef = useRef(null);
    const toasterRef = useRef(null);
    const headerRef = useRef(null);
    const [hasOpenPopover, setHasOpenPopover] = useState(false);
    const drillDownContextValue = useDrillDownContextState({
      defaultDrillDownIndex
    });
    const id = useId();
    const { state, isOpenOrOpening } = useDialogTransitionStates(elRef, open, {
      onOpenAnimationStart: useCallback(() => {
        onOpenAnimationStart?.();
      }, [onOpenAnimationStart]),
      onOpenAnimationComplete: useCallback(() => {
        onOpenAnimationComplete?.();
      }, [onOpenAnimationComplete]),
      onCloseAnimationStart: useCallback(() => {
        onCloseAnimationStart?.();
      }, [onCloseAnimationStart]),
      onCloseAnimationComplete: useCallback(() => {
        onCloseAnimationComplete?.();
      }, [onCloseAnimationComplete])
    });
    const previousOpenRef = useRef(open);
    useLayoutEffect(() => {
      if (open && !previousOpenRef.current) {
        drillDownContextValue.setHostTrigger?.(
          document.activeElement instanceof HTMLElement ? document.activeElement : null
        );
      }
    }, [open, drillDownContextValue]);
    useEffect(() => {
      previousOpenRef.current = open;
    }, [open]);
    useEffect(() => {
      if (state === "closing") {
        drillDownContextValue.onHostClose?.();
      }
    }, [state, drillDownContextValue]);
    useEffect(() => {
      if (state === "closed") {
        drillDownContextValue.onHostClosed?.();
      }
    }, [state, drillDownContextValue]);
    const drillDownContextProviderValue = useMemo(
      () => ({
        ...drillDownContextValue,
        hostIsInteractive: state !== "closing" && state !== "closed"
      }),
      [drillDownContextValue, state]
    );
    useLayoutEffect(() => {
      onDrillDownContextChange?.(drillDownContextProviderValue);
    }, [drillDownContextProviderValue]);
    const initial = useRef(true);
    useEffect(() => {
      if (initial.current) {
        initial.current = false;
      }
    }, [id, isOpenOrOpening]);
    const classNames = cx([styles.dialog, drillDownStyles.dialog], className, {
      [styles["closing"]]: state === "closing",
      [styles["fullscreen"]]: fullScreen,
      ...size && { [styles[size]]: true }
    });
    const { focusables } = useKeyboardFocusables(contentRef, {
      observeChange: true
    });
    useDialogScrollLock({
      open: isOpenOrOpening,
      id,
      enableScrollChaining,
      elementRef: elRef
    });
    useEffect(() => {
      if (open) {
        registerLayer(id);
      } else {
        unregisterLayer(id);
      }
      return () => {
        unregisterLayer(id);
      };
    }, [open, id]);
    useOnClickOutside({
      onClickOutsideBegin: (e) => {
        if (!open) return;
        onClickOutside?.(e);
      },
      targets: [
        contentRef.current,
        toasterRef.current
      ],
      onClickOutside: () => {
        if (disableCloseOnClickOutside || !open) return;
        onClose?.();
      },
      layerId: id
    });
    const computeFocus = useCallback((focusables2) => {
      return focusables2.find(
        (focusable) => focusable.dataset.anv !== "dialog-cancel-button"
      ) || focusables2[0];
    }, []);
    useInitialFocus(elRef, {
      computeFocus: initialFocusResolver || computeFocus
    });
    const onKeyDownHandler = (e) => {
      onKeyDown?.(e);
      if (e.code === "Escape") {
        e.preventDefault();
        if (disableCloseOnEscape) return;
        if (hasOpenPopover) return;
        onClose?.();
        return;
      }
      if (e.code === "Tab") {
        if (e.shiftKey && e.target === focusables?.[0]) {
          e.preventDefault();
          focusables[focusables.length - 1]?.focus();
          return;
        }
        if (e.target === focusables?.[focusables.length - 1] && !e.shiftKey) {
          e.preventDefault();
          focusables[0].focus();
          return;
        }
      }
    };
    return (
      // dialog element does seem to be interactive on MDN guideline
      /* @__PURE__ */ jsxs(
        "dialog",
        {
          className: classNames,
          "data-anv": "dialog",
          "data-anv-scroll-chaining": enableScrollChaining,
          "data-anv-transition-state": state,
          ref: useMergeRefs([ref, elRef]),
          onKeyDown: onKeyDownHandler,
          ...rest,
          children: [
            /* @__PURE__ */ jsx(ToastProvider, { isDialogToaster: open, children: /* @__PURE__ */ jsx(ToasterPopover, { children: /* @__PURE__ */ jsx(ToasterContent, { id: "dialog-toaster", ref: toasterRef }) }) }),
            /* @__PURE__ */ jsx(DrillDownContext.Provider, { value: drillDownContextProviderValue, children: /* @__PURE__ */ jsx(
              DialogContext.Provider,
              {
                value: {
                  close: () => onClose?.(),
                  ref: elRef,
                  hasOpenPopover,
                  setHasOpenPopover,
                  headerRef,
                  state
                },
                children: /* @__PURE__ */ jsx(
                  "section",
                  {
                    ref: contentRef,
                    className: styles["container"],
                    "data-open": open,
                    children
                  }
                )
              }
            ) })
          ]
        }
      )
    );
  }),
  {
    /**
     * DialogHeader component for the header section of a Dialog.
     *
     * Features:
     * - Displays dialog title with headline typography
     * - Includes close button with proper accessibility
     * - Sticky positioning for long content
     * - Consistent spacing and styling
     * - Automatic focus management
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Dialog.Header>Confirm Delete</Dialog.Header>
     */
    Header: DialogHeader,
    /**
     * DialogFooter component for the footer section of a Dialog.
     *
     * Features:
     * - Container for dialog action buttons
     * - Optional sticky positioning for long content
     * - Consistent spacing and alignment
     * - Right-aligned button layout by default
     * - Flexible content area for custom layouts
     *
     * @example
     * <Dialog.Footer sticky>
     *   <Dialog.CancelButton>Cancel</Dialog.CancelButton>
     *   <Button appearance="primary">Save</Button>
     * </Dialog.Footer>
     */
    Footer: DialogFooter,
    /**
     * DialogContent component for the main content area of a Dialog.
     *
     * Features:
     * - Main content container for dialog body
     * - Flexible height with overflow handling
     * - Consistent padding and spacing
     * - Responsive design
     * - Proper content scrolling for long content
     *
     * @example
     * <Dialog.Content>
     *   <p>This is the main content of the dialog.</p>
     * </Dialog.Content>
     */
    Content: DialogContent,
    /**
     * DialogCancelButton component for cancel/close actions in a Dialog.
     *
     * Features:
     * - Button that automatically closes the dialog when clicked
     * - Extends all Button component props and functionality
     * - Proper accessibility with close dialog semantics
     * - Automatic focus management
     * - Consistent styling with other dialog elements
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Dialog.CancelButton appearance="ghost">Cancel</Dialog.CancelButton>
     */
    CancelButton: DialogCancelButton
  }
);
Dialog.displayName = "Dialog";

export { Dialog as D };
//# sourceMappingURL=Dialog-DGmF6qx3.js.map
