import { useContext as b, useState as P, useRef as m, useEffect as f, useCallback as s, useMemo as H } from "react";
import { useAreasStore as L } from "../../../../../../../hooks/useAreas/index.js";
import D from "../../../../../../../utils/useOnClickOutside/index.js";
import { ModalContext as U } from "../../../../../../../../../contexts/ModalContext/index.js";
import { isHorizontalPanelSide as n, clampPanelSize as j, getPanelSlotStyle as q, getInlineResizeHandleStyle as B } from "../helpers/panelRuntime.js";
const V = ({
  areaId: w,
  overlay: M,
  panel: e,
  selected: W
}) => {
  const y = L((t) => t.windowActions.close), l = L((t) => t.areaActions.setPanelSize), C = b(U)?.open === !0, [v, z] = P(e.width), [g, a] = P(e.height), S = m(null), O = S, r = m(e.width), d = m(e.height), c = m(null);
  f(() => {
    z(e.width), r.current = e.width;
  }, [e.width]), f(() => {
    a(e.height), d.current = e.height;
  }, [e.height]), D(O, () => {
    W && M && !C && y(e.windowId);
  });
  const R = s(
    (t) => {
      const u = c.current;
      if (!u)
        return;
      const X = S.current?.parentElement ?? null, E = (n(e.side) ? t.clientX : t.clientY) - u.pointerStart, Y = e.side === "left" || e.side === "top" ? u.sizeStart + E : u.sizeStart - E, h = j(
        e.side,
        Y,
        X,
        e
      );
      if (n(e.side)) {
        r.current = h, z(h);
        return;
      }
      d.current = h, a(h);
    },
    [e]
  ), x = s(() => {
    if (c.current) {
      if (c.current = null, n(e.side)) {
        l(w, e.windowId, {
          width: r.current,
          maxWidth: e.maxWidth
        });
        return;
      }
      l(w, e.windowId, {
        height: d.current,
        maxHeight: e.maxHeight
      });
    }
  }, [w, e, l]), i = s(
    (t) => {
      R(t);
    },
    [R]
  ), o = s(() => {
    window.removeEventListener("mousemove", i), window.removeEventListener("mouseup", o), x();
  }, [i, x]);
  f(() => () => {
    window.removeEventListener("mousemove", i), window.removeEventListener("mouseup", o);
  }, [i, o]);
  const A = s(
    (t) => {
      t.preventDefault(), t.stopPropagation(), c.current = {
        pointerStart: n(e.side) ? t.clientX : t.clientY,
        sizeStart: n(e.side) ? r.current : d.current
      }, window.addEventListener("mousemove", i), window.addEventListener("mouseup", o);
    },
    [i, o, e.side]
  ), k = H(
    () => q({
      ...e,
      width: v,
      height: g
    }),
    [g, v, e]
  ), I = H(
    () => B(e.side),
    [e.side]
  );
  return {
    containerRef: S,
    resizeHandleStyle: I,
    slotStyle: k,
    handleResizeStart: A
  };
};
export {
  V as useOverlayPanelResize
};
