/* 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, safeClassMap, safeStyleMap } from "@arcgis/lumina";
const styles = css`/** @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;
  --solutions-theme-foreground-color: var(--calcite-color-foreground-1);
  width: 100%;
}

.width-full {
  width: 100%;
}

.height-full {
  height: 100%;
}

.display-flex {
  display: flex;
}

.border-bottom-1 {
  border-bottom-width: 1px !important;
  border-width: 0px;
}

.border-bottom-2 {
  border-bottom-width: 2px !important;
  border-width: 0px;
}

.border-solid {
  border-style: solid;
  border-color: var(--calcite-color-border-3);
}

.border-left-right {
  border-left: 1px solid var(--calcite-color-border-3);
  border-right: 1px solid var(--calcite-color-border-3);
}

.action-bar-size {
  height: 51px;
  width: 100%;
}

.map-list {
  display: flex;
  flex-direction: column;
  animation: calcite-scrim-fade-in var(--calcite-internal-animation-timing-medium) ease-in-out;
  background-color: var(--calcite-color-background);
  z-index: 1000;
}

.display-none {
  display: none;
}

.adjusted-height {
  max-height: calc(100% - 68px);
  overflow-y: auto;
}

.position-absolute {
  position: absolute;
}

.position-relative {
  position: relative;
}

.popover-map-list {
  overflow: auto;
  width: 250px;
}

.max-width-200 {
  max-width: 200px;
}

.min-width-150 {
  min-width: 150px;
}

calcite-action-bar {
  --calcite-internal-action-bar-gap: 0px;
  --calcite-internal-action-bar-padding: 0px;
}`;
class MapPicker extends LitElement {
  constructor() {
    super();
    this.mapInfos = [];
    this.isMapLayout = false;
    this.showMapListInPopover = false;
    this.referenceElement = "";
    this.selectedWebMapId = "";
    this._mapListExpanded = false;
    this._isValidWebMap = true;
    this._translations = useT9n({ name: "map-picker", blocking: true });
    this._list = createRef();
    this._loadedId = "";
    this._skipEditCheck = false;
    this._popover = createRef();
    this._mapPickerButton = createRef();
    this.beforeMapInfoChange = createEvent();
    this.mapInfoChange = createEvent();
    this.listenOn(window, "mapChanged", this.mapChanged);
  }
  static {
    this.properties = { mapInfos: [0, {}, { attribute: false }], isMapLayout: [5, {}, { type: Boolean }], height: [9, {}, { type: Number }], showMapListInPopover: [5, {}, { type: Boolean }], referenceElement: 1, selectedWebMapId: 1, _mapListExpanded: [16, {}, { state: true }], _isValidWebMap: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  willUpdate(changes) {
    if (changes.has("mapInfos") && this.hasUpdated) {
      void this.mapInfosWatchHandler(this.mapInfos, changes.get("mapInfos"));
    }
    if (changes.has("selectedWebMapId") && this.hasUpdated) {
      void this.selectedWebMapIdWatchHandler(this.selectedWebMapId);
    }
  }
  _webMapInfoWatchHandler(v, oldV) {
    if (v && JSON.stringify(v) !== JSON.stringify(oldV)) {
      this._loadedId = v?.id;
      this.mapInfoChange.emit(v);
    }
  }
  async mapInfosWatchHandler(v, oldV) {
    if (v && JSON.stringify(v) !== JSON.stringify(oldV)) {
      const webMapInfo = this._getWebMapInfo();
      this._webMapSelected(webMapInfo);
    }
  }
  async selectedWebMapIdWatchHandler(v) {
    this._loadedId = v;
  }
  async setMapByID(id, skipEditCheck = false) {
    this._skipEditCheck = skipEditCheck;
    const mapInfos = this.mapInfos?.filter((i) => i.id === id);
    if (id && mapInfos?.length > 0) {
      this._webMapSelected(mapInfos[0]);
    }
    this._skipEditCheck = false;
  }
  async close() {
    if (this._mapListExpanded) {
      this._mapListExpanded = false;
    }
  }
  async toggle(mapListExpanded) {
    this._mapListExpanded = mapListExpanded;
  }
  async mapChanged(_evt) {
    const _isValid = _evt.detail.isValid;
    this._isValidWebMap = _isValid;
  }
  render() {
    return html`${!this.showMapListInPopover && this._getToolbar() || ""}${this.showMapListInPopover ? this._getMapListPopover() : this._getMapNameList(this._mapListExpanded)}`;
  }
  loaded() {
    const webMapInfo = this._getWebMapInfo();
    if (webMapInfo) {
      this._webMapSelected(webMapInfo);
    }
  }
  _getMapPicker() {
    const id = "map-picker-expand-toggle";
    const mapListIcon = this._mapListExpanded ? "chevron-up" : "chevron-down";
    const position = this.isMapLayout ? "" : "position-absolute";
    const width = this.isMapLayout ? "max-width-200" : "width-full";
    const iconStart = this._isValidWebMap ? "map" : "exclamation-mark-triangle";
    return html`<div class=${safeClassMap(width)}><calcite-button alignment=icon-end-space-between appearance=transparent class=${`width-full height-full ${position}`} .iconEnd=${mapListIcon} .iconStart=${iconStart} id=${id} kind=neutral @click=${() => this._chooseMap()} width=full ${ref(this._mapPickerButton)}>${this._getWebMapInfo().name}</calcite-button><calcite-tooltip placement=bottom .referenceElement=${id}><span>${this._translations.switchMap}</span></calcite-tooltip></div>`;
  }
  _getToolbar() {
    const borderBottom = this.isMapLayout ? "border-bottom-1" : "border-bottom-2";
    const position = this.isMapLayout ? "" : "position-relative";
    return html`<div class=${`display-flex border-left-right ${position}`}><calcite-action-bar class=${`border-solid action-bar-size overflow-hidden ${borderBottom}`} expand-disabled layout=horizontal slot=header>${this._getMapPicker()}${this._updateMapPickerIconColor()}</calcite-action-bar></div>`;
  }
  _updateMapPickerIconColor() {
    void this._mapPickerButton.value?.componentOnReady().then(() => {
      const buttonEl = this._mapPickerButton.value;
      const lastChild = buttonEl?.shadowRoot?.lastChild;
      let iconStart = null;
      if (lastChild && lastChild instanceof HTMLElement) {
        const iconElements = lastChild.getElementsByClassName("icon icon--start");
        if (iconElements.length > 0) {
          iconStart = iconElements[0];
        }
      }
      if (iconStart) {
        if (this._isValidWebMap) {
          iconStart.style.setProperty("color", "var(--calcite-color-text-1)");
        } else {
          iconStart.style.setProperty("color", "var(--calcite-color-status-danger)");
        }
      }
    });
  }
  _getMapNameList(show) {
    const position = this.showMapListInPopover ? "position-relative" : "position-absolute";
    const width = this.isMapLayout ? "max-width-200 min-width-150" : "width-full";
    const borderBottom = this.isMapLayout ? "border-bottom-1" : "border-bottom-2";
    const listClass = show ? `map-list border-solid ${borderBottom} adjusted-height ${width} ${position}` : "display-none";
    return html`<div class=${safeClassMap(listClass)}><calcite-list id=mapList label selection-appearance=border selection-mode=single-persist ${ref(this._list)}>${this.mapInfos.map((mapInfo) => {
      return html`<calcite-list-item .label=${mapInfo.name} @click=${() => this._webMapSelected(mapInfo)} .selected=${mapInfo.id === this._loadedId} .value=${mapInfo.id}></calcite-list-item>`;
    })}</calcite-list></div>`;
  }
  _getMapListPopover() {
    const style = this.height && this.height > 0 && this.showMapListInPopover ? { "max-height": `${this.height.toString()}px` } : {};
    return html`<calcite-popover auto-close focus-trap-disabled .label=${this.referenceElement} placement=left .referenceElement=${this.referenceElement} ${ref(this._popover)}><div style=${safeStyleMap(style)} class=popover-map-list>${this._getMapNameList(true)}</div></calcite-popover>`;
  }
  _getWebMapInfo() {
    let webMapInfo = this.mapInfos.find((mapInfo) => this.selectedWebMapId === mapInfo.id);
    if (!webMapInfo && this.mapInfos.length > 0) {
      webMapInfo = this.mapInfos[0];
    }
    if (!webMapInfo) {
      throw new Error("No valid web map info available");
    }
    return webMapInfo;
  }
  _webMapSelected(webMapInfo) {
    const currentId = this._loadedId;
    this._loadedId = webMapInfo.id;
    let updateWebMapInfo = false;
    if (this._skipEditCheck) {
      updateWebMapInfo = true;
    } else {
      const _evt = this.beforeMapInfoChange.emit({
        currentId,
        mapInfo: webMapInfo,
        ref: this.el
      });
      if (!_evt.defaultPrevented) {
        updateWebMapInfo = true;
      }
    }
    if (updateWebMapInfo) {
      this._webMapInfoWatchHandler(webMapInfo, this._webMapInfo);
      this._webMapInfo = webMapInfo;
    }
    if (this._popover.value) {
      this._popover.value.open = false;
    }
    this._mapListExpanded = false;
  }
  _chooseMap() {
    this._mapListExpanded = !this._mapListExpanded;
  }
}
customElement("map-picker", MapPicker);
export {
  MapPicker
};
