import { useRef as w, useState as v, useCallback as r, useEffect as f } from "react";
import { useAreasStore as W } from "../../../../../../../hooks/useAreas/index.js";
import { isHorizontalPanelSide as d, getPointerPositionForPanelSide as R, clampPanelSize as b } from "../helpers/panelRuntime.js";
const M = (l) => {
  const u = W((e) => e.areaActions.setPanelSize), P = w(null), m = w(null), o = w(null), [n, z] = v(null), [p, a] = v({}), g = !!n, E = r(
    (e) => {
      const t = p[e.windowId];
      return t ? {
        ...e,
        width: t.width ?? e.width,
        height: t.height ?? e.height
      } : e;
    },
    [p]
  ), S = r((e) => d(e) ? P.current : m.current, []), L = r(
    (e, t) => {
      t.preventDefault(), t.stopPropagation(), z({
        panel: e,
        pointerStart: R(e.side, t),
        sizeStart: d(e.side) ? e.width : e.height
      }), o.current = d(e.side) ? e.width : e.height, a((s) => ({
        ...s,
        [e.windowId]: {
          width: e.width,
          height: e.height
        }
      }));
    },
    []
  ), h = r(
    (e) => {
      if (!n)
        return;
      const s = R(
        n.panel.side,
        e
      ) - n.pointerStart, x = n.panel.side === "left" || n.panel.side === "top" ? n.sizeStart + s : n.sizeStart - s, c = b(
        n.panel.side,
        x,
        S(n.panel.side),
        n.panel
      );
      o.current = c, a((I) => ({
        ...I,
        [n.panel.windowId]: d(
          n.panel.side
        ) ? { width: c } : { height: c }
      }));
    },
    [S, n]
  ), i = r(() => {
    if (n) {
      if (d(n.panel.side)) {
        const e = o.current ?? n.panel.width;
        u(l, n.panel.windowId, {
          width: e,
          maxWidth: n.panel.maxWidth
        });
      } else {
        const e = o.current ?? n.panel.height;
        u(l, n.panel.windowId, {
          height: e,
          maxHeight: n.panel.maxHeight
        });
      }
      z(null), o.current = null, a((e) => {
        const t = { ...e };
        return delete t[n.panel.windowId], t;
      });
    }
  }, [l, n, u]);
  return f(() => {
    if (n)
      return window.addEventListener("blur", i), () => {
        window.removeEventListener("blur", i);
      };
  }, [n, i]), f(() => {
    if (!n)
      return;
    const e = (s) => {
      h(s);
    }, t = () => {
      i();
    };
    return window.addEventListener("mousemove", e, !0), window.addEventListener("mouseup", t, !0), () => {
      window.removeEventListener(
        "mousemove",
        e,
        !0
      ), window.removeEventListener("mouseup", t, !0);
    };
  }, [h, n, i]), {
    centerColumnRef: m,
    handlePinnedResizeMove: h,
    handlePinnedResizeStart: L,
    isPinnedResizeActive: g,
    middleRowRef: P,
    pinnedResizeSession: n,
    resolvePinnedPanelRuntime: E,
    stopPinnedResize: i
  };
};
export {
  M as usePinnedPanelResize
};
