import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { t as translate, a as tooltipIconSvg } from './tooltipIcon.js';
import './input-field-shared-styles.js';
import './vaadin-combo-box.js';

const selectInputCss = "*,*::before,*::after{padding:0;margin:0;box-sizing:border-box}:host{height:100%}vaadin-combo-box>input{background-color:var(--emfe-w-color-white, #FFFFFF);color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000));font-weight:300;font-size:16px;-webkit-font-smoothing:initial;}.select{font-family:\"Roboto\";font-style:normal}.select__wrapper{position:relative;width:100%;display:flex;flex-direction:column;gap:5px}.select__wrapper--autofilled{pointer-events:none}.select__wrapper--autofilled .select__label{color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000))}.select__wrapper--autofilled .select__input::part(input-field){color:var(--emfe-w-color-black, #000000)}.select__wrapper--flex{display:flex;gap:5px}.select__wrapper--relative{position:relative}.select__label{font-family:inherit;font-style:normal;font-weight:500;font-size:16px;line-height:20px;color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000))}.select__label--required::after{content:\"*\";font-family:inherit;color:var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C));margin-left:2px}.select__input{border:none;width:inherit;position:relative}.select__input[focused]::part(input-field){border-color:var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C))}.select__input[invalid]::part(input-field){border:1px solid var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909))}.select__input vaadin-date-picker-overlay-content>vaadin-button{color:var(--emfe-w-color-black, #000000)}.select__input::part(input-field){border-radius:4px;background-color:var(--emfe-w-color-white, #FFFFFF);border:1px solid var(--emfe-w-color-gray-100, #E6E6E6);color:var(--emfe-w-color-black, #000000);font-family:inherit;font-style:normal;font-size:16px;font-weight:300;line-height:1.5;padding:0;height:44px}.select__input::part(toggle-button){position:relative;right:10px}.select__input>input{padding:5px 15px}.select__error-message{position:absolute;top:calc(100% + 5px);left:0;color:var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909))}.select__tooltip-icon{width:16px;height:auto}.select__tooltip{position:absolute;top:0;left:20px;background-color:var(--emfe-w-color-white, #FFFFFF);border:1px solid var(--emfe-w-color-gray-100, #E6E6E6);color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000));padding:10px;border-radius:5px;opacity:0;transition:opacity 0.3s ease-in-out;z-index:10}.select__tooltip.visible{opacity:1}";

const SelectInput = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.sendValidityState = createEvent(this, "sendValidityState", 7);
    this.sendInputValue = createEvent(this, "sendInputValue", 7);
    /**
     * Default value for the input.
     */
    this.defaultValue = '';
    /**
     * Options of the input.
     */
    this.options = [];
    /**
     * Client custom styling via inline style
     */
    this.clientStyling = '';
    this.limitStylingAppends = false;
    this.showTooltip = false;
    this.touched = false;
    this.handleChange = (event) => {
      this.touched = true;
      const selectedValue = event.target.value;
      // Find the original option based on case-insensitive comparison
      const originalOption = this.options.find(option => option.value.toLowerCase() === selectedValue.toLowerCase());
      if (originalOption) {
        this.value = originalOption.value;
      }
      else {
        this.value = selectedValue;
      }
      this.isValid = this.setValidity();
      this.errorMessage = this.setErrorMessage();
      this.emitValueHandler(true);
    };
    this.setClientStyling = () => {
      let sheet = document.createElement('style');
      sheet.innerHTML = this.clientStyling;
      this.stylingContainer.prepend(sheet);
    };
  }
  validityChanged() {
    this.validityStateHandler({ valid: this.isValid, name: this.name });
    if (this.emitValue == true) {
      this.valueHandler({ name: this.name, value: this.value });
    }
  }
  validityStateHandler(inputStateEvent) {
    this.sendValidityState.emit(inputStateEvent);
  }
  emitValueHandler(newValue) {
    if (newValue == true && this.isValid) {
      this.valueHandler({ name: this.name, value: this.value });
    }
  }
  valueHandler(inputValueEvent) {
    this.sendInputValue.emit(inputValueEvent);
  }
  handleClickOutside(event) {
    if (event.composedPath()[0] === this.tooltipIconReference)
      return;
    if (event.composedPath()[0] !== this.tooltipReference)
      this.showTooltip = false;
  }
  connectedCallback() {
    this.displayedOptions = this.options.map(option => ({
      label: option.label,
      value: option.value.toUpperCase()
    }));
  }
  componentWillLoad() {
    if (this.action && !this.options.length) {
      if (this.action.split(" ")[0] == 'GET') {
        const endpoint = this.action.split(" ")[1];
        return this.getOptions(endpoint).then((options) => {
          const firstKey = Object.keys(options)[0];
          this.displayedOptions = options[firstKey].map(option => {
            return { label: option.Name, value: option.Alpha2Code };
          });
        });
      }
    }
  }
  componentDidRender() {
    // start custom styling area
    if (!this.limitStylingAppends && this.stylingContainer) {
      if (this.clientStyling)
        this.setClientStyling();
      this.limitStylingAppends = true;
    }
    // end custom styling area
  }
  componentDidLoad() {
    this.inputReference = this.element.shadowRoot.querySelector('input');
    this.isValid = this.setValidity();
    if (this.defaultValue) {
      this.value = this.defaultValue.toUpperCase();
      this.valueHandler({ name: this.name, value: this.value });
    }
  }
  getOptions(endpoint) {
    const url = new URL(endpoint);
    return new Promise((resolve, reject) => {
      fetch(url.href)
        .then((res) => res.json())
        .then((options) => {
        resolve(options);
      }).catch((err) => {
        console.error(err);
        reject(err);
      });
    });
  }
  setValidity() {
    return this.inputReference.validity.valid;
  }
  setErrorMessage() {
    if (this.inputReference.validity.valueMissing) {
      return translate('requiredError', this.language);
    }
  }
  renderTooltip() {
    if (this.showTooltip) {
      return (h("div", { class: `select__tooltip ${this.showTooltip ? 'visible' : ''}`, ref: (el) => this.tooltipReference = el, innerHTML: this.tooltip }));
    }
    return null;
  }
  render() {
    let invalidClass = '';
    if (this.touched) {
      invalidClass = this.isValid == true || this.isValid == undefined ? '' : 'text__input--invalid';
    }
    return h("div", { class: `select__wrapper ${this.autofilled ? 'select__wrapper--autofilled' : ''}  ${this.name}__input`, ref: el => this.stylingContainer = el }, h("div", { class: 'select__wrapper--flex' }, h("label", { class: 'select__label', htmlFor: `${this.name}__input` }, `${this.displayName} ${this.validation.mandatory ? '*' : ''}`), h("div", { class: 'select__wrapper--relative' }, this.tooltip &&
      h("img", { class: 'select__tooltip-icon', src: tooltipIconSvg, alt: "", ref: (el) => this.tooltipIconReference = el, onClick: () => this.showTooltip = !this.showTooltip }), this.renderTooltip())), h("vaadin-combo-box", { name: this.name, id: `${this.name}__input`, class: `select__input ${invalidClass} ${this.autofilled ? 'select__input--autofilled' : ''}`, "item-label-path": "label", "item-value-path": "value", readOnly: this.autofilled, required: this.validation.mandatory, value: this.defaultValue, placeholder: `${this.placeholder}`, items: this.displayedOptions, onChange: this.handleChange }), h("small", { class: 'select__error-message' }, this.errorMessage));
  }
  get element() { return this; }
  static get watchers() { return {
    "isValid": ["validityChanged"],
    "emitValue": ["emitValueHandler"]
  }; }
  static get style() { return selectInputCss; }
}, [1, "select-input", {
    "name": [513],
    "displayName": [513, "display-name"],
    "placeholder": [513],
    "action": [513],
    "defaultValue": [513, "default-value"],
    "autofilled": [516],
    "tooltip": [513],
    "options": [16],
    "validation": [16],
    "language": [513],
    "emitValue": [516, "emit-value"],
    "clientStyling": [513, "client-styling"],
    "errorMessage": [32],
    "isValid": [32],
    "limitStylingAppends": [32],
    "showTooltip": [32]
  }, [[4, "click", "handleClickOutside"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["select-input"];
  components.forEach(tagName => { switch (tagName) {
    case "select-input":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SelectInput);
      }
      break;
  } });
}

export { SelectInput as S, defineCustomElement as d };
