import { g as P, c as E } from "../../chunks/runtime.js";
import { css as w, html as i, nothing as A } from "lit";
import { KeyCode as R } 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/editor/common/languages/supports/tokenization.js";
import { LitElement as y, createEvent as x, noShadowRoot as D, safeClassMap as r } from "@arcgis/lumina";
import { generateGuid as C } from "@arcgis/toolkit/string";
import { Deferred as k } from "@arcgis/toolkit/promise";
import { D as B, e as v } from "../../chunks/arcade-executor.js";
import { s as I } from "../../chunks/setup-monaco.js";
import { b as c } from "../../chunks/arcade-defaults.js";
import { a as M } from "../../chunks/arcade-service-accessors.js";
import { u as L } from "../../chunks/useT9n.js";
import { createRef as T, ref as F } from "lit/directives/ref.js";
import { s as U } from "../../chunks/editor.js";
import j from "@arcgis/core/identity/IdentityManager.js";
/*! 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.20 */
const z = w`@layer{arcgis-arcade-editor{display:flex;flex-direction:column;position:relative;overflow:hidden;border:var(--arcgis-coding-components-border)!important;box-sizing:border-box;background-color:var(--arcgis-coding-components-background-color);height:100%;.sticky{position:sticky;top:0;z-index:10}.notice-container{margin:var(--calcite-spacing-xxs);padding:var(--calcite-spacing-sm);background-color:var(--calcite-color-foreground-1);text-align:center}.main-action-bar{border-bottom:var(--arcgis-coding-components-border)!important;flex:0 0 auto;calcite-action-group{padding-inline-end:var(--calcite-spacing-sm);calcite-action{padding-inline-end:var(--calcite-spacing-sm)}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)}}arcgis-arcade-results{border-top:var(--arcgis-coding-components-border)!important;box-sizing:border-box;max-height:50%;min-height:50%;margin-bottom:-1px}calcite-flow{[slot=footer]{word-break:break-word}}.hidden{display:none}}}`, N = "https://services6.arcgis.com/HXHga6CfMLMBOlBX/ArcGIS/rest/services/survey123_6e349a50b4504ca6b6107216d568db5f_form/FeatureServer/0", O = (s) => {
  const { aiAssistantsEnabled: e } = s;
  return e === void 0 ? (console.warn("areAiAssistantsEnabled is not defined in the organizations settings."), !1) : e;
}, H = (s) => !(!s || !("id" in s)), V = async (s) => (await j.getCredential(s)).token;
async function G({
  portalUrl: s,
  profile: e
}) {
  if (!H(e))
    return console.warn("Arcade assistant addon initialization failed: unsupported profile."), { shouldRender: !1 };
  const t = s.replace(/\/sharing\/rest(\/.*)?$/iu, "").replace(/\/$/u, ""), a = await V(s), n = `${t}/sharing/rest/portals/self?f=json&token=${a}`, l = `${t}/sharing/rest/portals/self/settings?f=json&token=${a}`, d = `${t}/sharing/rest/portals/self/signinSettings?f=json&token=${a}`, h = await Promise.allSettled([
    fetch(n, { credentials: "include" }).then((o) => o.json()),
    fetch(l, { credentials: "include" }).then((o) => o.json()),
    fetch(d, { credentials: "include" }).then((o) => o.json())
  ]), [p, u, g] = h, f = p.status === "fulfilled" ? p.value : (console.warn("Failed to fetch selfUrl", p.reason), {}), _ = u.status === "fulfilled" ? u.value : (console.warn("Failed to fetch settingsUrl", u.reason), {}), S = g.status === "fulfilled" ? g.value : (console.warn("Failed to fetch signinSettingsUrl", g.reason), {}), m = f?.helperServices?.aiAssistantServices?.url;
  if (!m)
    return console.warn("Arcade Assistant service URL is not available in the portal self response."), { shouldRender: !1 };
  const $ = f.helpBase || "";
  if (!_)
    return console.warn("Arcade Assistant settings response is not available."), { shouldRender: !1 };
  let b = O(_);
  return S.blockBetaApps === !0 && (console.warn(
    "Arcade Assistant is blocked by the organization settings. To enable it, do not block beta apps in the organization settings."
  ), b = !1), {
    shouldRender: !0,
    serviceUrl: m,
    helpBase: $,
    assistantsEnabled: b,
    feedbackServiceUrl: N
  };
}
class X extends y {
  constructor() {
    super(...arguments), this._codeEditorElt = T(), this._componentReadyDefer = new k(), this._disposables = [], this._editorProfilePromise = Promise.resolve(void 0), this.messages = L(), this._modelId = C(), this._openArcadeHelp = () => void window.open(B, "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(console.error);
    }, 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 = x({ bubbles: !1 }), this.arcgisScriptChange = x({ 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.shadowRootOptions = D;
  }
  static {
    this.styles = [z, U];
  }
  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 = P("./assets");
    I(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") && c.updateApiContextForModel(this._modelId, {
      snippets: this.snippets
    }), e.has("arcadeAssistant") && this._updateArcadeAssistantRemoteState();
  }
  async loaded() {
    this._componentReadyDefer.resolve(), await this._updateApiLibrary();
    const e = await M();
    this._disposables.push(e.onDiagnosticsChange((t) => !this._preparingArcade && this.arcgisDiagnosticsChange.emit(t.diagnostics))), this.testData && this._addExecuteScriptAction(), await this._codeEditorElt.value?.setFocus();
  }
  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(console.error);
  }
  async _updateEditorProfile() {
    this._preparingArcade = !0;
    try {
      await c.setProfileForModel(this._modelId, this.profile, {
        locale: this.messages._t9nLocale,
        snippets: this.snippets
      }), this._editorProfile = c.getEditorProfileForModel(this._modelId);
    } catch {
      this._editorProfile = void 0;
    } finally {
      this._editorProfilePromise = Promise.resolve(this._editorProfile), this._preparingArcade = !1;
    }
  }
  async _updateApiLibrary() {
    this._apiLibrary = await c.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 a = this._codeEditorElt.value?.value;
      this._executionResult = await v(t.definition, a, e, (n) => setTimeout(() => this._consoleLogs = [...this._consoleLogs, n], 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(console.error);
  }
  _insertAsText(e) {
    this._insertText(e.detail);
  }
  _insertText(e) {
    this._codeEditorElt.value?.insertText(e).catch(console.error);
  }
  _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: [R.F5],
      contextMenuGroupId: "code",
      contextMenuOrder: 1,
      run: () => {
        this.testData && this._executeScript().catch(console.error);
      }
    });
    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 G({
      ...this.arcadeAssistant,
      profile: this.profile
    }));
  }
  renderMainActionBar() {
    return this.testData ? i`<calcite-action-bar class="main-action-bar" layout=horizontal scale=s expanded expand-disabled><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(console.error)}></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 class="flex-adjustable" .editorOptions=${this.editorOptions} .language=${c.languageId} .value=${this.script ?? ""} .modelId=${this._modelId} @arcgisValueChange=${this._onCodeEditorValueChange} ${F(this._codeEditorElt)}></arcgis-code-editor>`;
  }
  renderAction({ id: e, label: t, icon: a, active: n, panelName: l, iconFlipRtl: d = !1, onClick: h = this._toggleSidePanel }) {
    return i`<calcite-action id=${e ?? A} .text=${t} .textEnabled=${this.sideActionBarExpanded} .icon=${a} .active=${n} @click=${h} data-panel-name=${l ?? A} .iconFlipRtl=${d}></calcite-action>${!this.sideActionBarExpanded && i`<calcite-tooltip .referenceElement=${e}><span>${t}</span></calcite-tooltip>` || ""}`;
  }
  renderSideActionBar() {
    return this.hideSideBar ? null : i`<calcite-action-bar class="side-action-bar border-inline-start" .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 ? this.renderAction({
      id: e.id,
      label: e.name,
      icon: e.icon,
      active: this.openedSidePanel === e.id,
      panelName: e.id
    }) : null)}${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 class=${r(e === "api" && "code-editor-side-panel flex-panel border-inline-start")} .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 class=${r(e === "variables" && "code-editor-side-panel flex-panel border-inline-start")} .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 class=${r(e === "suggestions" && "code-editor-side-panel flex-panel border-inline-start")} .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 class=${r(e === "arcade-assistant" && "code-editor-side-panel flex-panel border-inline-start")} .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) => (
      /** If useFlows is true, we check to make sure the input starts with calcite-flow-item, and if so, we allow them to render custom flow items */
      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 class=${r(e === t.id ? "code-editor-side-panel flex-panel border-inline-start" : "hidden")}><calcite-flow-item .heading=${t.name} heading-level=2 closable @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 class="flex-adjustable" .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`${this.renderMainActionBar()}<div class="flex-row flex-adjustable"><div class="flex-column flex-adjustable">${this.renderMainPanel()}${this.renderResultsPanel()}</div>${this.renderSidePanel()}${this.renderSideActionBar()}</div>`;
  }
}
E("arcgis-arcade-editor", X);
export {
  X as ArcgisArcadeEditor
};
