'use strict';

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

const shared_tailwindElement_index = require('../../index-aaa67d55.cjs');
const queryAssignedElements = require('../../query-assigned-elements-1d5d9d4c.cjs');
const state = require('../../state-f73a8b4f.cjs');
const index = require('../../index-e9668573.cjs');
require('../lukso-icon/index.cjs');
require('../lukso-profile/index.cjs');
require('../lukso-username/index.cjs');
require('../../directive-8278ab14.cjs');
require('../../style-map-74906707.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.selected = void 0;
    this.hasFocus = false;
    this.hasHighlight = false;
    this.isDebouncing = false;
    this.resultsParsed = [];
    this.searchTerm = "";
    this.defaultInputStyles = `bg-neutral-100 paragraph-inter-14-regular px-4 py-3 pr-10
    border-solid h-[48px] placeholder:text-neutral-70
    outline-none transition transition-all duration-150 appearance-none rounded-12`;
  }
  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"
          });
        }
      }
    }
  }
  inputTemplate() {
    return shared_tailwindElement_index.x`
      <input
        name=${this.name}
        type="text"
        .value=${this.value}
        placeholder=${this.placeholder}
        ?autofocus=${this.autofocus}
        autocomplete=${this.autocomplete}
        id=${this.id || this.name}
        data-testid=${this.name ? `input-${this.name}` : "input"}
        ?readonly=${this.isReadonly ? true : void 0}
        ?disabled=${this.isDisabled ? true : void 0}
        class=${index.customClassMap({
      [this.defaultInputStyles]: true,
      [this.error === "" ? "border-neutral-90" : "border-red-85"]: !this.hasHighlight,
      [this.error === "" ? "border-neutral-35" : "border-red-65"]: this.hasHighlight,
      ["w-full"]: this.isFullWidth,
      ["w-[350px]"]: !this.isFullWidth,
      ["cursor-not-allowed text-neutral-60"]: this.isDisabled,
      ["text-neutral-20"]: !this.isDisabled,
      ["cursor-not-allowed"]: this.isReadonly,
      [this.customClass]: !!this.customClass,
      [this.borderless ? "border-0" : "border"]: true
    })}
        @focus=${this.handleFocus}
        @input=${this.handleSearch}
        @blur=${this.handleBlur}
        @click=${this.handleInputClick}
        @mouseenter=${this.handleMouseOver}
        @mouseleave=${this.handleMouseOut}
      />
    `;
  }
  labelTemplate() {
    return shared_tailwindElement_index.x`
      <label
        for=${this.name}
        class="heading-inter-14-bold text-neutral-20 pb-2 block"
        >${this.label}</label
      >
    `;
  }
  descriptionTemplate() {
    return shared_tailwindElement_index.x`
      <div class="paragraph-inter-12-regular text-neutral-20 pb-2">
        ${this.description ?? shared_tailwindElement_index.A}
      </div>
    `;
  }
  errorTemplate() {
    return shared_tailwindElement_index.x`<div class="paragraph-inter-12-regular text-red-65 pt-2">
      ${this.error}
    </div>`;
  }
  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`${this.dropdownWrapperTemplate(resultTemplates)}`;
  }
  noResultsTemplate() {
    return shared_tailwindElement_index.x`${this.dropdownWrapperTemplate(
      shared_tailwindElement_index.x`<div class="paragraph-inter-14-semi-bold text-neutral-20 pl-1">
        ${this.noResultsText}
      </div>`
    )}`;
  }
  loadingTemplate() {
    if (this.showNoResults) {
      return shared_tailwindElement_index.x`${this.dropdownWrapperTemplate(shared_tailwindElement_index.x`
        <div role="status" class="flex flex-col gap-1">
          <div
            class="h-10 bg-neutral-95 w-full rounded-8 animate-pulse animation-delay-none"
          ></div>
        </div>
      `)}`;
    }
    if (this.resultsParsed.length === 0 || this.resultsParsed.length > 5) {
      return shared_tailwindElement_index.x`${this.dropdownWrapperTemplate(shared_tailwindElement_index.x`
        <div role="status" class="flex flex-col gap-1">
          ${[...Array(5)].map(
        () => shared_tailwindElement_index.x`<div
                class="h-10 bg-neutral-95 w-full rounded-8 animate-pulse animation-delay-none"
              ></div>`
      )}
        </div>
      `)}`;
    }
    return shared_tailwindElement_index.x`${this.dropdownWrapperTemplate(shared_tailwindElement_index.x`
      <div role="status" class="flex flex-col gap-1">
        ${this.resultsParsed.map(
      () => shared_tailwindElement_index.x`<div
              class="h-10 bg-neutral-95 w-full rounded-8 animate-pulse animation-delay-none"
            ></div>`
    )}
      </div>
    `)}`;
  }
  dropdownWrapperTemplate(innerTemplate) {
    return shared_tailwindElement_index.x`<div
      class="bg-neutral-100 border border-neutral-90 shadow-1xl rounded-12 p-3 mt-2 z-50 flex absolute w-full flex-col gap-1 overflow-y-auto max-h-64"
    >
      ${innerTemplate}
    </div>`;
  }
  resultStringTemplate(result, index$1) {
    return shared_tailwindElement_index.x`<div
      data-id="${result.id}"
      data-index="${index$1 + 1}"
      class="paragraph-inter-14-regular text-neutral-20 cursor-pointer hover:bg-neutral-98 rounded-8 p-2 ${index.customClassMap(
      {
        ["bg-neutral-98"]: this.selected === index$1 + 1
      }
    )}"
      @click=${() => this.handleSelect(result)}
    >
      ${result.value}
    </div>`;
  }
  resultProfileTemplate(result, index$1) {
    return shared_tailwindElement_index.x`<div
      data-id="${result.address}"
      data-index="${index$1 + 1}"
      class="cursor-pointer hover:bg-neutral-98 rounded-8 p-2 flex gap-2 items-center ${index.customClassMap(
      {
        ["bg-neutral-98"]: this.selected === index$1 + 1
      }
    )}"
      @click=${() => this.handleSelect(result)}
    >
      <lukso-profile
        profile-address="${result.address}"
        profile-url="${result.image}"
        size="x-small"
        has-identicon
      ></lukso-profile>
      <lukso-username
        name="${result.name?.toLowerCase()}"
        address="${result.address}"
        name-color="neutral-20"
        max-width="300"
        size="medium"
      ></lukso-username>
    </div>`;
  }
  async handleSelect(result) {
    await this.updateComplete;
    const selectEvent = new CustomEvent("on-select", {
      detail: {
        value: result
      },
      bubbles: false,
      composed: true
    });
    this.dispatchEvent(selectEvent);
  }
  handleFocus() {
    if (!this.isReadonly && !this.isDisabled) {
      this.hasFocus = true;
      this.hasHighlight = true;
    }
  }
  async handleBlur(event) {
    await this.updateComplete;
    this.hasFocus = false;
    this.hasHighlight = false;
    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) {
    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 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);
  }
  handleMouseOver() {
    if (!this.isReadonly && !this.isDisabled) {
      this.hasHighlight = true;
    }
  }
  handleMouseOut() {
    if (!this.hasFocus) {
      this.hasHighlight = false;
    }
  }
  render() {
    return shared_tailwindElement_index.x`
      <div class="relative w-full">
        ${this.label ? this.labelTemplate() : shared_tailwindElement_index.A}
        ${this.description ? this.descriptionTemplate() : shared_tailwindElement_index.A}
        <div class="flex relative items-center">
          ${this.inputTemplate()}
          <lukso-icon
            name="search"
            class="absolute right-0 mr-3 ${index.customClassMap({
      ["opacity-60 cursor-not-allowed"]: this.isDisabled,
      ["cursor-not-allowed"]: this.isReadonly
    })}"
            @mouseenter=${this.handleMouseOver}
          ></lukso-icon>
        </div>
        <!-- results dropdown -->
        ${this.results && !(this.isSearching || this.isDebouncing) ? this.resultsTemplate() : shared_tailwindElement_index.A}
        <!-- no results dropdown -->
        ${this.showNoResults && !(this.isSearching || this.isDebouncing) ? this.noResultsTemplate() : shared_tailwindElement_index.A}
        <!-- loading dropdown -->
        ${this.value && (this.isSearching || this.isDebouncing) ? this.loadingTemplate() : shared_tailwindElement_index.A}
        <!-- error -->
        ${this.error ? this.errorTemplate() : shared_tailwindElement_index.A}
      </div>
    `;
  }
};
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "value", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "name", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "placeholder", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "label", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "autocomplete", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "id", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "description", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "error", 2);
__decorateClass([
  queryAssignedElements.n({ type: String, attribute: "custom-class" })
], exports.LuksoSearch.prototype, "customClass", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-full-width" })
], exports.LuksoSearch.prototype, "isFullWidth", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-readonly" })
], exports.LuksoSearch.prototype, "isReadonly", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-disabled" })
], exports.LuksoSearch.prototype, "isDisabled", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean })
], exports.LuksoSearch.prototype, "autofocus", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean })
], exports.LuksoSearch.prototype, "borderless", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "results", 2);
__decorateClass([
  queryAssignedElements.n({ type: Number })
], exports.LuksoSearch.prototype, "debounce", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-searching" })
], exports.LuksoSearch.prototype, "isSearching", 2);
__decorateClass([
  queryAssignedElements.n({ type: String, attribute: "no-results-text" })
], exports.LuksoSearch.prototype, "noResultsText", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "show-no-results" })
], exports.LuksoSearch.prototype, "showNoResults", 2);
__decorateClass([
  queryAssignedElements.n({ type: Number })
], exports.LuksoSearch.prototype, "selected", 2);
__decorateClass([
  state.t()
], exports.LuksoSearch.prototype, "hasFocus", 2);
__decorateClass([
  state.t()
], exports.LuksoSearch.prototype, "hasHighlight", 2);
__decorateClass([
  state.t()
], exports.LuksoSearch.prototype, "isDebouncing", 2);
__decorateClass([
  state.t()
], exports.LuksoSearch.prototype, "debounceTimer", 2);
__decorateClass([
  state.t()
], exports.LuksoSearch.prototype, "resultsParsed", 2);
__decorateClass([
  state.t()
], exports.LuksoSearch.prototype, "searchTerm", 2);
exports.LuksoSearch = __decorateClass([
  queryAssignedElements.e("lukso-search")
], exports.LuksoSearch);
