'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.LuksoSelect = class LuksoSelect extends shared_tailwindElement_index.TailwindStyledElement(style) {
  constructor() {
    super(...arguments);
    this.value = "";
    this.placeholder = "";
    this.label = "";
    this.id = "";
    this.description = "";
    this.error = "";
    this.isFullWidth = false;
    this.isReadonly = false;
    this.isDisabled = false;
    this.borderless = false;
    this.options = "";
    this.selected = void 0;
    this.isOpen = false;
    this.openTop = false;
    this.optionsParsed = [];
    this.valueParsed = void 0;
    this.defaultInputStyles = `bg-neutral-100 paragraph-inter-14-regular px-4 py-3 pr-11
    border-solid h-[48px] placeholder:text-neutral-70 select-none whitespace-nowrap
    outline-none transition transition-all duration-150 appearance-none rounded-12`;
  }
  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"
          });
        }
      }
    }
    if (changedProperties.has("options") && !!this.options) {
      try {
        this.optionsParsed = JSON.parse(this.options);
      } catch (error) {
        console.warn("Could not parse options", error);
      }
    }
    if (changedProperties.has("value") && !!this.value) {
      try {
        this.valueParsed = JSON.parse(this.value);
      } catch (error) {
        console.warn("Could not parse value", error);
      }
    }
  }
  inputTemplate() {
    return shared_tailwindElement_index.x`
      <div
        id=${this.id}
        data-testid=${this.id ? `select-${this.id}` : "select"}
        class=${index.customClassMap({
      [this.defaultInputStyles]: true,
      ["border-neutral-90 group-hover:border-neutral-35"]: !!!this.error && !this.isDisabled,
      ["border-red-85 group-hover:border-red-65"]: !!this.error,
      ["w-full"]: this.isFullWidth,
      ["cursor-not-allowed text-neutral-60"]: this.isDisabled,
      ["text-neutral-20 cursor-pointer"]: !this.isDisabled,
      [this.borderless ? "border-0" : "border"]: true
    })}
        @blur=${this.handleBlur}
        @click=${this.handleClick}
      >
        ${this.value ? this.selectedValue() : this.placeholder}
      </div>
    `;
  }
  labelTemplate() {
    return shared_tailwindElement_index.x`
      <div class="heading-inter-14-bold text-neutral-20 pb-2 block">
        ${this.label}
      </div>
    `;
  }
  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>`;
  }
  optionsTemplate() {
    const optionTemplates = [];
    for (const option of Object.entries(this.optionsParsed)) {
      const index = Number(option[0]);
      if ("value" in option[1]) {
        optionTemplates.push(this.optionStringTemplate(option[1], index));
      } else {
        console.error("Unknown option type", option);
      }
    }
    return shared_tailwindElement_index.x`${this.dropdownWrapperTemplate(optionTemplates)}`;
  }
  dropdownWrapperTemplate(innerTemplate) {
    return shared_tailwindElement_index.x`<div
      class="bg-neutral-100 border w-full border-neutral-90 shadow-1xl rounded-12 p-3 z-50 flex absolute flex-col gap-1 overflow-y-auto max-h-64 ${index.customClassMap(
      {
        ["bottom-[48px] mb-2"]: this.openTop,
        ["mt-2"]: !this.openTop
      }
    )}
      )}"
    >
      ${innerTemplate}
    </div>`;
  }
  optionStringTemplate(option, index$1) {
    return shared_tailwindElement_index.x`<div
      data-id="${option.id}"
      data-index="${index$1 + 1}"
      class="paragraph-inter-14-regular text-neutral-20 cursor-pointer rounded-8 p-2 whitespace-nowrap ${index.customClassMap(
      {
        ["bg-neutral-95 hover:bg-neutral-95"]: this.valueParsed?.id === option.id,
        ["bg-neutral-98"]: this.selected === index$1 + 1 && this.valueParsed?.id !== option.id,
        ["hover:bg-neutral-98"]: this.valueParsed?.id !== option.id
      }
    )}"
      @click=${() => this.handleSelect(option)}
    >
      ${option.value}
    </div>`;
  }
  selectedValue() {
    const foundValue = this.optionsParsed.find(
      (option) => option.id === this.valueParsed?.id
    );
    if (foundValue) {
      return foundValue.value;
    }
    return "";
  }
  handleOutsideDropdownClick(event) {
    const element = event.target;
    if (element.tagName === "LUKSO-SELECT") {
      return;
    }
    this.isOpen = false;
  }
  async handleDropdownKeydown(event) {
    if (event.key === "ArrowUp" && this.selected && this.selected > 1 && this.isOpen) {
      event.preventDefault();
      this.selected = this.selected - 1;
    }
    if (event.key === "ArrowDown" && this.optionsParsed?.length && this.isOpen) {
      event.preventDefault();
      if (!this.selected) {
        this.selected = 1;
      } else if (this.selected < this.optionsParsed.length) {
        this.selected = this.selected + 1;
      }
    }
    if (event.key === "Enter" && this.isOpen) {
      if (this.optionsParsed?.length && this.selected) {
        const selectedResult = this.optionsParsed[this.selected - 1];
        await this.handleSelect(selectedResult);
      }
    }
  }
  async handleSelect(option) {
    if (this.isReadonly || this.isDisabled) {
      return;
    }
    await this.updateComplete;
    this.isOpen = false;
    const selectEvent = new CustomEvent("on-select", {
      detail: {
        value: option
      },
      bubbles: false,
      composed: true
    });
    this.dispatchEvent(selectEvent);
  }
  async handleBlur(event) {
    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);
  }
  handleClick() {
    if (this.isDisabled) {
      return;
    }
    this.isOpen = !this.isOpen;
  }
  render() {
    return shared_tailwindElement_index.x`
      <div class="relative w-[inherit]">
        ${this.label ? this.labelTemplate() : shared_tailwindElement_index.A}
        ${this.description ? this.descriptionTemplate() : shared_tailwindElement_index.A}
        <div class="group">
          <div class="flex relative items-center">
            ${this.inputTemplate()}<lukso-icon
              name=${this.isFullWidth ? "arrow-down-lg" : "arrow-down-sm"}
              class="absolute right-0 mr-3 transition ${index.customClassMap({
      ["opacity-60 cursor-not-allowed"]: this.isDisabled,
      ["cursor-pointer"]: !this.isDisabled,
      ["rotate-180"]: this.isOpen
    })}"
              @click=${this.handleClick}
            ></lukso-icon>
          </div>
          <!-- options dropdown -->
          ${this.isOpen && this.optionsParsed.length > 0 ? this.optionsTemplate() : shared_tailwindElement_index.A}
        </div>
        <!-- error -->
        ${this.error ? this.errorTemplate() : shared_tailwindElement_index.A}
      </div>
    `;
  }
};
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "value", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "placeholder", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "label", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "id", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "description", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "error", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-full-width" })
], exports.LuksoSelect.prototype, "isFullWidth", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-readonly" })
], exports.LuksoSelect.prototype, "isReadonly", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-disabled" })
], exports.LuksoSelect.prototype, "isDisabled", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean })
], exports.LuksoSelect.prototype, "borderless", 2);
__decorateClass([
  queryAssignedElements.n({ type: String })
], exports.LuksoSelect.prototype, "options", 2);
__decorateClass([
  queryAssignedElements.n({ type: Number })
], exports.LuksoSelect.prototype, "selected", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "is-open" })
], exports.LuksoSelect.prototype, "isOpen", 2);
__decorateClass([
  queryAssignedElements.n({ type: Boolean, attribute: "open-top" })
], exports.LuksoSelect.prototype, "openTop", 2);
__decorateClass([
  state.t()
], exports.LuksoSelect.prototype, "optionsParsed", 2);
__decorateClass([
  state.t()
], exports.LuksoSelect.prototype, "valueParsed", 2);
exports.LuksoSelect = __decorateClass([
  queryAssignedElements.e("lukso-select")
], exports.LuksoSelect);
