import { useEffect, useRef } from "preact/compat";
import CloseButton from "../CloseButton/CloseButton";
import NativeDialog from "../NativeDialog/NativeDialog";
import classNames from 'classnames';
import useDialogAnalytics from "./useDialogAnalytics";
import useId from "../utilities/useId";
import { t } from "../i18n";
import { useBodyScrollPrevention } from "./useBodyScrollPrevention";
import { jsx as _jsx } from "preact/compat/jsx-runtime";
import { jsxs as _jsxs } from "preact/compat/jsx-runtime";
/**
 * For information about how and when to use this component,
 * [refer to its full documentation page](https://design.cms.gov/components/modal-dialog/).
 */
export const Dialog = props => {
  const {
    actions,
    actionsClassName,
    alert,
    analytics,
    analyticsLabelOverride,
    analyticsEventTypeOverride,
    onAnalyticsEvent,
    ariaCloseLabel,
    children,
    className,
    headerClassName,
    heading,
    id,
    onEnter,
    onExit,
    size,
    ...modalProps
  } = props;
  const rootId = useId('dialog--', id);
  const headingRef = useDialogAnalytics(props);
  const headingId = `${rootId}__heading`;
  const contentId = `${rootId}__content`;
  const dialogClassNames = classNames('ds-c-dialog', className, size && `ds-c-dialog--${size}`);
  const headerClassNames = classNames('ds-c-dialog__header', headerClassName);
  const actionsClassNames = classNames('ds-c-dialog__actions', actionsClassName);
  const containerRef = useRef();
  useEffect(() => {
    if (onEnter) onEnter();
  }, []);

  // Set initial focus
  useEffect(() => {
    containerRef.current?.focus();
  }, [containerRef]);
  useBodyScrollPrevention(modalProps.isOpen ?? true);
  return /*#__PURE__*/_jsx(NativeDialog, {
    className: dialogClassNames,
    showModal: true,
    exit: onExit,
    ...modalProps,
    id: rootId,
    boundingBoxRef: containerRef,
    children: /*#__PURE__*/_jsxs("div", {
      className: "ds-c-dialog__window",
      role: "document",
      ref: containerRef,
      tabIndex: -1,
      "aria-labelledby": headingId,
      children: [/*#__PURE__*/_jsxs("header", {
        className: headerClassNames,
        children: [heading && /*#__PURE__*/_jsx("h1", {
          className: "ds-c-dialog__heading",
          id: headingId,
          ref: headingRef,
          children: heading
        }), /*#__PURE__*/_jsx(CloseButton, {
          "aria-label": ariaCloseLabel ?? t('dialog.ariaCloseLabel'),
          className: "ds-c-dialog__close",
          id: `${rootId}__close`,
          onClick: onExit
        })]
      }), /*#__PURE__*/_jsxs("main", {
        role: "main",
        className: "ds-c-dialog__body",
        children: [/*#__PURE__*/_jsx("div", {
          id: contentId,
          children: children
        }), actions && /*#__PURE__*/_jsx("div", {
          className: actionsClassNames,
          children: actions
        })]
      })]
    })
  });
};
export default Dialog;