import {
  useDialogPolyfill
} from "./chunk-RQJCLQZI.js";
import {
  supportsDialog
} from "./chunk-74GPBJTH.js";

// src/hooks/useDialog/useDialog.ts
import { useCallback, useEffect, useState } from "react";
import { useBodyScrollLock } from "@simplybusiness/mobius-hooks";
var TRANSITION_CLASS_NAME = "--transition";
var FALLBACK_TRANSITION_DURATION = 0;
var useDialog = (props) => {
  const { ref, isOpen, transition, onOpen, onClose } = props;
  const [hasDialogSupport, setHasDialogSupport] = useState(false);
  const shouldTransition = hasDialogSupport && transition.isEnabled;
  const { polyfillDialog } = useDialogPolyfill();
  useEffect(() => {
    setHasDialogSupport(supportsDialog());
  }, []);
  const TRANSITION_DURATION_IN_MS = ref.current && Number(
    getComputedStyle(ref.current).getPropertyValue(transition.CSSVariable).replace("ms", "")
  ) || FALLBACK_TRANSITION_DURATION;
  useBodyScrollLock({ enabled: isOpen });
  const open = useCallback(() => {
    ref.current?.showModal();
    onOpen?.();
  }, [onOpen, ref]);
  const close = useCallback(() => {
    ref.current?.close();
    onClose?.();
  }, [onClose, ref]);
  const handleClose = useCallback(
    (event) => {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }
      if (shouldTransition) {
        ref.current?.classList.remove(TRANSITION_CLASS_NAME);
        setTimeout(() => close(), TRANSITION_DURATION_IN_MS);
      } else {
        close();
      }
    },
    [TRANSITION_DURATION_IN_MS, close, ref, shouldTransition]
  );
  useEffect(() => {
    async function toggleDialog() {
      if (isOpen && !ref.current?.open) {
        await polyfillDialog(ref);
        open();
        setTimeout(() => {
          ref.current?.classList.add(TRANSITION_CLASS_NAME);
        }, 0);
      } else if (!isOpen && ref.current?.open) {
        handleClose();
      }
    }
    void toggleDialog();
  }, [handleClose, isOpen, open, ref, polyfillDialog]);
  return {
    open,
    close: handleClose
  };
};

export {
  useDialog
};
//# sourceMappingURL=chunk-7LSDEZNB.js.map
