import { c as B } from "../../chunks/runtime.js";
import { nothing as R, LitElement as H } from "@arcgis/lumina";
import { ref as L, createRef as j } from "lit/directives/ref.js";
import W from "@arcgis/core/identity/IdentityManager.js";
import { u as Q } from "../../chunks/useT9n.js";
import { b as M } from "../../chunks/arcade-defaults.js";
import { css as G } from "@lit/reactive-element/css-tag.js";
import { html as C } from "lit";
import q from "@arcgis/core/request.js";
import { e as J, a as Y } from "../../chunks/monaco-importer.js";
import { html as r } from "lit-html";
import { repeat as D } from "lit-html/directives/repeat.js";
import "@arcgis/components-utils";
import { unsafeHTML as S } from "lit/directives/unsafe-html.js";
import K from "@arcgis/core/layers/FeatureLayer.js";
import X from "@arcgis/core/Graphic.js";
import { b as Z } from "../../chunks/language-defaults-base.js";
/*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/4.33/esri/copyright.txt for details.
v4.33.0-next.164 */
const ee = G`:host(:not([closed])){--calcite-block-border-color: var(--calcite-color-transparent);flex:1 0 auto;border-inline-start:var(--arcgis-coding-components-border);box-sizing:border-box;max-width:var(--arcgis-coding-components-side-panel-max-w);width:var(--arcgis-coding-components-side-panel-w);.submission-actions-wrapper{display:flex;flex-direction:column;width:100%;gap:.75rem}.submission-actions{display:flex;flex-direction:row;gap:.5rem;justify-content:space-between}.gaps{display:flex;gap:.25rem}.align-inline-end{margin-inline-start:auto}.action .error-display{display:flex;flex-direction:row;gap:.5rem;justify-content:space-between}.context-popover p{padding:0 .5rem;font-size:var(--calcite-font-size-sm)}.prompt-list calcite-list-item{margin-block-end:.5rem;border-radius:var(--calcite-corner-radius-round);--calcite-color-border-3: transparent;overflow:hidden}.feedback-content{padding:1rem;display:flex;flex-direction:column;gap:.75rem}.feedback-sheet{--calcite-sheet-height: auto;--calcite-sheet-max-height: auto;--calcite-sheet-min-height: auto}calcite-chip[slot=header-actions-end]{align-self:center;margin-inline-end:.5rem}calcite-list-item:focus calcite-button{position:relative;top:-2px}.prompt-list calcite-list-item:last-of-type{margin-block-end:0}calcite-list{--calcite-color-foreground-1: transparent;background-color:transparent}calcite-list-item{--calcite-color-foreground-1: white}calcite-flow-item calcite-shell{background:transparent}calcite-block{width:100%;max-width:100%;align-self:flex-end;background-color:transparent;margin-block:0}calcite-sheet{--calcite-sheet-scrim-background: rgba(200, 200, 200, .5)}.type-suggestion{--calcite-color-foreground-1: var(--calcite-color-foreground-current);--calcite-color-text-3: var(--calcite-color-text-2);--calcite-icon-color: var(--calcite-color-brand)}.type-history{--calcite-icon-color: var(--calcite-color-text-2)}.type-response{--calcite-icon-color: var(--calcite-color-brand);--calcite-font-family: monospace}.block-response{align-self:flex-start;margin-block-end:4rem;border-block-end:0;--calcite-block-text-color: var(--calcite-color-brand)}calcite-list-item calcite-button{margin-inline-end:.25rem}.type-docs{--calcite-color-foreground-1: var(--calcite-color-foreground-3);--calcite-icon-color: var(--calcite-color-text-1)}.type-error{--calcite-icon-color: var(--calcite-color-status-danger);--calcite-font-family: monospace;border:1px solid var(--calcite-color-status-danger)}#thumbs-up{margin-inline-start:auto;--calcite-icon-color: var(--calcite-color-border-input)}#thumbs-down{--calcite-icon-color: var(--calcite-color-border-input)}calcite-flow-item calcite-shell calcite-notice{margin-block:1rem}.no-space-block,.no-space-block[open]{margin:0}calcite-block[open]:last-of-type{border-block-end:0}.text-area-wrapper{display:flex;border-radius:var(--calcite-corner-radius-round);margin:.75rem;overflow:hidden;--calcite-color-border-input: transparent;position:sticky;box-shadow:var(--calcite-shadow-sm);flex:none}calcite-text-area{height:auto;min-height:5.75rem;overflow:hidden;border-radius:var(--calcite-corner-radius-round) var(--calcite-corner-radius-round) 0 0;--calcite-font-weight-normal: 500;font-weight:500;line-height:1.2}calcite-tooltip{--calcite-tooltip-z-index: 1000}.standalone-list{margin:1rem;width:calc(100% - 2rem)}.result-disclaimer{display:block;width:24rem;max-width:90%;margin:1rem auto;text-align:center;line-height:1.125rem;font-size:.875rem;font-style:italic}calcite-flow{height:100%}calcite-popover calcite-list{--calcite-list-background-color: transparent;--calcite-input-border-color: transparent}calcite-popover calcite-list calcite-filter{--calcite-spacing-sm: 0}.break-spaces{white-space:break-spaces}.feedback-button-container{margin-inline-start:auto;gap:0}.info-heading{font-size:var(--calcite-font-size-1);color:var(--calcite-color-text-1)}.unstyled-h3{margin:unset;font-size:var(--calcite-font-size-md)}.unstyled-shell{position:unset;inset:unset;display:unset;block-size:unset;inline-size:unset}.suggestion-chips{--calcite-chip-background-color: var(--calcite-color-foreground-current);--calcite-chip-text-color: var(--calcite-color-brand);calcite-chip{cursor:pointer}}.info-block{max-width:450px}#result-block{calcite-card-group{--calcite-card-group-gap: 1.25rem}calcite-card{--calcite-card-corner-radius: var(--calcite-corner-radius-round);--calcite-card-background-color: white;--calcite-card-border-color: transparent;width:100%}.positioned-code-content{display:flex;flex-direction:row;gap:.5rem;padding:.5rem}calcite-card [slot=title] calcite-chip{margin-block-start:.25rem}.code-response-wrapper{position:relative;background:var(--calcite-color-foreground-2);border-radius:var(--calcite-corner-radius-round);margin-top:-1.5rem}.prior-prompt{margin:.25rem 0 .75rem;max-width:90%;overflow-y:hidden;overflow-x:auto;padding:0}code{white-space:pre;font-size:12px;margin:0;overflow-x:auto;font-family:Fira Mono,Consolas,Menlo,monospace;display:block;max-height:12rem;position:relative;padding:.5rem}.code-collapse{margin-inline-start:auto}.copy-button{margin-left:.5rem}.add-to-editor-button{--calcite-internal-button-border-color: unset}}.collapsible-code{padding:.5rem}.collapsible-code summary{cursor:pointer;font-weight:500;color:var(--calcite-color-brand);outline:none;padding:.25rem 0}.collapsible-code[open] summary{color:var(--calcite-color-text-2)}.collapsible-error{padding:.5rem}.collapsible-error summary{cursor:pointer;font-weight:500;color:var(--calcite-color-status-danger);outline:none;padding:.25rem 0}.collapsible-error[open] summary{color:var(--calcite-color-text-2)}.response-error-container{padding:.5rem;background:color-mix(in srgb,var(--calcite-color-status-danger) 10%,transparent);border-radius:var(--calcite-corner-radius-round);margin:1rem 0;font-size:var(--calcite-font-size--2);border:var(--calcite-color-status-danger) solid 1px}.response-error-container p{margin:0 0 0 1em}}:host([closed]){display:none}`;
class $ extends Error {
  constructor({
    message: e,
    code: t,
    subCode: o,
    details: a,
    source: s
  }) {
    super(e), this.name = "ArcadeAssistantError", this.code = t, this.subCode = o, this.details = a, this.source = s;
  }
}
function P(i) {
  if (!i)
    return;
  const e = i.indexOf('{"error":');
  if (e !== -1)
    try {
      const t = i.slice(e), o = JSON.parse(t);
      if (o && typeof o == "object" && o.error)
        return o.error;
    } catch {
      return;
    }
}
async function te(i) {
  const { baseUrl: e, skillId: t, message: o, authToken: a, previousConversationId: s, context: p } = i, c = t ? `${e}/skills/${t}/chat` : `${e}/chat`, n = [], h = {
    message: o,
    context: p
  };
  s && (h.conversation_id = s);
  let f;
  try {
    f = await q(c, {
      method: "post",
      headers: {
        "Content-Type": "application/json",
        token: a
      },
      body: JSON.stringify(h),
      responseType: "json"
    });
  } catch (g) {
    const v = g, A = v.details?.rawResponse || v.message || String(g), k = P(A);
    throw k ? new $(k) : g;
  }
  const b = f.data;
  n.push(b);
  const y = b.conversationId, l = b.inquiryId;
  let u = b.sequenceNumber;
  async function w() {
    let g = 0;
    const v = 25;
    for (; g < v; ) {
      await new Promise((x) => setTimeout(x, 1e3));
      const A = ie(y, u, l);
      let k;
      try {
        k = await q(c, {
          method: "post",
          headers: {
            "Content-Type": "application/json",
            token: a
          },
          body: JSON.stringify(A),
          responseType: "json"
        });
      } catch (x) {
        const T = x, V = T.details?.rawResponse || T.message || String(x), E = P(V);
        throw E ? new $(E) : x;
      }
      const m = k.data;
      if (m.context && m.context.kind === "ArcgisErrorAsContext" && m.context.error)
        throw new $({
          message: m.context.error.message || "ArcGIS Assistant error",
          code: m.context.error.code,
          subCode: m.context.error.subCode,
          details: m.context.error.details,
          source: "polling-response"
        });
      if (n.push(m), u = m.sequenceNumber, g++, !m.hasMore)
        break;
    }
    if (g === v)
      throw new $({
        message: "Request timed out",
        code: "TIMEOUT",
        source: "polling"
      });
  }
  const O = 2 * 60 * 1e3;
  return await Promise.race([
    w(),
    new Promise(
      (g, v) => setTimeout(
        () => v(
          new $({
            message: "Request timed out",
            code: "TIMEOUT",
            source: "hard-timeout"
          })
        ),
        O
      )
    )
  ]), n;
}
function ie(i, e, t) {
  return {
    conversationId: i,
    inquiryId: t,
    ackSequenceNumber: e
  };
}
function oe(i) {
  return i.message.match(/Error in prompt shield/u) ? "I'm having trouble with this request. Try again by rephrasing the question." : i.code === "TIMEOUT" ? "I'm having trouble with this request. Try again by re-asking the same question or rephrasing it." : i.message;
}
const ae = (i) => {
  const e = i.value.length, t = 72, o = 180, a = i.offsetWidth, p = Math.max(1, Math.floor(a / 8)), c = Math.ceil(e / p), n = t + (c - 2) * 24;
  i.style.setProperty("--calcite-text-area-min-height", `${Math.min(n, o)}px`);
};
function se({ messages: i }) {
  return r`<calcite-chip slot=header-actions-end scale=s appearance=outline-fill .label=${i.beta ?? "Beta"}>${i.beta ?? "Beta"}</calcite-chip>`;
}
function re({ popoverContent: i }) {
  return r`<calcite-action icon=information slot=header-actions-end id=legal-disclaimer text></calcite-action><calcite-popover reference-element=legal-disclaimer overlay-positioning=fixed label=legal-disclaimer placement=bottom auto-close>${i}</calcite-popover>`;
}
function z({ errorMessage: i, slot: e }) {
  return r`<div class="error-display"><calcite-input-message id=error-message status=invalid icon=exclamation-mark-triangle scale=m slot=${e ?? R}>${i}</calcite-input-message></div>`;
}
function ce({ active: i, setActive: e, messages: t }) {
  return r`<calcite-alert slot=alerts .open=${i} placement=bottom kind=success icon=check-circle-f auto-close @calciteAlertClose=${() => e(!1)} .label=${t.expressionapplied ?? "Expression applied"}><div slot=message>${t.expressionapplied ?? "Expression applied to editor."}</div></calcite-alert>`;
}
function ne({ context: i, messages: e }) {
  return i ? r`<div class="gaps">${i.profileName && r`<calcite-popover auto-close placement=top .label=${e.profilecontextlabel.replace("{profileName}", i.profileName)} reference-element=profile-context-button class="context-popover"><p>${e.profilecontextlabel.replace("{profileName}", i.profileName)}</p></calcite-popover><calcite-button round kind=neutral icon-start=map-information id=profile-context-button></calcite-button>` || ""}${i.layerName && r`<calcite-popover auto-close placement=top .label=${e.layercontextlabel.replace("{layerName}", i.layerName)} reference-element=layer-context-button class="context-popover"><p>${e.layercontextlabel.replace("{layerName}", i.layerName)}</p></calcite-popover><calcite-button round kind=neutral icon-start=layers id=layer-context-button></calcite-button>` || ""}</div>` : null;
}
function le({ isDisabled: i, isReadOnly: e, setQuestion: t, setIsViewingResult: o, textAreaRef: a, question: s, errorMessage: p, setErrorMessage: c, submitQuestion: n, messages: h, mode: f, context: b }) {
  return r`<div class="text-area-wrapper"><calcite-text-area resize=vertical .readOnly=${i || e} class="styled-text-area" .placeholder=${h.askaquestion ?? `Specify the calculation or logic you need in an Arcade expression. (e.g., 'Return "Yes" if value > 10')`} .value=${s} @calciteTextAreaInput=${(y) => {
    ae(y.target), t(y.target.value);
  }} ${L(a)}><div class="submission-actions-wrapper" slot=footer-start>${p && z({ errorMessage: p, slot: "footer-start" }) || ""}<div class="submission-actions">${ne({ context: b, messages: h })}<div class="align-inline-end gaps"><calcite-button round kind=neutral .hidden=${f !== "refine"} icon-start=arrow-left appearance=solid .disabled=${i} @click=${async () => {
    o(!1), t("");
  }}>${h.startover ?? "Start Over"}</calcite-button><calcite-button round icon-end=effects appearance=solid .loading=${i} .disabled=${i} @click=${async () => {
    c(s ? "" : h.enteraprompt ?? "Please enter a prompt"), await n();
  }}>${f === "prompt" ? h.ask ?? "Generate" : h.refine ?? "Refine"}</calcite-button></div></div></div></calcite-text-area></div>`;
}
const de = "https://www.esri.com/en-us/privacy/privacy-statements/privacy-statement", pe = "https://www.esri.com/en-us/privacy/privacy-statements/privacy-supplement";
function ue({ setOpen: i, messages: e, feedback: t, setFeedback: o, onSubmit: a }) {
  return r`<calcite-sheet class="feedback-sheet" .label=${e.feedback ?? "Feedback"} slot=sheets display-mode=float position=block-end .open=${t.active} @calciteSheetClose=${() => i(!1)}><calcite-panel .heading=${e.providefeedback ?? "Provide feedback"} .description=${e.experiencehelps ?? "Your experience helps guide future improvements"}><div class="feedback-content"><calcite-label>${e.experiencehelpful ?? "Was the assistant helpful?"}<calcite-segmented-control scale=l><calcite-segmented-control-item icon-start=thumbs-up .checked=${t.value === "good"} @click=${() => o({ ...t, value: "good" })}></calcite-segmented-control-item><calcite-segmented-control-item icon-start=thumbs-down .checked=${t.value === "bad"} @click=${() => o({ ...t, value: "bad" })}></calcite-segmented-control-item></calcite-segmented-control></calcite-label><calcite-label>${e.describeexperience ?? "Describe your experience"}<calcite-text-area resize=vertical .value=${t.text} @calciteTextAreaInput=${(s) => o({ ...t, text: s.target.value })}></calcite-text-area></calcite-label><calcite-label layout=inline scale=s><calcite-checkbox scale=l .checked=${t.termsAccepted} @calciteCheckboxChange=${(s) => {
    o({ ...t, termsAccepted: s.target.checked });
  }}></calcite-checkbox><span>${S(e.agreement?.replace("{EsriPrivacyStatement}", `<calcite-link href=${de} target="_blank">${e.esriprivacystatement ?? "Esri Privacy Statement"}</calcite-link>`).replace("{Supplement}", `<calcite-link href=${pe} target="_blank">${e.supplement ?? "Supplement"}</calcite-link>`))}</span></calcite-label></div><calcite-button slot=footer width=full @click=${a} .disabled=${!t.termsAccepted || t.submitting} .loading=${t.submitting}>${e.submitfeedback ?? "Submit Feedback"}</calcite-button></calcite-panel></calcite-sheet>`;
}
function N({ assistantsEnabled: i, messages: e, slot: t, assistantHelpUrl: o, helpTopicUrl: a }) {
  return r`<calcite-block .label=${e.assistantinformation ?? "Assistant information"} slot=${t ?? R} expanded class="info-block"><calcite-chip .label=${e.new ?? "new"} kind=brand>${e.new}</calcite-chip><h1 class="info-heading">${e.introducing}</h1><p>${e.capabilities}</p>${i ? r`<p>${e.keepinmind ?? "Keep in mind the following:"}<ul><li>${e.beconsise ?? "Be concise, but also clear in your request"}</li><li>${e.avoidambiguity ?? "Avoid ambiguity and vagueness"}</li><li>${e.moredetails ?? "you do not need to use exact field names in your instructions, but more detail is generally better"}</li></ul>${S((e.seedocumentation ?? "Please see the {documentation} for more information, including limitations and additional resources.").replace("{documentation}", `<calcite-link href=${a} target="_blank">${e.documentation ?? "documentation"}</calcite-link>`))}</p>` : r`<p>${S(e.useofassistant?.replace("{aiassistants}", `<strong>${e.aiassistants ?? "Ai Assistants"}</strong>`))}<calcite-link .href=${o} target=_blank icon-end=launch-2>${e.opensettings ?? "Open Settings"}</calcite-link></p>`}</calcite-block>`;
}
function he({ messages: i, onProceed: e, onExit: t, helpTopicUrl: o }) {
  return r`<calcite-dialog close-disabled placement=top .heading=${i.welcome} slot=dialogs open width-scale=m id=welcome-dialog><h3 class="unstyled-h3">${i.beforeyougetstarted}</h3><ul><li>${i.maybeincorrect}</li><li>${S(i.pleasereadhelp.replace("{helpTopic}", `<calcite-link href=${o} target="_blank">${i.helptopic}</calcite-link>`))}</li></ul><calcite-button id=welcome-proceed slot=footer-end @click=${e}>${i.proceed}</calcite-button><calcite-button id=welcome-decline slot=footer-start @click=${t} kind=neutral>${i.exit}</calcite-button></calcite-dialog>`;
}
function me({ messages: i, suggestions: e, onSuggestionClick: t }) {
  return r`<calcite-block .heading=${i.promptsuggestions} expanded collapsible id=suggestion-block><calcite-chip-group .label=${i.promptsuggestions} class="suggestion-chips">${D(e, (o) => o, (o) => r`<calcite-chip .label=${i.promptsuggestion} .value=${o} icon=effects @click=${() => t?.(o)}>${o}</calcite-chip>`)}</calcite-chip-group></calcite-block>`;
}
function U({ hidden: i = !1, expanded: e = !1, messages: t, cards: o, heading: a, collapsible: s = !1, showEffectsIcon: p = !1, editorInsertMode: c = "add", setEditorInsertMode: n, copySuccessConversationId: h }) {
  const f = c === "replace", b = f ? t.replaceineditor ?? "Replace in editor" : t.addtoeditor ?? "Add to editor", y = f ? t.addtoeditor ?? "Add to editor" : t.replaceineditor ?? "Replace in editor";
  return r`<calcite-block .hidden=${i} id=result-block .heading=${a ?? t.besteffort ?? "Here is the assistant's best effort"} .expanded=${e} .collapsible=${s}>${p && r`<calcite-chip .label=${t.assistantresponses} slot=content-start icon=effects scale=m class="suggestion-chips"></calcite-chip>` || ""}<calcite-card-group .label=${t.assistantresponses}>${D(o, (l) => l.conversationId, (l) => r`<calcite-card><div slot=heading><div class="prior-prompt">${l.priorPrompt}</div>${l.message && r`<div class="collapsible-error response-error-container"><div class="error-display">${z({ errorMessage: r`<details open><summary>Error</summary><p>${l.message}</p></details>` })}</div></div>` || ""}</div><div><div class="code-response-wrapper"><div class="positioned-code-content">${l.chips?.map((u, w) => r`${u.tooltip && r`<calcite-tooltip .referenceElement=${`response-chip-${u.conversationId}-${w}`} placement=top-start>${u.tooltip}</calcite-tooltip>` || ""}<calcite-chip .label=${u.label} .scale=${u.scale ?? "s"} .appearance=${u.appearance ?? "outline"} .icon=${u.icon} .id=${`response-chip-${u.conversationId}-${w}`}>${u.label}</calcite-chip>`)}</div><details class="collapsible-code" open><summary>Code response</summary><code>${l.code}</code></details></div></div><div slot=footer-start><calcite-split-button primary-text=${b ?? R} appearance=outline-fill class="add-to-editor-button" @calciteSplitButtonPrimaryClick=${() => l.onAddToEditor()} overlay-positioning=fixed><calcite-dropdown-item @calciteDropdownItemSelect=${() => {
    n?.(f ? "add" : "replace");
  }}>${y}</calcite-dropdown-item></calcite-split-button><calcite-button round icon-start=copy-to-clipboard kind=neutral @click=${() => l.onCopy(l.conversationId)} class="copy-button">${l.conversationId === h ? t.copied ?? "copied" : ""}</calcite-button></div><div slot=footer-end class="feedback-actions"><calcite-action .text=${t.thumbsup} scale=s icon=thumbs-up @click=${l.onThumbsUp}></calcite-action><calcite-action .text=${t.thumbsdown} scale=s icon=thumbs-down @click=${l.onThumbsDown}></calcite-action></div></calcite-card>`)}</calcite-card-group></calcite-block>`;
}
const d = {
  welcome: "Welcome to the new assistant experience",
  beforeyougetstarted: "Before you get started be aware:",
  maybeincorrect: "AI generated code may occasionally be incorrect or biased. Review carefully.",
  pleasereadhelp: "Read the Arcade Assistant (beta) {helpTopic} to get started and learn details on security, privacy and limitations.",
  proceed: "Proceed",
  exit: "Exit",
  promptsuggestions: "Prompt suggestions",
  promptsuggestion: "Prompt suggestion",
  assistantresponses: "Assistant responses",
  collapse: "Collapse",
  thumbsup: "Thumbs up",
  thumbsdown: "Thumbs down",
  refine: "Refine",
  startover: "Start over",
  helptopic: "help topic",
  agreement: "I agree to the {EsriPrivacyStatement} (and {Supplement}).",
  esriprivacystatement: "Esri Privacy Statement",
  supplement: "Supplement",
  disclaimerpt2: "AI-generated content may be inaccurate. Review before using.",
  replaceineditor: "Replace in editor",
  keepinmind: "Keep in mind the following:",
  beconsise: "Be concise, but also clear in your request",
  avoidambiguity: "Avoid ambiguity and vagueness",
  documentation: "documentation",
  useexamples: "Use examples to clarify your request",
  moredetails: "You do not need to use exact field names in your instructions, but more detail is generally better",
  seedocumentation: "Please see the {documentation} for more information, including limitations and additional resources.",
  assistantinformation: "Assistant information",
  profilecontextlabel: "Profile context: {profileName}",
  layercontextlabel: "Layer context: {layerName}",
  numlayers: "{numLayers} {layerOrLayers}",
  numlayersplural: "layers",
  numlayerssingular: "layer"
}, fe = "arcade_generation", be = "ArcadeCodeRequest", I = "visualization", ge = "ArcadeAssistant", ve = [
  "your_comments",
  "user_evaluation",
  "question",
  "answer",
  "useragent",
  "_source",
  "version",
  "context",
  "extras"
];
let F = [], _ = !0;
class ye extends H {
  constructor() {
    super(...arguments), this.textAreaRef = j(), this.messages = Q(), this._feedbackService = void 0, this.handleFeedbackButton = (e, t) => {
      this.feedback = { ...this.feedback, active: !0, value: e, item: t };
    }, this.handleFeedbackSheetClose = () => {
      this.feedback = {
        active: !1,
        value: void 0,
        text: "",
        item: void 0,
        submitting: !1,
        termsAccepted: !1
      };
    }, this.handleFeedbackSubmit = async () => {
      this.feedback = { ...this.feedback, submitting: !0 };
      const e = await this.ensureFeedbackService();
      if (!e) {
        this.handleFeedbackSheetClose();
        return;
      }
      const t = this.getModel(), o = t ? await this.getProfileAndMetadata(t.uri) : void 0, a = {
        user_evaluation: this.feedback.value,
        your_comments: this.feedback.text || void 0,
        question: this.question,
        answer: this.feedback.item?.script ?? "",
        useragent: navigator.userAgent,
        _source: ge,
        version: this.appVersion ?? "",
        context: o ? JSON.stringify(o) : "",
        extras: o?.profileName ?? "",
        conversation_id: this.feedback.item?.conversationId ?? "",
        privacy_statement: this.feedback.termsAccepted ? "I_agree" : ""
      };
      try {
        await e.applyEdits({ addFeatures: [new X({ attributes: a })] });
      } catch (s) {
        console.error("Error submitting feedback:", s);
      }
      this.handleFeedbackSheetClose();
    }, this.handleClose = (e) => {
      this.closed = !0, this.closePanel?.(e);
    }, this.setQuestion = (e) => {
      this.question = e;
    }, this.onSuggestionClick = (e) => {
      this.textAreaRef.value && (this.textAreaRef.value.value = e, this.textAreaRef.value.setFocus(), this.setQuestion(e));
    }, this.isViewingResult = !1, this.confirmationActive = !1, this.isSubmitting = !1, this.errorMessage = void 0, this.question = "", this.history = [], this.feedback = {
      active: !1,
      value: void 0,
      text: "",
      item: void 0,
      termsAccepted: !1,
      submitting: !1
    }, this.copySuccessConversationId = void 0, this.splashActive = !0, this.editorInsertMode = "add", this.context = void 0, this.historyCards = [], this.helpBase = "", this.assistantsEnabled = !1, this.closed = !1;
  }
  static {
    this.properties = { isViewingResult: 16, confirmationActive: 16, isSubmitting: 16, errorMessage: 16, question: 16, history: 16, feedback: 16, copySuccessConversationId: 16, splashActive: 16, editorInsertMode: 16, context: 16, historyCards: 16, closePanel: 0, insertText: 0, helpBase: 1, assistantsEnabled: 5, layer: [1, { type: Object }], orgBaseUrl: 1, serviceUrl: 1, closed: 7, editorRef: 0, feedbackServiceUrl: 1, appVersion: 1 };
  }
  static {
    this.styles = ee;
  }
  get disclaimerComment() {
    return `// ${this.messages.disclaimercomment}
// ${d.disclaimerpt2}`;
  }
  get assistantHelpUrl() {
    return `${this.helpBase ?? "https://doc.arcgis.com/en/arcgis-online/"}administer/configure-assistants.htm`;
  }
  get helpTopicUrl() {
    return `${this.helpBase ?? "https://doc.arcgis.com/en/arcgis-online/"}create-maps/arcade-assistant.htm`;
  }
  async destroy() {
  }
  load() {
    const e = async () => {
      const t = this.getModel();
      if (!t) {
        this.context = void 0;
        return;
      }
      const o = await this.getProfileAndMetadata(t.uri);
      this.context = o;
    };
    e().catch((t) => {
      console.error("Error setting initial context in Arcade Assistant:", t);
    }), this.manager.onLifecycle(() => ({ remove: M.onModelContextDidChange(async () => {
      e().catch((o) => {
        console.error("Error setting context in Arcade Assistant:", o);
      });
    }).dispose }));
  }
  willUpdate(e) {
    e.has("history") && (this.historyCards = this.getHistoryCards());
  }
  connectedCallback() {
    super.connectedCallback(), this.history = F, this.splashActive = _;
  }
  disconnectedCallback() {
    super.disconnectedCallback(), F = this.history, _ = this.splashActive, this.copySuccessTimer && (clearTimeout(this.copySuccessTimer), this.copySuccessTimer = void 0);
  }
  getHistoryCards() {
    return this.history.reduce((e, t) => (!t.script || (e.push({
      priorPrompt: t.question,
      code: t.formattedScript || t.error || "",
      chips: [
        {
          label: t.profile ?? I,
          icon: "map-information",
          appearance: "outline",
          scale: "s",
          conversationId: t.conversationId ?? "",
          tooltip: d.profilecontextlabel.replace("{profileName}", t.profile ?? I)
        },
        ...t.layerName ? [
          {
            label: d.numlayers.replace("{numLayers}", "1").replace("{layerOrLayers}", d.numlayerssingular),
            icon: "layer",
            appearance: "outline",
            scale: "s",
            conversationId: t.conversationId ?? "",
            tooltip: d.layercontextlabel.replace("{layerName}", t.layerName ?? "No layer")
          }
        ] : []
      ],
      onAddToEditor: () => {
        J(this.editorRef.editorInstance, t.formattedScript ?? "", this.editorInsertMode, this.disclaimerComment);
      },
      onCopy: (o) => {
        const a = t.formattedScript ? `${this.disclaimerComment}
${t.formattedScript}` : "";
        a && navigator.clipboard.writeText(a).then(() => {
          this.copySuccessConversationId = o, this.copySuccessTimer && clearTimeout(this.copySuccessTimer), this.copySuccessTimer = window.setTimeout(() => {
            this.copySuccessConversationId = void 0, this.copySuccessTimer = void 0;
          }, 1500);
        });
      },
      onThumbsUp: () => this.handleFeedbackButton("good", t),
      onThumbsDown: () => this.handleFeedbackButton("bad", t),
      conversationId: t.conversationId ?? "",
      message: t.message
    }), this.isViewingResult), e), []);
  }
  setFeedbackState(e) {
    this.feedback = e;
  }
  async ensureFeedbackService() {
    if (this._feedbackService)
      return this._feedbackService;
    if (!this.feedbackServiceUrl)
      return;
    const e = new K({ url: this.feedbackServiceUrl });
    await e.load();
    const t = ve.filter((o) => !e.fields.some((a) => a.name === o));
    if (t.length > 0) {
      console.error(`Missing the following fields in feedback service: ${t.join(", ")}. Feedback will not be logged.`);
      return;
    }
    return this._feedbackService = e, e;
  }
  getModel() {
    return this.editorRef.editorInstance?.getModel();
  }
  async submitQuestion() {
    if (this.question) {
      this.isSubmitting = !0;
      try {
        const e = await this.getToken(), t = this.getModel();
        if (!t)
          return;
        const { profileName: o, metadata: a, layerName: s } = await this.getProfileAndMetadata(t.uri), c = (await te({
          baseUrl: this.serviceUrl,
          skillId: fe,
          message: this.question,
          authToken: e,
          context: {
            kind: be,
            context: {
              profile_name: o,
              metadata: a
            }
          }
        })).find((n) => n.context?.kind === "ArcadeCodeResponse");
        if (!c)
          return;
        c.context?.kind === "ArcadeCodeResponse" && (this.history = [
          {
            script: c?.context?.arcadeCode?.code,
            formattedScript: Y(c?.context?.arcadeCode?.code ?? ""),
            error: void 0,
            question: this.question,
            profile: o,
            conversationId: c.conversationId,
            layerName: s ?? void 0,
            ...c.message ? { message: c.message } : {}
          },
          ...this.history
        ], this.isViewingResult = !0, this.errorMessage = void 0);
      } catch (e) {
        e instanceof Error && e.name === "ArcadeAssistantError" ? this.errorMessage = oe(e) || this.messages.erroroccurred || "An error occurred." : this.errorMessage = this.messages.erroroccurred || "An error occurred.", console.error("Error in Arcade Assistant:", e);
      } finally {
        this.isSubmitting = !1;
      }
    }
  }
  async getToken() {
    const { token: e } = await W.getCredential(this.orgBaseUrl);
    return e;
  }
  async getProfileAndMetadata(e) {
    let t = I;
    const o = M.getEditorProfileForModel(e);
    o?.loaded || await o?.loadSource();
    const a = this.editorRef.profile;
    a && "id" in a && (t = a.id);
    const s = o?.definition?.variables?.find((n) => n.type === "feature");
    let p = [], c;
    return s?.definition && "fields" in s.definition && (p = s.definition.fields.map((n) => ({
      name: n.name,
      type: n.type,
      alias: n.alias
    })), Z(s?.definition) && (c = s.definition.title)), { profileName: t, metadata: p, layerName: c };
  }
  render() {
    return this.closed ? null : this.assistantsEnabled ? C`<calcite-flow><calcite-flow-item closable .heading=${this.messages.arcadeassistant ?? "Arcade assistant"} @calciteFlowItemClose=${this.handleClose}>${this.splashActive && C`<calcite-scrim></calcite-scrim>` || ""}${se({ messages: this.messages })}${re({ popoverContent: N({ assistantsEnabled: this.assistantsEnabled, messages: { ...this.messages, ...d }, assistantHelpUrl: this.assistantHelpUrl, helpTopicUrl: this.helpTopicUrl }) })}<calcite-shell class="unstyled-shell">${this.splashActive && he({ messages: { ...d, ...this.messages }, onProceed: () => {
      this.splashActive = !1;
    }, helpTopicUrl: this.helpTopicUrl, onExit: (e) => this.closePanel && this.closePanel(e) }) || ""}${ce({ active: this.confirmationActive, setActive: (e) => this.confirmationActive = e, messages: this.messages })}${le({ isDisabled: this.isSubmitting, isReadOnly: !1, setQuestion: this.setQuestion, setIsViewingResult: (e) => this.isViewingResult = e, mode: this.isViewingResult ? "refine" : "prompt", textAreaRef: this.textAreaRef, question: this.question, errorMessage: this.errorMessage, setErrorMessage: (e) => this.errorMessage = e, submitQuestion: this.submitQuestion.bind(this), messages: { ...d, ...this.messages }, context: this.context })}<calcite-block-group label="interactive blocks">${!this.isViewingResult && !this.isSubmitting && me({ messages: { ...this.messages, ...d }, suggestions: ["Round value to one decimal place", 'Return "Yes" if value > 10'], onSuggestionClick: this.onSuggestionClick }) || ""}<calcite-block .hidden=${!this.isSubmitting} .heading=${this.messages.generatingresponse ?? "Generating response..."}></calcite-block>${U({
      expanded: this.isViewingResult,
      messages: { ...this.messages, ...d },
      collapsible: !0,
      showEffectsIcon: !0,
      editorInsertMode: this.editorInsertMode,
      setEditorInsertMode: (e) => this.editorInsertMode = e,
      /** Only show the latest history card */
      cards: this.historyCards.length ? [this.historyCards[0]] : [],
      heading: this.messages.besteffort ?? "Here's the assistant's best effort",
      hidden: this.isSubmitting || !this.isViewingResult,
      copySuccessConversationId: this.copySuccessConversationId
    })}${U({ expanded: !this.isViewingResult, messages: { ...this.messages, ...d }, collapsible: !0, editorInsertMode: this.editorInsertMode, setEditorInsertMode: (e) => this.editorInsertMode = e, cards: this.isViewingResult ? this.historyCards.slice(1) : this.historyCards, heading: this.messages.recentprompts ?? "Recent prompts", hidden: this.isSubmitting || this.history.length === 0, copySuccessConversationId: this.copySuccessConversationId })}</calcite-block-group>${this.feedback.active ? ue({ setOpen: this.handleFeedbackSheetClose, messages: { ...this.messages, ...d }, onSubmit: this.handleFeedbackSubmit, feedback: this.feedback, setFeedback: this.setFeedbackState.bind(this) }) : null}</calcite-shell></calcite-flow-item></calcite-flow>` : C`<calcite-flow><calcite-flow-item .selected=${!this.isViewingResult} closable .heading=${this.messages.arcadeassistant ?? "Arcade assistant"} @calciteFlowItemClose=${this.handleClose}>${N({ slot: "content-top", messages: { ...this.messages, ...d }, assistantsEnabled: this.assistantsEnabled, assistantHelpUrl: this.assistantHelpUrl, helpTopicUrl: this.helpTopicUrl })}</calcite-flow-item></calcite-flow>`;
  }
}
B("arcgis-arcade-coding-assistant", ye);
export {
  ye as ArcgisArcadeCodingAssistant
};
