import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { c as cx } from './index-De1g9FRV.js';
import { I as Icon } from './Icon-B4uCvMU9.js';
import { S as Spinner } from './Spinner-B7tTWcP6.js';
import { a as SvgCheckBoxOutlineBlank, S as SvgCheckBox } from './check_box-0U1tbEAd.js';
import { S as SvgIndeterminateCheckBox } from './indeterminate_check_box-jjLG4UY6.js';
import { F as Flex } from './Flex-Bb3iHExM.js';
import { T as Text } from './Text-mDcQHC2U.js';
import { A as Avatar } from './Avatar-DX96Mxe7.js';
import { C as Chip } from './Chip-CxgryK86.js';
import { forwardRef, useRef, useCallback, useEffect, useState } from 'react';
import { a as useOnClickOutside } from './useOnClickOutside-Zw5vzxSq.js';
import { p as portalScopeClassNames } from './portalScopeClassNames-BTyv0FY8.js';
import { c as computePosition, o as offset, h as autoPlacement, a as size, b as autoUpdate } from './floating-ui.react-dom-CyrxPiI-.js';
import { D as DialogCancelButton } from './DialogCancelButton-DmSUPuCR.js';
import { S as SvgClose } from './close-DZj38AEh.js';
import { D as DialogContext } from './DialogContext-DBgtApl9.js';
import { t as tabbable } from './usePopoverTransitionStates-CDXCdyKa.js';
import { u as useDialogScrollLock } from './useDialogScrollLock-BW-aVboo.js';
import { u as useBreakpoint } from './useBreakpoint-BBNRlMGZ.js';

import './useAdaptiveView.css';const checkbox = "_checkbox_1xh9p_1";
const checked = "_checked_1xh9p_9";
const unchecked = "_unchecked_1xh9p_13";
const indeterminate = "_indeterminate_1xh9p_17";
const loading = "_loading_1xh9p_21";
const styles$4 = {
	checkbox: checkbox,
	checked: checked,
	unchecked: unchecked,
	indeterminate: indeterminate,
	loading: loading
};

const iconMap = {
  checked: SvgCheckBox,
  unchecked: SvgCheckBoxOutlineBlank,
  indeterminate: SvgIndeterminateCheckBox
};
function OptionCheckbox({ checkState, className }) {
  if (checkState === "loading") {
    return /* @__PURE__ */ jsx("span", { className: cx(styles$4["loading"], className), children: /* @__PURE__ */ jsx(Spinner, { size: "small", "aria-hidden": "true" }) });
  }
  return /* @__PURE__ */ jsx(
    Icon,
    {
      "aria-hidden": "true",
      size: "large",
      svg: iconMap[checkState],
      className: cx(styles$4["checkbox"], styles$4[checkState], className)
    }
  );
}

const disabled = "_disabled_1tqi5_27";
const styles$3 = {
	"option-row": "_option-row_1tqi5_2",
	disabled: disabled,
	"side-content": "_side-content_1tqi5_35"
};

const OptionRow = forwardRef(
  function OptionRow2({ disabled, children, className, ...rest }, ref) {
    const optionRowClass = cx(
      styles$3["option-row"],
      { [styles$3["disabled"]]: disabled },
      className
    );
    return /* @__PURE__ */ jsx("div", { ref, ...rest, className: optionRowClass, children });
  }
);
const OptionRowSideContent = forwardRef(function OptionRowSideContent2({ children, className, ...rest }, ref) {
  const sideContentClass = cx(styles$3["side-content"], className);
  return /* @__PURE__ */ jsx("div", { ref, ...rest, className: sideContentClass, children });
});

const title = "_title_te5wz_1";
const description = "_description_te5wz_10";
const styles$2 = {
	title: title,
	description: description,
	"chips-row": "_chips-row_te5wz_21"
};

function OptionContentArea({
  label,
  content,
  children
}) {
  const hasAvatar = !!content?.avatar;
  const hasChips = !!content?.chips?.length;
  const hasIcon = !!content?.icon;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    hasAvatar && /* @__PURE__ */ jsx(OptionRowSideContent, { "aria-hidden": "true", children: /* @__PURE__ */ jsx(Avatar, { size: "medium", ...content.avatar }) }),
    /* @__PURE__ */ jsxs(Flex, { grow: 1, shrink: 1, direction: "column", justifyContent: "center", children: [
      /* @__PURE__ */ jsx(Text, { size: "small", className: styles$2["title"], children: content?.title ?? label }),
      content?.description && /* @__PURE__ */ jsx(Text, { size: "small", className: styles$2["description"], children: content.description }),
      hasChips && /* @__PURE__ */ jsx(
        Flex,
        {
          wrap: "wrap",
          gap: "1",
          className: styles$2["chips-row"],
          role: "group",
          "aria-label": "Tags",
          children: content.chips.map((chip, i) => /* @__PURE__ */ jsx(Chip, { size: "small", ...chip }, `${chip.label}-${i}`))
        }
      ),
      children
    ] }),
    hasIcon && /* @__PURE__ */ jsx(OptionRowSideContent, { children: /* @__PURE__ */ jsx(
      Icon,
      {
        size: "large",
        svg: content.icon.svg,
        color: content.icon.color,
        "aria-hidden": content.icon.label ? void 0 : "true",
        "aria-label": content.icon.label
      }
    ) })
  ] });
}

const styles$1 = {
	"options-popover": "_options-popover_cp2or_2",
	"options-popover-body": "_options-popover-body_cp2or_37",
	"options-popover-footer": "_options-popover-footer_cp2or_48"
};

function resolveWidth(width, referenceWidth) {
  if (width === "reference") return `${referenceWidth}px`;
  if (typeof width === "number") return `${width}px`;
  if (typeof width === "string") return width;
  return void 0;
}
const OptionsPopover = (props) => {
  const ref = useRef(null);
  const { id, children, referenceElement, open, onClose, width, footer } = props;
  const lastCloseRef = useRef(0);
  const safeClose = useCallback(() => {
    const now = Date.now();
    if (now - lastCloseRef.current < 50) return;
    lastCloseRef.current = now;
    onClose();
  }, [onClose]);
  useOnClickOutside({
    targets: [ref.current ?? void 0, referenceElement.current ?? void 0],
    onClickOutside: safeClose,
    disable: !open
  });
  useEffect(() => {
    if (open) {
      ref.current?.showPopover();
    } else {
      ref.current?.hidePopover();
    }
  }, [open]);
  useEffect(() => {
    if (!open) return;
    const popoverEl = ref.current;
    if (!popoverEl) return;
    const handleFocusOut = (e) => {
      const next = e.relatedTarget;
      if (!next) {
        safeClose();
        return;
      }
      if (popoverEl.contains(next)) return;
      const trigger = referenceElement.current;
      if (trigger && trigger.contains(next)) return;
      safeClose();
    };
    popoverEl.addEventListener("focusout", handleFocusOut);
    return () => popoverEl.removeEventListener("focusout", handleFocusOut);
  }, [open, safeClose, referenceElement]);
  useEffect(() => {
    if (!open) return;
    const popoverEl = ref.current;
    if (!popoverEl) return;
    const handleKeyDown = (e) => {
      if (e.key !== "Escape" || e.defaultPrevented) return;
      e.preventDefault();
      referenceElement.current?.focus();
      safeClose();
    };
    popoverEl.addEventListener("keydown", handleKeyDown);
    return () => popoverEl.removeEventListener("keydown", handleKeyDown);
  }, [open, safeClose, referenceElement]);
  const updatePosition = useCallback(async () => {
    if (!ref.current || !referenceElement.current) return;
    const position = await computePosition(
      referenceElement.current,
      ref.current,
      {
        placement: "bottom-start",
        middleware: [
          offset(8),
          autoPlacement({
            allowedPlacements: [
              "bottom-start",
              "bottom-end",
              "top-start",
              "top-end"
            ],
            padding: 8
          }),
          size({
            padding: 8,
            apply({ rects, elements, availableHeight, availableWidth }) {
              const resolved = resolveWidth(width, rects.reference.width);
              Object.assign(elements.floating.style, {
                ...resolved != null && { width: resolved },
                maxWidth: `${Math.max(0, availableWidth)}px`,
                maxHeight: `${Math.max(0, availableHeight)}px`
              });
            }
          })
        ]
      }
    );
    ref.current.style.left = `${position.x}px`;
    ref.current.style.top = `${position.y}px`;
  }, [ref, referenceElement, width]);
  useEffect(() => {
    if (!ref.current || !referenceElement.current || !open) return;
    const cleanup = autoUpdate(
      referenceElement.current,
      ref.current,
      updatePosition
    );
    return () => {
      cleanup();
    };
  }, [referenceElement, ref, updatePosition, open]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref,
      id,
      className: cx(styles$1["options-popover"], portalScopeClassNames),
      popover: "manual",
      "data-anv": "popover-content",
      children: [
        /* @__PURE__ */ jsx("div", { className: styles$1["options-popover-body"], children }),
        footer ? /* @__PURE__ */ jsx("div", { className: styles$1["options-popover-footer"], children: footer }) : null
      ]
    }
  );
};

const header = "_header_1lxz8_41";
const field = "_field_1lxz8_2";
const content = "_content_1lxz8_54";
const footer = "_footer_1lxz8_60";
const styles = {
	"field-dialog": "_field-dialog_1lxz8_2",
	"field-dialog-visual-viewport-height": "_field-dialog-visual-viewport-height_1lxz8_21",
	header: header,
	field: field,
	content: content,
	footer: footer
};

const OptionsDialog = ({
  id,
  isOpen,
  onClose,
  field,
  children,
  title,
  initialFocusResolver,
  footer
}) => {
  const elRef = useRef(null);
  const visualViewportHeightRef = useRef(null);
  useDialogScrollLock({
    open: isOpen,
    id,
    enableScrollChaining: false,
    elementRef: elRef
  });
  const computeFocus = useCallback(
    (focusables) => {
      if (initialFocusResolver) {
        return initialFocusResolver(focusables);
      }
      return focusables.find(
        (focusable) => focusable.dataset.anv !== "dialog-cancel-button"
      ) || focusables[0];
    },
    [initialFocusResolver]
  );
  useEffect(() => {
    if (isOpen) {
      elRef.current?.showModal();
      if (elRef.current) {
        computeFocus(tabbable(elRef.current)).focus();
      }
    } else {
      elRef.current?.close();
    }
  }, [isOpen]);
  useEffect(() => {
    if (isOpen) {
      const handleResize = () => {
        if (!visualViewportHeightRef.current) return;
        visualViewportHeightRef.current.style.height = `${window.visualViewport?.height ?? 0}px`;
        visualViewportHeightRef.current.style.maxHeight = `${window.visualViewport?.height ?? 0}px`;
      };
      window.visualViewport?.addEventListener("resize", handleResize);
      return () => {
        window.visualViewport?.removeEventListener("resize", handleResize);
      };
    }
  }, [isOpen]);
  return /* @__PURE__ */ jsx(
    "dialog",
    {
      ref: elRef,
      id,
      "data-anv": "field-dialog",
      className: styles["field-dialog"],
      onKeyDown: (e) => {
        if (e.code === "Escape") {
          e.preventDefault();
          onClose();
        }
      },
      children: /* @__PURE__ */ jsxs(
        "div",
        {
          className: styles["field-dialog-visual-viewport-height"],
          ref: visualViewportHeightRef,
          children: [
            /* @__PURE__ */ jsxs(Flex, { direction: "row", className: styles["header"], children: [
              /* @__PURE__ */ jsx(Text, { variant: "headline", el: "h1", children: title }),
              /* @__PURE__ */ jsx("span", { className: styles["close-container"], children: /* @__PURE__ */ jsx(DialogContext.Provider, { value: { close: onClose }, children: /* @__PURE__ */ jsx(
                DialogCancelButton,
                {
                  className: styles["close-button"],
                  size: "small",
                  appearance: "ghost",
                  "aria-label": "Close dialog",
                  icon: SvgClose
                }
              ) }) })
            ] }),
            field ? /* @__PURE__ */ jsx(Flex, { direction: "column", className: styles["field"], children: field }) : null,
            /* @__PURE__ */ jsx(Flex, { direction: "column", className: styles["content"], children }),
            footer ? /* @__PURE__ */ jsx("div", { className: styles["footer"], children: footer }) : null
          ]
        }
      )
    }
  );
};

function detectCoarsePointer() {
  if (typeof window === "undefined" || !window.matchMedia) {
    return false;
  }
  return window.matchMedia("(pointer: coarse)").matches;
}
function useAdaptiveView() {
  const breakpoint = useBreakpoint();
  const [hasCoarsePointer, setHasCoarsePointer] = useState(detectCoarsePointer);
  useEffect(() => {
    setHasCoarsePointer(detectCoarsePointer());
    const mediaQuery = window.matchMedia("(pointer: coarse)");
    const handleChange = (e) => {
      setHasCoarsePointer(e.matches);
    };
    mediaQuery.addEventListener("change", handleChange);
    return () => mediaQuery.removeEventListener("change", handleChange);
  }, []);
  const isSmallScreen = !breakpoint?.md;
  const isMobile = isSmallScreen && hasCoarsePointer;
  return {
    view: isMobile ? "mobile" : "desktop",
    isMobile,
    isDesktop: !isMobile
  };
}

export { OptionsDialog as O, OptionsPopover as a, OptionRow as b, OptionRowSideContent as c, OptionCheckbox as d, OptionContentArea as e, useAdaptiveView as u };
//# sourceMappingURL=useAdaptiveView-AvsDkChF.js.map
