/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as h } from "../../chunks/runtime.js";
import p from "@arcgis/core/Graphic.js";
import { css as g, html as s } from "lit";
import { createRef as d, ref as f } from "lit/directives/ref.js";
import { unsafeHTML as b } from "lit/directives/unsafe-html.js";
import { LitElement as _, safeStyleMap as y } from "@arcgis/lumina";
import * as l from "@arcgis/toolkit/log";
import { isSharedTemplateMetadata as c, isStandardFeatureTemplate as v } from "@arcgis/core/applications/Components/templateUtils.js";
import "@arcgis/core/editing/sharedTemplates/SharedTemplateMetadata.js";
import { renderPreviewHTML as w } from "@arcgis/core/symbols/support/symbolUtils.js";
import { isTable as I } from "@arcgis/core/applications/Components/layerUtils.js";
const D = g`.esri-thumbnail-preview{width:22px;height:22px;background-position:50% 50%;background-repeat:no-repeat}.template-image-container{width:32px;height:32px;display:flex;align-items:center;justify-content:center}`;
async function x(e, t, i) {
  if (c(e) && e.thumbnail) {
    const u = `data:image/png;base64,${e.thumbnail.imageData}`;
    return s`<div class="esri-thumbnail-preview" style=${y({ backgroundImage: `url(${u})` })}></div>`;
  }
  if (I(t))
    return s`<calcite-icon icon=table scale=s></calcite-icon>`;
  const r = await T(t, e);
  if (r == null)
    return null;
  const n = { maxSize: 24, ariaLabel: i?.ariaLabel };
  v(e) && "renderer" in t && t.renderer?.type === "dictionary" && (n.fieldMap = t.renderer.fieldMap ?? void 0, n.feature = {
    attributes: e.prototype.attributes ?? {}
  });
  const o = await w(r, n);
  return o ? s`${b(o.outerHTML)}` : null;
}
async function T(e, t) {
  if (c(t))
    return await m(e);
  if ("renderer" in e && e.renderer) {
    const { renderer: i } = e, r = new p({ attributes: t.prototype.attributes });
    if ("getSymbolAsync" in i) {
      const a = await i.getSymbolAsync(r);
      if (a)
        return a;
    }
  }
  return await m(e);
}
async function C(e) {
  const t = e === "point" || e === "multipoint" ? await import("@arcgis/core/symbols/SimpleMarkerSymbol.js") : e === "polyline" ? await import("@arcgis/core/symbols/SimpleLineSymbol.js") : e === "polygon" || e === "mesh" || e === "multipatch" ? await import("@arcgis/core/symbols/SimpleFillSymbol.js") : null;
  return t ? new t.default() : null;
}
async function m(e) {
  return "geometryType" in e && e.geometryType ? await C(e.geometryType) : null;
}
class L extends _ {
  constructor() {
    super(...arguments), this._lastRun = 0, this._attempted = !1, this._isCurrentlyInView = !1, this._intersectionObserver = null, this._imageContainerDiv = d(), this._generatedImageData = null;
  }
  static {
    this.properties = { _generatedImageData: 16, template: 0 };
  }
  static {
    this.styles = D;
  }
  get rootLayer() {
    return this.template?.layer?.type === "subtype-sublayer" ? this.template.layer.parent : this.template?.layer;
  }
  willUpdate(t) {
    t.has("template") && (this.hasUpdated || this.template !== null) && this._resetData();
  }
  updated() {
    !this._attempted && this._isCurrentlyInView && (this._attempted = !0, this._handleImage().catch((t) => {
      l.log("warn", this, "Failed processing image");
    }));
  }
  loaded() {
    this.manager.onLifecycle(() => (this._addIntersectionObserver(), () => {
      this._removeIntersectionObserver();
    }));
  }
  _resetData() {
    this._generatedImageData = null, this._attempted = !1;
  }
  async _generateImage() {
    return this.template ? await x(this.template.template, this.template.layer) : "";
  }
  async _handleImage() {
    const t = ++this._lastRun;
    if (!this._generatedImageData || this._generatedImageData === "")
      try {
        const i = await this._generateImage();
        if (this._lastRun !== t || this._generatedImageData === i)
          return;
        this._generatedImageData = i;
      } finally {
        this._attempted = !0;
      }
  }
  _addIntersectionObserver() {
    const t = {
      // If the image gets within 50px in the Y axis, start the download.
      rootMargin: "50px 0px",
      threshold: 0.01
    };
    this._imageContainerDiv.value && requestAnimationFrame(() => {
      this.isConnected && (this._intersectionObserver = new IntersectionObserver((i) => {
        let r = !1;
        i.forEach((a) => {
          a.intersectionRatio > 0 && !r ? (r = !0, this._isCurrentlyInView = !0, this._handleImage().catch((n) => {
            l.log("warn", this, "Failed processing image");
          })) : this._isCurrentlyInView = !1;
        });
      }, t), this._intersectionObserver?.observe(this._imageContainerDiv.value));
    });
  }
  _removeIntersectionObserver() {
    this._intersectionObserver?.disconnect(), this._intersectionObserver = null;
  }
  render() {
    return s`<div class="template-image-container" ${f(this._imageContainerDiv)}>${this._generatedImageData ?? ""}</div>`;
  }
}
h("arcgis-template-image", L);
export {
  L as ArcgisTemplateImage
};
