import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { t as translate, a as tooltipIconSvg } from './tooltipIcon.js';
import { i as inputFieldShared, c as InputControlMixin, d as inputFieldShared$1 } from './input-field-shared-styles.js';
import { r as registerStyles, c as InputController, e as LabelledInputController, h as html, T as TooltipController, f as defineCustomElement$1, g as ThemableMixin, E as ElementMixin, P as PolymerElement, i, G as SlotController } from './field-mixin.js';
import { b as button, B as Button } from './vaadin-button.js';

/**
 * @license
 * Copyright (c) 2017 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

registerStyles('vaadin-text-field', inputFieldShared, {
  moduleId: 'lumo-text-field-styles',
});

/**
 * @license
 * Copyright (c) 2021 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

/**
 * A mixin to provide logic for vaadin-text-field and related components.
 *
 * @polymerMixin
 * @mixes InputControlMixin
 */
const InputFieldMixin = (superclass) =>
  class InputFieldMixinClass extends InputControlMixin(superclass) {
    static get properties() {
      return {
        /**
         * Whether the value of the control can be automatically completed by the browser.
         * List of available options at:
         * https://developer.mozilla.org/en/docs/Web/HTML/Element/input#attr-autocomplete
         */
        autocomplete: {
          type: String,
        },

        /**
         * This is a property supported by Safari that is used to control whether
         * autocorrection should be enabled when the user is entering/editing the text.
         * Possible values are:
         * on: Enable autocorrection.
         * off: Disable autocorrection.
         */
        autocorrect: {
          type: String,
        },

        /**
         * This is a property supported by Safari and Chrome that is used to control whether
         * autocapitalization should be enabled when the user is entering/editing the text.
         * Possible values are:
         * characters: Characters capitalization.
         * words: Words capitalization.
         * sentences: Sentences capitalization.
         * none: No capitalization.
         */
        autocapitalize: {
          type: String,
          reflectToAttribute: true,
        },
      };
    }

    static get delegateAttrs() {
      return [...super.delegateAttrs, 'autocapitalize', 'autocomplete', 'autocorrect'];
    }

    // Workaround for https://github.com/Polymer/polymer/issues/5259
    get __data() {
      return this.__dataValue || {};
    }

    set __data(value) {
      this.__dataValue = value;
    }

    /**
     * @param {HTMLElement} input
     * @protected
     * @override
     */
    _inputElementChanged(input) {
      super._inputElementChanged(input);

      if (input) {
        // Discard value set on the custom slotted input.
        if (input.value && input.value !== this.value) {
          console.warn(`Please define value on the <${this.localName}> component!`);
          input.value = '';
        }

        if (this.value) {
          input.value = this.value;
        }
      }
    }

    /**
     * Override an event listener from `FocusMixin`.
     * @param {boolean} focused
     * @protected
     * @override
     */
    _setFocused(focused) {
      super._setFocused(focused);

      // Do not validate when focusout is caused by document
      // losing focus, which happens on browser tab switch.
      if (!focused && document.hasFocus()) {
        this.validate();
      }
    }

    /**
     * Override an event listener from `InputMixin`
     * to mark as valid after user started typing.
     * @param {Event} event
     * @protected
     * @override
     */
    _onInput(event) {
      super._onInput(event);

      if (this.invalid) {
        this.validate();
      }
    }

    /**
     * Override an observer from `InputMixin` to validate the field
     * when a new value is set programmatically.
     *
     * @param {string | undefined} newValue
     * @param {string | undefined} oldValue
     * @protected
     * @override
     */
    _valueChanged(newValue, oldValue) {
      super._valueChanged(newValue, oldValue);

      if (oldValue === undefined) {
        return;
      }

      if (this.invalid) {
        this.validate();
      }
    }
  };

/**
 * @license
 * Copyright (c) 2021 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

/**
 * A mixin providing common text field functionality.
 *
 * @polymerMixin
 * @mixes InputFieldMixin
 */
const TextFieldMixin = (superClass) =>
  class TextFieldMixinClass extends InputFieldMixin(superClass) {
    static get properties() {
      return {
        /**
         * Maximum number of characters (in Unicode code points) that the user can enter.
         */
        maxlength: {
          type: Number,
        },

        /**
         * Minimum number of characters (in Unicode code points) that the user can enter.
         */
        minlength: {
          type: Number,
        },

        /**
         * A regular expression that the value is checked against.
         * The pattern must match the entire value, not just some subset.
         */
        pattern: {
          type: String,
        },
      };
    }

    static get delegateAttrs() {
      return [...super.delegateAttrs, 'maxlength', 'minlength', 'pattern'];
    }

    static get constraints() {
      return [...super.constraints, 'maxlength', 'minlength', 'pattern'];
    }

    constructor() {
      super();
      this._setType('text');
    }

    /** @protected */
    get clearElement() {
      return this.$.clearButton;
    }

    /** @protected */
    ready() {
      super.ready();

      this.addController(
        new InputController(this, (input) => {
          this._setInputElement(input);
          this._setFocusElement(input);
          this.stateTarget = input;
          this.ariaTarget = input;
        }),
      );
      this.addController(new LabelledInputController(this.inputElement, this._labelController));
    }
  };

/**
 * @license
 * Copyright (c) 2017 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

registerStyles('vaadin-text-field', inputFieldShared$1, { moduleId: 'vaadin-text-field-styles' });

/**
 * `<vaadin-text-field>` is a web component that allows the user to input and edit text.
 *
 * ```html
 * <vaadin-text-field label="First Name"></vaadin-text-field>
 * ```
 *
 * ### Prefixes and suffixes
 *
 * These are child elements of a `<vaadin-text-field>` that are displayed
 * inline with the input, before or after.
 * In order for an element to be considered as a prefix, it must have the slot
 * attribute set to `prefix` (and similarly for `suffix`).
 *
 * ```html
 * <vaadin-text-field label="Email address">
 *   <div slot="prefix">Sent to:</div>
 *   <div slot="suffix">@vaadin.com</div>
 * </vaadin-text-field>
 * ```
 *
 * ### Styling
 *
 * The following custom properties are available for styling:
 *
 * Custom property                | Description                | Default
 * -------------------------------|----------------------------|---------
 * `--vaadin-field-default-width` | Default width of the field | `12em`
 *
 * The following shadow DOM parts are available for styling:
 *
 * Part name            | Description
 * ---------------------|----------------
 * `label`              | The label element
 * `input-field`        | The element that wraps prefix, value and suffix
 * `clear-button`       | The clear button
 * `error-message`      | The error message element
 * `helper-text`        | The helper text element wrapper
 * `required-indicator` | The `required` state indicator element
 *
 * The following state attributes are available for styling:
 *
 * Attribute           | Description | Part name
 * --------------------|-------------|------------
 * `disabled`          | Set to a disabled text field | :host
 * `has-value`         | Set when the element has a value | :host
 * `has-label`         | Set when the element has a label | :host
 * `has-helper`        | Set when the element has helper text or slot | :host
 * `has-error-message` | Set when the element has an error message | :host
 * `invalid`           | Set when the element is invalid | :host
 * `input-prevented`   | Temporarily set when invalid input is prevented | :host
 * `focused`           | Set when the element is focused | :host
 * `focus-ring`        | Set when the element is keyboard focused | :host
 * `readonly`          | Set to a readonly text field | :host
 *
 * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.
 *
 * @fires {Event} input - Fired when the value is changed by the user: on every typing keystroke, and the value is cleared using the clear button.
 * @fires {Event} change - Fired when the user commits a value change.
 * @fires {CustomEvent} invalid-changed - Fired when the `invalid` property changes.
 * @fires {CustomEvent} value-changed - Fired when the `value` property changes.
 * @fires {CustomEvent} validated - Fired whenever the field is validated.
 *
 * @customElement
 * @extends HTMLElement
 * @mixes ElementMixin
 * @mixes ThemableMixin
 * @mixes TextFieldMixin
 */
class TextField extends TextFieldMixin(ThemableMixin(ElementMixin(PolymerElement))) {
  static get is() {
    return 'vaadin-text-field';
  }

  static get template() {
    return html`
      <style>
        [part='input-field'] {
          flex-grow: 0;
        }
      </style>

      <div class="vaadin-field-container">
        <div part="label">
          <slot name="label"></slot>
          <span part="required-indicator" aria-hidden="true" on-click="focus"></span>
        </div>

        <vaadin-input-container
          part="input-field"
          readonly="[[readonly]]"
          disabled="[[disabled]]"
          invalid="[[invalid]]"
          theme$="[[_theme]]"
        >
          <slot name="prefix" slot="prefix"></slot>
          <slot name="input"></slot>
          <slot name="suffix" slot="suffix"></slot>
          <div id="clearButton" part="clear-button" slot="suffix" aria-hidden="true"></div>
        </vaadin-input-container>

        <div part="helper-text">
          <slot name="helper"></slot>
        </div>

        <div part="error-message">
          <slot name="error-message"></slot>
        </div>
      </div>
      <slot name="tooltip"></slot>
    `;
  }

  static get properties() {
    return {
      /**
       * Maximum number of characters (in Unicode code points) that the user can enter.
       */
      maxlength: {
        type: Number,
      },

      /**
       * Minimum number of characters (in Unicode code points) that the user can enter.
       */
      minlength: {
        type: Number,
      },
    };
  }

  /** @protected */
  ready() {
    super.ready();

    this._tooltipController = new TooltipController(this);
    this._tooltipController.setPosition('top');
    this._tooltipController.setAriaTarget(this.inputElement);
    this.addController(this._tooltipController);
  }
}

defineCustomElement$1(TextField);

/**
 * @license
 * Copyright (c) 2021 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

const passwordFieldButton = i`
  :host {
    position: absolute;
    right: 0;
    top: 0;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    min-width: auto;
    background: transparent;
    outline: none;
  }
`;

registerStyles('vaadin-password-field-button', [button, passwordFieldButton], {
  moduleId: 'lumo-password-field-button',
});

/**
 * @license
 * Copyright (c) 2021 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

const passwordField = i`
  [part='reveal-button']::before {
    content: var(--lumo-icons-eye);
  }

  :host([password-visible]) [part='reveal-button']::before {
    content: var(--lumo-icons-eye-disabled);
  }

  /* Make it easy to hide the button across the whole app */
  [part='reveal-button'] {
    position: relative;
    display: var(--lumo-password-field-reveal-button-display, block);
  }

  [part='reveal-button'][hidden] {
    display: none !important;
  }
`;

registerStyles('vaadin-password-field', [inputFieldShared, passwordField], { moduleId: 'lumo-password-field' });

/**
 * @license
 * Copyright (c) 2021 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

/**
 * An element used internally by `<vaadin-password-field>`. Not intended to be used separately.
 *
 * @customElement
 * @extends Button
 * @private
 */
class PasswordFieldButton extends Button {
  static get is() {
    return 'vaadin-password-field-button';
  }

  static get template() {
    return html`
      <style>
        :host {
          display: block;
        }

        :host([hidden]) {
          display: none !important;
        }
      </style>
      <slot name="tooltip"></slot>
    `;
  }
}

defineCustomElement$1(PasswordFieldButton);

/**
 * @license
 * Copyright (c) 2021 - 2023 Vaadin Ltd.
 * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
 */

const ownTemplate = html`
  <div part="reveal-button" slot="suffix">
    <slot name="reveal"></slot>
  </div>
`;

let memoizedTemplate;

/**
 * `<vaadin-password-field>` is an extension of `<vaadin-text-field>` component for entering passwords.
 *
 * ```html
 * <vaadin-password-field label="Password"></vaadin-password-field>
 * ```
 *
 * ### Styling
 *
 * `<vaadin-password-field>` provides the same set of shadow DOM parts and state attributes as `<vaadin-text-field>`.
 * See [`<vaadin-text-field>`](#/elements/vaadin-text-field) for the styling documentation.
 *
 * In addition to `<vaadin-text-field>` parts, the following parts are available for theming:
 *
 * Part name       | Description
 * ----------------|----------------------------------------------------
 * `reveal-button` | The eye icon which toggles the password visibility
 *
 * In addition to `<vaadin-text-field>` state attributes, the following state attributes are available for theming:
 *
 * Attribute          | Description
 * -------------------|---------------------------------
 * `password-visible` | Set when the password is visible
 *
 * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.
 *
 * @fires {Event} input - Fired when the value is changed by the user: on every typing keystroke, and the value is cleared using the clear button.
 * @fires {Event} change - Fired when the user commits a value change.
 * @fires {CustomEvent} invalid-changed - Fired when the `invalid` property changes.
 * @fires {CustomEvent} value-changed - Fired when the `value` property changes.
 * @fires {CustomEvent} validated - Fired whenever the field is validated.
 *
 * @customElement
 * @extends TextField
 */
class PasswordField extends TextField {
  static get is() {
    return 'vaadin-password-field';
  }

  static get template() {
    if (!memoizedTemplate) {
      // Clone the superclass template
      memoizedTemplate = super.template.cloneNode(true);

      // Retrieve this element's dom-module template
      const revealButton = ownTemplate.content.querySelector('[part="reveal-button"]');

      // Append reveal-button and styles to the text-field template
      const inputField = memoizedTemplate.content.querySelector('[part="input-field"]');
      inputField.appendChild(revealButton);
    }

    return memoizedTemplate;
  }

  static get properties() {
    return {
      /**
       * Set to true to hide the eye icon which toggles the password visibility.
       * @attr {boolean} reveal-button-hidden
       */
      revealButtonHidden: {
        type: Boolean,
        observer: '_revealButtonHiddenChanged',
        value: false,
      },

      /**
       * True if the password is visible ([type=text]).
       * @attr {boolean} password-visible
       */
      passwordVisible: {
        type: Boolean,
        value: false,
        reflectToAttribute: true,
        observer: '_passwordVisibleChanged',
        readOnly: true,
      },

      /**
       * An object with translated strings used for localization.
       * It has the following structure and default values:
       *
       * ```
       * {
       *   // Translation of the reveal icon button accessible label
       *   reveal: 'Show password'
       * }
       * ```
       */
      i18n: {
        type: Object,
        value: () => {
          return {
            reveal: 'Show password',
          };
        },
      },
    };
  }

  static get observers() {
    return ['__i18nChanged(i18n.*)'];
  }

  constructor() {
    super();
    this._setType('password');
    this.__boundRevealButtonClick = this._onRevealButtonClick.bind(this);
    this.__boundRevealButtonMouseDown = this._onRevealButtonMouseDown.bind(this);
    this.__lastChange = '';
  }

  /** @protected */
  get slotStyles() {
    const tag = this.localName;
    return [
      ...super.slotStyles,
      `
        ${tag} [slot="input"]::-ms-reveal {
          display: none;
        }
      `,
    ];
  }

  /** @protected */
  get _revealNode() {
    return this._revealButtonController && this._revealButtonController.node;
  }

  /** @protected */
  ready() {
    super.ready();

    this._revealPart = this.shadowRoot.querySelector('[part="reveal-button"]');

    this._revealButtonController = new SlotController(this, 'reveal', 'vaadin-password-field-button', {
      initializer: (btn) => {
        btn.disabled = this.disabled;

        btn.addEventListener('click', this.__boundRevealButtonClick);
        btn.addEventListener('mousedown', this.__boundRevealButtonMouseDown);
      },
    });
    this.addController(this._revealButtonController);

    this.__updateAriaLabel(this.i18n);

    this._updateToggleState(false);
    this._toggleRevealHidden(this.revealButtonHidden);

    if (this.inputElement) {
      this.inputElement.autocapitalize = 'off';
    }
  }

  /**
   * Override an event listener inherited from `InputControlMixin`
   * to store the value at the moment of the native `change` event.
   * @param {Event} event
   * @protected
   * @override
   */
  _onChange(event) {
    super._onChange(event);

    this.__lastChange = this.inputElement.value;
  }

  /**
   * Override method inherited from `FocusMixin` to mark field as focused
   * when focus moves to the reveal button using Shift Tab.
   * @param {Event} event
   * @return {boolean}
   * @protected
   */
  _shouldSetFocus(event) {
    return event.target === this.inputElement || event.target === this._revealNode;
  }

  /**
   * Override method inherited from `FocusMixin` to not hide password
   * when focus moves to the reveal button or back to the input.
   * @param {Event} event
   * @return {boolean}
   * @protected
   */
  _shouldRemoveFocus(event) {
    return !(
      event.relatedTarget === this._revealNode ||
      (event.relatedTarget === this.inputElement && event.target === this._revealNode)
    );
  }

  /**
   * Override method inherited from `FocusMixin` to toggle password visibility.
   * @param {boolean} focused
   * @protected
   * @override
   */
  _setFocused(focused) {
    super._setFocused(focused);

    if (!focused) {
      this._setPasswordVisible(false);

      // Detect if `focusout` was prevented and if so, dispatch `change` event manually.
      if (this.__lastChange !== this.inputElement.value) {
        this.__lastChange = this.inputElement.value;
        this.dispatchEvent(new CustomEvent('change', { bubbles: true }));
      }
    } else {
      const isButtonFocused = this.getRootNode().activeElement === this._revealNode;
      // Remove focus-ring from the field when the reveal button gets focused
      this.toggleAttribute('focus-ring', this._keyboardActive && !isButtonFocused);
    }
  }

  /** @private */
  __updateAriaLabel(i18n) {
    if (i18n.reveal && this._revealNode) {
      this._revealNode.setAttribute('aria-label', i18n.reveal);
    }
  }

  /** @private */
  __i18nChanged(i18n) {
    this.__updateAriaLabel(i18n.base);
  }

  /** @private */
  _revealButtonHiddenChanged(hidden) {
    this._toggleRevealHidden(hidden);
  }

  /** @private */
  _togglePasswordVisibility() {
    this._setPasswordVisible(!this.passwordVisible);
  }

  /** @private */
  _onRevealButtonClick() {
    this._togglePasswordVisibility();
  }

  /** @private */
  _onRevealButtonMouseDown(e) {
    // Cancel the following focusout event
    e.preventDefault();

    // Focus the input to avoid problem with password still visible
    // when user clicks the reveal button and then clicks outside.
    this.inputElement.focus();
  }

  /** @private */
  _toggleRevealHidden(hidden) {
    if (this._revealNode) {
      if (hidden) {
        this._revealPart.setAttribute('hidden', '');
        this._revealNode.setAttribute('tabindex', '-1');
        this._revealNode.setAttribute('aria-hidden', 'true');
      } else {
        this._revealPart.removeAttribute('hidden');
        this._revealNode.setAttribute('tabindex', '0');
        this._revealNode.removeAttribute('aria-hidden');
      }
    }
  }

  /** @private */
  _updateToggleState(passwordVisible) {
    if (this._revealNode) {
      this._revealNode.setAttribute('aria-pressed', passwordVisible ? 'true' : 'false');
    }
  }

  /** @private */
  _passwordVisibleChanged(passwordVisible) {
    this._setType(passwordVisible ? 'text' : 'password');

    this._updateToggleState(passwordVisible);
  }

  /**
   * Override method inherited from `DisabledMixin` to synchronize the reveal button
   * disabled state with the password field disabled state.
   * @param {boolean} disabled
   * @param {boolean} oldDisabled
   * @protected
   */
  _disabledChanged(disabled, oldDisabled) {
    super._disabledChanged(disabled, oldDisabled);

    if (this._revealNode) {
      this._revealNode.disabled = disabled;
    }
  }
}

defineCustomElement$1(PasswordField);

const passwordInputCss = "*,*::before,*::after{padding:0;margin:0;box-sizing:border-box}.password{font-family:\"Roboto\";font-style:normal}.password__wrapper{position:relative;width:100%;display:flex;flex-direction:column;gap:5px}.password__wrapper--autofilled{pointer-events:none}.password__wrapper--autofilled .password__label{color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000))}.password__wrapper--autofilled .password__input::part(input-field){color:var(--emfe-w-color-black, #000000)}.password__wrapper--flex{display:flex;gap:5px}.password__wrapper--relative{position:relative}.password__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))}.password__label--required::after{content:\"*\";font-family:inherit;color:var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C));margin-left:2px}.password__input{width:inherit;border:none}.password__input[focused]::part(input-field){border-color:var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C))}.password__input[invalid]::part(input-field){border:1px solid var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909))}.password__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);background-color:var(--emfe-w-color-white, #FFFFFF);font-family:inherit;font-style:normal;font-weight:300;font-size:16px;line-height:1.5;position:relative;margin-bottom:unset;height:44px;padding:0;width:100%}.password__input::part(reveal-button){position:relative;right:10px}.password__input::part(reveal-button)::before{color:var(--emfe-w-registration-typography, var(--emfe-w-color-black, #000000))}.password__input>input{padding:5px 15px}.password__input>input:placeholder-shown{color:var(--emfe-w-color-gray-150, #828282)}.password__error-message{position:absolute;top:calc(100% + 5px);left:0;color:var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909))}.password__complexity{position:relative;padding:10px;display:flex;flex-direction:column;gap:20px;justify-content:center;margin-top:20px;font-weight:300;background:var(--emfe-w-color-white, #FFFFFF);-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;height:150px;border:1px solid #B0B0B0;}.password__complexity meter{border-color:transparent;}.password__complexity meter[value=\"1\"]::-moz-meter-bar{background-color:var(--emfe-w-color-valid, #48952a)}.password__complexity meter[value=\"1\"]::-webkit-meter-optimum-value{background-color:var(--emfe-w-color-valid, #48952a)}.password__complexity meter:not([value=\"1\"])::-moz-meter-bar{background-color:var(--emfe-w-color-error, #FD2839)}.password__complexity meter:not([value=\"1\"])::-webkit-meter-optimum-value{background-color:var(--emfe-w-color-error, #FD2839)}.password__complexity--strength{display:flex;justify-content:space-evenly;align-items:center}.password__complexity--strength meter::-moz-meter-bar{background:#B0B0B0}.password__complexity--hidden{display:none}.password__complexity--text-bold{font-weight:500}.password__complexity--checkbox{margin-right:5px}.password__complexity:after{content:\"\";position:absolute;width:25px;height:25px;border-top:1px solid var(--emfe-w-color-gray-150, #828282);border-right:0 solid var(--emfe-w-color-gray-150, #828282);border-left:1px solid var(--emfe-w-color-gray-150, #828282);border-bottom:0 solid var(--emfe-w-color-gray-150, #828282);bottom:92%;left:50%;margin-left:-25px;transform:rotate(45deg);margin-top:-25px;background-color:var(--emfe-w-color-white, #FFFFFF)}.password__tooltip-icon{width:16px;height:auto}.password__tooltip{position:absolute;top:0;left:20px;background-color:var(--emfe-w-color-white, #FFFFFF);border:1px solid var(--emfe-w-color-gray-150, #828282);color:#2B2D3F;padding:10px;border-radius:5px;opacity:0;transition:opacity 0.3s ease-in-out;z-index:10}.password__tooltip.visible{opacity:1}";

const PasswordInput = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.sendOriginalValidityState = createEvent(this, "sendOriginalValidityState", 7);
    this.sendValidityState = createEvent(this, "sendValidityState", 7);
    this.sendInputValue = createEvent(this, "sendInputValue", 7);
    /**
     * Default value for the input.
     */
    this.defaultValue = '';
    /**
     * Client custom styling via inline style
     */
    this.clientStyling = '';
    this.limitStylingAppends = false;
    this.showTooltip = false;
    this.value = '';
    this.touched = false;
    this.originalValid = false;
    this.validationPattern = '';
    this.duplicateInputValue = null;
    this.handleInput = (event) => {
      this.value = event.target.value;
      this.calculateComplexity(this.value);
      this.showPopup = true;
      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 = (event) => {
      this.value = event.target.value;
      this.showPopup = false;
      this.touched = true;
      this.isValid = this.setValidity();
      this.errorMessage = this.setErrorMessage();
    };
    this.handleFocus = () => {
      this.showPopup = true;
      this.calculateComplexity(this.value);
    };
    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 });
    }
  }
  valueChanged() {
    if (!this.isDuplicateInput) {
      // recalculate complexity immediately in order to send the correct validity to the duplicate
      this.calculateComplexity(this.value);
      this.sendOriginalValidityState.emit({ name: this.name, valid: this.setValidity() });
    }
  }
  emitValueHandler(newValue) {
    if (newValue == true && this.isValid) {
      this.valueHandler({ name: this.name, value: this.value, type: 'duplicate' });
    }
  }
  validityStateHandler(inputStateEvent) {
    this.sendValidityState.emit(inputStateEvent);
  }
  valueHandler(inputValueEvent) {
    this.sendInputValue.emit(inputValueEvent);
  }
  originalValidityChangedHandler(event) {
    if (this.isDuplicateInput) {
      if (event.detail.valid) {
        this.originalValid = true;
        this.isValid = this.setValidity();
      }
      else {
        this.originalValid = false;
        this.isValid = false;
        // only show error if the user has touched the input, in order to not show errors on empty inputs
        this.value !== '' && (this.errorMessage = this.setErrorMessage());
      }
    }
  }
  valueChangedHandler(event) {
    if (this.isDuplicateInput && this.name === event.detail.name + 'Duplicate') {
      this.duplicateInputValue = event.detail.value;
      if (this.touched) {
        this.isValid = this.setValidity();
        this.errorMessage = this.setErrorMessage();
      }
    }
    if (this.name === event.detail.name + 'Duplicate'
      && this.name.replace('Duplicate', '') === event.detail.name
      && this.touched === true) {
      this.isValid = this.setValidity();
      this.errorMessage = this.setErrorMessage();
    }
  }
  handleClickOutside(event) {
    if (event.composedPath()[0] === this.tooltipIconReference)
      return;
    if (event.composedPath()[0] !== this.tooltipReference)
      this.showTooltip = false;
  }
  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.passwordButton = this.element.shadowRoot.querySelector('vaadin-password-field-button');
    this.passwordButton.tabIndex = -1;
    if (this.defaultValue) {
      this.value = this.defaultValue;
      this.calculateComplexity(this.value);
      this.valueHandler({ name: this.name, value: this.value });
      if (this.isDuplicateInput) {
        this.duplicateInputValue = this.defaultValue;
        this.touched = true;
      }
    }
    this.isValid = this.setValidity();
  }
  calculateComplexity(password) {
    this.passwordComplexity = this.validation.custom
      .filter(rule => rule.rule === 'regex')
      .map(rule => {
      const ruleRegex = new RegExp(rule.pattern);
      const passed = ruleRegex.test(password);
      return { rule: rule.displayName, ruleKey: rule.errorKey, passed };
    });
  }
  setValidity() {
    var _a, _b;
    if (this.isDuplicateInput && this.duplicateInputValue !== this.value) {
      return false;
    }
    else if (!((_a = this.passwordComplexity) === null || _a === void 0 ? void 0 : _a.every(complexity => complexity.passed))) {
      return false;
    }
    else {
      return (_b = this.inputReference) === null || _b === void 0 ? void 0 : _b.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, _c, _d;
    if (this.isDuplicateInput && !this.originalValid) {
      return translate('invalidOriginalPasswordError', this.language);
    }
    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);
    }
    if (this.isDuplicateInput && this.duplicateInputValue !== this.value) {
      const errorCode = (_c = this.validation.custom.find(customRule => customRule.rule === 'duplicate-input')) === null || _c === void 0 ? void 0 : _c.errorKey;
      const errorMessage = (_d = this.validation.custom.find(customRule => customRule.rule === 'duplicate-input')) === null || _d === void 0 ? void 0 : _d.errorMessage;
      return translate(`${errorCode}`, this.language) ? translate(`${errorCode}`, this.language) : errorMessage;
    }
  }
  renderTooltip() {
    if (this.showTooltip) {
      return (h("div", { class: `password__tooltip ${this.showTooltip ? 'visible' : ''}`, ref: (el) => this.tooltipReference = el, innerHTML: this.tooltip }));
    }
    return null;
  }
  renderComplexityPopup() {
    const totalRules = this.passwordComplexity.length;
    const passedRules = this.passwordComplexity.filter(complexity => complexity.passed).length;
    const meterValue = passedRules / totalRules;
    const allRulesPassed = this.passwordComplexity.every(complexity => complexity.passed);
    return (h("div", { class: `password__complexity ${!this.showPopup ? 'password__complexity--hidden' : ''}` }, h("div", { class: 'password__complexity--strength' }, h("p", { class: 'password__complexity--text' }, translate('passwordStrength', this.language), "\u00A0", h("span", { class: 'password__complexity--text-bold' }, translate(`${allRulesPassed ? 'passwordStrengthStrong' : 'passwordStrengthWeak'}`, this.language))), h("meter", { value: meterValue, min: "0", max: "1" })), h("div", null, this.passwordComplexity.map((complexity, index) => {
      return (h("div", { key: index }, h("input", { class: 'password__complexity--checkbox', type: "checkbox", checked: complexity.passed, disabled: true }), h("span", null, translate(`${complexity.ruleKey}`, this.language) ? translate(`${complexity.ruleKey}`, this.language) : complexity.rule)));
    }))));
  }
  render() {
    let invalidClass = '';
    if (this.touched) {
      invalidClass = this.isValid == true || this.isValid == undefined ? '' : 'text__input--invalid';
    }
    return h("div", { class: `password__wrapper ${this.autofilled ? 'password__wrapper--autofilled' : ''} ${this.name}__input`, ref: el => this.stylingContainer = el }, h("div", { class: 'password__wrapper--flex' }, h("label", { class: `password__label  ${this.validation.mandatory ? 'password__label--required' : ''}`, htmlFor: `${this.name}__input` }, this.displayName), h("div", { class: 'password__wrapper--relative' }, this.tooltip &&
      h("img", { class: 'password__tooltip-icon', src: tooltipIconSvg, alt: "", ref: (el) => this.tooltipIconReference = el, onClick: () => this.showTooltip = !this.showTooltip }), this.renderTooltip())), h("vaadin-password-field", { type: "password", id: `${this.name}__input`, class: `password__input ${invalidClass}`, name: this.name, readOnly: this.autofilled, value: this.defaultValue, required: this.validation.mandatory, maxlength: this.validation.maxLength, minlength: this.validation.minLength, pattern: this.validationPattern, placeholder: `${this.placeholder}`, onInput: this.handleInput, onBlur: this.handleBlur, onFocus: this.handleFocus }), h("small", { class: 'password__error-message' }, this.errorMessage), this.passwordComplexity && this.showPopup && !this.isDuplicateInput && this.renderComplexityPopup());
  }
  get element() { return this; }
  static get watchers() { return {
    "isValid": ["validityChanged"],
    "value": ["valueChanged"],
    "emitValue": ["emitValueHandler"]
  }; }
  static get style() { return passwordInputCss; }
}, [1, "password-input", {
    "name": [513],
    "displayName": [513, "display-name"],
    "placeholder": [513],
    "defaultValue": [513, "default-value"],
    "autofilled": [516],
    "tooltip": [513],
    "validation": [16],
    "language": [513],
    "emitValue": [516, "emit-value"],
    "isDuplicateInput": [516, "is-duplicate-input"],
    "clientStyling": [513, "client-styling"],
    "isValid": [32],
    "errorMessage": [32],
    "limitStylingAppends": [32],
    "showTooltip": [32],
    "passwordComplexity": [32],
    "showPopup": [32],
    "value": [32]
  }, [[16, "sendOriginalValidityState", "originalValidityChangedHandler"], [16, "sendInputValue", "valueChangedHandler"], [4, "click", "handleClickOutside"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["password-input"];
  components.forEach(tagName => { switch (tagName) {
    case "password-input":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, PasswordInput);
      }
      break;
  } });
}

export { PasswordInput as P, defineCustomElement as d };
