'use strict';

Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });

const shared_tailwindElement_index = require('../../index-68c61387.cjs');
const property = require('../../property-bf2eee83.cjs');
const state = require('../../state-375dfffc.cjs');
const index = require('../../index-2b104ecb.cjs');
const components_luksoProfile_index = require('../../index-67915f32.cjs');
require('../lukso-icon/index.cjs');
require('../lukso-username/index.cjs');
require('../lukso-input/index.cjs');
require('../../index-104cf124.cjs');
require('../lukso-dropdown-option/index.cjs');
require('../lukso-image/index.cjs');
require('../../style-map-8e54f508.cjs');
require('../../directive-8278ab14.cjs');
require('../../index-3926da18.cjs');
require('../../tailwind-config.cjs');
require('../../cn-b6daa995.cjs');

const style = ":host {\n\n    display: inline-flex\n}\n\n:host([is-full-width]) {\n\n    display: flex;\n\n    width: 100%\n}";

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};
exports.LuksoSearch = class LuksoSearch extends shared_tailwindElement_index.TailwindStyledElement(style) {
  constructor() {
    super(...arguments);
    this.value = "";
    this.name = "";
    this.placeholder = "";
    this.label = "";
    this.autocomplete = "off";
    this.id = "";
    this.description = "";
    this.error = "";
    this.customClass = "";
    this.isFullWidth = false;
    this.isReadonly = false;
    this.isDisabled = false;
    this.autofocus = false;
    this.borderless = false;
    this.results = "";
    this.debounce = 700;
    this.isSearching = false;
    this.noResultsText = "";
    this.showNoResults = false;
    this.hideLoading = false;
    this.hasReset = false;
    this.keepValueOnEscapeHit = false;
    this.selected = void 0;
    this.size = "medium";
    this.isDebouncing = false;
    this.resultsParsed = [];
    this.searchTerm = "";
    this.styles = index.ce({
      slots: {
        loading: "bg-neutral-95 w-full animate-pulse animation-delay-none"
      },
      variants: {
        size: {
          small: {
            loading: "h-7 rounded-4"
          },
          medium: {
            loading: "h-10 rounded-8"
          }
        }
      }
    });
  }
  connectedCallback() {
    super.connectedCallback();
    window.addEventListener("click", this.handleOutsideDropdownClick.bind(this));
    window.addEventListener("keydown", this.handleDropdownKeydown.bind(this));
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    window.removeEventListener("click", this.handleOutsideDropdownClick);
    window.removeEventListener("keydown", this.handleDropdownKeydown);
  }
  willUpdate(changedProperties) {
    if (changedProperties.has("selected")) {
      const selectedOption = this.shadowRoot?.querySelector(
        `[data-index="${changedProperties.get("selected")}"`
      );
      if (selectedOption) {
        if ("scrollIntoViewIfNeeded" in selectedOption && typeof selectedOption.scrollIntoViewIfNeeded === "function") {
          selectedOption.scrollIntoViewIfNeeded();
        } else {
          selectedOption.scrollIntoView({
            behavior: "smooth",
            block: "center"
          });
        }
      }
    }
  }
  resultsTemplate() {
    const resultTemplates = [];
    this.resultsParsed = JSON.parse(this.results);
    for (const result of Object.entries(this.resultsParsed)) {
      const index = Number(result[0]);
      if ("value" in result[1]) {
        resultTemplates.push(this.resultStringTemplate(result[1], index));
      } else if ("address" in result[1]) {
        resultTemplates.push(this.resultProfileTemplate(result[1], index));
      } else {
        console.error("Unknown result type", result);
      }
    }
    return shared_tailwindElement_index.x`<lukso-dropdown
      size=${this.size}
      is-open
      is-open-on-outside-click
      is-full-width
      >${resultTemplates}</lukso-dropdown
    >`;
  }
  noResultsTemplate() {
    return shared_tailwindElement_index.x`<lukso-dropdown
      size=${this.size}
      is-open
      is-open-on-outside-click
      is-full-width
      >${shared_tailwindElement_index.x`<div class="paragraph-inter-14-semi-bold text-neutral-20 pl-1">
        ${this.noResultsText}
      </div>`}</lukso-dropdown
    >`;
  }
  loadingTemplate() {
    const { loading } = this.styles({
      size: this.size
    });
    if (this.showNoResults) {
      return shared_tailwindElement_index.x`<lukso-dropdown
        size=${this.size}
        is-open
        is-open-on-outside-click
        is-full-width
        >${shared_tailwindElement_index.x`
          <div role="status" class="flex flex-col gap-1">
            <div class=${loading()}></div>
          </div>
        `}</lukso-dropdown
      >`;
    }
    if (this.resultsParsed.length === 0 || this.resultsParsed.length > 5) {
      return shared_tailwindElement_index.x`<lukso-dropdown
        size=${this.size}
        is-open
        is-open-on-outside-click
        is-full-width
        >${shared_tailwindElement_index.x`
          <div role="status" class="flex flex-col gap-1">
            ${[...Array(5)].map(() => shared_tailwindElement_index.x`<div class=${loading()}></div>`)}
          </div>
        `}</lukso-dropdown
      >`;
    }
    return shared_tailwindElement_index.x`<lukso-dropdown
      size=${this.size}
      is-open
      is-open-on-outside-click
      is-full-width
      >${shared_tailwindElement_index.x`
        <div role="status" class="flex flex-col gap-1">
          ${this.resultsParsed.map(() => shared_tailwindElement_index.x`<div class=${loading()}></div>`)}
        </div>
      `}</lukso-dropdown
    >`;
  }
  resultStringTemplate(result, index) {
    return shared_tailwindElement_index.x`<lukso-dropdown-option
      data-id="${result.id}"
      data-index="${index + 1}"
      ?is-selected=${this.selected === index + 1}
      size=${this.size}
      @click=${() => this.handleSelect(result)}
    >
      ${result.value}
    </lukso-dropdown-option>`;
  }
  resultProfileTemplate(result, index) {
    const eoaProfilePicture = shared_tailwindElement_index.x`<lukso-profile
      profile-address="${result.address}"
      profile-url="${result.address ? components_luksoProfile_index.makeBlockie(result.address) : ""}"
      size="x-small"
    ></lukso-profile>`;
    const lsp3ProfilePicture = shared_tailwindElement_index.x`<lukso-profile
      profile-address="${result.address}"
      profile-url="${result.image}"
      size="x-small"
      has-identicon
    ></lukso-profile>`;
    const profilePicture = result.isEOA ? eoaProfilePicture : lsp3ProfilePicture;
    return shared_tailwindElement_index.x`<lukso-dropdown-option
      data-id="${result.address}"
      data-index="${index + 1}"
      ?is-selected=${this.selected === index + 1}
      size=${this.size}
      @click=${() => this.handleSelect(result)}
    >
      ${profilePicture}
      <lukso-username
        name="${result.name?.toLowerCase()}"
        address="${result.address}"
        name-color="neutral-20"
        max-width="300"
        size="medium"
        class="ml-1"
      ></lukso-username>
    </lukso-dropdown-option>`;
  }
  async handleOutsideDropdownClick(event) {
    const element = event.target;
    if (element?.dataset?.component === "lukso-search") {
      return;
    }
    this.results = "";
  }
  async handleDropdownKeydown(event) {
    if (event.key === "ArrowUp" && this.selected && this.selected > 1 && this.resultsParsed?.length) {
      event.preventDefault();
      this.selected = this.selected - 1;
    }
    if (event.key === "ArrowDown" && this.resultsParsed?.length) {
      event.preventDefault();
      if (!this.selected) {
        this.selected = 1;
      } else if (this.selected < this.resultsParsed.length) {
        this.selected = this.selected + 1;
      }
    }
    if (event.key === "Enter" && this.resultsParsed?.length) {
      if (this.selected) {
        const selectedResult = this.resultsParsed[this.selected - 1];
        await this.handleSelect(selectedResult);
      }
    }
    if (event.key === "Escape") {
      this.results = "";
    }
  }
  async handleSelect(result) {
    await this.updateComplete;
    const selectEvent = new CustomEvent("on-select", {
      detail: {
        value: result
      },
      bubbles: false,
      composed: true
    });
    this.dispatchEvent(selectEvent);
  }
  async handleBlur(event) {
    event.stopPropagation();
    await this.updateComplete;
    const target = event.target;
    const blurEvent = new CustomEvent("on-blur", {
      detail: {
        value: target.value,
        event
      },
      bubbles: false,
      composed: true
    });
    this.dispatchEvent(blurEvent);
  }
  async handleInputClick(event) {
    event.stopPropagation();
    await this.updateComplete;
    const target = event.target;
    const clickEvent = new CustomEvent("on-input-click", {
      detail: {
        value: target.value,
        event
      },
      bubbles: false,
      composed: true
    });
    this.dispatchEvent(clickEvent);
  }
  async handleKeyUp(event) {
    event.stopPropagation();
    await this.updateComplete;
    const value = event?.detail?.value;
    if (!this.keepValueOnEscapeHit && event?.detail?.event?.key === "Escape") {
      this.value = "";
      event.detail.value = "";
      this.handleSearch(event);
    }
    const keyEvent = new CustomEvent("on-key-up", {
      detail: {
        value,
        event
      },
      bubbles: true,
      composed: true
    });
    this.dispatchEvent(keyEvent);
  }
  async handleReset(event) {
    if (!this.hasReset) {
      return;
    }
    await this.updateComplete;
    this.value = "";
    const target = event.target;
    const clickEvent = new CustomEvent("on-reset", {
      detail: {
        value: target.value,
        event
      },
      bubbles: false,
      composed: true
    });
    this.dispatchEvent(clickEvent);
  }
  async searchDebounce(searchTerm) {
    await this.updateComplete;
    this.value = searchTerm;
    this.debounceTimer = setTimeout(() => {
      const changeEvent = new CustomEvent("on-search", {
        detail: {
          value: searchTerm
        },
        bubbles: false,
        composed: true
      });
      this.dispatchEvent(changeEvent);
      this.isDebouncing = false;
    }, this.debounce);
  }
  handleSearch(event) {
    if (this.isDebouncing) {
      clearTimeout(this.debounceTimer);
    }
    this.isDebouncing = true;
    const target = event.target;
    this.searchDebounce(target.value);
  }
  render() {
    return shared_tailwindElement_index.x`
      <div class="relative w-full">
        <lukso-input
          name=${this.name}
          type="text"
          .value=${this.value}
          placeholder=${this.placeholder}
          autocomplete=${this.autocomplete}
          label=${this.label}
          description=${this.description}
          error=${this.error}
          custom-class=${this.customClass}
          id=${this.id}
          size=${this.size}
          data-component="lukso-search"
          right-icon="${this.hasReset && this.value ? "close-sm" : "search"}"
          ?is-right-icon-clickable=${this.hasReset && this.value}
          ?autofocus=${this.autofocus}
          ?is-readonly=${this.isReadonly}
          ?is-disabled=${this.isDisabled}
          ?is-full-width=${this.isFullWidth}
          keep-focus-on-escape
          @on-input=${this.handleSearch}
          @on-blur=${this.handleBlur}
          @on-input-click=${this.handleInputClick}
          @on-right-icon-click=${this.handleReset}
          @on-key-up=${this.handleKeyUp}
        ></lukso-input>
        <!-- results dropdown -->
        ${this.results && !(this.isSearching || this.isDebouncing) ? this.resultsTemplate() : shared_tailwindElement_index.E}
        <!-- no results dropdown -->
        ${this.showNoResults && !(this.isSearching || this.isDebouncing) ? this.noResultsTemplate() : shared_tailwindElement_index.E}
        <!-- loading dropdown -->
        ${!this.hideLoading && this.value && (this.isSearching || this.isDebouncing) ? this.loadingTemplate() : shared_tailwindElement_index.E}
      </div>
    `;
  }
};
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "value", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "name", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "placeholder", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "label", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "autocomplete", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "id", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "description", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "error", 2);
__decorateClass([
  property.n({ type: String, attribute: "custom-class" })
], exports.LuksoSearch.prototype, "customClass", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "is-full-width" })
], exports.LuksoSearch.prototype, "isFullWidth", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "is-readonly" })
], exports.LuksoSearch.prototype, "isReadonly", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "is-disabled" })
], exports.LuksoSearch.prototype, "isDisabled", 2);
__decorateClass([
  property.n({ type: Boolean })
], exports.LuksoSearch.prototype, "autofocus", 2);
__decorateClass([
  property.n({ type: Boolean })
], exports.LuksoSearch.prototype, "borderless", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "results", 2);
__decorateClass([
  property.n({ type: Number })
], exports.LuksoSearch.prototype, "debounce", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "is-searching" })
], exports.LuksoSearch.prototype, "isSearching", 2);
__decorateClass([
  property.n({ type: String, attribute: "no-results-text" })
], exports.LuksoSearch.prototype, "noResultsText", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "show-no-results" })
], exports.LuksoSearch.prototype, "showNoResults", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "hide-loading" })
], exports.LuksoSearch.prototype, "hideLoading", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "has-reset" })
], exports.LuksoSearch.prototype, "hasReset", 2);
__decorateClass([
  property.n({ type: Boolean, attribute: "keep-value-on-escape-hit" })
], exports.LuksoSearch.prototype, "keepValueOnEscapeHit", 2);
__decorateClass([
  property.n({ type: Number })
], exports.LuksoSearch.prototype, "selected", 2);
__decorateClass([
  property.n({ type: String })
], exports.LuksoSearch.prototype, "size", 2);
__decorateClass([
  state.r()
], exports.LuksoSearch.prototype, "isDebouncing", 2);
__decorateClass([
  state.r()
], exports.LuksoSearch.prototype, "debounceTimer", 2);
__decorateClass([
  state.r()
], exports.LuksoSearch.prototype, "resultsParsed", 2);
__decorateClass([
  state.r()
], exports.LuksoSearch.prototype, "searchTerm", 2);
exports.LuksoSearch = __decorateClass([
  property.t("lukso-search")
], exports.LuksoSearch);
