import { T as TailwindStyledElement, x, A } from '../../index-8c5a9941.js';
import { n, e } from '../../query-assigned-elements-1c8c9e90.js';
import { t } from '../../state-b9ca4e74.js';
import { c as ce } from '../../index-ca8e900d.js';
import '../lukso-icon/index.js';
import '../lukso-profile/index.js';
import '../lukso-username/index.js';
import { u as uniqId } from '../../index-0e619106.js';
import '../lukso-dropdown-option/index.js';
import '../../bundle-mjs-fbc6e2a8.js';
import '../../style-map-1ee93d7f.js';
import '../../directive-2bb7789e.js';
import '../lukso-image/index.js';
import '../../index-464e8d00.js';
import '../../tailwind-config.js';
import '../../cn-b54dcc61.js';

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;
};
let LuksoSelect = class extends TailwindStyledElement(style) {
  constructor() {
    super();
    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.isLargeIcon = false;
    this.isRight = false;
    this.size = "medium";
    this.showSelectionCounter = false;
    this.optionsParsed = [];
    this.valueParsed = void 0;
    this.inputStyles = ce({
      base: `bg-neutral-100
      border border-solid placeholder:text-neutral-70 select-none whitespace-nowrap
      outline-none transition transition-all duration-150 appearance-none
      text-neutral-20 cursor-pointer border-neutral-90 group-hover:border-neutral-35
      flex items-center`,
      variants: {
        isFullWidth: {
          true: "w-full"
        },
        isDisabled: {
          true: "cursor-not-allowed text-neutral-60 group-hover:border-neutral-90"
        },
        hasError: {
          true: "border-red-85 group-hover:border-red-65"
        },
        borderless: {
          true: "border-0"
        },
        size: {
          small: "h-[28px] px-3 py-2 pr-8 paragraph-inter-12-regular rounded-8",
          medium: "h-[48px] px-4 py-3 pr-11 paragraph-inter-14-regular rounded-12"
        }
      }
    });
    this.counterStyles = ce({
      base: "border border-neutral-20",
      variants: {
        isDisabled: {
          true: "opacity-60 cursor-not-allowed"
        },
        size: {
          small: "paragraph-inter-10-semi-bold rounded-4 py-[1px] px-[5px] ml-1.5",
          medium: "paragraph-inter-14-semi-bold rounded-8 py-[2px] px-[10px] ml-3"
        }
      }
    });
    this.iconStyles = ce({
      base: "absolute right-0 transition cursor-pointer",
      variants: {
        isDisabled: {
          true: "opacity-60 cursor-not-allowed"
        },
        isOpen: {
          true: "rotate-180"
        },
        size: {
          small: "mr-2",
          medium: "mr-3"
        }
      }
    });
    if (!this.id) {
      this.id = uniqId();
    }
  }
  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);
        this.optionsParsed = [];
      }
    }
    if (changedProperties.has("value") && !!this.value) {
      try {
        const value = JSON.parse(this.value);
        this.valueParsed = Array.isArray(value) ? value : [value];
      } catch (error) {
        console.warn("Could not parse value", error);
      }
    }
  }
  inputTemplate() {
    const inputStyles = this.inputStyles({
      isFullWidth: this.isFullWidth,
      isDisabled: this.isDisabled,
      hasError: !!this.error,
      borderless: this.borderless,
      size: this.size
    });
    return x`
      <div
        id=${this.id}
        data-testid=${this.id ? `select-${this.id}` : "select"}
        class=${inputStyles}
        @blur=${this.handleBlur}
        @click=${this.handleClick}
      >
        ${this.placeholder ? this.placeholder : A}
        ${!this.placeholder && this.valueParsed?.length ? this.selectedValueTemplate() : A}
        ${this.showSelectionCounter && this.valueParsed?.length ? this.selectedOptionsCounterTemplate() : A}
      </div>
    `;
  }
  selectedOptionsCounterTemplate() {
    const counterStyles = this.counterStyles({
      isDisabled: this.isDisabled,
      size: this.size
    });
    return x`<div class=${counterStyles}>${this.valueParsed?.length}</div>`;
  }
  labelTemplate() {
    return x`
      <div class="heading-inter-14-bold text-neutral-20 pb-2 block">
        ${this.label}
      </div>
    `;
  }
  descriptionTemplate() {
    return x`
      <div class="paragraph-inter-12-regular text-neutral-20 pb-2">
        ${this.description ?? A}
      </div>
    `;
  }
  errorTemplate() {
    return 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 ("values" in option[1]) {
        optionTemplates.push(this.optionGroupedStringTemplate(option[1], index));
      } else if ("value" in option[1]) {
        optionTemplates.push(this.optionStringTemplate(option[1], index));
      } else if ("address" in option[1]) {
        optionTemplates.push(this.optionProfileTemplate(option[1], index));
      } else {
        console.error("Unknown option type", option);
      }
    }
    return x`<lukso-dropdown
      size=${this.size}
      is-open
      is-open-on-outside-click
      ?is-right=${this.isRight}
      ?open-top=${this.openTop}
      >${optionTemplates}</lukso-dropdown
    >`;
  }
  optionGroupedStringTemplate(option, index) {
    return x`<div
        class="paragraph-inter-10-bold-uppercase text-neutral-20 p-1"
      >
        ${option.group}
      </div>
      ${option.values.map((value, valueIndex) => {
      return this.optionStringTemplate(
        { id: `${option.id}-${valueIndex}`, group: option.group, value },
        index
      );
    })}`;
  }
  optionStringTemplate(option, index) {
    return x`<lukso-dropdown-option
      data-id="${option.id}"
      data-index="${index + 1}"
      ?is-selected=${!!this.valueParsed?.find((value) => value.id === option.id)}
      ?is-active=${this.selected === index + 1 && !this.valueParsed?.find((value) => value.id === option.id)}
      size=${this.size}
      ?is-group=${!!option.group}
      ?is-disabled=${this.isDisabled}
      ?is-readonly=${this.isReadonly}
      @click=${() => this.handleSelect(option)}
    >
      ${this.optionStringValue(option)}
    </lukso-dropdown-option>`;
  }
  optionProfileTemplate(option, index) {
    return x`<lukso-dropdown-option
      data-id="${option.id}"
      data-index="${index + 1}"
      ?is-selected=${!!this.valueParsed?.find((value) => value.id === option.id)}
      ?is-active=${this.selected === index + 1 && !this.valueParsed?.find((value) => value.id === option.id)}
      size=${this.size}
      ?is-disabled=${this.isDisabled}
      ?is-readonly=${this.isReadonly}
      @click=${() => this.handleSelect(option)}
    >
      ${this.optionProfileValue(option)}
    </lukso-dropdown-option>`;
  }
  optionStringValue(option) {
    return option.value;
  }
  optionProfileValue(option) {
    return x`<lukso-profile
        profile-address="${option.address}"
        profile-url="${option.image}"
        size="x-small"
        has-identicon
        class="mr-2"
      ></lukso-profile>
      <lukso-username
        name="${option.name?.toLowerCase()}"
        address="${option.address}"
        name-color="neutral-20"
        max-width="150"
        slice-by="4"
        size=${this.size}
      ></lukso-username>`;
  }
  selectedValueTemplate() {
    const firstOption = this.optionsParsed[0];
    if (!firstOption) {
      return "";
    }
    if ("value" in firstOption) {
      const foundValues = this.optionsParsed.filter(
        (option) => !!this.valueParsed?.find((value) => value.id === option.id)
      );
      return foundValues.map((value) => this.optionStringValue(value)).join(", ");
    }
    if ("values" in firstOption) {
      const foundValues = [];
      for (const option of this.optionsParsed) {
        for (const [index, value] of option.values.entries()) {
          for (const parsedValue of this.valueParsed) {
            if (parsedValue.id === `${option.id}-${index}`) {
              foundValues.push({
                id: `${option.id}-${index}`,
                value
              });
            }
          }
        }
      }
      return foundValues.map((value) => this.optionStringValue(value)).join(", ");
    }
    if ("address" in firstOption) {
      const foundValues = this.optionsParsed.filter(
        (option) => !!this.valueParsed?.find((value) => value.id === option.id)
      );
      const optionProfileValues = [];
      for (const value of foundValues) {
        optionProfileValues.push(
          this.optionProfileValue(value)
        );
      }
      return optionProfileValues;
    }
    console.error("Unknown value type", this.valueParsed);
    return "";
  }
  handleOutsideDropdownClick(event) {
    const element = event.target;
    if (element.tagName === "LUKSO-SELECT" && this.id === element.id) {
      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);
      }
    }
    if (event.key === "Escape") {
      this.isOpen = false;
    }
  }
  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() {
    const iconStyles = this.iconStyles({
      isDisabled: this.isDisabled,
      isOpen: this.isOpen,
      size: this.size
    });
    return x`
      <div class="relative w-[inherit]">
        ${this.label ? this.labelTemplate() : A}
        ${this.description ? this.descriptionTemplate() : A}
        <div class="group">
          <div class="flex relative items-center">
            ${this.inputTemplate()}<lukso-icon
              name=${this.isLargeIcon ? "arrow-down-lg" : "arrow-down-sm"}
              class="${iconStyles}"
              @click=${this.handleClick}
            ></lukso-icon>
          </div>
          <!-- options dropdown -->
          ${this.isOpen && this.optionsParsed.length > 0 ? this.optionsTemplate() : A}
        </div>
        <!-- error -->
        ${this.error ? this.errorTemplate() : A}
      </div>
    `;
  }
};
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "value", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "placeholder", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "label", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "id", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "description", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "error", 2);
__decorateClass([
  n({ type: Boolean, attribute: "is-full-width" })
], LuksoSelect.prototype, "isFullWidth", 2);
__decorateClass([
  n({ type: Boolean, attribute: "is-readonly" })
], LuksoSelect.prototype, "isReadonly", 2);
__decorateClass([
  n({ type: Boolean, attribute: "is-disabled" })
], LuksoSelect.prototype, "isDisabled", 2);
__decorateClass([
  n({ type: Boolean })
], LuksoSelect.prototype, "borderless", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "options", 2);
__decorateClass([
  n({ type: Number })
], LuksoSelect.prototype, "selected", 2);
__decorateClass([
  n({ type: Boolean, attribute: "is-open" })
], LuksoSelect.prototype, "isOpen", 2);
__decorateClass([
  n({ type: Boolean, attribute: "open-top" })
], LuksoSelect.prototype, "openTop", 2);
__decorateClass([
  n({ type: Boolean, attribute: "is-large-icon" })
], LuksoSelect.prototype, "isLargeIcon", 2);
__decorateClass([
  n({ type: Boolean, attribute: "is-right" })
], LuksoSelect.prototype, "isRight", 2);
__decorateClass([
  n({ type: String })
], LuksoSelect.prototype, "size", 2);
__decorateClass([
  n({ type: Boolean, attribute: "show-selection-counter" })
], LuksoSelect.prototype, "showSelectionCounter", 2);
__decorateClass([
  t()
], LuksoSelect.prototype, "optionsParsed", 2);
__decorateClass([
  t()
], LuksoSelect.prototype, "valueParsed", 2);
LuksoSelect = __decorateClass([
  e("lukso-select")
], LuksoSelect);

export { LuksoSelect };
