'use strict';

var React = require('react');
var constants = require('../constants.js');
var jsxRuntime = require('react/jsx-runtime');

const LIVE_REGION_ROLE_BY_POLITENESS = {
  assertive: 'alert',
  polite: 'status'
};
let nextPoliteAnnouncementAt = 0;
let nextAssertiveAnnouncementAt = 0;
const getNextAnnouncementAt = politeness => {
  if (politeness === 'polite') {
    return nextPoliteAnnouncementAt;
  }
  return nextAssertiveAnnouncementAt;
};
const setNextAnnouncementAt = (politeness, value) => {
  if (politeness === 'polite') {
    nextPoliteAnnouncementAt = value;
    return;
  }
  nextAssertiveAnnouncementAt = value;
};
const calcAnnouncementDelayMs = (politeness, now) => {
  return Math.max(now + constants.WDS_LIVE_REGION_DELAY_MS, getNextAnnouncementAt(politeness)) - now;
};
const scheduleAnnouncement = politeness => {
  const now = Date.now();
  const delayMs = calcAnnouncementDelayMs(politeness, now);
  setNextAnnouncementAt(politeness, now + delayMs + constants.WDS_LIVE_REGION_DELAY_MS);
  return delayMs;
};
/**
 * Renders an ARIA live region with the correct implicit role.
 *
 * - `aria-live="polite"` → `role="status"`
 * - `aria-live="assertive"` → `role="alert"`
 * - `aria-live="off"` → no live region (renders children unwrapped)
 *
 * The `role` prop is intentionally excluded from the public API
 * to prevent mismatches between `aria-live` and `role`.
 */
const LiveRegion = ({
  'aria-live': ariaLive,
  announceOnChange,
  children,
  className,
  ...props
}) => {
  const [shouldAnnounce, setShouldAnnounce] = React.useState(false);
  const announcementTrigger = announceOnChange ?? (typeof children === 'string' || typeof children === 'number' ? children : undefined);
  React.useEffect(() => {
    if (ariaLive === 'off') {
      return;
    }
    // Reset announcement state, then schedule new announcement
    // This two-step process ensures screen readers re-announce the content
    // eslint-disable-next-line react-hooks/set-state-in-effect -- Deliberately resetting state to force re-announcement for screen readers
    setShouldAnnounce(false);
    const timeoutId = window.setTimeout(() => setShouldAnnounce(true), scheduleAnnouncement(ariaLive));
    return () => window.clearTimeout(timeoutId);
  }, [ariaLive, announcementTrigger]);
  if (ariaLive === 'off') {
    return /*#__PURE__*/jsxRuntime.jsx(jsxRuntime.Fragment, {
      children: children
    });
  }
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    role: LIVE_REGION_ROLE_BY_POLITENESS[ariaLive],
    "aria-live": ariaLive,
    "aria-atomic": "true",
    className: `wds-LiveRegion ${className ?? ''}`,
    ...props,
    children: /*#__PURE__*/jsxRuntime.jsx("div", {
      "aria-hidden": shouldAnnounce ? undefined : 'true',
      children: children
    })
  });
};

exports.LiveRegion = LiveRegion;
//# sourceMappingURL=LiveRegion.js.map
