import g from "../../../@babel/runtime/helpers/esm/extends.js";
import { useState as V, useRef as y, createElement as c, useCallback as Y, forwardRef as h, useEffect as I, useMemo as ve, Fragment as re } from "react";
import { createPortal as me } from "react-dom";
import { composeEventHandlers as P } from "../../primitive/dist/index.js";
import { useComposedRefs as se } from "../../react-compose-refs/dist/index.js";
import { createCollection as we } from "../../react-collection/dist/index.js";
import { createContextScope as Ee } from "../../react-context/dist/index.js";
import { Branch as xe, Root as ye } from "../../react-dismissable-layer/dist/index.js";
import { Portal as Ce } from "../../react-portal/dist/index.js";
import { Presence as Pe } from "../../react-presence/dist/index.js";
import { Primitive as O, dispatchDiscreteCustomEvent as ge } from "../../react-primitive/dist/index.js";
import { useCallbackRef as B } from "../../react-use-callback-ref/dist/index.js";
import { useControllableState as he } from "../../react-use-controllable-state/dist/index.js";
import { useLayoutEffect as _e } from "../../react-use-layout-effect/dist/index.js";
import { VisuallyHidden as ae } from "../../react-visually-hidden/dist/index.js";
const ie = "ToastProvider", [ee, Se, Re] = we("Toast"), [ce, lt] = Ee("Toast", [
  Re
]), [De, q] = ce(ie), de = (e) => {
  const { __scopeToast: o, label: n = "Notification", duration: t = 5e3, swipeDirection: i = "right", swipeThreshold: l = 50, children: p } = e, [f, b] = V(null), [s, x] = V(0), w = y(!1), M = y(!1);
  return /* @__PURE__ */ c(ee.Provider, {
    scope: o
  }, /* @__PURE__ */ c(De, {
    scope: o,
    label: n,
    duration: t,
    swipeDirection: i,
    swipeThreshold: l,
    toastCount: s,
    viewport: f,
    onViewportChange: b,
    onToastAdd: Y(
      () => x(
        (R) => R + 1
      ),
      []
    ),
    onToastRemove: Y(
      () => x(
        (R) => R - 1
      ),
      []
    ),
    isFocusedToastEscapeKeyDownRef: w,
    isClosePausedRef: M
  }, p));
};
de.propTypes = {
  label(e) {
    if (e.label && typeof e.label == "string" && !e.label.trim()) {
      const o = `Invalid prop \`label\` supplied to \`${ie}\`. Expected non-empty \`string\`.`;
      return new Error(o);
    }
    return null;
  }
};
const Ae = "ToastViewport", Ie = [
  "F8"
], Q = "toast.viewportPause", Z = "toast.viewportResume", Fe = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, hotkey: t = Ie, label: i = "Notifications ({hotkey})", ...l } = e, p = q(Ae, n), f = Se(n), b = y(null), s = y(null), x = y(null), w = y(null), M = se(o, w, p.onViewportChange), R = t.join("+").replace(/Key/g, "").replace(/Digit/g, ""), D = p.toastCount > 0;
  I(() => {
    const a = (E) => {
      var u;
      t.every(
        (T) => E[T] || E.code === T
      ) && ((u = w.current) === null || u === void 0 || u.focus());
    };
    return document.addEventListener("keydown", a), () => document.removeEventListener("keydown", a);
  }, [
    t
  ]), I(() => {
    const a = b.current, E = w.current;
    if (D && a && E) {
      const u = () => {
        if (!p.isClosePausedRef.current) {
          const m = new CustomEvent(Q);
          E.dispatchEvent(m), p.isClosePausedRef.current = !0;
        }
      }, $ = () => {
        if (p.isClosePausedRef.current) {
          const m = new CustomEvent(Z);
          E.dispatchEvent(m), p.isClosePausedRef.current = !1;
        }
      }, T = (m) => {
        !a.contains(m.relatedTarget) && $();
      }, v = () => {
        a.contains(document.activeElement) || $();
      };
      return a.addEventListener("focusin", u), a.addEventListener("focusout", T), a.addEventListener("pointermove", u), a.addEventListener("pointerleave", v), window.addEventListener("blur", u), window.addEventListener("focus", $), () => {
        a.removeEventListener("focusin", u), a.removeEventListener("focusout", T), a.removeEventListener("pointermove", u), a.removeEventListener("pointerleave", v), window.removeEventListener("blur", u), window.removeEventListener("focus", $);
      };
    }
  }, [
    D,
    p.isClosePausedRef
  ]);
  const d = Y(({ tabbingDirection: a }) => {
    const u = f().map(($) => {
      const T = $.ref.current, v = [
        T,
        ...ze(T)
      ];
      return a === "forwards" ? v : v.reverse();
    });
    return (a === "forwards" ? u.reverse() : u).flat();
  }, [
    f
  ]);
  return I(() => {
    const a = w.current;
    if (a) {
      const E = (u) => {
        const $ = u.altKey || u.ctrlKey || u.metaKey;
        if (u.key === "Tab" && !$) {
          const N = document.activeElement, F = u.shiftKey;
          if (u.target === a && F) {
            var v;
            (v = s.current) === null || v === void 0 || v.focus();
            return;
          }
          const A = d({
            tabbingDirection: F ? "backwards" : "forwards"
          }), H = A.findIndex(
            (r) => r === N
          );
          if (J(A.slice(H + 1)))
            u.preventDefault();
          else {
            var m, _;
            F ? (m = s.current) === null || m === void 0 || m.focus() : (_ = x.current) === null || _ === void 0 || _.focus();
          }
        }
      };
      return a.addEventListener("keydown", E), () => a.removeEventListener("keydown", E);
    }
  }, [
    f,
    d
  ]), /* @__PURE__ */ c(xe, {
    ref: b,
    role: "region",
    "aria-label": i.replace("{hotkey}", R),
    tabIndex: -1,
    style: {
      pointerEvents: D ? void 0 : "none"
    }
  }, D && /* @__PURE__ */ c(oe, {
    ref: s,
    onFocusFromOutsideViewport: () => {
      const a = d({
        tabbingDirection: "forwards"
      });
      J(a);
    }
  }), /* @__PURE__ */ c(ee.Slot, {
    scope: n
  }, /* @__PURE__ */ c(O.ol, g({
    tabIndex: -1
  }, l, {
    ref: M
  }))), D && /* @__PURE__ */ c(oe, {
    ref: x,
    onFocusFromOutsideViewport: () => {
      const a = d({
        tabbingDirection: "backwards"
      });
      J(a);
    }
  }));
}), Le = "ToastFocusProxy", oe = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, onFocusFromOutsideViewport: t, ...i } = e, l = q(Le, n);
  return /* @__PURE__ */ c(ae, g({
    "aria-hidden": !0,
    tabIndex: 0
  }, i, {
    ref: o,
    style: {
      position: "fixed"
    },
    onFocus: (p) => {
      var f;
      const b = p.relatedTarget;
      !((f = l.viewport) !== null && f !== void 0 && f.contains(b)) && t();
    }
  }));
}), j = "Toast", Oe = "toast.swipeStart", Me = "toast.swipeMove", Ne = "toast.swipeCancel", ke = "toast.swipeEnd", Ke = /* @__PURE__ */ h((e, o) => {
  const { forceMount: n, open: t, defaultOpen: i, onOpenChange: l, ...p } = e, [f = !0, b] = he({
    prop: t,
    defaultProp: i,
    onChange: l
  });
  return /* @__PURE__ */ c(Pe, {
    present: n || f
  }, /* @__PURE__ */ c(ue, g({
    open: f
  }, p, {
    ref: o,
    onClose: () => b(!1),
    onPause: B(e.onPause),
    onResume: B(e.onResume),
    onSwipeStart: P(e.onSwipeStart, (s) => {
      s.currentTarget.setAttribute("data-swipe", "start");
    }),
    onSwipeMove: P(e.onSwipeMove, (s) => {
      const { x, y: w } = s.detail.delta;
      s.currentTarget.setAttribute("data-swipe", "move"), s.currentTarget.style.setProperty("--radix-toast-swipe-move-x", `${x}px`), s.currentTarget.style.setProperty("--radix-toast-swipe-move-y", `${w}px`);
    }),
    onSwipeCancel: P(e.onSwipeCancel, (s) => {
      s.currentTarget.setAttribute("data-swipe", "cancel"), s.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"), s.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"), s.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"), s.currentTarget.style.removeProperty("--radix-toast-swipe-end-y");
    }),
    onSwipeEnd: P(e.onSwipeEnd, (s) => {
      const { x, y: w } = s.detail.delta;
      s.currentTarget.setAttribute("data-swipe", "end"), s.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"), s.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"), s.currentTarget.style.setProperty("--radix-toast-swipe-end-x", `${x}px`), s.currentTarget.style.setProperty("--radix-toast-swipe-end-y", `${w}px`), b(!1);
    })
  })));
}), [Ve, He] = ce(j, {
  onClose() {
  }
}), ue = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, type: t = "foreground", duration: i, open: l, onClose: p, onEscapeKeyDown: f, onPause: b, onResume: s, onSwipeStart: x, onSwipeMove: w, onSwipeCancel: M, onSwipeEnd: R, ...D } = e, d = q(j, n), [a, E] = V(null), u = se(
    o,
    (r) => E(r)
  ), $ = y(null), T = y(null), v = i || d.duration, m = y(0), _ = y(v), N = y(0), { onToastAdd: F, onToastRemove: z } = d, L = B(() => {
    var r;
    (a == null ? void 0 : a.contains(document.activeElement)) && ((r = d.viewport) === null || r === void 0 || r.focus()), p();
  }), A = Y((r) => {
    !r || r === 1 / 0 || (window.clearTimeout(N.current), m.current = (/* @__PURE__ */ new Date()).getTime(), N.current = window.setTimeout(L, r));
  }, [
    L
  ]);
  I(() => {
    const r = d.viewport;
    if (r) {
      const C = () => {
        A(_.current), s == null || s();
      }, S = () => {
        const k = (/* @__PURE__ */ new Date()).getTime() - m.current;
        _.current = _.current - k, window.clearTimeout(N.current), b == null || b();
      };
      return r.addEventListener(Q, S), r.addEventListener(Z, C), () => {
        r.removeEventListener(Q, S), r.removeEventListener(Z, C);
      };
    }
  }, [
    d.viewport,
    v,
    b,
    s,
    A
  ]), I(() => {
    l && !d.isClosePausedRef.current && A(v);
  }, [
    l,
    v,
    d.isClosePausedRef,
    A
  ]), I(() => (F(), () => z()), [
    F,
    z
  ]);
  const H = ve(() => a ? be(a) : null, [
    a
  ]);
  return d.viewport ? /* @__PURE__ */ c(re, null, H && /* @__PURE__ */ c(We, {
    __scopeToast: n,
    role: "status",
    "aria-live": t === "foreground" ? "assertive" : "polite",
    "aria-atomic": !0
  }, H), /* @__PURE__ */ c(Ve, {
    scope: n,
    onClose: L
  }, /* @__PURE__ */ me(/* @__PURE__ */ c(ee.ItemSlot, {
    scope: n
  }, /* @__PURE__ */ c(ye, {
    asChild: !0,
    onEscapeKeyDown: P(f, () => {
      d.isFocusedToastEscapeKeyDownRef.current || L(), d.isFocusedToastEscapeKeyDownRef.current = !1;
    })
  }, /* @__PURE__ */ c(O.li, g({
    // Ensure toasts are announced as status list or status when focused
    role: "status",
    "aria-live": "off",
    "aria-atomic": !0,
    tabIndex: 0,
    "data-state": l ? "open" : "closed",
    "data-swipe-direction": d.swipeDirection
  }, D, {
    ref: u,
    style: {
      userSelect: "none",
      touchAction: "none",
      ...e.style
    },
    onKeyDown: P(e.onKeyDown, (r) => {
      r.key === "Escape" && (f == null || f(r.nativeEvent), r.nativeEvent.defaultPrevented || (d.isFocusedToastEscapeKeyDownRef.current = !0, L()));
    }),
    onPointerDown: P(e.onPointerDown, (r) => {
      r.button === 0 && ($.current = {
        x: r.clientX,
        y: r.clientY
      });
    }),
    onPointerMove: P(e.onPointerMove, (r) => {
      if (!$.current)
        return;
      const C = r.clientX - $.current.x, S = r.clientY - $.current.y, k = !!T.current, K = [
        "left",
        "right"
      ].includes(d.swipeDirection), W = [
        "left",
        "up"
      ].includes(d.swipeDirection) ? Math.min : Math.max, $e = K ? W(0, C) : 0, Te = K ? 0 : W(0, S), G = r.pointerType === "touch" ? 10 : 2, U = {
        x: $e,
        y: Te
      }, te = {
        originalEvent: r,
        delta: U
      };
      k ? (T.current = U, X(Me, w, te, {
        discrete: !1
      })) : ne(U, d.swipeDirection, G) ? (T.current = U, X(Oe, x, te, {
        discrete: !1
      }), r.target.setPointerCapture(r.pointerId)) : (Math.abs(C) > G || Math.abs(S) > G) && ($.current = null);
    }),
    onPointerUp: P(e.onPointerUp, (r) => {
      const C = T.current, S = r.target;
      if (S.hasPointerCapture(r.pointerId) && S.releasePointerCapture(r.pointerId), T.current = null, $.current = null, C) {
        const k = r.currentTarget, K = {
          originalEvent: r,
          delta: C
        };
        ne(C, d.swipeDirection, d.swipeThreshold) ? X(ke, R, K, {
          discrete: !0
        }) : X(Ne, M, K, {
          discrete: !0
        }), k.addEventListener(
          "click",
          (W) => W.preventDefault(),
          {
            once: !0
          }
        );
      }
    })
  })))), d.viewport))) : null;
});
ue.propTypes = {
  type(e) {
    if (e.type && ![
      "foreground",
      "background"
    ].includes(e.type)) {
      const o = `Invalid prop \`type\` supplied to \`${j}\`. Expected \`foreground | background\`.`;
      return new Error(o);
    }
    return null;
  }
};
const We = (e) => {
  const { __scopeToast: o, children: n, ...t } = e, i = q(j, o), [l, p] = V(!1), [f, b] = V(!1);
  return qe(
    () => p(!0)
  ), I(() => {
    const s = window.setTimeout(
      () => b(!0),
      1e3
    );
    return () => window.clearTimeout(s);
  }, []), f ? null : /* @__PURE__ */ c(Ce, {
    asChild: !0
  }, /* @__PURE__ */ c(ae, t, l && /* @__PURE__ */ c(re, null, i.label, " ", n)));
}, Ue = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, ...t } = e;
  return /* @__PURE__ */ c(O.div, g({}, t, {
    ref: o
  }));
}), Xe = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, ...t } = e;
  return /* @__PURE__ */ c(O.div, g({}, t, {
    ref: o
  }));
}), Ye = "ToastAction", le = /* @__PURE__ */ h((e, o) => {
  const { altText: n, ...t } = e;
  return n ? /* @__PURE__ */ c(fe, {
    altText: n,
    asChild: !0
  }, /* @__PURE__ */ c(pe, g({}, t, {
    ref: o
  }))) : null;
});
le.propTypes = {
  altText(e) {
    return e.altText ? null : new Error(`Missing prop \`altText\` expected on \`${Ye}\``);
  }
};
const Be = "ToastClose", pe = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, ...t } = e, i = He(Be, n);
  return /* @__PURE__ */ c(fe, {
    asChild: !0
  }, /* @__PURE__ */ c(O.button, g({
    type: "button"
  }, t, {
    ref: o,
    onClick: P(e.onClick, i.onClose)
  })));
}), fe = /* @__PURE__ */ h((e, o) => {
  const { __scopeToast: n, altText: t, ...i } = e;
  return /* @__PURE__ */ c(O.div, g({
    "data-radix-toast-announce-exclude": "",
    "data-radix-toast-announce-alt": t || void 0
  }, i, {
    ref: o
  }));
});
function be(e) {
  const o = [];
  return Array.from(e.childNodes).forEach((t) => {
    if (t.nodeType === t.TEXT_NODE && t.textContent && o.push(t.textContent), je(t)) {
      const i = t.ariaHidden || t.hidden || t.style.display === "none", l = t.dataset.radixToastAnnounceExclude === "";
      if (!i)
        if (l) {
          const p = t.dataset.radixToastAnnounceAlt;
          p && o.push(p);
        } else
          o.push(...be(t));
    }
  }), o;
}
function X(e, o, n, { discrete: t }) {
  const i = n.originalEvent.currentTarget, l = new CustomEvent(e, {
    bubbles: !0,
    cancelable: !0,
    detail: n
  });
  o && i.addEventListener(e, o, {
    once: !0
  }), t ? ge(i, l) : i.dispatchEvent(l);
}
const ne = (e, o, n = 0) => {
  const t = Math.abs(e.x), i = Math.abs(e.y), l = t > i;
  return o === "left" || o === "right" ? l && t > n : !l && i > n;
};
function qe(e = () => {
}) {
  const o = B(e);
  _e(() => {
    let n = 0, t = 0;
    return n = window.requestAnimationFrame(
      () => t = window.requestAnimationFrame(o)
    ), () => {
      window.cancelAnimationFrame(n), window.cancelAnimationFrame(t);
    };
  }, [
    o
  ]);
}
function je(e) {
  return e.nodeType === e.ELEMENT_NODE;
}
function ze(e) {
  const o = [], n = document.createTreeWalker(e, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (t) => {
      const i = t.tagName === "INPUT" && t.type === "hidden";
      return t.disabled || t.hidden || i ? NodeFilter.FILTER_SKIP : t.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  for (; n.nextNode(); )
    o.push(n.currentNode);
  return o;
}
function J(e) {
  const o = document.activeElement;
  return e.some((n) => n === o ? !0 : (n.focus(), document.activeElement !== o));
}
const pt = de, ft = Fe, bt = Ke, $t = Ue, Tt = Xe, vt = le, mt = pe;
export {
  vt as Action,
  mt as Close,
  Tt as Description,
  pt as Provider,
  bt as Root,
  $t as Title,
  Ke as Toast,
  le as ToastAction,
  pe as ToastClose,
  Xe as ToastDescription,
  de as ToastProvider,
  Ue as ToastTitle,
  Fe as ToastViewport,
  ft as Viewport,
  lt as createToastScope
};
