import { jsx as W } from "@emotion/react/jsx-runtime";
import { Paper as re } from "@mui/material";
import { useForkRef as ie } from "@mui/material/utils";
import $ from "clsx";
import { createPortal as se } from "react-dom";
import { forwardRef as ae, useRef as j, useState as ce, useLayoutEffect as le, useEffect as U } from "react";
import { getPropDataTestId as fe } from "../../../../test/getNameDataTestId.js";
import { POPOVER_CLASS_NAME_SPECIFY as pe, POPOVER_PREFIX as ue } from "./constants.js";
import { PopoverRootStyled as de } from "./slots/PopoverSlots.js";
import { PopoverSlots as me } from "./slots/PopoverEnum.js";
const X = {
  left: "0px",
  top: "0px",
  transformOrigin: "top left",
  visibility: "hidden"
}, F = {
  overflow: "inherit",
  p: 1
};
function k(t) {
  const e = typeof t == "function" ? t() : t;
  return e && e.nodeType === 1 ? e : null;
}
function M(t, e) {
  return typeof document > "u" ? null : t ? typeof t == "function" ? t() : t ?? null : k(e)?.ownerDocument.body ?? document.body;
}
function Y(t, e) {
  return typeof e == "number" ? e : e === "center" ? t.height / 2 : e === "bottom" ? t.height : 0;
}
function q(t, e) {
  return typeof e == "number" ? e : e === "center" ? t.width / 2 : e === "right" ? t.width : 0;
}
function G(t) {
  return [t.horizontal, t.vertical].map((e) => typeof e == "number" ? `${e}px` : e).join(" ");
}
function he(t) {
  const {
    anchorEl: e,
    anchorOrigin: y,
    anchorPosition: P,
    anchorReference: r,
    marginThreshold: n,
    paperElement: w,
    transformOrigin: b
  } = t, g = {
    height: w.offsetHeight,
    width: w.offsetWidth
  }, a = {
    horizontal: q(g, b.horizontal),
    vertical: Y(g, b.vertical)
  };
  if (r === "none")
    return {
      left: "0px",
      top: "0px",
      transformOrigin: G(a),
      visibility: "visible"
    };
  const D = k(e), E = r === "anchorPosition" ? {
    bottom: P?.top ?? 0,
    height: 0,
    left: P?.left ?? 0,
    right: P?.left ?? 0,
    top: P?.top ?? 0,
    width: 0
  } : D?.getBoundingClientRect() ?? {
    height: 0,
    left: 0,
    top: 0,
    width: 0
  }, T = {
    left: E.left + q(E, y.horizontal),
    top: E.top + Y(E, y.vertical)
  };
  let m = T.top - a.vertical, h = T.left - a.horizontal;
  const R = m + g.height, L = h + g.width, p = D?.ownerDocument.defaultView ?? window, S = p.innerHeight - (n ?? 0), A = p.innerWidth - (n ?? 0);
  if (n !== null && m < n) {
    const i = m - n;
    m -= i, a.vertical += i;
  } else if (n !== null && R > S) {
    const i = R - S;
    m -= i, a.vertical += i;
  }
  if (n !== null && h < n) {
    const i = h - n;
    h -= i, a.horizontal += i;
  } else if (n !== null && L > A) {
    const i = L - A;
    h -= i, a.horizontal += i;
  }
  return {
    left: `${Math.round(h)}px`,
    top: `${Math.round(m)}px`,
    transformOrigin: G(a),
    visibility: "visible"
  };
}
const Ne = ae(
  function(e, y) {
    const {
      action: P,
      anchorEl: r,
      anchorOrigin: n = { horizontal: "right", vertical: "bottom" },
      anchorPosition: w,
      anchorReference: b = "anchorEl",
      arrowType: g = "no-arrow",
      BackdropComponent: a,
      BackdropProps: D,
      children: E,
      className: T,
      closeAfterTransition: m,
      component: h,
      components: R,
      componentsProps: L,
      container: p,
      disableAutoFocus: S,
      disableEnforceFocus: A,
      disableEscapeKeyDown: i,
      disablePortal: ve,
      disableRestoreFocus: B = !1,
      disableScrollLock: Ee,
      elevation: J = 8,
      hideBackdrop: Pe,
      instaceDataTestId: Q,
      keepMounted: we,
      marginThreshold: I = 16,
      onBackdropClick: be,
      onClose: O,
      onTransitionEnter: ge,
      onTransitionExited: _e,
      open: u = !1,
      ownerState: ye,
      PaperProps: N = {},
      size: Te,
      slotProps: x,
      slots: Oe,
      sx: Z,
      transformOrigin: V = { horizontal: "right", vertical: "top" },
      TransitionComponent: xe,
      transitionDuration: ke,
      TransitionProps: De,
      ...ee
    } = e, c = j(null), te = ie(
      c,
      ((typeof x?.paper == "function" ? void 0 : x?.paper) ?? N)?.ref
    ), [oe, K] = ce(
      X
    ), z = j(null), H = u ? M(p, r) : null, d = (typeof x?.paper == "function" ? void 0 : x?.paper) ?? N, ne = Array.isArray(
      d?.sx
    ) ? [F, ...d.sx] : d?.sx ? [F, d.sx] : F;
    return le(() => {
      if (!u || !c.current) {
        K(X);
        return;
      }
      const o = () => {
        if (!c.current)
          return;
        const s = he({
          anchorEl: r,
          anchorOrigin: n,
          anchorPosition: w,
          anchorReference: b,
          marginThreshold: I,
          paperElement: c.current,
          transformOrigin: V
        });
        K((v) => v.left === s.left && v.top === s.top && v.transformOrigin === s.transformOrigin && v.visibility === s.visibility ? v : s);
      }, l = c.current.ownerDocument, _ = k(r), f = typeof ResizeObserver > "u" ? null : new ResizeObserver(() => {
        o();
      });
      return o(), l.defaultView?.addEventListener("resize", o), l.addEventListener("scroll", o, !0), f?.observe(c.current), _ && f?.observe(_), () => {
        l.defaultView?.removeEventListener("resize", o), l.removeEventListener("scroll", o, !0), f?.disconnect();
      };
    }, [
      r,
      n,
      w,
      b,
      I,
      u,
      V
    ]), U(() => {
      if (!u)
        return;
      const o = c.current?.ownerDocument ?? M(p, r)?.ownerDocument ?? document;
      return z.current = o.activeElement instanceof HTMLElement ? o.activeElement : null, () => {
        B || z.current?.focus?.(), z.current = null;
      };
    }, [r, p, B, u]), U(() => {
      if (!u || !O)
        return;
      const o = c.current?.ownerDocument ?? M(p, r)?.ownerDocument ?? document, l = (f) => {
        const s = f.target, v = k(r);
        if (!s || c.current?.contains(s) || v?.contains(s))
          return;
        const C = s instanceof Element ? s : s.parentElement;
        C?.closest(".MuiModal-root") || C?.closest(".MuiPopper-root") || C?.closest(".MuiDialog-root") || O(
          f,
          "backdropClick"
        );
      }, _ = (f) => {
        f.key === "Escape" && O(
          f,
          "escapeKeyDown"
        );
      };
      return o.addEventListener("mousedown", l, !0), o.addEventListener("touchstart", l, !0), o.addEventListener("keydown", _), () => {
        o.removeEventListener("mousedown", l, !0), o.removeEventListener("touchstart", l, !0), o.removeEventListener("keydown", _);
      };
    }, [r, p, O, u]), !u || !H ? null : se(
      /* @__PURE__ */ W(
        de,
        {
          ...fe(
            ue,
            me.root,
            Q
          ),
          ...ee,
          ref: y,
          className: $(T, pe),
          ownerState: { position: oe },
          sx: Z,
          children: /* @__PURE__ */ W(
            re,
            {
              ...d,
              ref: te,
              "aria-label": d?.["aria-label"] ?? "Paper-popover-root",
              className: $(d?.className),
              elevation: d?.elevation ?? J,
              sx: ne,
              children: E
            }
          )
        }
      ),
      H
    );
  }
);
export {
  Ne as Popover
};
