import I, { useState as c, useEffect as x } from "react";
import { renderNodeArray as A } from "./Node.es.es.js";
import { useId as C } from "../../../../../@react-aria/utils/dist/module.es.js";
import { listToTree as K } from "./utils/listToTree.es.es.js";
import { DndWrapper as M } from "../../utilities/dnd/DndWrapper.es.es.js";
import { DropZonePosition as d } from "../../utilities/dnd/types.es.es.js";
import { draggableItemCompareFn as B } from "../../utilities/dnd/draggableItemCompareFn.es.es.js";
const q = ({
  nodes: i,
  onSelect: m,
  activeNodeIds: k,
  onDragAndDrop: p,
  onEditableSave: f,
  onNodeExpand: w
}) => {
  const [b, s] = c(!1), [o, v] = c(k), [h, D] = c([]), a = C();
  x(() => {
    const e = K(i);
    D(e);
  }, [i]);
  const L = (e) => {
    if (b) {
      const t = o.includes(e) ? [...o].filter((n) => n !== e) : [...o, e];
      v(t), m(t);
    } else
      v([e]), m([e]);
  }, N = p ? (e, t, n) => {
    const T = () => {
      switch (n) {
        case d.After:
          const r = i.filter((l) => l.parentId === e.parentId);
          r.sort(B);
          const y = r.findIndex((l) => l.id === e.id);
          return y === r.length - 1 ? null : r[y + 1].id;
        case d.Before:
          return e.id;
        case d.Within:
          return null;
      }
    }, W = n === d.Within ? e.id : e.parentId, $ = T();
    p(t.id, W, $);
  } : void 0, S = f ? (e, t) => {
    f(e, t);
  } : void 0, g = w ? (e) => {
    w(e);
  } : void 0, u = (e) => {
    e.key === "Meta" || e.ctrlKey ? s(!0) : s(!1);
  }, E = (e) => {
    (e.key === "Meta" || e.ctrlKey) && s(!1);
  };
  return x(() => (window.addEventListener("keydown", u), window.addEventListener("keyup", E), () => {
    window.removeEventListener("keydown", u), window.removeEventListener("keyup", E);
  }), []), /* @__PURE__ */ I.createElement("ul", {
    id: a,
    "data-test-id": "tree",
    className: "tw-p-0 tw-m-0 tw-font-sans tw-font-normal tw-list-none tw-text-left tw-text-sm tw-select-none"
  }, /* @__PURE__ */ I.createElement(M, {
    id: a
  }, A({
    nodes: h,
    treeId: a,
    activeIds: o,
    onClick: L,
    onDrop: N,
    onEditableSave: S,
    onNodeExpand: g
  })));
};
export {
  q as Tree
};
//# sourceMappingURL=Tree.es.es.js.map
