import { jsx as se, jsxs as Ee } from "@emotion/react/jsx-runtime";
import { forwardRef as Pe, useMemo as Ue, useState as b, useRef as Ge, useEffect as j, useCallback as m } from "react";
import We from "clsx";
import { noop as z, isEqualLayout as ce, cloneLayout as _, getLayoutItem as H, cloneLayoutItem as le, getLayoutItemH as ke, moveElement as ue, compact as Y, withLayoutItem as Be, bottom as je, getAllCollisions as Ye } from "./utils.js";
import { MemonizedGridItem as de } from "./subcomponents/GridItem/index.js";
import { GridLayoutRoot as qe } from "./styles.js";
import { DEFAULT_COLS as Xe, DEFAULT_CONTAINER_PADDING as Je, DEFAULT_MARGIN as Ke, DEFAULT_ROW_HEIGHT as Qe, DEFAULT_COLAPSED_HEIGHT as Ve, DEFAULT_CONTAINER_WIDTH as Ze, DEFAULT_CONTAINER_HEIGHT as $e, DEFAULT_TRANSFORM_SCALE as et } from "./constants.js";
import { gridLayoutClasses as fe } from "./classes/index.js";
import { useForkRef as tt } from "@mui/material/utils";
const ft = Pe((me, ye) => {
  const {
    layoutItemRender: q,
    innerRef: ge,
    //Referencia requerida por el provedor WidthProvider para detectar los cambios de tamaño
    autoSize: X = !0,
    cols: g = Xe,
    containerPadding: D = Je,
    margin: v = Ke,
    rowHeight: p = Qe,
    colapsedHeight: x = Ve,
    containerWidth: F = Ze,
    containerHeight: N = $e,
    transformScale: E = et,
    className: pe = "",
    style: he = {},
    draggableHandle: J = "",
    draggableCancel: K = "",
    maxRows: P = 1 / 0,
    // infinite vertical growth
    layout: I = [],
    isBounded: Q = !1,
    isDraggable: V = !0,
    isResizable: Z = !0,
    allowOverlap: y = !1,
    useCSSTransforms: U = !0,
    compactType: S = "vertical",
    preventCollision: G = !1,
    resizeHandles: $ = ["se"],
    resizeHandle: ee,
    maximizeId: W,
    onLayoutChange: ve = z,
    onDragStart: xe = z,
    onDrag: ze = z,
    onDragStop: He = z,
    onResizeStart: De = z,
    onResize: Ie = z,
    onResizeStop: Re = z,
    children: te
  } = me, we = tt(ye, ge), Se = Ue(() => te, [te]), [oe, C] = b({
    mounted: !1
  }), [re, Ce] = b(0), [M, A] = b(I), [L, ne] = b(() => I.filter((e) => e.freeMove).map((e) => e.i)), t = Ge({
    layout: I,
    oldDragItem: void 0,
    oldLayout: void 0,
    oldResizeItem: void 0,
    zIndexes: L,
    colapsedHeight: x,
    rowHeight: p
  });
  t.current.colapsedHeight = x, t.current.rowHeight = p, j(() => {
    C({ mounted: !0 });
  }, []), j(() => {
    re > 0 && ve(t.current.layout);
  }, [re]), j(() => {
    if (!ce(M, I)) {
      const e = _(I), n = [...L];
      for (let s = 0; s < e.length; s++) {
        const r = e[s];
        r.freeMove && n.indexOf(r.i) === -1 && n.push(r.i);
      }
      t.current.layout = e, A(e), n.length !== L.length && (ne(n), t.current.zIndexes = n);
    }
  }, [I]);
  const ae = m((e, n) => {
    n || (n = t.current.layout), ce(n, e) || Ce((s) => s + 1);
  }, []), Le = m(
    (e, n, s, r) => {
      const { layout: l } = t.current, { e: i, node: c } = r, a = H(l, e);
      if (a)
        return t.current = {
          ...t.current,
          oldDragItem: le(a),
          oldLayout: l
          //Punto de arranque, layout actual
        }, a && a.freeMove && k(a.i, "onDragStart"), r.e.type !== "touchmove" && r.e.preventDefault(), r.e.stopPropagation(), xe(l, a, a, void 0, i, c);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  ), _e = m(
    (e, n, s, r) => {
      const { oldDragItem: l, layout: i } = t.current, { e: c, node: a } = r, o = H(i, e);
      if (!o)
        return;
      const u = {
        w: o.w,
        h: ke(o, t.current.colapsedHeight, t.current.rowHeight),
        x: o.x,
        y: o.y,
        placeholder: !0,
        i: e
      }, h = !0;
      try {
        let d;
        o.freeMove ? (o.x = n, o.y = s, u.x = n, u.y = s, d = _(i)) : d = ue(
          i,
          o,
          n,
          s,
          h,
          G,
          S,
          g,
          t.current.colapsedHeight,
          t.current.rowHeight,
          y
        );
        const R = y || o.freeMove ? d : Y(
          d,
          S,
          g,
          t.current.colapsedHeight,
          t.current.rowHeight,
          y
        );
        t.current = {
          ...t.current,
          layout: R,
          activeDrag: u
        }, C((f) => ({
          ...f,
          activeDrag: u
        })), A(R), r.e.type !== "touchmove" && r.e.preventDefault(), r.e.stopPropagation(), ze(d, l, o, u, c, a);
      } catch {
        console.warn("GridLayout error capturado");
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  ), Me = m(
    (e, n, s, { e: r, node: l }) => {
      if (!t.current.activeDrag)
        return;
      const { oldDragItem: i, layout: c, oldLayout: a } = t.current, o = H(c, e);
      if (!o)
        return;
      let u;
      o.freeMove ? (o.x = n, o.y = s, u = _(c)) : u = ue(
        c,
        o,
        n,
        s,
        !0,
        G,
        S,
        g,
        t.current.colapsedHeight,
        t.current.rowHeight,
        y
      );
      const d = y ? u || o.freeMove : Y(
        u,
        S,
        g,
        t.current.colapsedHeight,
        t.current.rowHeight,
        y
      );
      C((R) => ({
        ...R,
        activeDrag: void 0
      })), A(d), t.current = {
        ...t.current,
        layout: d,
        oldDragItem: void 0,
        oldLayout: void 0,
        activeDrag: void 0
      }, r.type !== "touchmove" && r.preventDefault(), r.stopPropagation(), ae(d, a), He(c, i, o, void 0, r, l);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  ), Ae = m(
    (e, n, s, { e: r, node: l }) => {
      const { layout: i } = t.current, c = H(i, e);
      c && (t.current = {
        ...t.current,
        oldResizeItem: le(c),
        oldLayout: t.current.layout
        //Punto de arranque, layout actual
      }, De(i, c, c, void 0, r, l), c && c.freeMove && k(c.i, "onResizeStart"));
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  ), Oe = m(
    (e, n, s, { e: r, node: l }) => {
      const { layout: i, oldResizeItem: c } = t.current;
      let a, o;
      if (c?.freeMove)
        a = _(i), o = H(a, e), o && (o.w = n, o.h = s);
      else {
        const h = (f) => {
          let B;
          if (G && !y) {
            const ie = Ye(
              i,
              { ...f, w: n, h: s },
              t.current.colapsedHeight,
              t.current.rowHeight
            ).filter((w) => w.i !== f.i);
            if (B = ie.length > 0, B) {
              let w = 1 / 0, O = 1 / 0;
              ie.forEach((T) => {
                T.x > f.x && (w = Math.min(w, T.x)), T.y > f.y && (O = Math.min(O, T.y));
              }), Number.isFinite(w) && (f.w = w - f.x), Number.isFinite(O) && (f.h = O - f.y);
            }
          }
          return B || (f.w = n, f.h = s), f;
        }, [d, R] = Be(_(i), e, h);
        a = d, o = R;
      }
      if (!o)
        return;
      const u = {
        w: o.w,
        h: o.h,
        x: o.x,
        y: o.y,
        static: !0,
        i: e
      };
      try {
        const h = y || o.freeMove ? a : Y(
          a,
          S,
          g,
          t.current.colapsedHeight,
          t.current.rowHeight,
          y
        );
        t.current = {
          ...t.current,
          layout: h,
          activeDrag: u
        }, A(h), C((d) => ({ ...d, activeDrag: u })), Ie(a, c, o, u, r, l);
      } catch {
      }
      r.type !== "touchmove" && r.preventDefault(), r.stopPropagation();
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  ), Te = m(
    (e, n, s, { e: r, node: l }) => {
      if (!t.current.activeDrag)
        return;
      const { layout: i, oldResizeItem: c, oldLayout: a } = t.current, o = H(i, e);
      t.current = {
        ...t.current,
        // layout: finalLayout,
        oldResizeItem: void 0,
        oldLayout: void 0,
        activeDrag: void 0
      }, C((u) => ({ ...u, activeDrag: void 0 })), ae(i, a), o && Re(i, c, o, void 0, r, l);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  ), k = m((e, n) => {
    const { layout: s } = t.current, r = t.current.zIndexes.indexOf(e), l = H(s, e);
    if (l && l?.freeMove && (r !== t.current.zIndexes.length - 1 || r === -1)) {
      const i = [...t.current.zIndexes];
      r !== -1 && i.splice(r, 1), i.push(e), t.current.zIndexes = i, ne(i);
    }
  }, []), be = () => {
    const { activeDrag: e } = oe;
    return e ? /* @__PURE__ */ se(
      de,
      {
        type: "placeholder",
        layoutItemRender: q,
        w: e.w,
        h: e.h,
        x: e.x,
        y: e.y,
        i: e.i,
        className: fe.gridItemPlaceholder,
        containerWidth: F,
        containerHeight: N,
        cols: g,
        margin: v,
        containerPadding: D,
        maxRows: P,
        rowHeight: p,
        isDraggable: !1,
        isResizable: !1,
        isBounded: !1,
        useCSSTransforms: U,
        transformScale: E,
        draggableCancel: "",
        draggableHandle: "",
        minW: 0,
        maxW: 0,
        minH: 0,
        maxH: 0,
        maximize: "none",
        colapsed: e.colapsed,
        colapsedHeight: x
      }
    ) : null;
  }, Fe = m(
    (e, n) => {
      const s = typeof e.isDraggable == "boolean" ? e.isDraggable : !e.static && V, r = typeof e.isResizable == "boolean" ? e.isResizable : !e.static && Z, l = e.resizeHandles || $, i = s && Q && e.isBounded !== !1, c = W ? W === e.i ? "maximize_me" : "maximize_other" : "none";
      let a, o;
      return e.freeMove && (a = L.indexOf(e.i), a !== -1 && (a = a + 1, o = { zIndex: a })), /* @__PURE__ */ se(
        de,
        {
          type: "layoutItem",
          layoutItemRender: q,
          containerWidth: F,
          containerHeight: N,
          cols: g,
          margin: v,
          containerPadding: D || v,
          maxRows: P,
          rowHeight: p,
          draggableCancel: K,
          draggableHandle: J,
          onDragStart: Le,
          onDrag: _e,
          onDragStop: Me,
          onResizeStart: Ae,
          onResize: Oe,
          onResizeStop: Te,
          onFreeMoveClick: e.freeMove ? k : void 0,
          isDraggable: s,
          isResizable: r,
          isBounded: i,
          useCSSTransforms: U && n,
          usePercentages: !n,
          transformScale: E,
          w: e.w,
          h: e.h,
          x: e.x,
          y: e.y,
          i: e.i,
          minH: e.minH,
          minW: e.minW,
          maxH: e.maxH,
          maxW: e.maxW,
          static: e.static,
          resizeHandles: l,
          resizeHandle: ee,
          maximize: c,
          freeMove: e.freeMove,
          colapsed: e.colapsed,
          visible: e.visible,
          colapsedHeight: x,
          style: o
        },
        e.i
      );
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      F,
      N,
      g,
      v,
      D,
      P,
      p,
      K,
      J,
      V,
      Z,
      Q,
      U,
      E,
      $,
      ee,
      W,
      L,
      x,
      p
    ]
  ), Ne = {
    height: m(() => {
      if (!X)
        return;
      const e = je(M, x, p), n = D ? D[1] : v[1];
      return e * p + (e - 1) * v[1] + n * 2 + "px";
    }, [X, D, v, M, x])(),
    ...he
  };
  return /* @__PURE__ */ Ee(
    qe,
    {
      className: We(fe.root, pe),
      style: Ne,
      ref: we,
      children: [
        Se,
        M.map((e) => Fe(e, !!oe.mounted)),
        be()
      ]
    }
  );
});
export {
  ft as GridLayout
};
