import { jsx, jsxs } from "react/jsx-runtime";
import * as RadixToast from "@radix-ui/react-toast";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { useArmstrongConfig } from "../config/config.context.js";
import { Toast } from "./toast.component.js";
import "./toast.theme.css.js";
const initialContext = {
  addToast: () => {
    throw new Error("Unable to dispatch toast, are you sure you've added either the <ArmstrongProvider> or <ToastProvider>?");
  },
  dismissToastByKey: () => {
    throw new Error("Unable to dismiss toast, are you sure you've added either the <ArmstrongProvider> or <ToastProvider>?");
  }
};
const ToastContext = React.createContext(initialContext);
const ToastProvider = ({ children, duration, position, closeButtonIcon, displayMode, ignorePredicate }) => {
  const globals = useArmstrongConfig({
    toastDuration: duration,
    toastPosition: position,
    toastCloseButtonIcon: closeButtonIcon,
    toastDisplayMode: displayMode,
    toastIgnorePredicate: ignorePredicate
  });
  const nextToastKey = React.useRef(1);
  const [toasts, setToasts] = React.useState([]);
  const swipeDirection = globals.toastPosition === "bottom-left" || globals.toastPosition === "top-left" ? "left" : "right";
  const addToast = React.useCallback((newToast) => {
    var _a;
    if ((_a = globals.toastIgnorePredicate) == null ? void 0 : _a.call(globals, toasts.filter((t) => !t.exited).map(({ key: key2, exited, ...toast2 }) => toast2), newToast)) {
      return void 0;
    }
    const key = `toast-${nextToastKey.current}`;
    nextToastKey.current += 1;
    const toast = { ...newToast, key, exited: false };
    setToasts((prevToasts) => {
      if (globals.toastDisplayMode === "add") {
        return [...prevToasts, toast];
      }
      return [toast];
    });
    return key;
  }, [globals, toasts]);
  const removeToastByKey = React.useCallback((key) => {
    setToasts((prevToasts) => prevToasts.map((toast) => toast.key === key ? { ...toast, exited: true } : toast));
  }, []);
  const dismissToastByKey = React.useCallback((key) => {
    setToasts((prevToasts) => prevToasts.filter((toast) => toast.key !== key));
  }, []);
  return jsx(ToastContext.Provider, { value: { addToast, dismissToastByKey }, children: jsxs(RadixToast.Provider, { swipeDirection, duration: globals.toastDuration, children: [children, toasts.map(({ key, ...toast }) => jsx(Toast, { duration: globals.toastDuration, position: globals.toastPosition, closeButtonIcon: globals.toastCloseButtonIcon, onExit: () => removeToastByKey(key), ...toast }, key)), globals.globalPortalTo && ReactDOM.createPortal(jsx(RadixToast.Viewport, { className: "arm-toast-viewport", "data-position": globals.toastPosition }), globals.globalPortalTo)] }) });
};
ToastProvider.displayName = "ToastProvider";
export {
  ToastContext,
  ToastProvider
};
//# sourceMappingURL=toast.context.js.map
