/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot, safeClassMap } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { p as pnContext } from "../../chunks/publicNotificationContext.js";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel";
import Sketch from "@arcgis/core/widgets/Sketch";
const styles = css`@layer{
/** @license
 * Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

:host {
  display: block;
}

.border {
  outline: 1px solid var(--calcite-color-border-input);
}

.border-left {
  border-left: 1px solid rgba(110, 110, 110, 0.3);
}

.border-left[dir='rtl'] {
  border-right: 1px solid rgba(110, 110, 110, 0.3);
}

/* from js api */
.esri-widget {
  box-sizing: border-box;
  color: #323232;
  font-size: 14px;
  font-family: 'Avenir Next', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  line-height: 1.3em;
  background-color: #fff;
  --esri-widget-padding-v: 12px;
  --esri-widget-padding-h: 15px;
  --esri-widget-padding: var(--esri-widget-padding-v) var(--esri-widget-padding-h);
}

.esri-sketch__panel {
  align-items: center;
  display: flex;
  flex-flow: row wrap;
  padding: 0;
  justify-content: flex-start !important;
}

.esri-sketch__section {
  align-items: center;
  display: flex;
  flex-flow: row wrap;
  padding: 0 7px;
  margin: 6px 0;
}

.esri-responsive-toolbar__bar--horizontal {
  --calcite-action-group-border-color: var(--calcite-color-border-3) !important;
}
}`;
class MapDrawTools extends LitElement {
  constructor() {
    super(...arguments);
    this.active = false;
    this.drawMode = "SKETCH";
    this.editGraphicsEnabled = true;
    this.graphics = [];
    this.redoEnabled = false;
    this.undoEnabled = false;
    this._translations = useT9n({ name: "map-draw-tools", blocking: true });
    this._pnContextConsumer = useContextConsumer({
      context: pnContext,
      subscribe: true
    });
    this._sketchElement = createRef();
    this.selectionLoadingChange = createEvent();
    this.sketchGraphicsChange = createEvent();
    this.drawUndo = createEvent();
    this.drawRedo = createEvent();
  }
  static {
    this.properties = { active: [5, {}, { type: Boolean }], drawMode: 1, editGraphicsEnabled: [5, {}, { type: Boolean }], graphics: [0, {}, { attribute: false }], mapView: [0, {}, { attribute: false }], pointSymbol: [0, {}, { attribute: false }], polylineSymbol: [0, {}, { attribute: false }], polygonSymbol: [0, {}, { attribute: false }], redoEnabled: [5, {}, { type: Boolean }], undoEnabled: [5, {}, { type: Boolean }], _translations: [16, {}, { state: true }], _selectionMode: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("graphics")) {
      this.graphicsWatchHandler(this.graphics, changes.get("graphics"));
    }
    if (changes.has("mapView") && this.mapView) {
      this.mapViewWatchHandler(this.mapView, changes.get("mapView"));
    }
  }
  graphicsWatchHandler(v, oldV) {
    if (v && v.length > 0 && JSON.stringify(v) !== JSON.stringify(oldV) && this._sketchGraphicsLayer) {
      this._updateGraphicsSymbols(v);
      this._sketchGraphicsLayer.removeAll();
      this._sketchGraphicsLayer.addMany(v);
    }
  }
  mapViewWatchHandler(v, oldV) {
    if (v && v !== oldV) {
      this._init();
    }
  }
  async clear() {
    this._clearSketch();
  }
  async updateGraphics() {
    this._updateGraphics();
  }
  loaded() {
    this._init();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._sketchWidget?.cancel();
    this._clearSketch();
  }
  render() {
    const containerClass = this.drawMode === "SKETCH" ? "border" : "border esri-widget esri-sketch__panel";
    const undoRedoClass = this.drawMode === "SKETCH" ? "display-none" : "esri-widget esri-sketch__panel border-left esri-sketch__section";
    return html`<div class=${safeClassMap(containerClass)}><div ${ref(this._sketchElement)}></div><div class=${safeClassMap(undoRedoClass)}><calcite-action appearance=solid .disabled=${!this.undoEnabled} icon=undo @click=${() => this._undo()} scale=s .text=${this._translations.undo}></calcite-action><calcite-action appearance=solid .disabled=${!this.redoEnabled} icon=redo @click=${() => this._redo()} scale=s .text=${this._translations.redo}></calcite-action></div></div>`;
  }
  _init() {
    if (this.mapView && this._sketchElement.value) {
      this._initGraphicsLayer();
      this._initSketch();
    }
  }
  _initGraphicsLayer() {
    const _state = this._pnContextConsumer.value;
    const title = this._translations.sketchLayer;
    if (this.mapView) {
      const sketchIndex = this.mapView.map.layers.findIndex((l) => l.title === title);
      if (sketchIndex > -1) {
        this._sketchGraphicsLayer = this.mapView.map.layers.getItemAt(sketchIndex);
      } else {
        this._sketchGraphicsLayer = new GraphicsLayer({ title, listMode: "hide" });
        if (this._sketchGraphicsLayer) {
          _state.managedLayers[title] = "sketch";
          this.mapView.map.layers.add(this._sketchGraphicsLayer);
        }
      }
      if (this.graphics && this.graphics.length > 0 && this._sketchGraphicsLayer) {
        this._sketchGraphicsLayer.addMany(this.graphics);
      }
    }
  }
  _initSketch() {
    const sketchOptions = {
      layer: this._sketchGraphicsLayer,
      view: this.mapView,
      defaultCreateOptions: {
        mode: "hybrid"
      },
      defaultUpdateOptions: {
        preserveAspectRatio: false,
        enableScaling: false,
        enableRotation: false,
        tool: "reshape",
        toggleToolOnClick: false
      }
    };
    this._sketchWidget = new Sketch({
      ...sketchOptions,
      container: this._sketchElement.value,
      creationMode: "single",
      toolbarKind: "docked",
      visibleElements: {
        duplicateButton: false,
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false
        },
        createTools: {
          circle: false
        },
        undoRedoMenu: false,
        settingsMenu: this.drawMode === "SKETCH"
      }
    });
    if (this._sketchWidget && this._sketchWidget.viewModel) {
      this._sketchViewModel = new SketchViewModel({
        ...sketchOptions
      });
      if (this.polylineSymbol) {
        this._sketchWidget.viewModel.polylineSymbol = this.polylineSymbol;
      }
      if (this.pointSymbol) {
        this._sketchWidget.viewModel.pointSymbol = this.pointSymbol;
      }
      if (this.polygonSymbol) {
        this._sketchWidget.viewModel.polygonSymbol = this.polygonSymbol;
      }
      void this._sketchWidget?.when(async () => {
        await new Promise((resolve) => setTimeout(resolve, 50));
        const settingsMenuPopover = this._sketchElement.value?.getElementsByTagName("calcite-popover")[0];
        settingsMenuPopover?.setAttribute("placement", "auto");
      });
      let forceCreate = false;
      this._sketchWidget.viewModel.addHandles(this._sketchWidget.on("create", (_evt) => {
        if (_evt.state === "complete") {
          this.graphics = _evt.graphic ? [_evt.graphic] : [];
          this.sketchGraphicsChange.emit({
            graphics: this.graphics,
            useOIDs: false
          });
          if (this.drawMode === "REFINE") {
            forceCreate = true;
            this._sketchWidget?.viewModel.create(_evt.tool);
          }
        }
        if (_evt.state === "cancel" && this.drawMode === "REFINE" && forceCreate) {
          forceCreate = !forceCreate;
          this._sketchWidget?.viewModel.create(_evt.tool);
        }
      }));
      let debounceTimer;
      this._sketchWidget.viewModel.addHandles(this._sketchWidget.on("update", (_evt) => {
        if (!this.editGraphicsEnabled) {
          this._sketchWidget?.viewModel.cancel();
          this._sketchViewModel?.cancel();
        } else {
          const eventType = _evt?.toolEventInfo?.type;
          if (eventType === "move" || eventType === "reshape-stop" || eventType === "move-stop") {
            clearTimeout(debounceTimer);
            debounceTimer = window.setTimeout(async () => {
              this.graphics = _evt.graphics;
              this.sketchGraphicsChange.emit({
                graphics: this.graphics,
                useOIDs: false
              });
            }, 1e3);
          }
        }
      }));
      this._sketchWidget.viewModel.addHandles(this._sketchWidget.on("delete", () => {
        this.graphics = [];
        this.sketchGraphicsChange.emit({
          graphics: this.graphics,
          useOIDs: false
        });
      }));
      this._sketchWidget.viewModel.addHandles(this._sketchWidget.on("undo", (_evt) => {
        this.graphics = _evt.graphics;
        this.sketchGraphicsChange.emit({
          graphics: this.graphics,
          useOIDs: false
        });
      }));
      this._sketchWidget.viewModel.addHandles(this._sketchWidget.on("redo", (_evt) => {
        this.graphics = _evt.graphics;
        this.sketchGraphicsChange.emit({
          graphics: this.graphics,
          useOIDs: false
        });
      }));
    }
  }
  _clearSketch() {
    this._sketchWidget?.viewModel.cancel();
    this.graphics = [];
    this._sketchGraphicsLayer?.removeAll();
  }
  _undo() {
    this.drawUndo.emit();
  }
  _redo() {
    this.drawRedo.emit();
  }
  _updateGraphics() {
    setTimeout(() => {
      if (this.graphics.length === 1 && this._sketchWidget) {
        void this._sketchWidget.update(this.graphics, {
          tool: "reshape",
          enableRotation: false,
          enableScaling: false,
          preserveAspectRatio: false,
          toggleToolOnClick: false
        });
      }
    }, 100);
  }
  _updateGraphicsSymbols(graphics) {
    const graphic = graphics[0];
    const type = graphic?.geometry?.type;
    const symbol = type === "point" ? this.pointSymbol : type === "polyline" ? this.polylineSymbol : type === "polygon" ? this.polygonSymbol : void 0;
    if (symbol) {
      graphics.forEach((g) => g.symbol = symbol);
    }
  }
}
customElement("map-draw-tools", MapDrawTools);
export {
  MapDrawTools
};
