import { r as t, g as e, h as i, H as s, a as n } from "./p-9b9ccd0c.js";

import { g as o } from "./p-d42e842b.js";

import "./p-6534555e.js";

import "lit";

import "lit/directives/when.js";

import "lit/directives/if-defined.js";

import { L as a } from "./p-311eedf3.js";

const r = o({
  category: "system",
  name: "check-circle",
  colorType: "primary"
});

const convertItemsNodeListToFlattenedTreeViewModel = (t, e) => {
  const i = [];
  const processNode = t => {
    var s;
    const n = t.active && !t.iconStart ? r : t.iconStart;
    const o = !((s = t.nodes) === null || s === void 0 ? void 0 : s.length);
    const a = e === "all" || e === "custom" && t.checkbox || e === "leaf" && o;
    const c = JSON.stringify({
      versionType: t.type
    });
    i.push({
      caption: t.name,
      checkbox: a,
      checked: t.checked,
      startImgSrc: n,
      endImgSrc: t.iconEnd,
      expanded: t.expanded,
      id: t.id.toString(),
      items: null,
      leaf: o,
      metadata: c,
      parts: t.parts,
      selected: t.selected,
      order: t.order
    });
    if (t.nodes) {
      t.nodes.forEach((t => processNode(t)));
    }
  };
  t.forEach((t => processNode(t)));
  return i;
};

const convertItemsListToTreeViewModel = (t, e) => {
  const i = [];
  t.forEach((t => {
    var s;
    const n = t.active && !t.iconStart ? r : t.iconStart;
    const o = !((s = t.nodes) === null || s === void 0 ? void 0 : s.length);
    const a = e === "all" || e === "custom" && t.checkbox || e === "leaf" && o;
    const c = t.expanded;
    const h = n;
    const l = t.iconEnd;
    const d = JSON.stringify({
      versionType: t.type
    });
    const f = parseInt(t.id);
    i.push({
      caption: t.name,
      checkbox: a,
      checked: t.checked,
      startImgSrc: h,
      endImgSrc: l,
      expanded: c,
      id: t.id.toString(),
      items: !o ? convertItemsListToTreeViewModel(t.nodes, e) : null,
      leaf: o,
      metadata: d,
      parts: t.parts,
      order: f,
      selected: t.selected
    });
  }));
  return i;
};

const findItemNode = (t, e) => {
  if (e.id === t) {
    return e;
  }
  if (e.nodes) {
    for (const i of e.nodes) {
      const e = findItemNode(t, i);
      if (e) {
        return e;
      }
    }
  }
  return null;
};

function findItemInArray(t, e) {
  for (const i of t) {
    const t = findItemNode(e, i);
    if (t) {
      return t;
    }
  }
  return null;
}

const setAllLeafsCheckedFalse = t => {
  const uncheck = t => {
    var e;
    t.checked = false;
    if ((e = t.nodes) === null || e === void 0 ? void 0 : e.length) {
      t.nodes.forEach((t => uncheck(t)));
    }
  };
  t.forEach((t => uncheck(t)));
  return t;
};

const unselectAllNodes = t => {
  const unselect = t => {
    var e;
    t.selected = false;
    if ((e = t.nodes) === null || e === void 0 ? void 0 : e.length) {
      t.nodes.forEach((t => unselect(t)));
    }
  };
  t.forEach((t => unselect(t)));
};

const checkItems = (t, e) => {
  setAllLeafsCheckedFalse(t);
  e.forEach((e => {
    const i = findItemInArray(t, e);
    if (i) {
      i.checked = true;
    }
  }));
  return t;
};

const expandItems = (t, e) => {
  e.forEach((e => {
    const i = findItemInArray(t, e);
    if (i) {
      i.expanded = true;
    }
  }));
  return t;
};

const selectItems = (t, e) => {
  e.forEach((e => {
    const i = findItemInArray(t, e);
    if (i) {
      i.selected = true;
    }
  }));
  return t;
};

function searchInNode(t, e) {
  var i;
  // If the current node is the searched node, we return an empty list (it has no parents in this branch)
    if (t.id === e) {
    return [];
  }
  // We traverse each child looking for the target node
    if ((i = t.nodes) === null || i === void 0 ? void 0 : i.length) {
    for (const i of t.nodes) {
      const s = searchInNode(i, e);
      if (s !== null) {
        // If we find it, we include the current node at the beginning of the path and return
        return [ t.id, ...s ];
      }
    }
  }
  return null;
}

const searchParentsItems = (t, e) => {
  const i = [];
  for (const s of e) {
    for (const e of t) {
      const t = searchInNode(e, s);
      if (t !== null) {
        t.forEach((t => {
          i.push(t);
        }));
      }
    }
  }
  return i;
};

/**
 * Recursively searches for the first node with the active=true property
 * @param nodes Array of nodes to search through
 * @returns An object with caption, iconStart, and path to the first active node found, or null if none is found
 */ const findFirstActiveNode = t => {
  // Helper function that keeps track of the path during recursion
  const findActiveWithPath = (t, e = []) => {
    // Base case: if nodes is undefined or empty
    if (!t || t.length === 0) {
      return null;
    }
    // Iterate through each node in the array
        for (const i of t) {
      // Create a new path that includes the current node
      const t = [ ...e, i.id ];
      // Check if the current node is active
            if (i.active === true) {
        return {
          caption: i.name,
          iconStart: i.iconStart,
          path: t
        };
      }
      // If the node has children, search through them with the updated path
            if (i.nodes && i.nodes.length > 0) {
        const e = findActiveWithPath(i.nodes, t);
        // If we find an active node in this subtree, return it immediately
                if (e !== null) {
          return e;
        }
      }
    }
    // No active node found in any of the nodes
        return null;
  };
  // Start the search with an empty path
    return findActiveWithPath(t);
};

const c = "button.button-secondary{border-color:var(--color-border-neutral-default)}:host{--search-input-max-inline-size:400px;display:grid;block-size:100%}:host(:not(.has-footer)){grid-template-rows:max-content 1fr}:host(.has-footer){grid-template-rows:max-content 1fr max-content}.header.has-active-item{grid-area:header}.section{display:contents}.header__first-row,.header__second-row{display:grid;grid-auto-flow:column}.header__first-row{grid-auto-columns:max-content}.header__second-row{grid-template-columns:minmax(150px, var(--search-input-max-inline-size)) max-content}.header__second-row--one-row{grid-template-columns:minmax(150px, var(--search-input-max-inline-size))}.active-item{background-color:var(--color-accent-surface-elevation-1);border-radius:4px;padding:var(--control-padding-block) var(--control-padding-inline);display:flex;align-items:center;gap:var(--spacing-gap-m)}.active-item__icon-container{display:contents}.active-item__icon{pointer-events:none}.active-item__link{text-decoration:underline;color:var(--color-text-primary-default);cursor:pointer}.active-item__link:hover{color:var(--color-text-primary-hover)}.active-item__link:active{color:var(--color-text-primary-pressed)}.trees{position:relative}";

var h = undefined && undefined.__classPrivateFieldGet || function(t, e, i, s) {
  if (i === "a" && !s) throw new TypeError("Private accessor was defined without a getter");
  if (typeof e === "function" ? t !== e || !s : !e.has(t)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return i === "m" ? s : i === "a" ? s.call(t) : s ? s.value : e.get(t);
};

var l = undefined && undefined.__classPrivateFieldSet || function(t, e, i, s, n) {
  if (s === "m") throw new TypeError("Private method is not writable");
  if (s === "a" && !n) throw new TypeError("Private accessor was defined without a setter");
  if (typeof e === "function" ? t !== e || !n : !e.has(t)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return s === "a" ? n.call(t, i) : n ? n.value = i : e.set(t, i), i;
};

var d, f, u, p, m, v, w, g, k, y, b, x, _, I, W, M, C, S, T, j, z, E, N, A;

const L = [ "resets/box-sizing", "chameleon/scrollbar", "components/tooltip", "components/tree-view", "utils/form--full", "utils/layout", "utils/spacing", "utils/typography" ];

const O = o({
  category: "system",
  name: "search",
  colorType: "on-surface"
});

const P = "tree";

const J = "list";

const X = "on";

const Y = class {
  constructor(s) {
    t(this, s);
    d.add(this);
    f.set(this, void 0);
    u.set(this, void 0);
    p.set(this, []);
    m.set(this, e(`./gx-ide-assets/select-kb-items/shortcuts.json`));
    v.set(this, []);
    w.set(this, void 0);
    g.set(this, void 0);
    y.set(this, (() => {
      if (this.cancelCallback) {
        this.cancelCallback();
      }
    }));
    b.set(this, (async t => {
      let e = [];
      t.detail.forEach((t => {
        if (t.item.checked) {
          e.push(t.item.id);
        }
      }));
      if (this.singleChecks) {
        // Detect the last change by comparing previous and new state
        let i = null;
        // If there are more in the new state, it was a check; if less, it was an uncheck
                if (e.length > this.checkedNodesIds.length) {
          // Find the newly checked item
          i = e.find((t => !this.checkedNodesIds.includes(t))) || null;
        } else if (e.length < this.checkedNodesIds.length) {
          // Find the unchecked item (not used in single check, but kept for clarity)
          i = this.checkedNodesIds.find((t => !e.includes(t))) || null;
        }
        // Only allow one if multiChecks is false
                if (this.singleChecks && e.length > 1) {
          // If we detected the last checked, keep it; otherwise, keep the first
          e = i ? [ i ] : [ e[0] ];
          // Uncheck the others
                    h(this, g, "f").updateItemsProperties(Array.from(t.detail.keys()).filter((t => t !== e[0])), {
            checked: false
          });
        }
      }
      this.checkedNodesIds = e;
      l(this, v, checkItems(this.itemsList, this.checkedNodesIds), "f");
      if (this.checkedChanged) {
        this.checkedChanged(this.checkedNodesIds);
      }
    }));
    x.set(this, (() => {
      if (this.confirmCallback) {
        this.confirmCallback(this.checkedNodesIds);
      }
    }));
    _.set(this, (async t => {
      if (this.itemContextMenuCallback) {
        let e;
        const i = h(this, p, "f").find((e => e === t.detail.id));
        if (!h(this, p, "f").length || !i) {
          await h(this, g, "f").updateItemsProperties(h(this, p, "f"), {
            selected: false
          });
          await h(this, g, "f").updateItemsProperties([ t.detail.id ], {
            selected: true
          });
          e = {
            clientX: t.detail.contextmenuEvent.clientX,
            clientY: t.detail.contextmenuEvent.clientY,
            selection: [ t.detail.id ]
          };
        } else {
          e = {
            clientX: t.detail.contextmenuEvent.clientX,
            clientY: t.detail.contextmenuEvent.clientY,
            selection: h(this, p, "f")
          };
        }
        this.itemContextMenuCallback(e);
      }
    }));
    I.set(this, (t => () => {
      t(this.checkedNodesIds, h(this, p, "f"));
    }));
    W.set(this, (t => {
      this.searchPatternValue = t.detail.toString();
    }));
    M.set(this, (() => i("div", null, this.dialogActions.map((t => i("button", {
      class: "button-tertiary",
      part: `button button-${t.name}`,
      onClick: h(this, I, "f").call(this, t.callback),
      disabled: this.loading
    }, t.name))))));
    C.set(this, (() => {
      var t;
      return i("footer", {
        class: "footer dialog-footer-with-border spacing-body-inline spacing-body-block-end dialog-footer-space-between"
      }, h(this, M, "f").call(this), i("div", {
        class: "buttons-spacer "
      }, this.cancelCallback && i("button", {
        class: "button-secondary",
        part: "cancel-button",
        onClick: h(this, y, "f")
      }, h(this, f, "f").footer.cancel), this.confirmCallback && i("button", {
        class: "button-primary",
        part: "confirm-button",
        onClick: h(this, x, "f"),
        disabled: this.loading || ((t = this.checkedNodesIds) === null || t === void 0 ? void 0 : t.length) === 0
      }, h(this, f, "f").footer.select)));
    }));
    S.set(this, (t => {
      const e = [];
      unselectAllNodes(this.itemsList);
      t.detail.forEach((t => {
        e.push(t.item.id);
      }));
      l(this, p, e, "f");
      if (this.selectionChanged) {
        this.selectionChanged(h(this, p, "f"));
      }
      l(this, v, selectItems(this.itemsList, e), "f");
    }));
    T.set(this, (async t => {
      const e = searchParentsItems(this.itemsList, t);
      const i = selectItems(this.itemsList, t);
      const s = expandItems(i, e);
      h(this, z, "f").call(this, s);
    }));
    j.set(this, (async t => {
      const e = searchParentsItems(this.itemsList, t);
      const i = expandItems(this.itemsList, e);
      h(this, z, "f").call(this, i);
    }));
    z.set(this, (t => {
      this.nodeVersionsListTreeModel = convertItemsListToTreeViewModel(t, this.checkboxType);
      this.nodeListFlattenedTreeModel = convertItemsNodeListToFlattenedTreeViewModel(t, this.checkboxType);
    }));
    E.set(this, (async t => {
      const e = t.detail;
      this.nodesVersionsViewType = e;
      if (this.nodesVersionsViewType === "tree") {
        await h(this, T, "f").call(this, h(this, p, "f"));
        await h(this, j, "f").call(this, this.checkedNodesIds);
      }
      h(this, z, "f").call(this, h(this, v, "f"));
    }));
    N.set(this, (t => {
      this.toggleCheckboxes = t.detail === X;
    }));
    A.set(this, (async () => {
      var t;
      const e = h(this, g, "f") && ((t = this.activeItemNode) === null || t === void 0 ? void 0 : t.path);
      if (e) {
        await h(this, g, "f").scrollIntoVisible(this.activeItemNode.path);
      }
      if (this.activeItemCallback) {
        await this.activeItemCallback();
      }
    }));
    this.activeItemNode = undefined;
    this.checkedNodesIds = [];
    this.renderFooter = false;
    this.nodeListFlattenedTreeModel = [];
    this.loading = true;
    this.nodesVersionsViewType = "tree";
    this.nodeVersionsListTreeModel = [];
    this.searchPatternValue = null;
    this.toggleCheckboxes = undefined;
    this.itemsList = [];
    this.activeItemCallback = undefined;
    this.cancelCallback = undefined;
    this.checkboxType = undefined;
    this.expandOnClick = true;
    this.checkedChanged = undefined;
    this.confirmCallback = undefined;
    this.dialogActions = [];
    this.itemContextMenuCallback = undefined;
    this.loadItemsCallback = undefined;
    this.showToggleCheckboxes = true;
    this.multiSelection = false;
    this.singleChecks = false;
    this.showActiveItemLink = false;
    this.useLoader = true;
    this.selectionChanged = undefined;
  }
  async componentWillLoad() {
    l(this, f, await a.getComponentStrings(this.el), "f");
    this.toggleCheckboxes = this.showToggleCheckboxes;
    l(this, w, [ {
      value: P,
      caption: h(this, f, "f").main.tree
    }, {
      value: J,
      caption: "List"
    } ], "f");
    this.renderFooter = this.dialogActions.length > 0 || !!this.cancelCallback || !!this.confirmCallback;
    h(this, d, "m", k).call(this);
  }
  async reloadItems() {
    await h(this, d, "m", k).call(this);
  }
  /**
     * Suspends or reactivates the shortcuts
     */  async suspendShortcuts(t) {
    if (t) {
      h(this, u, "f").suspend = true;
    } else {
      h(this, u, "f").suspend = false;
    }
  }
  /**
     * Allow to update the selected items
     */  async updateSelection(t) {
    // first clear selected
    h(this, g, "f").updateItemsProperties(h(this, p, "f"), {
      selected: false
    });
    // then select
        h(this, g, "f").updateItemsProperties(t, {
      selected: true
    });
  }
  /**
     * Allow to update the checked items
     */  async updateCheckedItems(t) {
    // first clear checks
    h(this, g, "f").updateItemsProperties(this.checkedNodesIds, {
      checked: false
    });
    // then select
        h(this, g, "f").updateItemsProperties(t, {
      checked: true
    });
    this.checkedNodesIds = t;
  }
  render() {
    return i(s, {
      class: {
        widget: true,
        "has-footer": this.renderFooter
      }
    }, i("ch-theme", {
      model: L
    }), i("ch-shortcuts", {
      src: h(this, m, "f"),
      ref: t => l(this, u, t, "f")
    }), i("section", {
      class: "section"
    }, i("header", {
      part: "header",
      class: "header dialog-header field-group spacing-body-block-start spacing-body-inline"
    }, i("div", {
      class: "header__first-row field-group"
    }, i("div", {
      class: "field field-inline"
    }, i("span", null, i("label", {
      class: "label",
      htmlFor: "view-mode"
    }, "Select view mode:")), i("ch-radio-group-render", {
      class: "radio-group dummy-control-block-size",
      id: "view-mode",
      model: h(this, w, "f"),
      onChange: h(this, E, "f"),
      value: h(this, w, "f")[0].value
    })), this.checkboxType !== "none" && this.showToggleCheckboxes && i("ch-checkbox", {
      class: "checkbox dummy-control-block-size",
      caption: "Toggle Checkboxes",
      id: "toggle-checkboxes",
      checkedValue: X,
      value: X,
      onInput: h(this, N, "f")
    })), i("div", {
      class: {
        "field-group": true,
        "header__second-row": true,
        "header__second-row--one-row": !this.showActiveItemLink
      }
    }, i("ch-edit", {
      class: "input",
      placeholder: h(this, f, "f").header.searchPatternPlaceholder,
      startImgSrc: O,
      onInput: h(this, W, "f"),
      accessibleName: "search pattern"
    }), this.activeItemNode && this.showActiveItemLink && i("div", {
      class: "active-item"
    }, i("span", {
      class: "active-item__icon-container"
    }, i("ch-image", {
      class: "icon-m active-item__icon",
      src: this.activeItemNode.iconStart || r,
      containerRef: null
    })), h(this, f, "f").header.activeItem, i("button", {
      class: "active-item__link",
      onClick: h(this, A, "f")
    }, this.activeItemNode.caption)))), i("div", {
      class: "spacing-body-inline-start trees"
    }, this.useLoader && this.loading ? i("gx-ide-loader", {
      loaderTitle: h(this, f, "f").loader.title,
      description: h(this, f, "f").loader.description,
      show: true
    }) : i("ch-tree-view-render", {
      class: "tree-view",
      model: this.nodesVersionsViewType === "tree" ? this.nodeVersionsListTreeModel : this.nodeListFlattenedTreeModel,
      "show-lines": this.nodesVersionsViewType === "tree" ? "all" : "none",
      expandableButton: this.nodesVersionsViewType === "tree" ? "decorative" : "no",
      onItemContextmenu: h(this, _, "f"),
      onCheckedItemsChange: h(this, b, "f"),
      onSelectedItemsChange: h(this, S, "f"),
      expandOnClick: this.expandOnClick,
      multiSelection: this.multiSelection,
      filter: this.searchPatternValue,
      filterType: "caption",
      toggleCheckboxes: this.toggleCheckboxes,
      ref: t => {
        l(this, g, t, "f");
      }
    })), this.renderFooter && h(this, C, "f").call(this)));
  }
  static get assetsDirs() {
    return [ "gx-ide-assets/select-kb-items" ];
  }
  get el() {
    return n(this);
  }
};

f = new WeakMap, u = new WeakMap, p = new WeakMap, m = new WeakMap, v = new WeakMap, 
w = new WeakMap, g = new WeakMap, y = new WeakMap, b = new WeakMap, x = new WeakMap, 
_ = new WeakMap, I = new WeakMap, W = new WeakMap, M = new WeakMap, C = new WeakMap, 
S = new WeakMap, T = new WeakMap, j = new WeakMap, z = new WeakMap, E = new WeakMap, 
N = new WeakMap, A = new WeakMap, d = new WeakSet, k = async function _GxIdeSelectKbItems_loadItems() {
  try {
    this.loading = true;
    this.itemsList = await this.loadItemsCallback();
    h(this, z, "f").call(this, this.itemsList);
    // Check and update activeItem
        this.activeItemNode = findFirstActiveNode(this.itemsList);
  } catch (t) {
    console.error("Error loading items:", t);
  } finally {
    this.loading = false;
  }
};

Y.style = c;

export { Y as gx_ide_select_kb_items };
//# sourceMappingURL=p-3bbdad29.entry.js.map