import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { c as cx } from './index-De1g9FRV.js';
import { useState, useEffect, useMemo, useCallback, createContext, useContext, forwardRef, useRef } from 'react';
import { B as Button } from './Button-Bnt8XUI7.js';
import { S as SrOnly } from './SrOnly-pnf8ajnh.js';
import { A as Alert } from './Alert-DmbqtMg_.js';
import { P as ProgressBar } from './ProgressBar-DSrjgLTx.js';
import { u as useSwipe } from './useSwipe-Cp-CJxLU.js';
import { g as getActiveElement } from './getActiveElement-BcSyVE7S.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { b as safeHidePopover, s as safeShowPopover } from './floating-ui.react-dom-CHrYz13o.js';

import './Toaster.css';const ToastProviderContext = createContext({
  toasts: [],
  setToasts: () => [],
  toastHeights: [],
  setToastHeights: () => [],
  getToastStackHeight: () => 0,
  toastsBeforeStack: 3,
  setToastsBeforeStack: () => [],
  extraToastsVisible: false,
  setExtraToastsVisible: () => [],
  isDialogToaster: false
});
const ToastProvider = ({
  children,
  isDialogToaster: isDialogToasterProp = false
}) => {
  const [toasts, setToasts] = useState([]);
  const [toastHeights, setToastHeights] = useState([]);
  const [toastsBeforeStack, setToastsBeforeStack] = useState(3);
  const [extraToastsVisible, setExtraToastsVisible] = useState(false);
  const [isDialogToaster, setIsDialogToaster] = useState(isDialogToasterProp);
  const removeDuplicateToasts = (toasts2) => {
    const toastIds = /* @__PURE__ */ new Set();
    const uniqueToasts = toasts2.filter((toast) => {
      if (toastIds.has(toast.id)) {
        console.error(
          `Encountered toast with duplicate id ${toast.id}. Each toast id needs to be unique.`
        );
        return false;
      } else {
        toastIds.add(toast.id);
        return true;
      }
    });
    return uniqueToasts;
  };
  useEffect(() => {
    const uniqueToasts = removeDuplicateToasts(toasts);
    if (toasts.length !== uniqueToasts.length) {
      setToasts(uniqueToasts);
    }
  }, [toasts]);
  useEffect(() => {
    setIsDialogToaster(isDialogToasterProp);
  }, [isDialogToasterProp]);
  const heightMap = useMemo(
    () => new Map(toastHeights.map((t) => [t.id, t.height])),
    [toastHeights]
  );
  const getToastStackHeight = useCallback(
    (index) => {
      const relevantToasts = index !== void 0 ? toasts.slice(index + 1) : toasts;
      const heights = relevantToasts.map((t) => heightMap.get(t.id)).filter((h) => h !== void 0);
      if (heights.length > 0) {
        if (extraToastsVisible) {
          return heights.reduce((total, current) => total + current);
        }
        return heights.slice(-toastsBeforeStack).reduce((total, current) => total + current);
      }
      return 0;
    },
    [toasts, heightMap, extraToastsVisible, toastsBeforeStack]
  );
  const value = useMemo(
    () => ({
      toasts,
      setToasts,
      toastHeights,
      setToastHeights,
      getToastStackHeight,
      toastsBeforeStack,
      setToastsBeforeStack,
      extraToastsVisible,
      setExtraToastsVisible,
      isDialogToaster
    }),
    [
      extraToastsVisible,
      getToastStackHeight,
      toastHeights,
      toasts,
      toastsBeforeStack,
      isDialogToaster
    ]
  );
  return /* @__PURE__ */ jsx(ToastProviderContext.Provider, { value, children });
};

const useToasts = () => {
  const context = useContext(ToastProviderContext);
  if (context == null) {
    throw new Error("useToasts must be wrapped in <ToastProvider />");
  }
  return context;
};

const popover = "_popover_pn5m3_1";
const toaster = "_toaster_pn5m3_9";
const hidden = "_hidden_pn5m3_27";
const stacked = "_stacked_pn5m3_112";
const open = "_open_pn5m3_170";
const close = "_close_pn5m3_173";
const styles = {
	popover: popover,
	toaster: toaster,
	hidden: hidden,
	"toast-stack": "_toast-stack_pn5m3_31",
	"disable-animations": "_disable-animations_pn5m3_58",
	"show-extra-toast": "_show-extra-toast_pn5m3_62",
	"has-overflow": "_has-overflow_pn5m3_66",
	"toast-wrapper": "_toast-wrapper_pn5m3_82",
	stacked: stacked,
	"stacked-show-extra": "_stacked-show-extra_pn5m3_113",
	"stack-one": "_stack-one_pn5m3_117",
	"stack-two": "_stack-two_pn5m3_118",
	"stacked-extra": "_stacked-extra_pn5m3_149",
	"toast-alert": "_toast-alert_pn5m3_163",
	open: open,
	close: close,
	"alert-action": "_alert-action_pn5m3_191",
	"message-container": "_message-container_pn5m3_198",
	"show-more-button-container": "_show-more-button-container_pn5m3_205",
	"fixed-position": "_fixed-position_pn5m3_225",
	"show-collapse-button": "_show-collapse-button_pn5m3_206",
	"toast-stack-spacer": "_toast-stack-spacer_pn5m3_242",
	"toast-stack-gradient-top": "_toast-stack-gradient-top_pn5m3_249",
	"toast-stack-gradient-bottom": "_toast-stack-gradient-bottom_pn5m3_250",
	"toast-stack-gradient-visible": "_toast-stack-gradient-visible_pn5m3_275"
};

const ToasterPopover = forwardRef(
  (props, ref) => {
    const { isDialogToaster } = useToasts();
    const popoverRef = useRef(null);
    const combinedRef = useMergeRefs([popoverRef, ref]);
    const { toasts } = useToasts();
    const toastCount = useMemo(() => toasts.length, [toasts]);
    useEffect(() => {
      if (!popoverRef.current) return;
      const currentPopover = popoverRef.current;
      let timeout;
      if (toastCount > 0) {
        if (isDialogToaster) {
          timeout = setTimeout(() => {
            safeHidePopover(currentPopover);
            safeShowPopover(currentPopover);
          });
        } else {
          safeShowPopover(currentPopover);
        }
      } else {
        safeHidePopover(currentPopover);
      }
      return () => {
        if (timeout) clearTimeout(timeout);
        if (toastCount === 0) {
          safeHidePopover(currentPopover);
        }
      };
    }, [toastCount, isDialogToaster]);
    return /* @__PURE__ */ jsx("div", { ref: combinedRef, className: styles.popover, popover: "manual", children: props.children });
  }
);
ToasterPopover.displayName = "ToasterPopover";

const ANIMATION_DURATION = 300;
const TOAST_STACK_PADDING = 48;
const EXPAND_BUTTON_HEIGHT_WITH_PADDING = 64;
const SCROLL_THRESHOLD = 64;
const EVENT_THROTTLE_MS = 16;

const addOrUpdateToastHeight = (toastId, toastHeight, setToastHeights) => {
  setToastHeights((prev) => {
    if (prev.find((t) => t.id === toastId)) {
      return prev.map((t) => {
        if (t.id === toastId) {
          return { ...t, height: toastHeight };
        }
        return t;
      });
    }
    return [
      ...prev,
      {
        id: toastId,
        height: toastHeight
      }
    ];
  });
};

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
  byteToHex.push((i + 0x100).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  // Note: Be careful editing this code!  It's been tuned for performance
  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  //
  // Note to future-self: No, you can't remove the `toLowerCase()` call.
  // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}

// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).

var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
  // lazy load so that environments that need to polyfill have a chance to do so
  if (!getRandomValues) {
    // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
    getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues) {
      throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
    }
  }
  return getRandomValues(rnds8);
}

var randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const native = {
  randomUUID
};

function v4(options, buf, offset) {
  if (native.randomUUID && true && !options) {
    return native.randomUUID();
  }
  options = options || {};
  var rnds = options.random || (options.rng || rng)();

  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = rnds[6] & 0x0f | 0x40;
  rnds[8] = rnds[8] & 0x3f | 0x80;
  return unsafeStringify(rnds);
}

const toast = () => {
  const toastMethods = [
    "info",
    "success",
    "warning",
    "danger",
    "promise",
    "update",
    "dismiss"
  ];
  console.error(
    "Please use one of the following toast methods:\n",
    ...toastMethods.map((m) => `	toast.${m}()
`)
  );
};
const TOAST_EVENT_NAME = "hammer-toast";
const TOAST_TYPES = ["info", "success", "warning", "danger"];
const methods = {};
TOAST_TYPES.forEach((type) => {
  methods[type] = (props) => {
    const uniqueId = v4();
    const ToastAddEvent = new CustomEvent(TOAST_EVENT_NAME, {
      composed: true,
      detail: {
        id: uniqueId,
        eventType: "add",
        status: type,
        createdAt: Date.now(),
        ...props
      }
    });
    dispatchEvent(ToastAddEvent);
    return uniqueId;
  };
});
const update = (id, props) => {
  const ToastEvent = new CustomEvent(
    TOAST_EVENT_NAME,
    {
      composed: true,
      detail: {
        eventType: "update",
        id,
        ...props
      }
    }
  );
  dispatchEvent(ToastEvent);
};
const dismiss = (id) => {
  const ToastEvent = new CustomEvent(
    TOAST_EVENT_NAME,
    {
      composed: true,
      detail: {
        eventType: "dismiss",
        id
      }
    }
  );
  dispatchEvent(ToastEvent);
};
const promise = async (promise2, toastConfig) => {
  const { onClose, ...loadingToastConfig } = toastConfig.loading;
  let closedWhileLoading = false;
  const onCloseWhileLoading = (e) => {
    toastConfig.loading.onClose?.(e);
    closedWhileLoading = true;
  };
  const id = toast.info({
    ...loadingToastConfig,
    onClose: onCloseWhileLoading,
    duration: false
  });
  await Promise.resolve(promise2).then((res) => {
    if (closedWhileLoading) {
      toast.success({
        ...toastConfig.success(res)
      });
    } else {
      toast.update(id, {
        ...toastConfig.success(res),
        status: "success"
      });
    }
  }).catch((err) => {
    if (closedWhileLoading) {
      toast.danger({
        ...toastConfig.error(err)
      });
    } else {
      toast.update(id, {
        ...toastConfig.error(err),
        status: "danger"
      });
    }
  });
  return id;
};
toast.info = methods.info;
toast.success = methods.success;
toast.warning = methods.warning;
toast.danger = methods.danger;
toast.update = update;
toast.dismiss = dismiss;
toast.promise = promise;

const setToastsAfterClose = (setToasts, setToastHeights, id) => {
  setToasts((prev) => id ? prev.filter((t) => t.id !== id) : []);
  setToastHeights((prev) => id ? prev.filter((t) => t.id !== id) : []);
};
const closeToast = (setToasts, setToastHeights, closingToastClassName, id) => {
  const prefersReducedMotion = globalThis.matchMedia(
    `(prefers-reduced-motion: reduce)`
  ).matches;
  if (prefersReducedMotion) {
    setToastsAfterClose(setToasts, setToastHeights, id);
  } else {
    setToasts(
      (prev) => prev.map((t) => {
        if (!id || t.id === id) {
          return {
            ...t,
            toastClassName: closingToastClassName
          };
        }
        return t;
      })
    );
    setTimeout(() => {
      setToastsAfterClose(setToasts, setToastHeights, id);
    }, ANIMATION_DURATION - 10);
  }
};
const useCloseToast = (closingToastClassName) => {
  const { setToasts, setToastHeights } = useToasts();
  return (id) => {
    closeToast(setToasts, setToastHeights, closingToastClassName, id);
  };
};

const STACKED_TOAST_HEIGHT = "5.3125rem";
const STACKED_TOAST_PEEK_HEIGHT = "1rem";
const useToastPositionStyles = (index) => {
  const {
    toasts,
    toastHeights,
    getToastStackHeight,
    toastsBeforeStack,
    extraToastsVisible
  } = useToasts();
  const toastCount = toasts.length;
  const toasterHeight = getToastStackHeight(index);
  return useMemo(() => {
    if (index === toastCount - 1) {
      return {
        top: 0,
        zIndex: 3
      };
    } else if (
      // all toasts when show more is clicked
      extraToastsVisible || // or visible toasts when stacked
      !extraToastsVisible && (toastCount <= toastsBeforeStack || toastCount > toastsBeforeStack && index >= toastCount - toastsBeforeStack)
    ) {
      return {
        top: toasterHeight
      };
    } else {
      if (toastCount > toastsBeforeStack) {
        if (index === toastCount - toastsBeforeStack - 1) {
          return {
            top: `calc(${toasterHeight || 0}px - ${STACKED_TOAST_HEIGHT} +
              ${STACKED_TOAST_PEEK_HEIGHT})`,
            zIndex: 1
          };
        } else if (index <= toastCount - toastsBeforeStack - 2) {
          return {
            top: `calc(${toasterHeight || 0}px -
              ${STACKED_TOAST_HEIGHT} 
             + ${STACKED_TOAST_PEEK_HEIGHT} * 2)`,
            zIndex: 0
          };
        }
      }
    }
    return void 0;
  }, [toastHeights]);
};

const Toast = forwardRef(
  ({
    actions,
    containerClassName,
    createdAt,
    duration: durationProp,
    index = 0,
    isBelowStackIndex,
    isStacked,
    message,
    onClose,
    onDismiss,
    pausedStatus,
    progress,
    toastClassName,
    ...alertProps
  }, ref) => {
    const { setToastHeights, extraToastsVisible, isDialogToaster } = useToasts();
    const closeToast = useCloseToast(styles.close);
    const toastPositionStyles = useToastPositionStyles(index);
    const toastWrapperRef = useRef(null);
    const timerRef = useRef();
    const pausedAtRef = useRef(0);
    const createdAtRef = useRef(createdAt ?? 0);
    const hasBeenStackedRef = useRef(false);
    const [transitionClass, setTransitionClass] = useState(
      styles.hidden
    );
    const [toastOpened, setToastOpened] = useState(false);
    const duration = actions ? false : durationProp;
    const alertClasses = cx(
      styles["toast-alert"],
      toastClassName,
      transitionClass
    );
    useEffect(() => {
      if (!toastOpened) {
        setTransitionClass(styles.open);
        setTimeout(() => {
          setTransitionClass(void 0);
        }, ANIMATION_DURATION);
        setToastOpened(true);
      }
      return () => {
        onDismiss?.();
      };
    }, []);
    useEffect(() => {
      if (toastWrapperRef.current && toastOpened && !isStacked) {
        if (isBelowStackIndex && extraToastsVisible || isDialogToaster) {
          const delay = isDialogToaster ? 0 : ANIMATION_DURATION;
          setTimeout(() => {
            const height = toastWrapperRef.current?.clientHeight;
            addOrUpdateToastHeight(alertProps.id, height ?? 0, setToastHeights);
          }, delay);
        } else {
          const height = toastWrapperRef.current.clientHeight;
          addOrUpdateToastHeight(alertProps.id, height, setToastHeights);
        }
      }
    }, [
      toastOpened,
      isStacked,
      extraToastsVisible,
      isDialogToaster,
      // toast updates
      actions,
      message,
      alertProps.title
    ]);
    useEffect(() => {
      if (duration && !isStacked) {
        if (!pausedStatus) {
          timerRef.current = setTimeout(
            () => closeToast(alertProps.id),
            duration
          );
          return () => clearTimeout(timerRef.current);
        } else if (typeof pausedStatus === "number") {
          clearTimeout(timerRef.current);
          pausedAtRef.current = pausedStatus;
        } else if (pausedStatus === "resumed") {
          const remainingDuration = (
            // rendering new toast after initial hover
            pausedAtRef.current === 0 ? duration : (
              // resume timer after valid hover
              duration + (createdAtRef.current || 0) - pausedAtRef.current
            )
          );
          timerRef.current = setTimeout(() => {
            closeToast(alertProps.id);
            pausedAtRef.current = 0;
          }, remainingDuration);
          return () => clearTimeout(timerRef.current);
        }
      }
    }, [createdAtRef.current, duration, pausedStatus]);
    useEffect(() => {
      if (duration) {
        if (isStacked) {
          clearTimeout(timerRef.current);
          hasBeenStackedRef.current = true;
        } else if (!isStacked && hasBeenStackedRef.current && !(typeof pausedStatus === "number")) {
          createdAtRef.current = Date.now();
          timerRef.current = setTimeout(() => {
            closeToast(alertProps.id);
            hasBeenStackedRef.current = false;
          }, duration);
          return () => clearTimeout(timerRef.current);
        }
      }
    }, [isStacked, duration]);
    const onSwipe = (dir) => {
      if (dir === "right") {
        toast.dismiss(alertProps.id);
        return;
      }
    };
    const { direction, ...touchProps } = useSwipe(onSwipe);
    const alertCloseProps = isStacked && !extraToastsVisible ? {} : {
      onClose
    };
    const hasMessage = message && message !== "";
    const hasProgress = progress != null;
    return /* @__PURE__ */ jsx(
      "div",
      {
        "data-anv": "toast",
        className: containerClassName,
        style: toastPositionStyles ?? { top: "1.5rem" },
        ref: toastWrapperRef,
        onAnimationStart: () => setToastOpened(true),
        role: isStacked ? "presentation" : void 0,
        ...touchProps,
        children: /* @__PURE__ */ jsx(
          Alert,
          {
            className: alertClasses,
            ...alertProps,
            ...alertCloseProps,
            ref,
            tabIndex: isStacked && !extraToastsVisible ? -1 : 0,
            children: hasMessage || hasProgress || actions ? /* @__PURE__ */ jsxs(Fragment, { children: [
              hasMessage ? /* @__PURE__ */ jsx(
                "div",
                {
                  className: styles["message-container"],
                  id: `toast-message-${alertProps.id}`,
                  children: message
                }
              ) : null,
              hasProgress ? /* @__PURE__ */ jsx(Fragment, { children: progress === "indeterminate" ? /* @__PURE__ */ jsx(
                ProgressBar,
                {
                  "aria-labelledby": `toast-message-${alertProps.id}`,
                  indeterminate: true
                }
              ) : /* @__PURE__ */ jsx(
                ProgressBar,
                {
                  "aria-labelledby": `toast-message-${alertProps.id}`,
                  value: progress
                }
              ) }) : null,
              actions ? /* @__PURE__ */ jsxs("div", { className: styles["alert-action"], children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    appearance: actions.primary.appearance,
                    onClick: actions.primary.onClick,
                    size: "small",
                    children: actions.primary.label
                  }
                ),
                actions.secondary && /* @__PURE__ */ jsx(
                  Button,
                  {
                    appearance: actions.secondary.appearance,
                    onClick: actions.secondary.onClick,
                    size: "small",
                    children: actions.secondary.label
                  }
                )
              ] }) : null
            ] }) : null
          }
        )
      }
    );
  }
);
Toast.displayName = "Toast";

const useHotkeyFocus = ({
  disabled,
  hotkey,
  onHotkeyIn,
  onHotkeyOut,
  refToFocus,
  rootRef
}) => {
  const [shouldEscapeRefocus, setShouldEscapeRefocus] = useState(false);
  const previousFocusElement = useRef(null);
  useEffect(() => {
    if (disabled || typeof document === "undefined") return;
    const rootElement = rootRef.current;
    const blurHandler = (e) => {
      if (e.relatedTarget && rootElement.contains(e.relatedTarget)) {
        return;
      }
      setShouldEscapeRefocus(false);
    };
    const keyDownHandler = async (e) => {
      const activeElement = getActiveElement(document);
      if (activeElement?.tagName.toLowerCase() !== "input" && activeElement?.tagName.toLowerCase() !== "textarea" && activeElement?.tagName.toLowerCase() !== "pre" && e.key === hotkey) {
        e.preventDefault();
        previousFocusElement.current = activeElement;
        await onHotkeyIn?.();
        if (refToFocus.current) {
          refToFocus.current.focus();
          setShouldEscapeRefocus(true);
          if (refToFocus.current.scrollTo) {
            refToFocus.current.scrollTo();
          }
        }
      } else if (e.code === "Escape" && shouldEscapeRefocus) {
        onHotkeyOut?.();
        if (previousFocusElement.current && previousFocusElement.current.tagName.toLowerCase() !== "body") {
          previousFocusElement.current.focus();
        } else {
          activeElement.blur();
        }
      }
    };
    document.addEventListener("keydown", keyDownHandler);
    rootElement.addEventListener("focusout", blurHandler);
    return () => {
      document.removeEventListener("keydown", keyDownHandler);
      rootElement.removeEventListener("focusout", blurHandler);
    };
  }, [
    hotkey,
    disabled,
    rootRef,
    shouldEscapeRefocus,
    onHotkeyIn,
    refToFocus,
    onHotkeyOut
  ]);
  return { returnFocusRef: previousFocusElement };
};

const useShowMoreButtonPositionStyles = () => {
  const { toasts, toastHeights, toastsBeforeStack } = useToasts();
  const totalToasts = toasts.length;
  const extraSpace = totalToasts > toastsBeforeStack + 1 ? "2rem" : "1rem";
  const top = useMemo(() => {
    if (totalToasts > toastsBeforeStack) {
      const heightMap = new Map(toastHeights.map((t) => [t.id, t.height]));
      return toasts.slice(-toastsBeforeStack).map((t) => heightMap.get(t.id)).filter((h) => h !== void 0).reduce((t, c) => t + c, 0);
    }
    return "unset";
  }, [toasts, toastHeights, toastsBeforeStack]);
  return {
    // -0.75px fixes hover issue when 1rem != 16px due to pixel rounding
    top: `calc(${top}px + ${extraSpace} - 0.75px)`,
    position: "absolute",
    display: totalToasts > toastsBeforeStack ? void 0 : "none",
    transition: "top var(--a2-toaster-animation-duration) ease-in"
  };
};

const ToastStack = forwardRef(
  ({
    className,
    duration = false,
    focusKey = "t",
    toasts,
    toastsBeforeStack = 3,
    ...props
  }, ref) => {
    const toastStackRef = useRef(null);
    const firstToastRef = useRef(null);
    const mergedToastStackRef = useMergeRefs([toastStackRef, ref]);
    const {
      setToastsBeforeStack,
      extraToastsVisible,
      setExtraToastsVisible,
      getToastStackHeight,
      isDialogToaster
    } = useToasts();
    const toastCount = toasts.length;
    const isToastStackEmpty = toastCount === 0;
    const lastToastCount = useRef(0);
    const resizeThrottleRef = useRef(false);
    const resizeTimerRef = useRef();
    const scrollThrottleRef = useRef(false);
    const scrollTimerRef = useRef();
    const [toastStackHeight, setToastStackHeight] = useState(0);
    const [disableAnimations, setDisableAnimations] = useState(false);
    const [toastPausedStatus, setToastPausedStatus] = useState(void 0);
    const [showTopGradient, setShowTopGradient] = useState(false);
    const [showBottomGradient, setShowBottomGradient] = useState(true);
    const [viewportHeight, setViewportHeight] = useState(0);
    const isOverflowing = toastStackHeight + EXPAND_BUTTON_HEIGHT_WITH_PADDING > viewportHeight;
    useEffect(() => {
      setViewportHeight(window.innerHeight - TOAST_STACK_PADDING);
      const handleResize = () => {
        if (resizeThrottleRef.current) return;
        resizeThrottleRef.current = true;
        resizeTimerRef.current = setTimeout(() => {
          setViewportHeight(window.innerHeight - TOAST_STACK_PADDING);
          resizeThrottleRef.current = false;
        }, EVENT_THROTTLE_MS);
      };
      window.addEventListener("resize", handleResize);
      return () => {
        clearTimeout(resizeTimerRef.current);
        window.removeEventListener("resize", handleResize);
      };
    }, []);
    useEffect(() => {
      if (toastCount === 0) {
        setToastPausedStatus(void 0);
      }
    }, [toastCount]);
    useEffect(() => {
      const toastStackElement = toastStackRef.current;
      if (!extraToastsVisible) {
        setShowTopGradient(false);
        setShowBottomGradient(isOverflowing);
        return;
      }
      if (!toastStackElement) {
        setShowTopGradient(false);
        setShowBottomGradient(true);
        return;
      }
      const updateGradients = () => {
        const { scrollTop, scrollHeight, clientHeight } = toastStackElement;
        const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
        setShowTopGradient(scrollTop > 0);
        setShowBottomGradient(distanceFromBottom > SCROLL_THRESHOLD);
      };
      const handleScroll = () => {
        if (scrollThrottleRef.current) return;
        scrollThrottleRef.current = true;
        scrollTimerRef.current = setTimeout(() => {
          updateGradients();
          scrollThrottleRef.current = false;
        }, EVENT_THROTTLE_MS);
      };
      updateGradients();
      toastStackElement.addEventListener("scroll", handleScroll, {
        passive: true
      });
      return () => {
        clearTimeout(scrollTimerRef.current);
        toastStackElement.removeEventListener("scroll", handleScroll);
      };
    }, [extraToastsVisible, isOverflowing]);
    useEffect(() => {
      const scrollListener = (e) => {
        e.preventDefault();
        e.stopPropagation();
        toastStackRef.current?.scrollTo({
          top: toastStackRef.current.scrollTop + e.deltaY
        });
      };
      if (isDialogToaster) {
        setDisableAnimations(isDialogToaster);
        const animationTimer = setTimeout(() => {
          setDisableAnimations(false);
        }, 500);
        const toastStackRefCurrent = toastStackRef.current;
        toastStackRefCurrent?.addEventListener("wheel", scrollListener, {
          passive: false
        });
        return () => {
          clearTimeout(animationTimer);
          toastStackRefCurrent?.removeEventListener("wheel", scrollListener);
        };
      }
    }, [isDialogToaster]);
    useEffect(() => {
      let timer;
      if (toastCount > lastToastCount.current || isDialogToaster || extraToastsVisible) {
        setToastStackHeight(getToastStackHeight());
      } else {
        timer = setTimeout(
          () => setToastStackHeight(getToastStackHeight()),
          ANIMATION_DURATION - 10
        );
      }
      lastToastCount.current = toastCount;
      return () => {
        clearTimeout(timer);
      };
    }, [getToastStackHeight, isDialogToaster, extraToastsVisible]);
    useEffect(() => {
      setToastsBeforeStack(toastsBeforeStack);
    }, [setToastsBeforeStack, toastsBeforeStack]);
    const handleCollapseStack = useCallback(() => {
      setExtraToastsVisible(false);
      setToastPausedStatus("resumed");
      if (toastStackRef.current?.scrollTo) {
        toastStackRef.current?.scrollTo(0, 0);
      }
    }, [setExtraToastsVisible]);
    const handleResumeToastTimers = useCallback(() => {
      setToastPausedStatus("resumed");
    }, []);
    const { returnFocusRef } = useHotkeyFocus({
      disabled: isToastStackEmpty,
      hotkey: focusKey,
      onHotkeyIn: async () => {
        setExtraToastsVisible(true);
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve();
          }, 100);
        });
      },
      onHotkeyOut: () => {
        handleResumeToastTimers();
      },
      refToFocus: firstToastRef,
      rootRef: toastStackRef
    });
    const showMoreButtonPositionStyles = useShowMoreButtonPositionStyles();
    const showExpandCollapseButton = toastCount > toastsBeforeStack;
    const expandCollapseButtonText = extraToastsVisible ? "Collapse all" : "Expand all";
    const currentStackHeight = useMemo(
      () => getToastStackHeight(),
      [getToastStackHeight]
    );
    const hasOverflow = currentStackHeight + EXPAND_BUTTON_HEIGHT_WITH_PADDING > viewportHeight;
    const expandCollapseButtonTop = hasOverflow ? `calc(100dvh - 4.5rem)` : extraToastsVisible ? `calc(${currentStackHeight}px - 1rem)` : showMoreButtonPositionStyles.top;
    const toastStackClasses = cx(styles["toast-stack"], className, {
      [styles["show-more-button"]]: showExpandCollapseButton && !extraToastsVisible,
      [styles["show-extra-toast"]]: extraToastsVisible,
      [styles["disable-animations"]]: disableAnimations,
      [styles["has-overflow"]]: hasOverflow
    });
    const handleToastStackFocusHover = () => {
      if (toastPausedStatus === "resumed" || toastPausedStatus === void 0) {
        setToastPausedStatus(Date.now());
      }
    };
    const handleToastStackOnBlur = () => {
      if (!toastStackRef.current?.matches(":focus-within")) {
        handleResumeToastTimers();
      }
    };
    const handleExpandCollapseClick = () => {
      if (extraToastsVisible) {
        handleCollapseStack();
      } else {
        setExtraToastsVisible(true);
      }
    };
    let toastStackHeightStyle = 0;
    if (extraToastsVisible) {
      toastStackHeightStyle = "calc(100vh - var(--a2-mod-toaster-stack-padding) * 2)";
    } else if (toastCount > toastsBeforeStack) {
      toastStackHeightStyle = `calc(${toastStackHeight}px + 3rem + var(--a2-mod-toaster-stack-padding))`;
    } else {
      toastStackHeightStyle = toastStackHeight;
    }
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs(
        "div",
        {
          "data-anv": "ToastStack",
          className: toastStackClasses,
          ref: mergedToastStackRef,
          onMouseOver: handleToastStackFocusHover,
          onMouseLeave: handleResumeToastTimers,
          onFocus: handleToastStackFocusHover,
          onBlur: handleToastStackOnBlur,
          style: {
            height: toastStackHeightStyle
          },
          ...props,
          children: [
            toasts.map(({ toastClassName, onClose, ...toastProps }, index) => {
              const isStacked = !extraToastsVisible && index < toastCount - toastsBeforeStack;
              const isLastToastDisplayed = index === toastCount - toastsBeforeStack;
              const isHidden = index < toastCount - toastsBeforeStack - 2;
              const toastClasses = cx(styles.toast, toastClassName);
              const toastContainerClasses = cx(styles["toast-wrapper"], {
                [styles.stacked]: isStacked || isLastToastDisplayed,
                [styles["stack-one"]]: isStacked && index === toastCount - toastsBeforeStack - 1,
                [styles["stack-two"]]: isStacked && index === toastCount - toastsBeforeStack - 2,
                [styles["stacked-extra"]]: isHidden,
                [styles["stacked-show-extra"]]: extraToastsVisible
              });
              const handleOnClose = (e) => {
                onClose?.(e);
                returnFocusRef.current?.focus();
                toast.dismiss(toastProps.id);
              };
              return /* @__PURE__ */ jsx(
                Toast,
                {
                  containerClassName: toastContainerClasses,
                  duration,
                  index,
                  isStacked,
                  isBelowStackIndex: index < toastCount - toastsBeforeStack,
                  onClose: handleOnClose,
                  pausedStatus: toastPausedStatus,
                  toastClassName: toastClasses,
                  ref: index === 0 ? firstToastRef : void 0,
                  ...toastProps
                },
                toastProps.id
              );
            }),
            showExpandCollapseButton && /* @__PURE__ */ jsx(
              "div",
              {
                className: cx(styles["show-more-button-container"], {
                  [styles["fixed-position"]]: hasOverflow
                }),
                style: { top: expandCollapseButtonTop },
                children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    className: styles["show-collapse-button"],
                    onClick: handleExpandCollapseClick,
                    appearance: "secondary",
                    children: expandCollapseButtonText
                  }
                )
              }
            ),
            extraToastsVisible && hasOverflow && /* @__PURE__ */ jsx(
              "div",
              {
                className: styles["toast-stack-spacer"],
                style: { top: `calc(${currentStackHeight}px + 2rem)` },
                "aria-hidden": "true"
              }
            ),
            /* @__PURE__ */ jsxs(SrOnly, { "aria-live": "polite", children: [
              "New toast message appeared. Press the ",
              focusKey,
              " key to focus on the toast messages. Press escape to return focus to previous position."
            ] })
          ]
        }
      ),
      hasOverflow && /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: cx(styles["toast-stack-gradient-top"], {
              [styles["toast-stack-gradient-visible"]]: showTopGradient
            }),
            "aria-hidden": "true"
          }
        ),
        /* @__PURE__ */ jsx(
          "div",
          {
            className: cx(styles["toast-stack-gradient-bottom"], {
              [styles["toast-stack-gradient-visible"]]: showBottomGradient
            }),
            "aria-hidden": "true"
          }
        )
      ] })
    ] });
  }
);
ToastStack.displayName = "ToastStack";

const ToasterContent = forwardRef(
  ({
    className,
    disableEvents = false,
    id,
    onToastEvent,
    // ToastStackProps
    duration,
    focusKey,
    toastsBeforeStack,
    ...props
  }, ref) => {
    const toasterRef = useRef(null);
    const mergedToasterRef = useMergeRefs([toasterRef, ref]);
    const { toasts, setToasts, isDialogToaster } = useToasts();
    const disableEventsRef = useRef(disableEvents);
    const toastCountRef = useRef(0);
    const isDialogToasterRef = useRef(isDialogToaster);
    const [shouldHideToaster, setShouldHideToaster] = useState(false);
    const updateDialogToasterStorage = useCallback(
      (isDialogToaster2) => {
        const dialogToasters = JSON.parse(
          window?.sessionStorage.getItem("dialog-toasters") ?? "[]"
        );
        if (isDialogToaster2) {
          if (!dialogToasters.includes(id)) {
            window?.sessionStorage.setItem(
              "dialog-toasters",
              JSON.stringify([...dialogToasters, id])
            );
          }
        } else if (dialogToasters.includes(id)) {
          window?.sessionStorage.setItem(
            "dialog-toasters",
            JSON.stringify(
              dialogToasters.filter(
                (dialogToaster) => dialogToaster !== id
              )
            )
          );
        }
      },
      [id]
    );
    useEffect(() => {
      disableEventsRef.current = disableEvents;
    }, [disableEvents]);
    useEffect(() => {
      toastCountRef.current = toasts.length;
    }, [toasts.length]);
    useEffect(() => {
      updateDialogToasterStorage(isDialogToaster);
      isDialogToasterRef.current = isDialogToaster;
      const DialogToasterEvent = new CustomEvent("dialog-toaster", {
        composed: true,
        detail: {
          eventType: "dialog-toaster"
        }
      });
      dispatchEvent(DialogToasterEvent);
    }, [isDialogToaster]);
    const closeToast = useCloseToast(styles.close);
    useEffect(() => {
      let timeout;
      updateDialogToasterStorage(isDialogToaster);
      const toastEventListener = (e) => {
        if (disableEventsRef.current) {
          return;
        }
        const { eventType, ...toastProps } = e.detail;
        if (eventType === "add") {
          const toastAddProps = toastProps;
          if (!toastAddProps.toasterId || toastAddProps.toasterId === id) {
            setToasts((prev) => [...prev, toastProps]);
          }
          timeout = setTimeout(() => {
            onToastEvent?.({
              eventType: "add",
              toastCount: toastCountRef.current,
              id: toastAddProps.id,
              toasterId: id,
              toastProps: toastAddProps
            });
          });
        } else if (eventType === "update") {
          const toastUpdateProps = toastProps;
          setToasts((prev) => {
            return prev.map((t) => {
              if (t.id === toastUpdateProps.id) {
                return {
                  ...t,
                  ...toastUpdateProps
                };
              } else {
                return t;
              }
            });
          });
          onToastEvent?.({
            eventType: "update",
            toastCount: toastCountRef.current,
            id: toastUpdateProps.id,
            toasterId: id,
            toastProps: toastUpdateProps
          });
        } else if (eventType === "dismiss") {
          if (toastProps.id) {
            closeToast(toastProps.id);
            timeout = setTimeout(() => {
              onToastEvent?.({
                eventType: "dismiss",
                toastCount: toastCountRef.current,
                id: toastProps.id,
                toasterId: id
              });
            }, ANIMATION_DURATION);
          } else {
            closeToast();
            onToastEvent?.({
              eventType: "dismiss-all",
              toastCount: 0,
              toasterId: id
            });
          }
        }
      };
      const dialogToasterEventListener = (e) => {
        const { eventType } = e.detail;
        if (eventType === "dialog-toaster") {
          const dialogToasters = JSON.parse(
            window?.sessionStorage.getItem("dialog-toasters") ?? "[]"
          );
          if (dialogToasters.length > 0) {
            if (isDialogToasterRef.current && dialogToasters[dialogToasters.length - 1] === id) {
              setShouldHideToaster(false);
            } else {
              setShouldHideToaster(true);
            }
          } else {
            setShouldHideToaster(false);
          }
        }
      };
      const onPageRefreshListener = () => {
        window?.sessionStorage.removeItem("dialog-toasters");
      };
      window?.addEventListener("hammer-toast", toastEventListener);
      window?.addEventListener("dialog-toaster", dialogToasterEventListener);
      window?.addEventListener("beforeunload", onPageRefreshListener);
      return () => {
        window?.removeEventListener("hammer-toast", toastEventListener);
        window?.removeEventListener(
          "dialog-toaster",
          dialogToasterEventListener
        );
        window?.removeEventListener("beforeunload", onPageRefreshListener);
        clearTimeout(timeout);
        updateDialogToasterStorage(false);
      };
    }, []);
    const toasterClasses = cx(styles.toaster, {
      [styles["hidden"]]: shouldHideToaster,
      [`${className}`]: className != null
    });
    return /* @__PURE__ */ jsx(
      "div",
      {
        "data-anv": "toaster",
        "data-toaster-id": id,
        "aria-hidden": shouldHideToaster,
        className: toasterClasses,
        ref: mergedToasterRef,
        ...props,
        children: /* @__PURE__ */ jsx(
          ToastStack,
          {
            toasts,
            duration,
            focusKey,
            toastsBeforeStack
          }
        )
      }
    );
  }
);
const Toaster = forwardRef(
  (props, ref) => {
    return /* @__PURE__ */ jsx(ToastProvider, { children: /* @__PURE__ */ jsx(ToasterPopover, { children: /* @__PURE__ */ jsx(ToasterContent, { ...props, ref }) }) });
  }
);
Toaster.displayName = "Toaster";
ToasterContent.displayName = "ToasterContent";

export { Toaster as T, ToastProvider as a, ToasterPopover as b, ToasterContent as c, toast as t };
//# sourceMappingURL=Toaster-Bq42x6Gx.js.map
