/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { css, html } from "lit";
import { keyed } from "lit/directives/keyed.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent } from "@arcgis/lumina";
import { c as configContext } from "../../chunks/deployAppContexts.js";
import { useContextConsumer } from "@arcgis/lumina/context";
import { d as EIndustry, T as TELEMETRY_CATEGORY } 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.
 */

.width-full {
  width: 100%
}

calcite-panel {
 --calcite-panel-background-color: var(--calcite-color-foreground-1);
 --calcite-panel-footer-space: var(--calcite-spacing-sm);
}

.border-color {
  --calcite-block-border-color: transparent;
}

calcite-block {
  margin: 0;
  --calcite-block-content-space: 0;
}

.tree-padding {
  padding: 0 0.2rem;
}
`;
const industryToDomainsMap = {
  PUBLICSAFETY: ["EMERGENCYMANAGEMENT", "FIRESERVICE", "LAWENFORCEMENT"],
  STATEANDLOCALGOVERNMENT: [
    "AGRICULTURE",
    "AIRPORT",
    "ASSESSMENTANDTAXATION",
    "ELECTIONS",
    "EMERGENCYMANAGEMENT",
    "FIRESERVICE",
    "FISHANDWILDLIFE",
    "HEALTHANDHUMANSERVICES",
    "LAWENFORCEMENT",
    "NATURALRESOURCES",
    "PARKS",
    "PLANNINGANDDEVELOPMENT",
    "PUBLICWORKS",
    "TRANSPORTATION"
  ],
  UTILITIES: ["DISTRICTENERGY", "ELECTRIC", "GAS", "SEWER", "STORMWATER", "WATER"]
};
const industryMatrix = Object.keys(EIndustry).reduce(
  (acc, industryKey) => {
    const typedKey = industryKey;
    acc[typedKey] = industryToDomainsMap[typedKey] ?? [];
    return acc;
  },
  {}
);
class SolutionsFilterPanel extends LitElement {
  constructor() {
    super();
    this.hideIndustryFilter = false;
    this.isAIDialogOpen = false;
    this.showReset = false;
    this._activeFilterSettings = {
      categories: []
    };
    this._translations = useT9n({ name: "solutions-filter-panel", blocking: true });
    this._userFirstName = "";
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true,
      callback: (config) => {
        if (config?.userSession && !this._userFirstName) {
          this._loadUserFirstName();
        }
      }
    });
    this.applyFilter = createEvent();
    this._handleFilterRemoved = (event) => {
      const detail = event.detail;
      if (Array.isArray(detail)) {
        this._activeFilterSettings = {
          ...this._activeFilterSettings,
          categories: [...detail]
        };
      }
    };
    this._industryMatchName = (industry) => {
      const matchedIndustry = Object.keys(this._translations.industries).find((industryTranslation) => industryTranslation.toUpperCase() === industry.replaceAll(" ", "").toUpperCase());
      return matchedIndustry && matchedIndustry in this._translations.industries ? this._translations.industries[matchedIndustry] : industry;
    };
    this.listenOn(window, "filterRemoved", this._handleFilterRemoved);
    this.listenOn(window, "closeAssistant", () => {
      this.isAIDialogOpen = false;
    });
    this.listenOn(window, "openAssistant", () => {
      this.isAIDialogOpen = true;
    });
  }
  static {
    this.properties = { hideIndustryFilter: [5, {}, { type: Boolean }], isAIDialogOpen: [5, {}, { type: Boolean }], showReset: [5, {}, { type: Boolean }], _activeFilterSettings: [16, {}, { state: true }], _translations: [16, {}, { state: true }], _userFirstName: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  changeIndustryFilter(industry, domain, displayValue, emit) {
    if (industry !== "" || domain !== "") {
      let nextCategories = [];
      if (domain !== "") {
        const industryDisplay = EIndustry[industry];
        const matchName = this._industryMatchName(industryDisplay);
        const industryObject = {
          displayValue: matchName,
          type: "industry",
          value: industry,
          industry,
          domain: ""
        };
        const domainObject = {
          displayValue,
          type: "domain",
          value: domain,
          industry,
          domain
        };
        nextCategories = [industryObject, domainObject];
      } else {
        const industryObject = {
          displayValue,
          type: domain !== "" ? "domain" : "industry",
          value: domain !== "" ? domain : industry,
          industry,
          domain
        };
        nextCategories = [industryObject];
      }
      this._activeFilterSettings = {
        ...this._activeFilterSettings,
        categories: [...nextCategories]
      };
      if (emit)
        this.applyFilter.emit(nextCategories);
    } else {
      const emitObject = {
        displayValue,
        type: "industry",
        value: industry,
        industry,
        domain
      };
      this._activeFilterSettings = {
        ...this._activeFilterSettings,
        categories: [emitObject]
      };
      if (emit) {
        this.applyFilter.emit(emitObject);
      }
    }
  }
  clearFilters() {
    this.changeIndustryFilter("", "", "");
    this.applyFilter.emit(null);
  }
  async load() {
    await this._loadUserFirstName();
  }
  render() {
    return html`<calcite-panel description heading>${this.showReset && html`<calcite-action appearance=solid icon=reset @click=${() => {
      this.clearFilters();
    }} slot=header-actions-end .text=${this._translations.resetFilters} text-enabled></calcite-action>` || ""}<calcite-block-group .label=${this._translations.filters} scale=l>${!this.hideIndustryFilter && this.renderIndustryBlock() || ""}</calcite-block-group><calcite-button id=solutions-assistant-button icon-start=speech-bubbles label="Solutions Assistant" @click=${() => {
      this._telemetry?.logEvent({
        category: TELEMETRY_CATEGORY.ASSISTANT,
        action: "Open"
      });
      this.isAIDialogOpen = true;
    }} round scale=l slot=footer-start></calcite-button><calcite-tooltip reference-element=solutions-assistant-button placement=right slot=footer-start offset-distance=10 open><span>${this._translations.assistant.welcomeTip}</span></calcite-tooltip><arcgis-solutions-assistant .open=${this.isAIDialogOpen} .token=${this._configContextConsumer.value?.userSession?.token} .userFirstName=${this._userFirstName}></arcgis-solutions-assistant></calcite-panel>`;
  }
  renderIndustryBlock() {
    const isSubSelected = (industry, sub) => {
      if (!this._activeFilterSettings || !this._activeFilterSettings.categories) {
        return false;
      }
      return this._activeFilterSettings.categories.some((c) => c.industry === industry && (c.domain ?? "") === sub);
    };
    const isIndustryOnlySelected = (industry) => {
      if (!this._activeFilterSettings || !this._activeFilterSettings.categories) {
        return false;
      }
      return this._activeFilterSettings.categories.some((c) => c.industry === industry && (c.domain ?? "") === "");
    };
    const isExpanded = (industry, subs) => subs.length > 0 && (isIndustryOnlySelected(industry) || this._activeFilterSettings.categories?.some((c) => c.industry === industry && !!c.domain && subs.includes(c.domain)) === true);
    const subTreeItems = (industry, subIndustries) => subIndustries.map((sub) => {
      const matchedDomain = Object.keys(this._translations.industriesDomain).find((d) => d.toUpperCase() === sub.toUpperCase());
      const matchName = matchedDomain && matchedDomain in this._translations.industriesDomain ? this._translations.industriesDomain[matchedDomain] : sub;
      const selected = isSubSelected(industry, sub);
      if (selected) {
        return keyed(sub, html`<calcite-tree-item .label=${matchName} @click=${() => this.changeIndustryFilter(industry, sub, matchName, true)} selected>${matchName}</calcite-tree-item>`);
      } else {
        return keyed(sub, html`<calcite-tree-item .label=${matchName} @click=${() => this.changeIndustryFilter(industry, sub, matchName, true)}>${matchName}</calcite-tree-item>`);
      }
    });
    const treeItems = Object.entries(industryMatrix).map(([industry, domain]) => {
      const matchName = this._industryMatchName(industry);
      const subs = domain;
      const selectedIndustryOnly = isIndustryOnlySelected(industry);
      const expanded = isExpanded(industry, subs);
      if (selectedIndustryOnly) {
        return keyed(industry, html`<calcite-tree-item .label=${matchName} @click=${() => this.changeIndustryFilter(industry, "", matchName, true)} selected .expanded=${expanded ? true : void 0}>${matchName}${subs.length > 0 && html`<calcite-tree slot=children selection-mode=multiple>${subTreeItems(industry, subs)}</calcite-tree>` || ""}</calcite-tree-item>`);
      } else {
        return keyed(industry, html`<calcite-tree-item .label=${matchName} @click=${() => this.changeIndustryFilter(industry, "", matchName, true)} .expanded=${expanded ? true : void 0}>${matchName}${subs.length > 0 && html`<calcite-tree slot=children selection-mode=multiple>${subTreeItems(industry, subs)}</calcite-tree>` || ""}</calcite-tree-item>`);
      }
    });
    return html`<calcite-block description expanded class="border-color" .heading=${this._translations.industriesHeader} .label=${this._translations.industriesHeader}><calcite-tree selection-mode=single-persist class="tree-padding">${treeItems}</calcite-tree></calcite-block>`;
  }
  async _loadUserFirstName() {
    try {
      const user = await this._configContextConsumer.value?.userSession?.getUser();
      if (user?.fullName) {
        const userFirstName = user.fullName.split(" ")[0];
        this._userFirstName = userFirstName;
      }
    } catch (error) {
    }
  }
}
customElement("solutions-filter-panel", SolutionsFilterPanel);
export {
  SolutionsFilterPanel
};
