'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const index_esm = require('../../../../helper-js@3.1.6/node_modules/helper-js/dist/index.esm.cjs');
const index = require('../../../../react-base-virtual-list@1.1.0_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/react-base-virtual-list/dist/index.cjs');

/*!
 * he-tree-react
 * Author: phphe <phphe@outlook.com> (https://github.com/phphe)
 * Released under the MIT License.
 */
const ne = {
  id: null,
  x: 0,
  y: 0,
  time: 0
}, Ke = {
  /**
   * 
   */
  idKey: "id",
  parentIdKey: "parent_id",
  childrenKey: "children",
  indent: 20,
  dragOpen: false,
  dragOpenDelay: 600,
  placeholderId: "__DRAG_PLACEHOLDER__",
  dataType: "flat",
  direction: "ltr",
  rootId: null,
  virtual: false
};
function He(r) {
  const e = { ...Ke, ...r }, { idKey: o, parentIdKey: n, childrenKey: I, placeholderId: g, isFunctionReactive: p } = e, u = { idKey: o, parentIdKey: n };
  if (!e.renderNode && !e.renderNodeBox)
    throw new Error("Either renderNodeBox or renderNode is required.");
  const i = e.direction === "rtl", d = React.useMemo(() => e.openIds ? [...e.openIds].sort().toString() : void 0, [e.openIds]), y = React.useMemo(() => new Set(e.openIds), [d]), E = React.useMemo(() => e.checkedIds ? [...e.checkedIds].sort().toString() : "", [e.checkedIds]), N = React.useMemo(() => new Set(e.checkedIds), [E]), O = React.useMemo(
    () => {
      var ie, ae;
      const D = {}, _ = {}, B = [], H = [], V = [], J = [];
      function* le() {
        if (e.dataType === "flat")
          for (const t of e.data)
            yield [t];
        else
          for (const t of $(e.data, I))
            yield t;
      }
      let U = 0;
      for (const [t, l] of le()) {
        const s = t[o] ?? U;
        J.push(s);
        let f = t[n];
        e.dataType === "tree" && (f = ((ie = l.parent) == null ? void 0 : ie[o]) ?? null);
        let R = _[f] || null;
        const C = D[f] || null, v = [], h = [], b = [];
        let x, k, T;
        C ? (x = C.childIds, k = C.children, T = C.childStats) : (x = B, k = H, T = V);
        const z = x.length, L = (C == null ? void 0 : C.level) + 1 || 1, F = {
          _isStat: true,
          id: s,
          pid: f,
          childIds: v,
          siblingIds: x,
          node: t,
          parent: R,
          parentStat: C,
          children: h,
          childStats: b,
          siblings: k,
          siblingStats: T,
          index: z,
          level: L,
          open: e.openIds ? y.has(s) : true,
          checked: N.has(s),
          draggable: false
        };
        D[s] = F, _[s] = t, x.push(s), k.push(t), T.push(F), U++;
      }
      for (const [t] of $(V, "childStats")) {
        let l = ((ae = e.canDrag) == null ? void 0 : ae.call(e, t)) ?? null;
        l === null && (l = t.parentStat ? t.parentStat.draggable : true), t.draggable = l;
      }
      return {
        // root
        rootIds: B,
        rootNodes: H,
        rootStats: V,
        // 
        allIds: J,
        // methods
        getStat: (t) => {
          let l;
          return typeof t == "object" ? l = t._isStat ? t.id : t[o] : l = t, D[l];
        }
      };
    },
    [
      e.data,
      e.dataType,
      o,
      n,
      y,
      N,
      p && e.canDrag
    ]
  ), { rootIds: K, rootStats: P, getStat: a } = O, S = e.indent, [c, m] = React.useState(), [M, A] = React.useState(), X = React.useRef(null), Y = React.useRef(null), [w, ee] = React.useState(), re = !c, ke = React.useMemo(
    () => {
      const D = [], _ = [];
      for (const [t, { skipChildren: l }] of $(P, "childStats")) {
        const s = B(t);
        t === c && (Object.assign(s.style, {
          position: "fixed",
          top: 0,
          left: 0,
          pointerEvents: "none",
          zIndex: "-999999999",
          visibility: "hidden"
        }), s["data-dragging"] = true), _.push(s), D.push(t.id), (!t.open || t === c) && l();
      }
      if (w) {
        const l = ((f, R) => {
          let C = ((f == null ? void 0 : f.childStats) || P)[R], v;
          if (C)
            v = D.indexOf(C.id);
          else {
            const h = (x) => x.siblingStats[x.siblingStats.indexOf(x) + 1];
            let b;
            if (f) {
              for (const x of ve(f, "parentStat", { withSelf: true }))
                if (b = h(x), b)
                  break;
            }
            b ? v = D.indexOf(b.id) : v = D.length;
          }
          return v;
        })(w.parentStat, w.index);
        D.splice(l, 0, g);
        const s = B({
          id: g,
          level: w.level
        }, true);
        s["data-drag-placeholder"] = true, _.splice(l, 0, s);
      }
      function B(t, l = false) {
        return {
          key: t.id,
          draggable: t.draggable,
          style: { [`padding${i ? "Right" : "Left"}`]: (t.level - 1) * S + "px" },
          "data-key": t.id + "",
          "data-level": t.level + "",
          "data-node-box": true,
          onDragStart(s) {
            var v;
            if (l) {
              s.preventDefault();
              return;
            }
            let f;
            const R = index_esm.findParent(s.target, (h) => (!f && h.hasAttribute("draggable") && (f = h), h.hasAttribute("data-node-box")), { withSelf: true });
            if (R.querySelector("[draggable]") && f === R) {
              s.preventDefault();
              return;
            }
            if (s.dataTransfer.setData("text/plain", "he-tree he-tree-react"), s.dataTransfer.dropEffect = "move", e.customDragImage)
              e.customDragImage(s, t);
            else {
              const h = R.children[0];
              s.dataTransfer.setDragImage(h, i ? h.offsetWidth : 0, 0);
            }
            setTimeout(() => {
              var h;
              m(t), ee({
                ...w,
                parentStat: t.parentStat,
                level: t.level,
                index: (((h = t.parentStat) == null ? void 0 : h.childIds) || K).indexOf(t.id)
              });
            }, 0), (v = e.onDragStart) == null || v.call(e, s, t);
          },
          onDragLeave(s) {
          }
        };
      }
      const H = (t) => {
        var R, C, v;
        if (re && !((R = e.onExternalDragOver) != null && R.call(e, t)))
          return;
        const l = s();
        if (l) {
          const h = a(l.getAttribute("data-key")), b = !!l.getAttribute("data-drag-placeholder");
          f(h, b) && e.onDragOpen(h);
          let x = pe(h, b);
          const { closest: k, next: T } = x;
          let { atTop: z } = x;
          const L = Y.current, F = l;
          let Ie = (() => {
            let G = F.getBoundingClientRect(), W;
            return i ? W = Math.ceil((G.right - t.clientX) / S) : W = Math.ceil((t.clientX - G.x) / S), index_esm.between(W, 0, ((k == null ? void 0 : k.level) || 0) + 1);
          })();
          if (!z && !b && k.id === K[0]) {
            const G = L.querySelector(`[data-key="${k.id}"]`);
            if (G) {
              const W = G.getBoundingClientRect();
              z = W.y + W.height / 2 > t.clientY;
            }
          }
          z && (Ie = 0);
          let de;
          if (z)
            U(null, 0) && (de = {
              ...w,
              parentStat: null,
              level: 1,
              index: 0
            });
          else {
            const G = T ? T.level - 1 : 0, W = [], De = [];
            let q = k;
            const ye = () => q ? q.level : 0;
            for (; ye() >= G; ) {
              const xe = ie(q, T);
              if (U(q, xe) && (Ie > ye() ? W : De).unshift({
                parentStat: q,
                index: xe
              }), !q)
                break;
              q = q.parentStat;
            }
            let Q = index_esm.arrayLast(W);
            Q || (Q = index_esm.arrayFirst(De)), Q && (de = {
              ...w,
              parentStat: Q.parentStat,
              level: (((C = Q.parentStat) == null ? void 0 : C.level) ?? 0) + 1,
              index: Q.index
            });
          }
          ee(de), de && t.preventDefault(), A(b ? void 0 : h), (v = e.onDragOver) == null || v.call(e, t, h, re);
        } else
          U(null, 0) && (ee({
            ...w,
            parentStat: null,
            level: 1,
            index: 0
          }), t.preventDefault());
        function s() {
          const b = Y.current.querySelectorAll("[data-node-box]:not([data-dragging])"), x = index_esm.binarySearch(
            // @ts-ignore
            b,
            (T) => T.getBoundingClientRect().top - t.clientY,
            { returnNearestIfNoHit: true }
          );
          let k;
          return x.hit || x.greater && (k = x.index - 1, k < 0 && (k = 0)), k == null && (k = x.index), b[k];
        }
        function f(h, b) {
          if (!e.dragOpen || b || h.open)
            return false;
          const x = () => Object.assign(ne, { id: h.id, x: t.clientX, y: t.clientY, time: Date.now() });
          if (ne.id !== h.id || Le(t.clientX, t.clientY, ne.x, ne.y) > 10)
            return x(), false;
          if (Date.now() - ne.time >= e.dragOpenDelay)
            return true;
        }
      }, V = (t) => {
        var l, s;
        if (!(re && !((l = e.onExternalDragOver) != null && l.call(e, t))) && w && (t.preventDefault(), re)) {
          const { index: f } = w;
          (s = e.onExternalDrop) == null || s.call(e, t, w.parentStat, f), le();
        }
      };
      function J(t) {
        var f, R;
        if (!c)
          return;
        let l = !w;
        if (!l) {
          let v = Y.current.getBoundingClientRect();
          l = !(t.clientX >= v.left && t.clientX <= v.right && t.clientY >= v.top && t.clientY <= v.bottom);
        }
        if (!(((f = e.onDragEnd) == null ? void 0 : f.call(e, t, c, l)) === false) && w) {
          let C = w.index;
          w.parentStat === c.parentStat && c.index < C && C--;
          const v = [...e.data];
          if (e.dataType === "flat") {
            const h = ((R = w.parentStat) == null ? void 0 : R.id) ?? e.rootId, b = Ae(v, c.id, u), x = { ...c.node, [n]: h };
            b[0] = x;
            const k = be(v, h, C, u);
            v.splice(k, 0, ...b);
          } else {
            const h = /* @__PURE__ */ new Map(), b = (T) => {
              if (!T)
                return v;
              const z = b(T.parentStat);
              let L = [...T.children];
              const F = h.get(T.node) || { ...T.node, [I]: L };
              return h.set(T.node, F), L = F[I], z[T.index] = F, L;
            }, x = b(c.parentStat), k = w.parentStat === c.parentStat ? x : b(w.parentStat);
            x.splice(c.index, 1), k.splice(C, 0, c.node);
          }
          e.onChange(v);
        }
        le();
      }
      function le() {
        A(void 0), m(void 0), ee(void 0);
      }
      function U(t, l) {
        var f, R;
        if (!t)
          return ((f = e.canDropToRoot) == null ? void 0 : f.call(e, l)) ?? true;
        if (!t.open)
          return false;
        let s = (R = e.canDrop) == null ? void 0 : R.call(e, t, l);
        return s == null && (s = U(t.parentStat)), s;
      }
      function pe(t, l) {
        let s = t, f = D.indexOf(l ? e.placeholderId : t.id), R = false;
        const C = (T) => T === g || a(T) === c, v = (T, z) => {
          let L = T, F;
          do
            L += z, F = D[L];
          while (F && C(F));
          return { id: F, i: L };
        }, h = (T, z) => {
          const L = v(T, z);
          s = a(L.id), f = L.i;
        }, b = 1;
        l && (h(f, -1), s || (R = true, h(-1, b)));
        const k = a(v(f, b).id);
        return { closest: s, atTop: R, next: k };
      }
      function ie(t, l) {
        const s = t ? t.childStats : P;
        let f = s.length;
        return l && l.siblingStats === s && (f = s.indexOf(l)), f;
      }
      function ae(t, l = "start") {
        const s = a(t);
        if (!s)
          return false;
        let f = D.indexOf(s.id);
        return f === -1 ? false : X.current ? (X.current.scrollToIndex(f, l), true) : false;
      }
      return { visibleIds: D, attrsList: _, onDragOverRoot: H, onDropToRoot: V, onDragEndOnRoot: J, scrollToNode: ae };
    },
    [
      O,
      S,
      c,
      // watch placeholder position
      w == null ? void 0 : w.parentStat,
      w == null ? void 0 : w.index,
      // watch props
      S,
      g,
      i,
      e.rootId,
      // watch func
      ...[e.canDrop, e.canDropToRoot, e.customDragImage, e.onDragStart, e.onDragOver, e.onExternalDragOver, e.onExternalDrop, e.onDragEnd, e.onChange, e.onDragOpen].map((D) => p && D)
    ]
  ), ue = React.useMemo(() => ({
    getEl: () => window,
    onDragOverWindow: (D) => {
      _() || (A(void 0), e.keepPlaceholder || ee(void 0));
      function _() {
        let B = false, H = D.target;
        if (H) {
          for (const V of ve(H, "parentElement", { withSelf: true }))
            if (V === Y.current) {
              B = true;
              break;
            }
        }
        return B;
      }
    }
  }), [e.keepPlaceholder]);
  Be(ue.getEl, "dragover", ue.onDragOverWindow);
  const { visibleIds: se, attrsList: he, onDragOverRoot: Te, onDropToRoot: me, onDragEndOnRoot: Ee, scrollToNode: Ce } = ke, Ne = React.useMemo(() => c ? [se.indexOf(c.id)] : [], [c, se]), ge = (D) => {
    let _ = e.renderNodeBox;
    if (!_) {
      const B = /* @__PURE__ */ jsxRuntime.jsx("div", { className: "he-tree-drag-placeholder", style: { minHeight: "20px", border: "1px dashed blue" } });
      _ = ({ stat: H, attrs: V, isPlaceholder: J }) => /* @__PURE__ */ React.createElement("div", { ...V, key: V.key }, J ? B : e.renderNode(H));
    }
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: `he-tree ${(D == null ? void 0 : D.className) || ""}`, style: D == null ? void 0 : D.style, ref: Y, onDragOver: Te, onDrop: me, onDragEnd: Ee, children: /* @__PURE__ */ jsxRuntime.jsx(
      index.VirtualList,
      {
        ref: X,
        className: (D == null ? void 0 : D.listClassName) || "",
        innerClassName: (D == null ? void 0 : D.listInnerClassName) || "",
        items: se,
        virtual: e.virtual,
        persistentIndices: Ne,
        style: { height: "100%" },
        renderItem: (B, H) => _({
          stat: a(B),
          attrs: he[H],
          isPlaceholder: B === g
        })
      }
    ) });
  };
  return {
    ...O,
    // 
    visibleIds: se,
    attrsList: he,
    // ref
    virtualListRef: X,
    // drag states
    draggingStat: c,
    dragOverStat: M,
    placeholder: w,
    // render
    renderTree: ge,
    renderHeTree: ge,
    // methods
    scrollToNode: Ce
  };
}
function* $(r, e = "children") {
  let o = false, n = false;
  const I = () => {
    o = true;
  }, g = () => {
    n = true;
  };
  yield* p(r, null, []);
  function* p(u, i, d) {
    let y = 0;
    for (const E of u) {
      if (yield [E, { parent: i, parents: d, siblings: u, index: y, skipChildren: I, exitWalk: g }], n)
        return;
      if (y++, o)
        o = false;
      else {
        const O = E[e];
        if (O && (yield* p(O, E, [...d, E]), n))
          return;
      }
    }
  }
}
function* ve(r, e, o = { withSelf: false }) {
  let n = r;
  for (; n; )
    (n !== r || o.withSelf) && (yield n), n = typeof e == "function" ? e(n) : n[e];
}
const Z = {
  idKey: "id",
  parentIdKey: "parent_id"
};
function* oe(r, e) {
  const o = { ...Z, ...e }, { idKey: n, parentIdKey: I } = o;
  let g = false, p = false;
  const u = () => {
    g = true;
  }, i = () => {
    p = true;
  }, d = {}, y = {}, E = {}, N = [];
  let O, K = 0;
  for (const P of r) {
    const a = P[n], S = P[I] ?? null;
    d[a] = P;
    const c = d[S] || null;
    E[a] = [];
    const m = c ? E[S] : N, M = m.length;
    m.push(a);
    const A = {
      parent: c,
      parents: c ? [...y[S].parents, c] : [],
      index: M,
      id: a,
      pid: S,
      treeIndex: K,
      skipChildren: u,
      exitWalk: i
    };
    y[a] = A;
    let X = false;
    if (g && O && (O.has(S) ? (O.add(a), X = true) : (g = false, O = void 0)), !X) {
      if (yield [P, A], p)
        break;
      g && (O = /* @__PURE__ */ new Set([a]));
    }
    K++;
  }
}
function be(r, e, o, n) {
  const I = { ...Z, ...n }, { idKey: g, parentIdKey: p } = I;
  let u = false, i = -1;
  for (const [d, { treeIndex: y, skipChildren: E, index: N }] of oe(r, I))
    if (e != null && !u)
      d[g] === e && (u = true);
    else if (e == null || d[p] === e)
      if (o != null && o === N) {
        i = y;
        break;
      } else
        E();
    else {
      i = y;
      break;
    }
  return i === -1 && (i = r.length), i;
}
function Ae(r, e, o) {
  if (e == null)
    return r.splice(0, r.length);
  const n = { ...Z, ...o }, { idKey: I, parentIdKey: g } = n;
  let p = -1, u = -1;
  for (const [i, { treeIndex: d, skipChildren: y }] of oe(r, n))
    if (p === -1)
      i[I] === e && (p = d, y());
    else {
      u = d;
      break;
    }
  return u === -1 && (u = r.length), p === -1 ? [] : r.splice(p, u - p);
}
function Le(r, e, o, n) {
  return Math.sqrt(Math.pow(o - r, 2) + Math.pow(n - e, 2));
}
function Be(r, e, o) {
  React.useLayoutEffect(() => {
    const n = r();
    return n == null || n.addEventListener(e, o), () => {
      n == null || n.removeEventListener(e, o);
    };
  }, [r, e, o]);
}

exports.convertIndexToTreeIndexInFlatData = be;
exports.defaultProps = Ke;
exports.removeByIdInFlatData = Ae;
exports.useHeTree = He;
exports.walkFlatDataGenerator = oe;
exports.walkParentsGenerator = ve;
exports.walkTreeDataGenerator = $;
