import { g as R, c as w } from "../../chunks/runtime.js";
import { css as y, html as i, nothing as b } from "lit";
import { KeyCode as D } from "monaco-editor";
import "monaco-editor/esm/vs/editor/standalone/browser/standaloneServices.js";
import "monaco-editor/esm/vs/editor/standalone/common/standaloneTheme.js";
import "monaco-editor/esm/vs/platform/hover/browser/hover.js";
import "monaco-editor/esm/vs/editor/common/languages/supports/tokenization.js";
import "monaco-editor/esm/vs/base/browser/dom.js";
import "monaco-editor/esm/vs/editor/browser/editorDom.js";
import "monaco-editor/esm/vs/editor/browser/controller/mouseTarget.js";
import { LitElement as C, createEvent as P, safeClassMap as l } from "@arcgis/lumina";
import { generateGuid as B } from "@arcgis/toolkit/string";
import { Deferred as I } from "@arcgis/toolkit/promise";
import { D as M, e as v } from "../../chunks/arcade-executor.js";
import { s as k, g as L } from "../../chunks/arcade-service-accessors.js";
import { b as d } from "../../chunks/arcade-defaults.js";
import { u as T } from "../../chunks/useT9n.js";
import { createRef as F, ref as U } from "lit/directives/ref.js";
import N from "@arcgis/core/identity/IdentityManager.js";
import { log as O, rethrowError as o } from "@arcgis/toolkit/log";
/*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
v5.0.0-next.125 */
const j = y`:host{height:100%}calcite-tooltip:not([calcite-hydrated])>*{display:none}.main-action-bar{calcite-action-group{padding-inline-end:var(--calcite-spacing-sm)}calcite-action-group calcite-action{padding-inline-end:var(--calcite-spacing-sm)}calcite-action-group calcite-action:not(:first-child){padding-inline-start:var(--calcite-spacing-sm)}calcite-action-group:last-child{border-inline-end-width:0px}calcite-action-group:not(:first-child){padding-inline-start:var(--calcite-spacing-sm)}}`, z = "https://services6.arcgis.com/HXHga6CfMLMBOlBX/ArcGIS/rest/services/survey123_6e349a50b4504ca6b6107216d568db5f_form/FeatureServer/0", a = (s, e) => O(s, "Arcade Assistant", e), H = (s) => {
  const { aiAssistantsEnabled: e } = s;
  return e === void 0 ? (a("warn", "`areAiAssistantsEnabled` is not defined in the organizations settings."), !1) : e;
}, V = (s) => !(!s || !("id" in s)), G = async (s) => (await N.getCredential(s)).token;
async function X({
  portalUrl: s,
  profile: e
}) {
  if (!V(e))
    return a("warn", "Addon initialization failed. Reason: unsupported profile."), { shouldRender: !1 };
  const t = s.replace(/\/sharing\/rest(\/.*)?$/iu, "").replace(/\/$/u, ""), n = await G(s), r = `${t}/sharing/rest/portals/self?f=json&token=${n}`, h = `${t}/sharing/rest/portals/self/settings?f=json&token=${n}`, p = `${t}/sharing/rest/portals/self/signinSettings?f=json&token=${n}`, u = await Promise.allSettled([
    fetch(r, { credentials: "include" }).then((c) => c.json()),
    fetch(h, { credentials: "include" }).then((c) => c.json()),
    fetch(p, { credentials: "include" }).then((c) => c.json())
  ]), [g, f, _] = u, m = g.status === "fulfilled" ? g.value : (a("warn", `Failed to fetch selfUrl. Reason: ${g.reason}.`), {}), A = f.status === "fulfilled" ? f.value : (a("warn", `Failed to fetch settingsUrl. Reason: ${f.reason}.`), {}), x = _.status === "fulfilled" ? _.value : (a("warn", `Failed to fetch signinSettingsUrl. Reason: ${_.reason}.`), {}), $ = m?.helperServices?.aiAssistantServices?.url;
  if (!$)
    return a("warn", "Service URL is not available in the portal self response."), { shouldRender: !1 };
  const E = m.helpBase || "";
  if (!A)
    return a("warn", "Settings response is not available."), { shouldRender: !1 };
  let S = H(A);
  return x.blockBetaApps === !0 && (a(
    "warn",
    "Arcade Assistant is blocked by the organization settings. To enable it, do not block beta apps in the organization settings."
  ), S = !1), {
    shouldRender: !0,
    serviceUrl: $,
    helpBase: E,
    assistantsEnabled: S,
    feedbackServiceUrl: z
  };
}
class q extends C {
  constructor() {
    super(...arguments), this._codeEditorElt = F(), this._componentReadyDefer = new I(), this._disposables = [], this._editorProfilePromise = Promise.resolve(void 0), this.messages = T(), this._modelId = B(), this._openArcadeHelp = () => void window.open(M, "Arcade Help"), this._toggleSidePanel = (e) => {
      if (!e.target)
        return;
      const t = e.target?.dataset.panelName ?? "none";
      this.openedSidePanel = t === this.openedSidePanel ? "none" : t, this.openedSidePanel === "none" && this._codeEditorElt.value?.setFocus().catch(o(this));
    }, this._consoleLogs = [], this._executingScript = !1, this._preparingArcade = !1, this._resultPanel = "output", this._showExecutionPanel = !1, this._arcadeAssistantRemoteState = { shouldRender: !1 }, this.hideDocumentationActions = !1, this.hideSideBar = !1, this.openedSidePanel = "none", this.script = "", this.sideActionBarExpanded = !1, this.arcgisDiagnosticsChange = P({ bubbles: !1 }), this.arcgisScriptChange = P({ bubbles: !1 });
  }
  static {
    this.properties = { _apiLibrary: 16, _consoleLogs: 16, _editorProfile: 16, _executingScript: 16, _executionResult: 16, _preparingArcade: 16, _resultPanel: 16, _showExecutionPanel: 16, _arcadeAssistantRemoteState: 16, editorInstance: 32, editorOptions: 0, hideDocumentationActions: 5, hideSideBar: 5, openedSidePanel: 2, profile: 0, script: 1, sideActionBarExpanded: 7, snippets: 0, suggestions: 0, testData: 0, customPanels: 0, arcadeAssistant: 0 };
  }
  static {
    this.styles = [j];
  }
  get editorInstance() {
    return this._codeEditorElt.value?.editorInstance;
  }
  async getEditorInstance() {
    return await this._componentReadyDefer.promise, this._codeEditorElt.value?.editorInstance;
  }
  async getScript() {
    return await this._componentReadyDefer.promise, this._codeEditorElt.value?.value;
  }
  async getTestResult() {
    if (!this.testData)
      return { type: "error", value: "Missing test data", error: null };
    const e = await this._editorProfilePromise;
    if (!e)
      return { type: "error", value: "Missing editor profile", error: null };
    await this._componentReadyDefer.promise;
    const t = this._codeEditorElt.value?.value;
    return await v(e.definition, t, this.testData);
  }
  async setFocus() {
    await this._componentReadyDefer.promise, await this._codeEditorElt.value?.setFocus();
  }
  async load() {
    const e = R("./assets");
    k(e), await this._updateDataModelDeps(), await this._updateArcadeAssistantRemoteState();
  }
  willUpdate(e) {
    (e.has("messages") || e.has("profile")) && this.hasUpdated && this._updateDataModelDeps(), e.has("testData") && this._testDataChanged(), e.has("snippets") && d.updateApiContextForModel(this._modelId, {
      snippets: this.snippets
    }), e.has("arcadeAssistant") && this._updateArcadeAssistantRemoteState();
  }
  async loaded() {
    this._componentReadyDefer.resolve(), await this._updateApiLibrary();
    const e = await L();
    this._disposables.push(e.onDiagnosticsChange((t) => !this._preparingArcade && this.arcgisDiagnosticsChange.emit(t.diagnostics))), this.testData && this._addExecuteScriptAction();
  }
  disconnectedCallback() {
    for (super.disconnectedCallback(); this._disposables.length; )
      this._disposables.pop()?.dispose();
  }
  async _updateDataModelDeps() {
    await this._updateEditorProfile(), await this._updateApiLibrary();
  }
  _testDataChanged() {
    !this.testData && this._executeScriptAction && (this._disposeSafely(this._executeScriptAction), this._executeScriptAction = void 0), this.testData && !this._executeScriptAction && this._addExecuteScriptAction(), this._showExecutionPanel && this._executeScript().catch(o(this));
  }
  async _updateEditorProfile() {
    this._preparingArcade = !0;
    try {
      await d.setProfileForModel(this._modelId, this.profile, {
        locale: this.messages._t9nLocale,
        snippets: this.snippets
      }), this._editorProfile = d.getEditorProfileForModel(this._modelId);
    } catch {
      this._editorProfile = void 0;
    } finally {
      this._editorProfilePromise = Promise.resolve(this._editorProfile), this._preparingArcade = !1;
    }
  }
  async _updateApiLibrary() {
    this._apiLibrary = await d.getApiLibraryForModel(this._modelId);
  }
  async _executeScript() {
    const e = this.testData;
    if (!this._codeEditorElt.value || !e)
      return;
    const t = await this._editorProfilePromise;
    if (!t) {
      this._executionResult = { type: "error", value: "Missing editor profile", error: null };
      return;
    }
    this._showExecutionPanel = !0, this._executingScript = !0, this._consoleLogs = [], setTimeout(() => void (async () => {
      const n = this._codeEditorElt.value?.value;
      this._executionResult = await v(t.definition, n, e, (r) => setTimeout(() => this._consoleLogs = [...this._consoleLogs, r], 0)), this._executingScript = !1;
    })(), 0);
  }
  _toggleShowExecutionPanel() {
    this._showExecutionPanel = !this._showExecutionPanel;
  }
  _toggleSideActionBarExpanded() {
    this.sideActionBarExpanded = !this.sideActionBarExpanded;
  }
  _onCodeEditorValueChange(e) {
    e.stopPropagation(), this.script = e.detail, this.arcgisScriptChange.emit(e.detail);
  }
  _insertAsSnippet(e) {
    this._codeEditorElt.value?.insertSnippet(e.detail).catch(o(this));
  }
  _insertAsText(e) {
    this._insertText(e.detail);
  }
  _insertText(e) {
    this._codeEditorElt.value?.insertText(e).catch(o(this));
  }
  _onResultPanelChange(e) {
    this._resultPanel = e.detail;
  }
  _onExecutionPanelClose() {
    this._showExecutionPanel = !1;
  }
  _addExecuteScriptAction() {
    const e = this.editorInstance?.addAction({
      // An unique identifier for the action.
      id: "run-script",
      label: "Run Arcade Expression",
      keybindings: [D.F5],
      contextMenuGroupId: "code",
      contextMenuOrder: 1,
      run: () => {
        this.testData && this._executeScript().catch(o(this));
      }
    });
    e && (this._executeScriptAction = e, this._disposables.push(e));
  }
  _disposeSafely(e) {
    const t = this._disposables.indexOf(e);
    t !== -1 && this._disposables.splice(t, 1), e.dispose();
  }
  async _updateArcadeAssistantRemoteState() {
    this.arcadeAssistant && (this._arcadeAssistantRemoteState = await X({
      ...this.arcadeAssistant,
      profile: this.profile
    }));
  }
  renderMainActionBar() {
    return this.testData ? i`<calcite-action-bar class="main-action-bar" layout=horizontal scale=s expanded expand-disabled slot=top-action-bar><calcite-action-group scale=s><calcite-action .text=${this.messages.run ?? ""} text-enabled icon=play scale=s .loading=${this._preparingArcade} @click=${() => void this._executeScript().catch(o(this))}></calcite-action>${this._executionResult ? i`<calcite-action .text=${this.messages.lastresults ?? ""} .active=${this._showExecutionPanel} text-enabled icon=access-string-results icon-flip-rtl scale=s @click=${this._toggleShowExecutionPanel}></calcite-action>` : null}</calcite-action-group></calcite-action-bar>` : null;
  }
  renderMainPanel() {
    return i`<arcgis-code-editor slot=editor .editorOptions=${this.editorOptions} .language=${d.languageId} .value=${this.script ?? ""} .modelId=${this._modelId} @arcgisValueChange=${this._onCodeEditorValueChange} ${U(this._codeEditorElt)}></arcgis-code-editor>`;
  }
  renderAction({ id: e, label: t, icon: n, active: r, panelName: h, iconFlipRtl: p = !1, onClick: u = this._toggleSidePanel }) {
    return i`<calcite-action id=${e ?? b} .text=${t} .textEnabled=${this.sideActionBarExpanded} .icon=${n} .active=${r} @click=${u} data-panel-name=${h ?? b} .iconFlipRtl=${p}></calcite-action>${!this.sideActionBarExpanded && i`<calcite-tooltip .referenceElement=${e}><span>${t}</span></calcite-tooltip>` || ""}`;
  }
  renderSideActionBar() {
    return this.hideSideBar ? null : i`<calcite-action-bar slot=side-action-bar class="side-action-bar" .expanded=${this.sideActionBarExpanded} position=end @calciteActionBarToggle=${this._toggleSideActionBarExpanded}><calcite-action-group>${this.renderAction({
      id: "profile-variables-action",
      label: this.messages.profilevariables ?? "",
      icon: "profile-variables",
      active: this.openedSidePanel === "variables",
      panelName: "variables"
    })}${this.renderAction({
      id: "function-action",
      label: this.messages.constantsandfunctions ?? "",
      icon: "function",
      active: this.openedSidePanel === "api",
      panelName: "api"
    })}${this.suggestions?.length ? this.renderAction({
      id: "suggestions-action",
      label: this.messages.suggestions ?? "",
      icon: "lightbulb",
      active: this.openedSidePanel === "suggestions",
      panelName: "suggestions"
    }) : null}${this._arcadeAssistantRemoteState.shouldRender && this.renderAction({
      id: "arcade-assistant-action",
      label: this.messages.arcadeassistant ?? "Arcade assistant",
      icon: "effects",
      active: this.openedSidePanel === "arcade-assistant",
      panelName: "arcade-assistant"
    }) || ""}${this.customPanels?.map((e) => e.enabled === !1 ? null : this.renderAction({
      id: e.id,
      label: e.name,
      icon: e.icon,
      active: this.openedSidePanel === e.id,
      panelName: e.id
    }))}${this.hideDocumentationActions ? null : this.renderAction({
      id: "developer-website-action",
      label: this.messages.help ?? "",
      icon: "question",
      active: !1,
      panelName: "none",
      iconFlipRtl: this.messages._lang === "ar",
      onClick: this._openArcadeHelp
    })}</calcite-action-group></calcite-action-bar>`;
  }
  renderSidePanel() {
    if (this.hideSideBar)
      return null;
    const { openedSidePanel: e } = this;
    return i`<arcgis-language-api-panel slot=side-panel class=${l(e === "api" ? "" : "hidden")} .loading=${this._preparingArcade} .apiLibrary=${this._apiLibrary} .hideDocumentationActions=${this.hideDocumentationActions} @arcgisItemSelected=${this._insertAsSnippet} @arcgisClose=${this._toggleSidePanel} data-panel-name=none .closed=${e !== "api"}></arcgis-language-api-panel><arcgis-editor-variables slot=side-panel class=${l(e === "variables" ? "" : "hidden")} .loading=${this._preparingArcade} .modelId=${this._modelId} @arcgisItemSelected=${this._insertAsText} @arcgisClose=${this._toggleSidePanel} data-panel-name=none .variable=${this._editorProfile} .closed=${e !== "variables"}></arcgis-editor-variables>${this.suggestions?.length && i`<arcgis-arcade-suggestions slot=side-panel class=${l(e === "suggestions" ? "" : "hidden")} .closed=${e !== "suggestions"} .suggestions=${this.suggestions} @arcgisItemSelected=${this._insertAsText} @arcgisClose=${this._toggleSidePanel} data-panel-name=none></arcgis-arcade-suggestions>` || ""}${this.arcadeAssistant && this._arcadeAssistantRemoteState.shouldRender && i`<arcgis-arcade-coding-assistant slot=side-panel class=${l(e === "arcade-assistant" ? "" : "hidden")} .closed=${e !== "arcade-assistant"} .insertText=${this._insertText.bind(this)} .closePanel=${this._toggleSidePanel} .portalUrl=${this.arcadeAssistant.portalUrl} .serviceUrl=${this._arcadeAssistantRemoteState.serviceUrl} .helpBase=${this._arcadeAssistantRemoteState.helpBase} .assistantsEnabled=${this._arcadeAssistantRemoteState.assistantsEnabled} .feedbackServiceUrl=${this._arcadeAssistantRemoteState.feedbackServiceUrl} .editorRef=${this.el} .appVersion=${this.arcadeAssistant.appVersion}></arcgis-arcade-coding-assistant>` || ""}${this.customPanels?.map((t) => i`<calcite-flow slot=side-panel class=${l(e === t.id ? "" : "hidden")}>${t?.useFlows ? t.renderer?.({
      closePanel: this._toggleSidePanel,
      insertText: this._insertText.bind(this),
      closed: e !== t.id,
      /** pass this.el instead of "this" as it is what actually gets attached to the dom */
      editorRef: this.el
    }) : i`<calcite-flow-item .heading=${t.name} heading-level=2 closable .closed=${e !== t.id} @calciteFlowItemClose=${this._toggleSidePanel} .description=${t.description}>${t.renderer?.({
      closePanel: this._toggleSidePanel,
      insertText: this._insertText.bind(this),
      closed: e !== t.id,
      /** pass this.el instead of "this" as it is what actually gets attached to the dom */
      editorRef: this.el
    })}</calcite-flow-item>`}</calcite-flow>`)}`;
  }
  renderResultsPanel() {
    return this._showExecutionPanel ? i`<arcgis-arcade-results slot=results-panel .openedResultPanel=${this._resultPanel} .loading=${this._executingScript} .result=${this._executionResult} .consoleLogs=${this._consoleLogs} @arcgisOpenedResultPanelChange=${this._onResultPanelChange} @arcgisClose=${this._onExecutionPanelClose}></arcgis-arcade-results>` : null;
  }
  render() {
    return i`<arcgis-code-editor-shell>${this.renderMainActionBar()}${this.renderMainPanel()}${this.renderResultsPanel()}${this.renderSidePanel()}${this.renderSideActionBar()}</arcgis-code-editor-shell>`;
  }
}
w("arcgis-arcade-editor", q);
export {
  q as ArcgisArcadeEditor
};
