import H from "../components/icon.js";
import oe from "../components/input.js";
import j from "../components/line-clamp.js";
import ce from "../components/select.js";
import ne from "../components/tag.js";
import { C as g, a as he } from "./tree.DZa7k-4E.js";
import { n as r, C as R } from "./lib-cortex-element.CVMmyPMC.js";
import { h as V, F as de, M as B, c as pe } from "./asset.types.KXRZEtBr.js";
import { c as Z } from "./component.styles.CRO4Odto.js";
import { c as U } from "./custom-element.L4WJXn1j.js";
import { L as M } from "./i18n.BABe9hN4.js";
import { w as f } from "./watch.BCJD77bD.js";
import { x as m, i as ue } from "./lit-element.jLBm65_O.js";
import { r as x } from "./state.CSDxrqLd.js";
import { e as J } from "./query.BBf1UFkC.js";
import { r as fe } from "./choose.BTbF6BAn.js";
import { C as K } from "./button.CAa1kvwe.js";
import { d as me } from "./debounce.DaHuiSGU.js";
import { g as X, p as W, e as ye } from "./string.DUgD4c9f.js";
import { o as y } from "./if-defined.BRoBj_Rp.js";
import { c as Y } from "./repeat.DbF2p5ae.js";
import { n as _ } from "./when.Dr1es41R.js";
import xe from "../components/space.js";
import { M as q } from "./asset-link-format.BSRDqHg7.js";
import { g as be } from "./template.ClovJacp.js";
import { e as ge } from "./class-map.BiVq-cVR.js";
var v = /* @__PURE__ */ ((e) => (e.CortexPath = "Document.CortexPath", e.DocType = "CoreField.DocType", e.HasBrowserChildren = "Document.HasBrowserChildren", e.RepresentativeAssetId = "Document.DocumentDirectRepresentativeRID", e.TitleWithFallback = "CoreField.TitleWithFallback", e.rawDocSubtype = "Document.RawDocSubType", e))(v || {});
const ve = 50;
async function L({
  allowedFolders: e,
  baseUrl: t,
  bearerToken: s,
  excludeVirtualFolders: l,
  folderId: a,
  includeDirectChild: p,
  limit: u = ve,
  searchTerm: $,
  self: F,
  start: G = 0,
  token: ae
}) {
  let k = [], A = p ?? !0;
  e && e.length > 0 && !a ? (k = e, F = !0, A = !1) : a && (k = [a]);
  try {
    return (await V.request({
      baseURL: t,
      headers: {
        Authorization: `Bearer ${s}`
      },
      method: "GET",
      params: {
        IncludeDirectChild: A,
        IncludeVirtualFolders: !l,
        Limit: u,
        ObjectRecordIDs: k,
        SeeThru: !!$,
        Self: F,
        Start: G,
        Text: $ || void 0,
        Token: ae || void 0
      },
      paramsSerializer: {
        indexes: null
      },
      responseType: "json",
      transformResponse: [
        ...Array.isArray(V.defaults.transformResponse) ? V.defaults.transformResponse : [],
        (S, Pe, w) => {
          if (w !== void 0 && (w < 200 || w >= 300))
            return {
              data: [],
              hasMore: !1,
              totalCount: 0
            };
          if (!S || typeof S != "object")
            throw new Error("Invalid response format");
          const ie = S.contentItems?.length ?? 0;
          return {
            data: S.contentItems?.map((b) => {
              const O = b.fields[v.DocType] ?? "", P = b.fields[v.TitleWithFallback] ?? "", I = b.fields[v.CortexPath] ?? "", E = I.endsWith("/") && I.length > 1 ? I.slice(0, -1) : I;
              let z = E;
              return (O === B.Album || O === B.ProjectDocument) && (z = E ? `${E}/${P}` : P), {
                docType: O,
                fullPath: z,
                hasChildren: b.fields[v.HasBrowserChildren] === "1",
                id: b.recordID,
                isShared: b.fields[v.rawDocSubtype] === "DO_OR1ND000001913488",
                representativeAssetId: b.fields[v.RepresentativeAssetId] ?? "",
                title: P
              };
            }) ?? [],
            hasMore: G + ie < S.totalCount,
            totalCount: S.totalCount
          };
        }
      ],
      url: de
    })).data;
  } catch {
    return {
      data: [],
      hasMore: !1,
      totalCount: 0
    };
  }
}
var C = /* @__PURE__ */ ((e) => (e.Input = "input", e.Select = "select", e))(C || {}), $e = Object.defineProperty, Se = Object.getOwnPropertyDescriptor, h = (e, t, s, l) => {
  for (var a = l > 1 ? void 0 : l ? Se(t, s) : t, p = e.length - 1, u; p >= 0; p--)
    (u = e[p]) && (a = (l ? u(t, s, a) : u(a)) || a);
  return l && a && $e(t, s, a), a;
};
let o = class extends R {
  constructor() {
    super(...arguments), this.localize = new M(this), this.role = "treeitem", this.disabledSyncCheckboxes = !0, this.folderId = "", this.hasChildren = !1, this.selectable = !1, this.fullPath = "", this.docType = q.Story, this.name = "", this.representativeAssetId = "", this.selectedValue = "", this.selection = "single", this.currentRootIDsSet = /* @__PURE__ */ new Set(), this.removedIDs = [], this.token = "", this.bearerToken = "", this.baseUrl = "", this.searchTerm = "", this.api = L, this.excludeVirtualFolders = !1, this.url = "", this.icon = "", this.data = null, this.hasMore = !1, this.loading = !1;
  }
  /**
   * This is used to render the cx-tree-item inside the cx-folder-item without the shadow root so that the cx-tree can query select the cx-tree-item inside
   */
  createRenderRoot() {
    return this;
  }
  async fetchFolders({
    folderId: e,
    start: t = 0
  }) {
    if (!this.api)
      return {
        data: [],
        hasMore: !1,
        totalCount: 0
      };
    try {
      const { data: s, hasMore: l, totalCount: a } = await this.api({
        baseUrl: this.baseUrl,
        bearerToken: this.bearerToken,
        excludeVirtualFolders: this.excludeVirtualFolders,
        folderId: e,
        start: t,
        token: this.token
      });
      return {
        data: s,
        hasMore: l,
        totalCount: a
      };
    } catch {
      return {
        data: [],
        hasMore: !1,
        totalCount: 0
      };
    }
  }
  async loadMore(e) {
    e.stopPropagation();
    const t = this.data?.length || 0;
    this.loading = !0;
    try {
      const { data: s, hasMore: l } = await this.fetchFolders({
        folderId: this.folderId,
        start: t
      });
      this.data = [...this.data || [], ...s], this.hasMore = l;
    } catch {
    } finally {
      this.loading = !1;
    }
  }
  async handleLazyLoad(e) {
    e.stopPropagation(), this.treeItem.expanded = !0;
    const t = this.data?.length || 0;
    try {
      const { data: s, hasMore: l } = await this.fetchFolders({
        folderId: this.folderId,
        start: t
      });
      this.data = s, this.hasMore = l;
    } catch {
      this.treeItem.expanded = !1;
    }
  }
  async syncBoxes() {
    if (this.selection !== "multiple" || (await this.updateComplete, !this.treeItem))
      return;
    const e = this.fullPath, t = X({ id: this.folderId, path: e }), s = W(e), l = this.currentRootIDsSet.has(t);
    let a = !1;
    if (e)
      for (const u of this.currentRootIDsSet) {
        const $ = ye(u);
        if (!$.path.trim() || !$.id.trim())
          continue;
        const F = W($.path);
        if (F.startsWith(s) && F !== s) {
          a = !0;
          break;
        }
      }
    const p = !l && a;
    this.treeItem.selected = l, await this.treeItem.updateComplete, this.treeItem.indeterminate = p;
  }
  render() {
    let e = "filled";
    return this.docType === q.Album && (e = "outlined"), m`<cx-tree-item class=${ge({
      "folder-select-tree-item": !0
    })} data-id=${this.folderId} data-url=${y(this.url)} data-name=${y(this.name?.trim() || void 0)} data-representative-asset-id=${y(
      this.representativeAssetId || void 0
    )} role="option" ?lazy=${this.hasChildren && this.data === null} ?selected=${this.selection !== "multiple" && this.selectedValue === this.folderId} ?disabled-sync-checkboxes=${this.selection === "multiple"} .selectable=${this.selectable} @cx-lazy-load=${this.handleLazyLoad}><cx-space class="folder-select-tree-item__label" direction="horizontal" spacing="x-small" align-items="center" wrap="nowrap"><cx-icon class="folder-select-tree__item__icon" name=${this.icon || "folder"} variant=${e}></cx-icon><cx-line-clamp lines="1" class="folder-select-tree-item__title">${be(this.name, this.searchTerm)}</cx-line-clamp></cx-space>${Y(
      this.data || [],
      (t) => t.id,
      (t) => m`<cx-folder-select-tree-item slot="children" folder-id=${t.id} full-path=${t.fullPath} name=${t.title} representative-asset-id=${t.representativeAssetId} selected-value=${this.selectedValue} selection=${this.selection} token=${this.token} bearer-token=${this.bearerToken} ?exclude-virtual-folders=${this.excludeVirtualFolders} ?has-children=${t.hasChildren} ?selectable=${this.selectable} base-url=${this.baseUrl} url=${y(t.url ?? void 0)} .api=${this.api} .currentRootIDsSet=${this.currentRootIDsSet} .removedIDs=${this.removedIDs} value=${t.url}></cx-folder-select-tree-item>`
    )}</cx-tree-item>${_(
      this.hasMore,
      () => m`<div slot="children" class="load-more-button"><cx-button variant="text" @click=${this.loadMore} ?loading=${this.loading}>${this.localize.term("more")}</cx-button></div>`
    )}
    `;
  }
};
o.styles = [Z];
o.dependencies = {
  "cx-button": K,
  "cx-icon": H,
  "cx-line-clamp": j,
  "cx-space": xe,
  "cx-tree-item": g
};
h([
  J("cx-tree-item")
], o.prototype, "treeItem", 2);
h([
  r({ attribute: "folder-id", reflect: !0, type: String })
], o.prototype, "folderId", 2);
h([
  r({ attribute: "has-children", reflect: !0, type: Boolean })
], o.prototype, "hasChildren", 2);
h([
  r({ reflect: !0, type: Boolean })
], o.prototype, "selectable", 2);
h([
  r({ attribute: "full-path", reflect: !0, type: String })
], o.prototype, "fullPath", 2);
h([
  r({ attribute: "doc-type", reflect: !0, type: String })
], o.prototype, "docType", 2);
h([
  r({ reflect: !0, type: String })
], o.prototype, "name", 2);
h([
  r({
    attribute: "representative-asset-id",
    reflect: !0,
    type: String
  })
], o.prototype, "representativeAssetId", 2);
h([
  r({ attribute: "selected-value", reflect: !0, type: String })
], o.prototype, "selectedValue", 2);
h([
  r({ attribute: "selection", reflect: !0, type: String })
], o.prototype, "selection", 2);
h([
  r({ attribute: !1, type: Object })
], o.prototype, "currentRootIDsSet", 2);
h([
  r({ attribute: !1, type: Array })
], o.prototype, "removedIDs", 2);
h([
  r({ reflect: !0, type: String })
], o.prototype, "token", 2);
h([
  r({ attribute: "bearer-token", reflect: !0, type: String })
], o.prototype, "bearerToken", 2);
h([
  r({ attribute: "base-url", reflect: !0, type: String })
], o.prototype, "baseUrl", 2);
h([
  r({ attribute: "search-term", reflect: !0, type: String })
], o.prototype, "searchTerm", 2);
h([
  r({ type: Function })
], o.prototype, "api", 2);
h([
  r({
    attribute: "exclude-virtual-folders",
    reflect: !0,
    type: Boolean
  })
], o.prototype, "excludeVirtualFolders", 2);
h([
  r({ reflect: !0, type: String })
], o.prototype, "url", 2);
h([
  r({ reflect: !0, type: String })
], o.prototype, "icon", 2);
h([
  x()
], o.prototype, "data", 2);
h([
  x()
], o.prototype, "hasMore", 2);
h([
  x()
], o.prototype, "loading", 2);
h([
  f("currentRootIDsSet"),
  f("removedIDs"),
  f("fullPath"),
  f("folderId")
], o.prototype, "syncBoxes", 1);
o = h([
  U("cx-folder-select-tree-item")
], o);
var Te = Object.defineProperty, Fe = Object.getOwnPropertyDescriptor, ee = (e) => {
  throw TypeError(e);
}, d = (e, t, s, l) => {
  for (var a = l > 1 ? void 0 : l ? Fe(t, s) : t, p = e.length - 1, u; p >= 0; p--)
    (u = e[p]) && (a = (l ? u(t, s, a) : u(a)) || a);
  return l && a && Te(t, s, a), a;
}, te = (e, t, s) => t.has(e) || ee("Cannot " + s), Ce = (e, t, s) => (te(e, t, "read from private field"), t.get(e)), Ie = (e, t, s) => t.has(e) ? ee("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, s), _e = (e, t, s, l) => (te(e, t, "write to private field"), t.set(e, s), s), D;
let n = class extends R {
  constructor() {
    super(...arguments), this.localize = new M(this), this.minQueryLength = 1, this.selection = "single", this.searchTerm = "", this.selectedValue = "", this.token = "", this.bearerToken = "", this.baseUrl = "", this.extraFolderId = "", this.extraFolderTitle = "", this.extraFolderIcon = "", this.seeThru = !1, this.extraFolderData = null, this.api = L, this.excludeVirtualFolders = !1, this.firstFetchCallback = null, this.data = [], this.hasMore = !1, this.loading = !1, this.currentRootIDsSet = /* @__PURE__ */ new Set(), this.removedIDs = [], Ie(this, D, !1);
  }
  get empty() {
    return !this.loading && this.data.length === 0;
  }
  /**
   * This is used to render the cx-tree inside the cx-folder-select without the shadow root so that the cx-folder-select can query select the cx-tree inside
   */
  createRenderRoot() {
    return this;
  }
  runFirstUpdated() {
    this.searchTerm = "", this.handleFetchFolders();
  }
  async handleExtraFolderIdChange() {
    if (!this.extraFolderId || !this.api) {
      this.extraFolderData = null;
      return;
    }
    const { data: e } = await this.api({
      baseUrl: this.baseUrl,
      bearerToken: this.bearerToken,
      excludeVirtualFolders: this.excludeVirtualFolders,
      folderId: this.extraFolderId,
      includeDirectChild: !1,
      limit: 1,
      searchTerm: this.searchTerm,
      seeThru: this.seeThru,
      self: !0,
      start: 0,
      token: this.token
    });
    this.extraFolderData = e[0] ?? null;
  }
  /**
   * Update `currentRootIDsSet` from a tree-item's toggle. Per-folder
   * selection: each folder is independent, so a click only adds/removes
   * the clicked folder — never its ancestors or descendants. Parents
   * showing an indeterminate hint is purely visual (computed in
   * `cx-folder-select-tree-item.syncBoxes` from path-prefix matches),
   * not a real selection.
   *
   * Only runs in multiple mode — single mode is still driven by `selectedValue`.
   */
  async handleSelectedChange(e) {
    if (this.selection !== "multiple")
      return;
    const t = e.target, s = t.dataset.id ?? "", l = t.closest(
      "cx-folder-select-tree-item"
    )?.fullPath;
    if (await t.updateComplete, !s.trim() || !l?.trim())
      return;
    const a = X({ id: s, path: l });
    t.indeterminate && !t.selected || (t.selected ? this.currentRootIDsSet.add(a) : this.currentRootIDsSet.delete(a), this.currentRootIDsSet = new Set(this.currentRootIDsSet));
  }
  async loadMore(e) {
    if (!this.api)
      return;
    e.stopPropagation();
    const t = this.data.length;
    this.loading = !0;
    const { data: s, hasMore: l } = await this.api({
      baseUrl: this.baseUrl,
      bearerToken: this.bearerToken,
      excludeVirtualFolders: this.excludeVirtualFolders,
      folderId: "",
      limit: 10,
      searchTerm: this.searchTerm,
      seeThru: this.seeThru,
      start: t,
      token: this.token
    });
    this.data = [...this.data, ...s], this.hasMore = l, this.loading = !1;
  }
  async handleFetchFolders() {
    const { data: e, hasMore: t } = await this.fetchFolders();
    Ce(this, D) || e.length > 0 && (this.firstFetchCallback?.(e), _e(this, D, !0)), this.data = e, this.hasMore = t, this.loading = !1;
  }
  async fetchFolders() {
    if (!this.api)
      return {
        data: [],
        hasMore: !1
      };
    if (this.searchTerm.length > 0 && this.searchTerm.length < this.minQueryLength)
      return {
        data: [],
        hasMore: !1
      };
    this.loading = !0;
    const { data: e, hasMore: t } = await this.api({
      baseUrl: this.baseUrl,
      bearerToken: this.bearerToken,
      excludeVirtualFolders: this.excludeVirtualFolders,
      folderId: "",
      limit: 10,
      searchTerm: this.searchTerm,
      seeThru: this.seeThru,
      start: 0,
      token: this.token
    });
    return this.data = e, this.hasMore = t, this.loading = !1, {
      data: e,
      hasMore: t
    };
  }
  renderFolder(e) {
    return m`<cx-folder-select-tree-item .api=${this.api} .currentRootIDsSet=${this.currentRootIDsSet} .removedIDs=${this.removedIDs} base-url=${this.baseUrl} doc-type=${e.docType} folder-id=${e.id} full-path=${y(e.fullPath ?? void 0)} name=${e.title} search-term=${this.searchTerm} selected-value=${this.selectedValue} selection=${this.selection} token=${this.token} bearer-token=${this.bearerToken} url=${y(e.url ?? void 0)} ?has-children=${e.hasChildren} ?selectable=${this.selection === "multiple"} ?exclude-virtual-folders=${this.excludeVirtualFolders}></cx-folder-select-tree-item>`;
  }
  render() {
    return m`<cx-tree class="folder-select-tree" selection=${this.selection} force-on-change disabled-auto-expand disabled-sync-checkboxes @cx-selected-change=${this.handleSelectedChange}>${_(
      this.empty,
      () => m`<div class="folder-select-tree__empty-message" role="status" aria-live="polite"><cx-typography variant="body3">${this.localize.term("noResults")}</cx-typography></div>`
    )}
      ${_(
      this.extraFolderData,
      () => m`<cx-folder-select-tree-item .api=${this.api} .currentRootIDsSet=${this.currentRootIDsSet} .removedIDs=${this.removedIDs} base-url=${this.baseUrl} doc-type=${y(this.extraFolderData?.docType ?? void 0)} folder-id=${y(this.extraFolderData?.id ?? void 0)} full-path=${y(this.extraFolderData?.fullPath ?? void 0)} icon=${this.extraFolderIcon} name=${this.extraFolderTitle || this.extraFolderData?.title} search-term=${this.searchTerm} selected-value=${this.selectedValue} selection=${this.selection} token=${this.token} bearer-token=${this.bearerToken} url=${y(this.extraFolderData?.url ?? void 0)} ?has-children=${this.extraFolderData?.hasChildren} ?selectable=${this.selection === "multiple"} ?exclude-virtual-folders=${this.excludeVirtualFolders}></cx-folder-select-tree-item>`
    )}
      ${Y(
      this.data,
      (e) => e.id,
      (e) => this.renderFolder(e)
    )}
      ${_(
      this.hasMore,
      () => m`<cx-button class="folder-select-tree__load-more" variant="text" @click=${this.loadMore} ?loading=${this.loading}>${this.localize.term("more")}</cx-button>`
    )}</cx-tree>`;
  }
};
D = /* @__PURE__ */ new WeakMap();
n.dependencies = {
  "cx-button": K,
  "cx-folder-select-tree-item": o,
  "cx-tree": he
};
d([
  r({ attribute: "min-query-length", reflect: !0, type: Number })
], n.prototype, "minQueryLength", 2);
d([
  r({ attribute: "selection", reflect: !0, type: String })
], n.prototype, "selection", 2);
d([
  r({ attribute: "search-term", reflect: !0, type: String })
], n.prototype, "searchTerm", 2);
d([
  r({ attribute: "selected-value", reflect: !0, type: String })
], n.prototype, "selectedValue", 2);
d([
  r({ reflect: !0, type: String })
], n.prototype, "token", 2);
d([
  r({ attribute: "bearer-token", reflect: !0, type: String })
], n.prototype, "bearerToken", 2);
d([
  r({ attribute: "base-url", reflect: !0, type: String })
], n.prototype, "baseUrl", 2);
d([
  r({ attribute: "extra-folder-id", reflect: !0, type: String })
], n.prototype, "extraFolderId", 2);
d([
  r({ attribute: "extra-folder-title", reflect: !0, type: String })
], n.prototype, "extraFolderTitle", 2);
d([
  r({ attribute: "extra-folder-icon", reflect: !0, type: String })
], n.prototype, "extraFolderIcon", 2);
d([
  r({ attribute: "see-thru", reflect: !0, type: Boolean })
], n.prototype, "seeThru", 2);
d([
  x()
], n.prototype, "extraFolderData", 2);
d([
  r({ type: Function })
], n.prototype, "api", 2);
d([
  r({
    attribute: "exclude-virtual-folders",
    reflect: !0,
    type: Boolean
  })
], n.prototype, "excludeVirtualFolders", 2);
d([
  r({ attribute: "first-fetch-callback", reflect: !1, type: Function })
], n.prototype, "firstFetchCallback", 2);
d([
  x()
], n.prototype, "data", 2);
d([
  x()
], n.prototype, "hasMore", 2);
d([
  x()
], n.prototype, "loading", 2);
d([
  x()
], n.prototype, "currentRootIDsSet", 2);
d([
  x()
], n.prototype, "removedIDs", 2);
d([
  f("extraFolderId")
], n.prototype, "handleExtraFolderIdChange", 1);
d([
  f("baseUrl", { waitUntilFirstUpdate: !0 }),
  f("token", { waitUntilFirstUpdate: !0 }),
  f("searchTerm", { waitUntilFirstUpdate: !0 }),
  f("excludeVirtualFolders", { waitUntilFirstUpdate: !0 }),
  me(500)
], n.prototype, "handleFetchFolders", 1);
n = d([
  U("cx-folder-select-tree")
], n);
const De = ue`:host{flex-direction:column;width:100%;height:100%;min-height:0;max-height:100%;display:flex}.folder-select{gap:var(--cx-spacing-x-small);flex-direction:column;flex:1;width:100%;min-height:0;display:flex}.folder-select__search{flex-shrink:0}.folder-select__tree{flex-direction:column;flex:1;min-height:0;display:flex}.folder-select-tree{flex:1;min-height:0;overflow:auto}.folder-select-tree__item__icon{color:var(--cx-color-primary)}.folder-select-tree__empty-message{font-size:var(--cx-font-size-small);color:var(--cx-color-neutral-500);padding-block:var(--cx-spacing-2x-small);padding-inline:var(--cx-spacing-small);text-align:center;cursor:default;user-select:none}.folder-select-tree__load-more{margin-inline:var(--cx-spacing-small)}.folder-select-tree-item::part(label),.folder-select-tree-item__label,.folder-select-tree-item__title{overflow:hidden}`;
var ke = Object.defineProperty, we = Object.getOwnPropertyDescriptor, re = (e) => {
  throw TypeError(e);
}, c = (e, t, s, l) => {
  for (var a = l > 1 ? void 0 : l ? we(t, s) : t, p = e.length - 1, u; p >= 0; p--)
    (u = e[p]) && (a = (l ? u(t, s, a) : u(a)) || a);
  return l && a && ke(t, s, a), a;
}, se = (e, t, s) => t.has(e) || re("Cannot " + s), Q = (e, t, s) => (se(e, t, "read from private field"), s ? s.call(e) : t.get(e)), Oe = (e, t, s) => t.has(e) ? re("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, s), N = (e, t, s, l) => (se(e, t, "write to private field"), t.set(e, s), s), T;
let i = class extends R {
  constructor() {
    super(), this.localize = new M(this), this.minQueryLength = 1, this.selection = "single", this.variant = C.Input, this.value = "", this.name = "", this.selectedLabel = "", this.baseUrl = "", this.open = !1, this.token = "", this.bearerToken = "", this.seeThru = !1, this.api = L, this.required = !1, this.form = void 0, this.excludeVirtualFolders = !1, this.extraFolderId = "", this.extraFolderTitle = "", this.extraFolderIcon = "", this.firstFetchCallback = null, this.searchTerm = "", Oe(this, T), this.selectGetOptionValue = this.selectGetOptionValue.bind(this), this.selectGetOptionLabel = this.selectGetOptionLabel.bind(this), this.selectGetOptionSelected = this.selectGetOptionSelected.bind(this), this.selectFilterCallback = this.selectFilterCallback.bind(this), this.selectSetOptionSelected = this.selectSetOptionSelected.bind(this), this.selectGetTag = this.selectGetTag.bind(this), this.updateWrappedApi();
  }
  updateWrappedApi() {
    if (!this.api) {
      N(this, T, void 0);
      return;
    }
    N(this, T, async (e) => {
      try {
        return await this.api(e);
      } catch (t) {
        return t instanceof pe && t.response?.status === 401 && this.emit("cx-renew-token"), { data: [], hasMore: !1, totalCount: 0 };
      }
    });
  }
  handleSearchTermChange() {
    this.emit("cx-folder-select-search-term-change", {
      detail: {
        value: this.searchTerm
      }
    });
  }
  handleSearchTermInputChange(e) {
    this.searchTerm = e.target.value;
  }
  handleSearchTermSelectChange(e) {
    e.target === e.currentTarget && (this.searchTerm = e.currentTarget.displayInput.value);
  }
  handleSelectClear() {
    if (this.searchTerm = "", this.selection !== "multiple")
      return;
    const e = this.shadowRoot?.querySelector("cx-folder-select-tree");
    e && (e.currentRootIDsSet = /* @__PURE__ */ new Set(), e.removedIDs = []);
  }
  /**
   * cx-select's selectedOptions cache (which drives the tag UI in
   * `multiple` mode) is only recomputed during its own `selectionChanged`
   * flow — that flow doesn't run in our setup because we no-op
   * `selectSetOptionSelected` for multi-select (cx-tree owns selection).
   * After the tree's selection change propagates through `syncBoxes` and
   * lands on each tree-item's `.selected`, ask cx-select to re-read its
   * options so the rendered tag list matches.
   */
  async handleTreeSelectedChange() {
    this.selection !== "multiple" || !this.selectEl || (await new Promise(
      (e) => requestAnimationFrame(() => e())
    ), this.selectEl.handleDefaultSlotChange(), await this.selectEl.updateComplete, this.selectEl.displayLabel = this.searchTerm);
  }
  selectGetOptionValue(e) {
    return !e || !(e instanceof g) ? this.value : e.dataset.id || this.value;
  }
  selectGetOptionLabel(e) {
    return !e || !(e instanceof g) ? this.selectedLabel : e.dataset.name || this.selectedLabel;
  }
  selectGetOptionSelected(e) {
    if (!(!e || !(e instanceof g)))
      return e.selected;
  }
  selectFilterCallback(e) {
    return !(!e || !(e instanceof g));
  }
  /**
   * Custom tag renderer for cx-select multi mode. Identical visuals to the
   * default tag, but the X click goes through cx-tree's selection flow
   * (`option.selected = false` → `cx-selected-change` →
   * cx-folder-select-tree.handleSelectedChange) rather than
   * cx-select.toggleOptionSelection (which our `selectSetOptionSelected`
   * no-ops in multi mode, so the default X click would do nothing).
   */
  selectGetTag(e) {
    return m`<cx-tag part="tag" exportparts="
          base:tag__base,
          content:tag__content,
          remove-button:tag__remove-button,
          remove-button__base:tag__remove-button__base
        " removable @cx-remove=${(s) => {
      s.stopPropagation(), e instanceof g && (e.selected = !1);
    }}><cx-line-clamp lines="1">${this.selectGetOptionLabel(e)}</cx-line-clamp></cx-tag>`;
  }
  selectSetOptionSelected(e, t) {
    if (!(!e || !(e instanceof g)) && this.selection !== "multiple") {
      if (t === void 0) {
        e.selected = !e.selected;
        return;
      }
      e.selected = t;
    }
  }
  updateFunctionProps() {
    this.selectEl && (this.selectEl.getOptionValue = this.selectGetOptionValue, this.selectEl.getOptionLabel = this.selectGetOptionLabel, this.selectEl.getOptionSelected = this.selectGetOptionSelected, this.selectEl.filterCallback = this.selectFilterCallback, this.selectEl.setOptionSelected = this.selectSetOptionSelected, this.selectEl.getTag = this.selectGetTag, this.selectEl.handleDefaultSlotChange());
  }
  handleOpenChange() {
    if (this.selectEl) {
      if (!this.open) {
        this.selectEl.hide();
        return;
      }
      this.updateFunctionProps();
    }
  }
  async handleVariantChange() {
    this.variant === C.Select && (await this.updateComplete, this.updateFunctionProps());
  }
  handleValueChange() {
    this.selectEl && (this.searchTerm = "", this.selectEl.getOptionValue = this.selectGetOptionValue, this.selectEl.getOptionLabel = this.selectGetOptionLabel, this.selectEl.getOptionSelected = this.selectGetOptionSelected, this.selectEl.filterCallback = this.selectFilterCallback, this.selectEl.setOptionSelected = this.selectSetOptionSelected, this.selectEl.getTag = this.selectGetTag, this.selectEl.handleDefaultSlotChange());
  }
  render() {
    return m`<div class="folder-select">${fe(this.variant, [
      [
        C.Input,
        () => m`<cx-input class="folder-select__search" aria-label=${this.localize.term("searchFolders")} placeholder=${`${this.localize.term("searchFolders")}...`} value=${this.searchTerm} clearable @cx-input=${this.handleSearchTermInputChange}><cx-icon name="search" slot="prefix"></cx-icon></cx-input><cx-folder-select-tree class="folder-select__tree" base-url=${this.baseUrl} extra-folder-id=${this.extraFolderId} extra-folder-title=${this.extraFolderTitle} extra-folder-icon=${this.extraFolderIcon} min-query-length=${this.minQueryLength} search-term=${this.searchTerm} selected-value=${this.value} selection=${this.selection} token=${this.token} bearer-token=${this.bearerToken} ?exclude-virtual-folders=${this.excludeVirtualFolders} ?see-thru=${this.seeThru} .api=${Q(this, T)} .firstFetchCallback=${this.firstFetchCallback}></cx-folder-select-tree>`
      ],
      [
        C.Select,
        () => m`<cx-select clearable hoist lazy name=${this.name} value=${this.value} .form=${this.form} ?required=${this.required} ?multiple=${this.selection === "multiple"} @input=${this.handleSearchTermSelectChange} @cx-clear=${this.handleSelectClear} @cx-selected-change=${this.handleTreeSelectedChange} allow-freetext><cx-folder-select-tree base-url=${this.baseUrl} extra-folder-id=${this.extraFolderId} extra-folder-title=${this.extraFolderTitle} extra-folder-icon=${this.extraFolderIcon} min-query-length=${this.minQueryLength} search-term=${this.searchTerm} selected-value=${this.value} selection=${this.selection} token=${this.token} bearer-token=${this.bearerToken} ?exclude-virtual-folders=${this.excludeVirtualFolders} ?see-thru=${this.seeThru} .api=${Q(this, T)} .firstFetchCallback=${this.firstFetchCallback}></cx-folder-select-tree></cx-select>`
      ]
    ])}</div>`;
  }
};
T = /* @__PURE__ */ new WeakMap();
i.styles = [Z, De];
i.dependencies = {
  "cx-folder-select-tree": n,
  "cx-icon": H,
  "cx-input": oe,
  "cx-line-clamp": j,
  "cx-select": ce,
  "cx-tag": ne
};
c([
  J("cx-select")
], i.prototype, "selectEl", 2);
c([
  r({ attribute: "min-query-length", reflect: !0, type: Number })
], i.prototype, "minQueryLength", 2);
c([
  r({ attribute: "selection", reflect: !0, type: String })
], i.prototype, "selection", 2);
c([
  r({ attribute: "variant", reflect: !0, type: String })
], i.prototype, "variant", 2);
c([
  r({ reflect: !0, type: String })
], i.prototype, "value", 2);
c([
  r({ reflect: !0, type: String })
], i.prototype, "name", 2);
c([
  r({ attribute: "selected-label", reflect: !0, type: String })
], i.prototype, "selectedLabel", 2);
c([
  r({ attribute: "base-url", reflect: !0, type: String })
], i.prototype, "baseUrl", 2);
c([
  r({ reflect: !0, type: Boolean })
], i.prototype, "open", 2);
c([
  r({ reflect: !1, type: String })
], i.prototype, "token", 2);
c([
  r({ attribute: "bearer-token", reflect: !0, type: String })
], i.prototype, "bearerToken", 2);
c([
  r({ attribute: "see-thru", reflect: !0, type: Boolean })
], i.prototype, "seeThru", 2);
c([
  r({ type: Function })
], i.prototype, "api", 2);
c([
  r({ reflect: !0, type: Boolean })
], i.prototype, "required", 2);
c([
  r({ reflect: !1 })
], i.prototype, "form", 2);
c([
  r({
    attribute: "exclude-virtual-folders",
    reflect: !0,
    type: Boolean
  })
], i.prototype, "excludeVirtualFolders", 2);
c([
  r({
    attribute: "extra-folder-id",
    reflect: !0,
    type: String
  })
], i.prototype, "extraFolderId", 2);
c([
  r({
    attribute: "extra-folder-title",
    reflect: !0,
    type: String
  })
], i.prototype, "extraFolderTitle", 2);
c([
  r({
    attribute: "extra-folder-icon",
    reflect: !0,
    type: String
  })
], i.prototype, "extraFolderIcon", 2);
c([
  r({ attribute: "first-fetch-callback", reflect: !1, type: Function })
], i.prototype, "firstFetchCallback", 2);
c([
  x()
], i.prototype, "searchTerm", 2);
c([
  f("api")
], i.prototype, "updateWrappedApi", 1);
c([
  f("searchTerm", { waitUntilFirstUpdate: !0 })
], i.prototype, "handleSearchTermChange", 1);
c([
  f("open")
], i.prototype, "handleOpenChange", 1);
c([
  f("variant")
], i.prototype, "handleVariantChange", 1);
c([
  f("selectedLabel", { waitUntilFirstUpdate: !0 }),
  f("value", { waitUntilFirstUpdate: !0 })
], i.prototype, "handleValueChange", 1);
i = c([
  U("cx-folder-select")
], i);
export {
  i as C,
  C as F,
  L as a
};
