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 ce, useRef as j, useState as ae, 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"
}, C = {
  overflow: "inherit",
  p: 1
};
function k(t) {
  const e = typeof t == "function" ? t() : t;
  return e && e.nodeType === 1 ? e : null;
}
function F(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: w,
    anchorReference: r,
    marginThreshold: n,
    paperElement: P,
    transformOrigin: b
  } = t, g = {
    height: P.offsetHeight,
    width: P.offsetWidth
  }, c = {
    horizontal: q(g, b.horizontal),
    vertical: Y(g, b.vertical)
  };
  if (r === "none")
    return {
      left: "0px",
      top: "0px",
      transformOrigin: G(c),
      visibility: "visible"
    };
  const R = k(e), E = r === "anchorPosition" ? {
    bottom: w?.top ?? 0,
    height: 0,
    left: w?.left ?? 0,
    right: w?.left ?? 0,
    top: w?.top ?? 0,
    width: 0
  } : R?.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 - c.vertical, h = T.left - c.horizontal;
  const D = m + g.height, L = h + g.width, p = R?.ownerDocument.defaultView ?? window, A = p.innerHeight - (n ?? 0), S = p.innerWidth - (n ?? 0);
  if (n !== null && m < n) {
    const i = m - n;
    m -= i, c.vertical += i;
  } else if (n !== null && D > A) {
    const i = D - A;
    m -= i, c.vertical += i;
  }
  if (n !== null && h < n) {
    const i = h - n;
    h -= i, c.horizontal += i;
  } else if (n !== null && L > S) {
    const i = L - S;
    h -= i, c.horizontal += i;
  }
  return {
    left: `${Math.round(h)}px`,
    top: `${Math.round(m)}px`,
    transformOrigin: G(c),
    visibility: "visible"
  };
}
const Ne = ce(
  function(e, y) {
    const {
      action: w,
      anchorEl: r,
      anchorOrigin: n = { horizontal: "right", vertical: "bottom" },
      anchorPosition: P,
      anchorReference: b = "anchorEl",
      arrowType: g = "no-arrow",
      BackdropComponent: c,
      BackdropProps: R,
      children: E,
      className: T,
      closeAfterTransition: m,
      component: h,
      components: D,
      componentsProps: L,
      container: p,
      disableAutoFocus: A,
      disableEnforceFocus: S,
      disableEscapeKeyDown: i,
      disablePortal: ve,
      disableRestoreFocus: M = !1,
      disableScrollLock: Ee,
      elevation: J = 8,
      hideBackdrop: we,
      instaceDataTestId: Q,
      keepMounted: Pe,
      marginThreshold: B = 16,
      onBackdropClick: be,
      onClose: O,
      onTransitionEnter: ge,
      onTransitionExited: _e,
      open: u = !1,
      ownerState: ye,
      PaperProps: I = {},
      size: Te,
      slotProps: x,
      slots: Oe,
      sx: Z,
      transformOrigin: N = { horizontal: "right", vertical: "top" },
      TransitionComponent: xe,
      transitionDuration: ke,
      TransitionProps: Re,
      ...ee
    } = e, a = j(null), te = ie(
      a,
      ((typeof x?.paper == "function" ? void 0 : x?.paper) ?? I)?.ref
    ), [oe, V] = ae(
      X
    ), z = j(null), K = u ? F(p, r) : null, d = (typeof x?.paper == "function" ? void 0 : x?.paper) ?? I, ne = Array.isArray(
      d?.sx
    ) ? [C, ...d.sx] : d?.sx ? [C, d.sx] : C;
    return le(() => {
      if (!u || !a.current) {
        V(X);
        return;
      }
      const o = () => {
        if (!a.current)
          return;
        const s = he({
          anchorEl: r,
          anchorOrigin: n,
          anchorPosition: P,
          anchorReference: b,
          marginThreshold: B,
          paperElement: a.current,
          transformOrigin: N
        });
        V((v) => v.left === s.left && v.top === s.top && v.transformOrigin === s.transformOrigin && v.visibility === s.visibility ? v : s);
      }, l = a.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(a.current), _ && f?.observe(_), () => {
        l.defaultView?.removeEventListener("resize", o), l.removeEventListener("scroll", o, !0), f?.disconnect();
      };
    }, [
      r,
      n,
      P,
      b,
      B,
      u,
      N
    ]), U(() => {
      if (!u)
        return;
      const o = a.current?.ownerDocument ?? F(p, r)?.ownerDocument ?? document;
      return z.current = o.activeElement instanceof HTMLElement ? o.activeElement : null, () => {
        M || z.current?.focus?.(), z.current = null;
      };
    }, [r, p, M, u]), U(() => {
      if (!u || !O)
        return;
      const o = a.current?.ownerDocument ?? F(p, r)?.ownerDocument ?? document, l = (f) => {
        const s = f.target, v = k(r);
        if (!s || a.current?.contains(s) || v?.contains(s))
          return;
        const H = s instanceof Element ? s : s.parentElement;
        H?.closest(".MuiModal-root") || H?.closest(".MuiAutocomplete-popper") || 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 || !K ? 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
            }
          )
        }
      ),
      K
    );
  }
);
export {
  Ne as Popover
};
