/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { css, html } from "lit";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent, nothing } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { c as configContext, i as isMobileContext } from "../../chunks/deployAppContexts.js";
import { x as getUserIsAdmin } from "../../chunks/interfaces.js";
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.
 */

.toolbar-sizing {
  display: flex;
  align-items: center;
  padding-right: 0px;
  padding-left: 0px;
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
  height: 65px;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.flex-grow-1 {
  flex-grow: 1;
}

calcite-input-text {
  --calcite-color-focus: transparent;
  --calcite-input-text-border-color: transparent;
  --calcite-color-border-input: transparent;
  --calcite-color-brand: transparent;
  display: grid;
  block-size: 65px;
  box-sizing: border-box;
  border-bottom: 2px solid transparent;
}

calcite-dropdown {
  --calcite-color-focus: transparent;
}

@media (prefers-color-scheme: dark) {
  calcite-input-text:focus {
    border-bottom: 2px solid #009AF2;
  }
}

@media (prefers-color-scheme: light) {
  calcite-input-text:focus {
    border-bottom: 2px solid #007AC2;
  }
}

.focus-color {
  --calcite-color-focus: transparent;
}

.padding-end-1-2 {
  padding-inline-end: 0.5rem;
}`;
class SolutionsSearchSortToolbar extends LitElement {
  constructor() {
    super();
    this.defaultSortType = "relevance";
    this.isOrgSolutions = false;
    this._activeSearchSortSettings = [
      {
        scope: "all-solutions",
        settings: {
          enabled: true,
          isOrgSolutions: false,
          searchTerm: "",
          sortType: "relevance"
        }
      },
      {
        scope: "deployments",
        settings: {
          enabled: true,
          isOrgSolutions: false,
          searchTerm: "",
          sortType: "created"
        }
      }
    ];
    this._isMobile = false;
    this._isOrgAdmin = false;
    this._translations = useT9n({ name: "solutions-searchsort-toolbar", blocking: true });
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true,
      callback: async (evt) => {
        if (evt) {
          this._isOrgAdmin = evt.authentication?.PortalUserSubset?.role === "org_admin" || getUserIsAdmin(evt.authentication);
        }
      }
    });
    this._isMobileContextConsumer = useContextConsumer({
      context: isMobileContext,
      subscribe: true,
      callback: (value) => this._isMobile = value
    });
    this.searchChanged = createEvent();
    this.sortTypeChanged = createEvent();
    this.toggleFilter = createEvent();
    this.updateUrlParams = createEvent();
    this.listenOn(window, "detailsCardSelected", () => {
      this.scope = void 0;
    });
    this.listenOn(window, "deployedCardSelected", () => {
      this.scope = void 0;
    });
    this.listenOn(window, "searchTermSet", (evt) => {
      const searchOptions = evt.detail;
      this.scope = searchOptions.scope;
      this.changeSearchFilter(searchOptions.searchTerm, false);
    });
    this.listenOn(window, "sortTypeSet", (evt) => {
      const sortOptions = evt.detail;
      this.scope = sortOptions.scope;
      this.sortChanged(sortOptions.sortType, false);
    });
    this.listenOn(window, "tabChanged", (evt) => {
      console.log("=============================================================");
      console.log("tab changed event received search sort toolbar");
      console.log(evt);
      console.log(this._activeSearchSortSettings);
      console.log(this.scope);
      console.log("=============================================================");
      this.scope = evt.detail;
      const curent = this._getCurrentScopeSetting();
      if (this.scope === "all-solutions" || this.scope === "deployments") {
        this.changeSearchFilter(curent?.searchTerm || "", false);
        this.sortChanged(curent?.sortType || this.defaultSortType, false);
        this._updateUrlParams(evt);
      }
    });
  }
  static {
    this.properties = { defaultSortType: [0, { type: String, attribute: "default-sort-type" }, {}], isOrgSolutions: [5, {}, { type: Boolean }], scope: 1, _activeSearchSortSettings: [16, {}, { state: true }], _isMobile: [16, {}, { state: true }], _isOrgAdmin: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  changeOwnerFilter(isMySolutions) {
    this.isOrgSolutions = !isMySolutions;
    this._activeSearchSortSettings = this._activeSearchSortSettings.map((setting) => setting.scope === this.scope ? {
      ...setting,
      settings: {
        ...setting.settings,
        isOrgSolutions: this.isOrgSolutions
      }
    } : setting);
    const emitObject = {
      displayValue: this.isOrgSolutions ? this._translations.myOrgSolutions : this._translations.mySolutions,
      type: "owner",
      value: this.isOrgSolutions ? `My organization's solutions` : "My solutions"
    };
    this.searchChanged.emit({ option: emitObject, scope: this.scope });
  }
  changeSearchFilter(searchTerm, emit, startTelemetryTimer) {
    console.log("changeSearchFilter");
    const _tempActiveSettings = this._activeSearchSortSettings.map((setting) => setting.scope === this.scope ? {
      ...setting,
      settings: {
        ...setting.settings,
        searchTerm
      }
    } : setting);
    let allowEmit = JSON.stringify(this._activeSearchSortSettings) !== JSON.stringify(_tempActiveSettings);
    this._activeSearchSortSettings = _tempActiveSettings;
    if (emit && allowEmit) {
      this.searchChanged.emit({ option: { searchTerm }, scope: this.scope });
    }
    if (startTelemetryTimer) {
      if (this._searchTelemetryTimer) {
        window.clearTimeout(this._searchTelemetryTimer);
      }
      this._searchTelemetryTimer = window.setTimeout(() => {
        this.searchChanged.emit({ option: { searchTerm }, scope: this.scope, logSearchTelemetry: true });
      }, 1e3);
    }
  }
  sortChanged(sortType, emit) {
    this._activeSearchSortSettings = this._activeSearchSortSettings.map((setting) => setting.scope === this.scope ? {
      ...setting,
      settings: {
        ...setting.settings,
        sortType
      }
    } : setting);
    if (emit) {
      this.sortTypeChanged.emit({ sortType, scope: this.scope });
    }
  }
  async load() {
    if (this._isMobileContextConsumer.value) {
      this._isMobile = this._isMobileContextConsumer.value;
    }
  }
  render() {
    const validScope = this.scope === "all-solutions" || this.scope === "deployments" && this._configContextConsumer.value?.authentication?.IsSignedIn;
    if (validScope) {
      console.log("this should only ever be true for all-solutions or deploymenbts");
    }
    const settings = validScope ? this._getCurrentScopeSetting() : void 0;
    const placeholderText = this.scope === "deployments" ? this._translations.search.deployments : this._translations.search.solutions;
    const filterButtonClass = this._isMobile ? "padding-end-1-2" : "";
    return validScope ? html`<div class="flex-row toolbar-sizing"><calcite-input-text class="flex-grow-1" clearable icon=search @calciteInputTextChange=${(event) => {
      const target = event.target;
      this.changeSearchFilter(target.value, true, false);
    }} @keyup=${(event) => {
      const target = event.target;
      if (event.key === "Enter") {
        this.changeSearchFilter(target.value, true, false);
      } else {
        if (target.value.length >= 3 || target.value.length === 0) {
          this.changeSearchFilter(target.value, target.value.length >= 3 || target.value.length === 0, true);
        }
      }
    }} .placeholder=${placeholderText} scale=l slot=content-top .value=${settings?.searchTerm}></calcite-input-text>${this._isMobile && this.scope === "all-solutions" ? html`<calcite-button appearance=transparent class=${`focus-color ${filterButtonClass}`} icon-start=filter kind=neutral .label=${this._translations.showFilters} @click=${this._toggleFilter}></calcite-button>` : ""}${this.scope === "deployments" && this._isOrgAdmin && this._renderOwnerBlock() || ""}${this._renderDropdown()}</div>` : "";
  }
  _renderOwnerBlock() {
    return html`<calcite-dropdown width=m overlay-positioning=fixed><calcite-button appearance=transparent class="header-button-padding" .iconStart=${!this.isOrgSolutions ? "user" : "organization"} kind=neutral slot=trigger>${this._isMobile ? "" : !this.isOrgSolutions ? this._translations.mySolutions : this._translations.myOrgSolutions}</calcite-button><calcite-dropdown-group group-title=${this._translations.filterBy ?? nothing}><calcite-dropdown-item icon-start=user @click=${() => {
      this.changeOwnerFilter(true);
    }} .selected=${!this.isOrgSolutions}>${this._translations.mySolutions}</calcite-dropdown-item><calcite-dropdown-item icon-start=organization @click=${() => {
      this.changeOwnerFilter(false);
    }} .selected=${this.isOrgSolutions}>${this._translations.myOrgSolutions}</calcite-dropdown-item></calcite-dropdown-group></calcite-dropdown>`;
  }
  _renderDropdown() {
    let dropdownItems = [];
    dropdownItems = [{
      displayValue: this._translations.sortByRelevance,
      sortType: "relevance"
    }, {
      displayValue: this._translations.sortByTitle,
      sortType: "title"
    }];
    if (this.scope === "deployments") {
      dropdownItems.push({
        displayValue: this._translations.sortByDateDeployed,
        sortType: "created"
      });
    } else {
      dropdownItems.push({
        displayValue: this._translations.sortByNew,
        sortType: "new"
      });
      dropdownItems.push({
        displayValue: this._translations.sortByUpdated,
        sortType: "updated"
      });
      if (this._configContextConsumer.value?.authentication?.IsSignedIn) {
        dropdownItems.push({
          displayValue: this._translations.sortBySuggestedForYou,
          sortType: "suggested"
        });
      }
    }
    const settings = this._getCurrentScopeSetting();
    return html`<calcite-dropdown width=m><calcite-button appearance=transparent class="header-button-padding" icon-start=sort-descending kind=neutral slot=trigger>${this._isMobile ? "" : settings?.sortType ? this._getString(settings.sortType) : ""}</calcite-button><calcite-dropdown-group group-title=${this._translations.chooseSortType ?? nothing}>${dropdownItems.map((dropdownItem) => {
      return this._getDropdownItem(dropdownItem.displayValue, dropdownItem.sortType);
    })}</calcite-dropdown-group></calcite-dropdown>`;
  }
  _getDropdownItem(displayValue, sortType) {
    const settings = this._getCurrentScopeSetting();
    return settings?.sortType && settings.sortType !== sortType ? html`<calcite-dropdown-item @click=${() => this.sortChanged(sortType, true)}>${displayValue}</calcite-dropdown-item>` : html`<calcite-dropdown-item @click=${() => this.sortChanged(sortType, true)} selected>${displayValue}</calcite-dropdown-item>`;
  }
  _getString(sortType) {
    let sortString = "";
    switch (sortType) {
      case "new":
        sortString = this._translations.sortByNew;
        break;
      case "relevance":
        sortString = this._translations.sortByRelevance;
        break;
      case "suggested":
        sortString = this._translations.sortBySuggestedForYou;
        break;
      case "title":
        sortString = this._translations.sortByTitle;
        break;
      case "updated":
        sortString = this._translations.sortByUpdated;
        break;
      case "created":
        sortString = this._translations.sortByDateDeployed;
        break;
    }
    return sortString;
  }
  _getCurrentScopeSetting() {
    const currentSetting = this._activeSearchSortSettings?.filter((setting) => setting.scope === this.scope);
    return currentSetting?.[0]?.settings;
  }
  _toggleFilter() {
    this.toggleFilter.emit();
  }
  _updateUrlParams(evt) {
    const tabType = evt.detail;
    let setting;
    this._activeSearchSortSettings.some((s) => {
      if (s.scope === tabType) {
        setting = s;
        return true;
      } else {
        return false;
      }
    });
    if (setting) {
      this.updateUrlParams.emit(setting);
    }
  }
}
customElement("solutions-searchsort-toolbar", SolutionsSearchSortToolbar);
export {
  SolutionsSearchSortToolbar
};
