/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { g as m, c as u } from "../../chunks/runtime.js";
import { LitElement as p } from "@arcgis/lumina";
import { slotChangeHasContent as g, observeAncestorsMutation as f, unsafeGetCalciteModeName as _ } from "@arcgis/toolkit/dom";
import { load as S } from "@arcgis/lumina/controllers";
import { i as v } from "../../chunks/monaco-importer.js";
import { css as E, html as a } from "lit";
import { w as l, s as h } from "../../chunks/setup-monaco-theme.js";
import { c as T, g as c, o as b } from "../../chunks/colorize.js";
import { s as C } from "../../chunks/arcade-service-accessors.js";
import { debounce as y } from "@arcgis/toolkit/function";
import { Task as N } from "@lit/task";
import { rethrowError as O, log as w } from "@arcgis/toolkit/log";
const z = E`pre{direction:ltr;overflow-x:auto;background-color:var(--calcite-color-foreground-2);padding:var(--calcite-spacing-sm);white-space:pre-line;code{font-size:var(--calcite-font-size--2);font-family:var(--calcite-font-family-code)}}:host([round]){pre{border-radius:var(--calcite-corner-radius-round)}}`;
class L extends p {
  constructor() {
    super(...arguments), this._monacoEditor = S(v), this.#t = Promise.withResolvers(), this.#e = "", this._slotContentObservers = [], this._onDefaultSlotChange = async (e) => {
      g(e) || (this._codeFromSlot = "");
      const t = e.target instanceof HTMLSlotElement ? e.target : null, o = t ? this._computeSlotText(t) : "";
      t && this._observeAssignedSlotNodes(t), o !== this._codeFromSlot && (this._codeFromSlot = o), this.#t.resolve();
    }, this._colorizeTask = new N(this, {
      task: async ([e, t], { signal: o }) => {
        if (await this.#t.promise, o.aborted)
          return this.#e;
        if (await l(t), o.aborted)
          return this.#e;
        const i = await T(e, t);
        return o.aborted ? this.#e : (this.#e = i, i);
      },
      args: () => [this._codeFromSlot, this.language]
    }), this._codeFromSlot = "", this.language = "arcade", this.round = !1;
  }
  static {
    this.properties = { _codeFromSlot: 16, language: 1, round: 7 };
  }
  static {
    this.styles = z;
  }
  #t;
  #e;
  async load() {
    C(m("./assets")), await h(this.language), await l(this.language), this._applyColorizeStyles(c()), this.manager.onLifecycle(() => (this._themeObserver = f(this.el, ["class"], () => this.updateTheme()), this._themeChangedListener = b(() => {
      this._applyColorizeStyles(c());
    }), this.updateTheme(), () => {
      this._themeObserver?.(), this._themeObserver = void 0, this._themeChangedListener?.dispose(), this._themeChangedListener = void 0;
    }));
  }
  loaded() {
    this.el.hasChildNodes() || this.#t.resolve();
  }
  willUpdate(e) {
    e.has("language") && h(this.language).then(() => l(this.language)).catch(O(this));
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._disposeSlotObservers();
  }
  _disposeSlotObservers() {
    this._slotContentObservers.length && (this._slotContentObservers.forEach((e) => e.disconnect()), this._slotContentObservers = []);
  }
  _observeAssignedSlotNodes(e) {
    this._disposeSlotObservers();
    const t = e.assignedNodes({ flatten: !0 });
    if (!t.length)
      return;
    const o = /* @__PURE__ */ new Set();
    for (const s of t)
      s.nodeType === Node.ELEMENT_NODE ? o.add(s) : s.nodeType === Node.TEXT_NODE && s.parentElement && o.add(s.parentElement);
    const i = { characterData: !0, childList: !0, subtree: !0 }, r = y(() => {
      const s = this._computeSlotText(e);
      s !== this._codeFromSlot && (this._codeFromSlot = s);
    }, 100), d = (s) => {
      if (s.some((n) => n.type === "childList")) {
        const n = this._computeSlotText(e);
        n !== this._codeFromSlot && (this._codeFromSlot = n);
        return;
      }
      r();
    };
    o.forEach((s) => {
      const n = new MutationObserver(d);
      n.observe(s, i), this._slotContentObservers.push(n);
    });
  }
  _computeSlotText(e) {
    const t = e.assignedNodes({ flatten: !0 }).filter((o) => o.nodeType !== Node.COMMENT_NODE);
    if (this.language === "html" && t.length) {
      const o = t.find((r) => r.nodeType === Node.ELEMENT_NODE && r.tagName === "TEMPLATE");
      if (o)
        return (o.innerHTML ?? "").trim();
      const i = t.map((r) => r.nodeType === Node.ELEMENT_NODE ? r.outerHTML : r.nodeType === Node.TEXT_NODE ? r.textContent ?? "" : "").join("").trim();
      return i && process.env.NODE_ENV !== "production" && w("warn", this, "Consider wrapping your snippet in a <template> for fully inert, intention-revealing markup."), i;
    }
    return t.map((o) => o.textContent ?? "").join("").trim();
  }
  updateTheme() {
    const e = _(this.el) === "light" ? "vs" : "vs-dark";
    e !== this._currentTheme && (this._currentTheme = e, this._monacoEditor.setTheme(e));
  }
  _applyColorizeStyles(e) {
    if (!this._colorizeSheet) {
      this._colorizeSheet = new CSSStyleSheet();
      const t = this.renderRoot;
      t.adoptedStyleSheets = [...t.adoptedStyleSheets, this._colorizeSheet];
    }
    this._colorizeSheet.replaceSync(e);
  }
  render() {
    return a`<div><slot @slotchange=${this._onDefaultSlotChange} style="display:none" aria-hidden=true></slot><pre class="arcgis-code-viewer" aria-label=${`${this.language} code snippet`}>${this._colorizeTask.render({
      error: () => null,
      pending: () => a`<code class=${`language-${this.language}`}></code>`,
      complete: (e) => a`<code class=${`language-${this.language}`} .innerHTML=${e ?? ""}></code>`
    })}</pre></div>`;
  }
}
u("arcgis-code-viewer", L);
export {
  L as ArcgisCodeViewer
};
