'use strict';

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

const shared_tailwindElement_index = require('../../index-d2227f06.cjs');
const queryAssignedElements = require('../../query-assigned-elements-d5e45650.cjs');
const state = require('../../state-d9fb972b.cjs');
const index = require('../../index-1d3f4a5a.cjs');
require('../lukso-icon/index.cjs');
require('../lukso-profile/index.cjs');
require('../lukso-username/index.cjs');
require('../lukso-input/index.cjs');
require('../../bundle-mjs-d58a83c6.cjs');
require('../../style-map-333da36f.cjs');
require('../../directive-8278ab14.cjs');
require('../lukso-image/index.cjs');
require('../../index-b9a3ecb2.cjs');
require('../../tailwind-config.cjs');
require('../../cn-5ceac001.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.inputStyles = index.ce({
      slots: {
        dropdownWrapper: "bg-neutral-100 border border-neutral-90 shadow-1xl z-50 flex absolute w-full flex-col gap-1 overflow-y-auto max-h-64",
        loading: "bg-neutral-95 w-full animate-pulse animation-delay-none"
      },
      variants: {
        size: {
          small: {
            dropdownWrapper: "rounded-8 p-2 mt-1",
            loading: "h-7 rounded-4"
          },
          medium: {
            dropdownWrapper: "rounded-12 p-3 mt-2",
            loading: "h-10 rounded-8"
          }
        }
      }
    });
    this.resultStyles = index.ce({
      slots: {
        resultString: "text-neutral-20 cursor-pointer hover:bg-neutral-98",
        resultProfile: "cursor-pointer hover:bg-neutral-98 flex gap-2 items-center"
      },
      variants: {
        selected: {
          true: {
            resultString: "bg-neutral-98",
            resultProfile: "bg-neutral-98"
          }
        },
        size: {
          small: {
            resultString: "paragraph-inter-12-regular rounded-4 py-1 px-2",
            resultProfile: "rounded-4 py-1 px-2"
          },
          medium: {
            resultString: "paragraph-inter-14-regular rounded-8 p-2",
            resultProfile: "rounded-8 p-2"
          }
        }
      }
    });
  }
  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`${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() {
    const { loading } = this.inputStyles({
      size: this.size
    });
    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=${loading()}></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=${loading()}></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=${loading()}></div>`)}
      </div>
    `)}`;
  }
  dropdownWrapperTemplate(innerTemplate) {
    const { dropdownWrapper } = this.inputStyles({
      size: this.size
    });
    return shared_tailwindElement_index.x`<div class=${dropdownWrapper()}>${innerTemplate}</div>`;
  }
  resultStringTemplate(result, index) {
    const { resultString } = this.resultStyles({
      selected: this.selected === index + 1,
      size: this.size
    });
    return shared_tailwindElement_index.x`<div
      data-id="${result.id}"
      data-index="${index + 1}"
      class=${resultString()}
      @click=${() => this.handleSelect(result)}
    >
      ${result.value}
    </div>`;
  }
  resultProfileTemplate(result, index) {
    const { resultProfile } = this.resultStyles({
      selected: this.selected === index + 1,
      size: this.size
    });
    return shared_tailwindElement_index.x`<div
      data-id="${result.address}"
      data-index="${index + 1}"
      class=${resultProfile()}
      @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 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;
    let value = event?.detail?.value;
    if (!this.keepValueOnEscapeHit && event?.detail?.event?.key === "Escape") {
      value = "";
      this.value = "";
      const changeEvent = new CustomEvent("on-search", {
        detail: {
          value
        },
        bubbles: false,
        composed: true
      });
      this.dispatchEvent(changeEvent);
    }
    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}
          @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.A}
        <!-- no results dropdown -->
        ${this.showNoResults && !(this.isSearching || this.isDebouncing) ? this.noResultsTemplate() : shared_tailwindElement_index.A}
        <!-- loading dropdown -->
        ${!this.hideLoading && this.value && (this.isSearching || this.isDebouncing) ? this.loadingTemplate() : 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: Boolean, attribute: "hide-loading" })
], exports.LuksoSearch.prototype, "hideLoading", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "has-reset" })
], exports.LuksoSearch.prototype, "hasReset", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "keep-value-on-escape-hit" })
], exports.LuksoSearch.prototype, "keepValueOnEscapeHit", 2);
__decorateClass([
  queryAssignedElements.n({ type: Number })
], exports.LuksoSearch.prototype, "selected", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSearch.prototype, "size", 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);
