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 telInputCss = "*,*::before,*::after{padding:0;margin:0;box-sizing:border-box}.tel{font-family:\"Roboto\";font-style:normal}.tel__wrapper{position:relative;width:100%;display:flex;flex-direction:column;gap:5px}.tel__wrapper--autofilled{pointer-events:none}.tel__wrapper--autofilled .tel__label{color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000))}.tel__wrapper--autofilled .tel__input::part(input-field){color:var(--emfe-w-color-black, #000000)}.tel__wrapper--flex{width:inherit;display:flex;align-items:center;border-radius:4px;border:1px solid var(--emfe-w-color-gray-100, #E6E6E6);background-color:var(--emfe-w-color-white, #FFFFFF);overflow:hidden}.tel__wrapper--flex:focus-within{border-color:var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C))}.tel__wrapper--flex--invalid{border:1px solid var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909))}.tel__wrapper--flex-label{display:flex;gap:5px}.tel__wrapper--flex--relative{position:relative}.tel__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))}.tel__label--required::after{content:\"*\";font-family:inherit;color:var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C));margin-left:2px}.tel__prefix{--vaadin-field-default-width:90px}.tel__prefix[focus]{outline:none}.tel__prefix::part(input-field){border-radius:0 5px 5px 0;background-color:var(--emfe-w-color-white, #FFFFFF);color:var(--emfe-w-color-black, #000000);font-family:inherit;font-style:normal;font-weight:300;font-size:16px;line-height:1.5;border:none;border-right:2px solid #DDE0EE;border-image-source:linear-gradient(to bottom, rgba(221, 224, 238, 0) 25%, #dde0ee 25%, #dde0ee 75%, rgba(221, 224, 238, 0) 75%);border-image-slice:1;border-image-repeat:round}.tel__prefix::part(input-field):hover{background-color:var(--emfe-w-color-white, #FFFFFF)}.tel__prefix::part(toggle-button){color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000))}.tel__input{font-family:inherit;border-radius:5px;width:100%;color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000));background-color:var(--emfe-w-color-white, #FFFFFF);border:none;width:inherit;position:relative;font-size:16px;font-weight:300;line-height:1.5;padding:5px 15px;height:42px;-moz-appearance:textfield;}.tel__input:focus{outline:none}.tel__input::-webkit-outer-spin-button,.tel__input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.tel__input::placeholder{color:var(--emfe-w-color-gray-150, #979797)}.tel__error-message{position:absolute;top:calc(100% + 5px);left:0;color:var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909))}.tel__tooltip-icon{width:16px;height:auto}.tel__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}.tel__tooltip.visible{opacity:1}";

const TelInput = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.sendValidityState = createEvent(this, "sendValidityState", 7);
    this.sendInputValue = createEvent(this, "sendInputValue", 7);
    /**
     * Client custom styling via inline style
     */
    this.clientStyling = '';
    this.limitStylingAppends = false;
    this.showTooltip = false;
    this.validationPattern = '';
    this.touched = false;
    this.handleInput = (event) => {
      this.phoneValue = event.target.value;
      this.value = { prefix: this.prefixValue, phone: this.phoneValue };
      this.touched = true;
      if (this.debounceTime) {
        clearTimeout(this.debounceTime);
      }
      this.debounceTime = setTimeout(() => {
        this.isValid = this.setValidity();
        this.errorMessage = this.setErrorMessage();
        this.emitValueHandler(true);
      }, 500);
    };
    this.handleBlur = () => {
      this.isValid = this.setValidity();
      this.touched = true;
      this.errorMessage = this.setErrorMessage();
    };
    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, type: 'tel' });
    }
  }
  validityStateHandler(inputStateEvent) {
    this.sendValidityState.emit(inputStateEvent);
  }
  emitValueHandler(newValue) {
    if (newValue == true && this.isValid) {
      this.valueHandler({ name: this.name, value: this.value, type: 'tel' });
    }
  }
  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.validationPattern = this.setPattern();
    if (this.defaultValue) {
      this.prefixValue = this.defaultValue.prefix ? this.defaultValue.prefix : this.defaultValue;
      this.phoneValue = this.defaultValue.phone || null;
    }
  }
  componentWillLoad() {
    if (this.action) {
      if (this.action.split(" ")[0] == 'GET') {
        const endpoint = this.action.split(" ")[1];
        return this.getPhoneCodes(endpoint).then((options) => {
          this.phoneCodesOptions = options.phoneCodes.map(code => {
            return { label: code.Prefix, value: code.Prefix };
          });
        });
      }
    }
  }
  componentDidRender() {
    // start custom styling area
    if (!this.limitStylingAppends && this.stylingContainer) {
      if (this.clientStyling)
        this.setClientStyling();
      this.limitStylingAppends = true;
    }
    // end custom styling area
  }
  componentDidLoad() {
    this.isValid = this.setValidity();
    if (this.defaultValue) {
      this.value = this.defaultValue;
      this.valueHandler({ name: this.name, value: this.value, type: 'tel' });
    }
  }
  getPhoneCodes(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);
      });
    });
  }
  handlePrefixInput(event) {
    this.prefixValue = event.target.value;
    this.value = { prefix: this.prefixValue, phone: this.phoneValue };
    this.emitValueHandler(true);
  }
  setValidity() {
    return this.inputReference.validity.valid;
  }
  setPattern() {
    var _a, _b;
    if (((_a = this.validation.custom) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      return (_b = this.validation.custom.find(customValidation => customValidation.rule === 'regex')) === null || _b === void 0 ? void 0 : _b.pattern;
    }
  }
  setErrorMessage() {
    var _a, _b;
    if (this.inputReference.validity.patternMismatch) {
      const errorCode = (_a = this.validation.custom.find(customValidation => customValidation.rule === 'regex')) === null || _a === void 0 ? void 0 : _a.errorKey;
      const errorMessage = (_b = this.validation.custom.find(customValidation => customValidation.rule === 'regex')) === null || _b === void 0 ? void 0 : _b.errorMessage;
      return translate(`${errorCode}`, this.language) ? translate(`${errorCode}`, this.language) : errorMessage;
    }
    if (this.inputReference.validity.tooShort || this.inputReference.validity.tooLong) {
      return translate('lengthError', this.language, { values: { minLength: this.validation.minLength, maxLength: this.validation.maxLength } });
    }
    if (this.inputReference.validity.valueMissing) {
      return translate('requiredError', this.language);
    }
  }
  renderTooltip() {
    if (this.showTooltip) {
      return (h("div", { class: `tel__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: `tel__wrapper ${this.autofilled ? 'tel__wrapper--autofilled' : ''} ${this.name}__input`, ref: el => this.stylingContainer = el }, h("div", { class: 'tel__wrapper--flex-label' }, h("label", { class: `tel__label ${this.validation.mandatory ? 'tel__label--required' : ''}`, htmlFor: `${this.name}__input` }, this.displayName), h("div", { class: 'tel__wrapper--relative' }, this.tooltip &&
      h("img", { class: 'tel__tooltip-icon', src: tooltipIconSvg, alt: "", ref: (el) => this.tooltipIconReference = el, onClick: () => this.showTooltip = !this.showTooltip }), this.renderTooltip())), h("div", { class: `tel__wrapper--flex ${invalidClass}` }, h("vaadin-combo-box", { class: 'tel__prefix', items: this.phoneCodesOptions, value: this.prefixValue, readOnly: this.autofilled, onChange: (e) => this.handlePrefixInput(e) }), h("input", { type: "tel", ref: (el) => this.inputReference = el, id: `${this.name}__input`, readOnly: this.autofilled, class: `tel__input`, value: this.phoneValue, placeholder: `${this.placeholder}`, required: this.validation.mandatory, minlength: this.validation.minLength, maxlength: this.validation.maxLength, pattern: this.validationPattern, onInput: this.handleInput, onBlur: this.handleBlur })), h("small", { class: 'tel__error-message' }, this.errorMessage));
  }
  static get watchers() { return {
    "isValid": ["validityChanged"],
    "emitValue": ["emitValueHandler"]
  }; }
  static get style() { return telInputCss; }
}, [1, "tel-input", {
    "name": [513],
    "displayName": [513, "display-name"],
    "placeholder": [513],
    "showLabels": [516, "show-labels"],
    "action": [513],
    "validation": [16],
    "defaultValue": [520, "default-value"],
    "autofilled": [516],
    "tooltip": [513],
    "language": [513],
    "emitValue": [516, "emit-value"],
    "clientStyling": [513, "client-styling"],
    "isValid": [32],
    "errorMessage": [32],
    "limitStylingAppends": [32],
    "showTooltip": [32]
  }, [[4, "click", "handleClickOutside"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["tel-input"];
  components.forEach(tagName => { switch (tagName) {
    case "tel-input":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, TelInput);
      }
      break;
  } });
}

export { TelInput as T, defineCustomElement as d };
