import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { d as defineCustomElement$d } from './checkbox-group-input2.js';
import { d as defineCustomElement$c } from './checkbox-input2.js';
import { d as defineCustomElement$b } from './date-input2.js';
import { d as defineCustomElement$a } from './email-input2.js';
import { a as defineCustomElement$2, d as defineCustomElement$9 } from './general-input2.js';
import { d as defineCustomElement$8 } from './number-input2.js';
import { d as defineCustomElement$7 } from './password-input2.js';
import { d as defineCustomElement$6 } from './radio-input2.js';
import { d as defineCustomElement$5 } from './select-input2.js';
import { d as defineCustomElement$4 } from './tel-input2.js';
import { d as defineCustomElement$3 } from './text-input2.js';

const DEFAULT_LANGUAGE = 'en';
const TRANSLATIONS = {
  "en": {
    "nextButton": 'Next',
    "backButton": 'Back',
    "doneButton": 'Done',
    "GmErr_BadRequest_Duplicate_User": 'A user with this information already exists.',
    "GmErr_BadRequest_PasswordContainsUsername": "The password cannot be the same as the username.",
    "GmErr_BadRequest_PasswordContainsEmail": "The password cannot be the same as the email.",
    "GmErr_BadRequest_Duplicate_PersonalId": "There is already a registration with the data you entered or you entered your data in an incorrect format.",
    "GmErr_Forbidden_UserAccount_NavExcluded": 'User is NAV Excluded. Registration was denied.',
    "GmErr_BadRequest_ModelValidationFailed": 'Something went wrong... Please try again.',
    "GmErr_BadInternalConfigs": 'Something went wrong... Please try again.',
    "GmErr_Unauthorized": 'Something went wrong... Please try again.',
    "GmErr_NotFound": 'Something went wrong... Please try again.',
    "GmErr_UnexpectedException": 'Something went wrong... Please try again.',
    "generalError": "Something went wrong... Please try again.",
    "successMessage": "Register successful"
  },
  "hu": {
    "nextButton": 'Következő',
    "backButton": 'Vissza',
    "doneButton": 'Kész',
    "GmErr_BadRequest_Duplicate_User": 'Már létezik felhasználó ezzel az információval.',
    "GmErr_BadRequest_PasswordContainsUsername": "The password cannot be the same as the username.",
    "GmErr_BadRequest_PasswordContainsEmail": "The password cannot be the same as the email.",
    "GmErr_BadRequest_Duplicate_PersonalId": "There is already a registration with the data you entered or you entered your data in an incorrect format.",
    "GmErr_Forbidden_UserAccount_NavExcluded": 'User is NAV Excluded. Registration was denied',
    "GmErr_BadRequest_ModelValidationFailed": 'Valami hiba történt... Kérjük, próbálja újra.',
    "GmErr_BadInternalConfigs": 'Valami hiba történt... Kérjük, próbálja újra.',
    "GmErr_Unauthorized": 'Valami hiba történt... Kérjük, próbálja újra.',
    "GmErr_NotFound": 'Valami hiba történt... Kérjük, próbálja újra.',
    "GmErr_UnexpectedException": 'Valami hiba történt... Kérjük, próbálja újra.',
    "generalError": "Valami hiba történt... Próbáld újra.",
    "successMessage": "Sikeres regisztráció"
  },
  "hr": {
    "nextButton": 'Sljedeće',
    "backButton": 'Nazad',
    "doneButton": 'Gotovo',
    "GmErr_BadRequest_Duplicate_User": 'Korisnik s ovim podacima već postoji.',
    "GmErr_BadRequest_PasswordContainsUsername": "The password cannot be the same as the username.",
    "GmErr_BadRequest_PasswordContainsEmail": "The password cannot be the same as the email.",
    "GmErr_BadRequest_Duplicate_PersonalId": "There is already a registration with the data you entered or you entered your data in an incorrect format.",
    "GmErr_Forbidden_UserAccount_NavExcluded": 'Korisnik je NAV isključen. Registracija je odbijena.',
    "GmErr_BadRequest_ModelValidationFailed": 'Nešto nije u redu... Molimo pokušajte ponovo',
    "GmErr_BadInternalConfigs": 'Nešto nije u redu... Molimo pokušajte ponovo',
    "GmErr_Unauthorized": 'Nešto nije u redu... Molimo pokušajte ponovo',
    "GmErr_NotFound": 'Nešto nije u redu... Molimo pokušajte ponovo',
    "GmErr_UnexpectedException": 'Nešto nije u redu... Molimo pokušajte ponovo',
    "generalError": "Nešto nije u redu... Molimo pokušajte ponovo",
    "successMessage": "Register successful"
  },
  'pt-br': {
    "nextButton": 'Seguindo',
    "backButton": 'Voltar',
    "doneButton": 'Terminar',
    "GmErr_BadRequest_Duplicate_User": 'Já existe um usuário com esta informação',
    "GmErr_Forbidden_UserAccount_NavExcluded": 'O usuário está excluído NAV. O registro foi negado',
    "GmErr_BadRequest_ModelValidationFailed": 'Alguma coisa deu errado. Por favor tente outra vez.',
    "GmErr_BadInternalConfigs": 'Alguma coisa deu errado. Por favor tente outra vez',
    "GmErr_Unauthorized": 'Alguma coisa deu errado. Por favor tente outra vez',
    "GmErr_NotFound": 'Alguma coisa deu errado. Por favor tente outra vez',
    "GmErr_UnexpectedException": 'Alguma coisa deu errado. Por favor tente outra vez',
    "generalError": 'Alguma coisa deu errado. Por favor tente outra vez',
    "successMessage": 'Registro bem-sucedido'
  },
  'es-mx': {
    "nextButton": 'Siguiente',
    "backButton": 'Atrás',
    "doneButton": 'Terminar',
    "GmErr_BadRequest_Duplicate_User": 'Un usuario con esta información ya existe',
    "GmErr_Forbidden_UserAccount_NavExcluded": 'Usuario es Excluído NA. Registro fue negado',
    "GmErr_BadRequest_ModelValidationFailed": 'Algo salió mal…por favor intente de nuevo.',
    "GmErr_BadInternalConfigs": 'Algo salió mal... Por favor intente de nuevo',
    "GmErr_Unauthorized": 'Algo salió mal... Por favor intente de nuevo',
    "GmErr_NotFound": 'Algo salió mal... Por favor intente de nuevo',
    "GmErr_UnexpectedException": 'Algo salió mal... Por favor intente de nuevo',
    "generalError": 'Algo salió mal... Por favor intente de nuevo',
    "successMessage": 'Registro exitoso'
  }
};
const getTranslations = (url) => {
  // fetch url, get the data, replace the TRANSLATIONS content
  return new Promise((resolve) => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
      Object.keys(data).forEach((item) => {
        for (let key in data[item]) {
          TRANSLATIONS[item][key] = data[item][key];
        }
      });
      resolve(true);
    });
  });
};
const translate = (key, customLang, values) => {
  const lang = customLang;
  let translation = TRANSLATIONS[lang !== undefined ? lang : DEFAULT_LANGUAGE][key];
  if (values !== undefined) {
    for (const [key, value] of Object.entries(values.values)) {
      const regex = new RegExp(`{${key}}`, 'g');
      translation = translation.replace(regex, value);
    }
  }
  return translation;
};

const generalRegistrationCss = "*,\n*::before,\n*::after {\n  padding: 0;\n  margin: 0;\n  box-sizing: border-box;\n}\n\n.registration__form.hidden {\n  display: none;\n}\n\n.registration {\n  font-family: \"Roboto\";\n  font-style: normal;\n  font-family: sans-serif;\n  display: flex;\n  flex-direction: column;\n  gap: 24px;\n  width: 100%;\n  height: 100%;\n  container-type: inline-size;\n}\n.registration__wrapper {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n.registration__error-message {\n  color: var(--emfe-w-color-error, var(--emfe-w-color-red, #ed0909));\n  font-size: 13px;\n  display: block;\n  justify-content: center;\n  text-align: center;\n}\n.registration__form {\n  display: grid;\n  grid-template-columns: repeat(1, 1fr);\n  gap: 40px;\n  justify-items: stretch;\n  align-content: flex-start;\n  overflow: auto;\n  width: 100%;\n  height: 100%;\n}\n.registration__buttons-wrapper {\n  display: flex;\n  flex-direction: column;\n  justify-content: space-around;\n  align-items: center;\n  position: relative;\n}\n.registration__button {\n  border-radius: 5px;\n  background: var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C));\n  border: 1px solid var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C));\n  color: var(--emfe-w-button-typography, var(--emfe-w-color-white, #FFFFFF));\n  text-transform: uppercase;\n  font-size: 20px;\n  height: 44px;\n  width: 100%;\n  margin: 0px auto;\n  padding: 10px 20px;\n  font-weight: normal;\n  box-shadow: none;\n  cursor: pointer;\n}\n.registration__button--disabled {\n  background: var(--emfe-w-color-gray-100, #E6E6E6);\n  border: 1px solid var(--emfe-w-color-gray-150, #828282);\n  pointer-events: none;\n  box-shadow: none;\n}\n.registration__button--first-step {\n  display: none;\n}\n\n@container (min-width: 450px) {\n  .registration__form {\n    grid-template-columns: repeat(2, 1fr);\n  }\n\n  .registration__buttons-wrapper {\n    flex-direction: row-reverse;\n    gap: 15px;\n  }\n}\n.spinner {\n  animation: rotate 2s linear infinite;\n  z-index: 2;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  margin: -25px 0 0 -25px;\n  width: 50px;\n  height: 50px;\n}\n.spinner .path {\n  stroke: var(--emfe-w-login-color-primary, var(--emfe-w-color-primary, #D0046C));\n  stroke-linecap: round;\n  animation: dash 1.5s ease-in-out infinite;\n}\n\n@keyframes rotate {\n  100% {\n    transform: rotate(360deg);\n  }\n}\n@keyframes dash {\n  0% {\n    stroke-dasharray: 1, 150;\n    stroke-dashoffset: 0;\n  }\n  50% {\n    stroke-dasharray: 90, 150;\n    stroke-dashoffset: -35;\n  }\n  100% {\n    stroke-dasharray: 90, 150;\n    stroke-dashoffset: -124;\n  }\n}";

const GeneralRegistration$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.registrationWidgetLoaded = createEvent(this, "registrationWidgetLoaded", 7);
    this.registrationStepUpdated = createEvent(this, "registrationStepUpdated", 7);
    /**
    * Currently selected language
    */
    this.language = 'en';
    /**
     * Client custom styling via inline styles
     */
    this.clientStyling = '';
    /**
     * Client custom styling via url
     */
    this.clientStylingUrl = '';
    /**
     * Translations via URL
     */
    this.translationUrl = '';
    /**
     * Affiliate code to be passed in and sent in the registration.
     */
    this.btag = null;
    this.isLoading = true;
    this.forms = [];
    this.limitStylingAppends = false;
    this.autofilled = false;
    this.listOfInputValues = [];
    this.listOfInputValidity = [];
    this.listOfActions = [];
    this.listOfInputs = [];
    this.emitValue = false;
    this.backButtonPressed = false;
    this.registerErrors = false;
    this.registrationStepsState = {
      regId: null
    };
    this.setClientStyling = () => {
      let sheet = document.createElement('style');
      sheet.innerHTML = this.clientStyling;
      this.host.shadowRoot.prepend(sheet);
    };
    this.setClientStylingURL = () => {
      let url = new URL(this.clientStylingUrl);
      let cssFile = document.createElement('style');
      fetch(url.href)
        .then((res) => res.text())
        .then((data) => {
        cssFile.innerHTML = data;
        this.clientStyling = data;
        setTimeout(() => { this.host.shadowRoot.prepend(cssFile); }, 1);
      });
    };
  }
  sendStep() {
    this.registrationStepUpdated.emit(this.registrationStep);
    window.postMessage({ type: 'registrationStepUpdated', step: this.registrationStep }, window.location.href);
  }
  setFormValidity() {
    this.errorMessage = '';
    if (this.listOfInputValidity) {
      this.isFormValid = !this.getInvalidStatus(this.listOfInputValidity);
    }
    //Check for autofilled.
    if (this.listOfInputs.some(inputs => inputs.autofill)) {
      this.autofilled = true;
    }
  }
  addBtag() {
    this.addBtagValue();
  }
  checkInputsValidityHandler(event) {
    // Set isValid state of the input in the list.
    this.listOfInputValidity.find(input => input.name == event.detail.name).isValid = event.detail.valid;
    // Check if any one is invalid.
    this.isFormValid = !this.getInvalidStatus(this.listOfInputValidity);
  }
  getInputsValueHandler(event) {
    this.listOfInputValues.find(input => {
      if (input.name == event.detail.name) {
        input.value = event.detail.value;
        input.type = event.detail.type || null;
      }
    });
    this.stepsStateMachine({ event: 'set', type: 'values' });
  }
  componentWillLoad() {
    return this.getRegisterConfig()
      .then((config) => {
      this.formatConfig(config);
      this.isFormValid = !this.getInvalidStatus(this.listOfInputValidity);
      this.stepsStateMachine({ event: 'set', type: 'inputs' });
    });
  }
  componentDidLoad() {
    this.registrationWidgetLoaded.emit();
    window.postMessage({ type: 'registrationWidgetLoaded' }, window.location.href);
    if (!this.limitStylingAppends && this.host) {
      if (this.clientStyling)
        this.setClientStyling();
      if (this.clientStylingUrl)
        this.setClientStylingURL();
      this.limitStylingAppends = true;
    }
  }
  nextHandler(e) {
    e.preventDefault();
    // Trigger events in subwidgets.
    this.emitValue = true;
    this.setRegisterStep();
  }
  backHandler(e) {
    e.preventDefault();
    this.registrationStep = this.stepChange('decrement');
    this.stepsStateMachine({ event: 'get', type: 'inputs' });
    this.stepsStateMachine({ event: 'get', type: 'values' });
  }
  stepsStateMachine(state) {
    switch (state.event) {
      case 'set':
        if (state.type == 'inputs') {
          this.registrationStepsState[this.registrationStep].fields = this.listOfInputs;
          this.registrationStepsState[this.registrationStep].actions = this.listOfActions;
          this.registrationStepsState[this.registrationStep].fieldsValidity = this.listOfInputValidity;
        }
        if (state.type == 'values') {
          this.registrationStepsState[this.registrationStep].registerUserData = this.listOfInputValues.reduce((acc, curr) => {
            acc[curr.name] = { value: curr.value, isDuplicate: curr.isDuplicate };
            return acc;
          }, {});
        }
        localStorage.setItem('registrationStepsState', JSON.stringify(this.registrationStepsState));
        break;
      case 'get':
        const savedUserData = JSON.parse(localStorage.getItem('registrationStepsState'));
        if (!savedUserData)
          return;
        if (state.type == 'inputs') {
          this.listOfInputs = this.registrationStepsState[this.registrationStep].fields;
          this.listOfActions = this.registrationStepsState[this.registrationStep].actions;
          this.listOfInputValidity = this.registrationStepsState[this.registrationStep].fieldsValidity;
        }
        if (state.type == 'values') {
          const savedValues = savedUserData[this.registrationStep].registerUserData;
          this.listOfInputValues = Object.keys(savedValues).map(name => {
            return { name, value: savedValues[name].value, isDuplicate: savedValues[name].isDuplicate };
          });
          // Give to each field the user input as the default value.
          this.listOfInputValues.forEach(inputValue => {
            const input = this.listOfInputs.find(input => input.name === inputValue.name);
            if (input) {
              input.defaultValue = inputValue.value;
            }
          });
        }
        this.isFormValid = !this.getInvalidStatus(this.listOfInputValidity);
        break;
    }
  }
  getRegisterConfig(registrationID) {
    const url = new URL(`${this.endpoint}/v1/player/legislation/registration/config`);
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    if (registrationID) {
      url.searchParams.append('registrationId', registrationID);
    }
    const options = {
      method: 'GET',
      headers
    };
    return new Promise((resolve, reject) => {
      this.isLoading = true;
      fetch(url.href, options)
        .then((res) => res.json())
        .then((config) => {
        this.isLoading = false;
        resolve(config);
      }).catch((err) => {
        this.isLoading = false;
        console.error(err);
        reject(err);
      }).finally(() => {
        this.isLoading = false;
      });
    });
  }
  setRegisterStep() {
    this.isLoadingPOST = true;
    const url = new URL(`${this.endpoint}/v1/player/legislation/registration/step`);
    const registerStep = {
      registrationId: this.registrationID,
      registerUserDto: this.listOfInputValues
        .filter(input => !input.isDuplicate)
        .reduce((acc, curr) => {
        // Because the API is very robust, some values need to be split as separate entities.  
        if (curr.name === 'TypeOfPublicArea') {
          acc[curr.name] = curr.value.toLowerCase();
        }
        else if (curr.type === 'tel') {
          //@ts-ignore
          acc['MobilePrefix'] = curr.value.prefix;
          //@ts-ignore
          acc[curr.name] = curr.value.phone;
        }
        else if (curr.type === 'checkboxgroup') {
          // Skip adding the parent of the checkboxgroup as a key. 
          if (curr.value !== null) {
            Object.entries(curr.value).forEach(([key, value]) => {
              acc[key] = value ? 'true' : 'false';
            });
          }
        }
        else {
          acc[curr.name] = curr.value;
        }
        return acc;
      }, {}),
      step: this.registrationStep,
    };
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    const options = {
      method: 'POST',
      body: JSON.stringify(registerStep),
      headers
    };
    fetch(url.href, options)
      .then((res) => {
      if (!res.ok) {
        return res.json().then(error => {
          this.errorCode = error.thirdPartyResponse.errorCode;
          // Show the idomsoft error if it is the case
          if (this.errorCode == 'GmErr_BadRequest_IdomsoftVerification_ShouldRetry') {
            this.errorMessage = error.thirdPartyResponse.message;
          }
          else if (this.errorCode === 'GmErr_Forbidden_UserAccount_NavExcluded') {
            this.errorMessage = translate(`${this.errorCode}`, this.language);
          }
          else if (this.errorCode == 'GmErr_BadRequest') {
            this.errorMessage = error.thirdPartyResponse.message;
          }
          else {
            this.errorMessage = translate(`${this.errorCode}`, this.language) || translate(`generalError`, this.language);
          }
        });
      }
      return res.json();
    })
      .then((data) => {
      this.isLoadingPOST = false;
      this.registrationID = data.registrationId;
      if (this.listOfActions.some(action => action == '/register')) {
        this.setRegister();
      }
      else {
        // After sending the current step, increment and check if the next one is in state.
        this.registrationStep = this.stepChange('increment');
        // If step is present in state do NOT fetch the next config.
        if (Object.keys(this.registrationStepsState).find(key => key == this.registrationStep)) {
          // Use the one from state
          this.stepsStateMachine({ event: 'get', type: 'inputs' });
          this.stepsStateMachine({ event: 'get', type: 'values' });
        }
        else {
          this.getRegisterConfig(this.registrationID).then((config) => {
            // Format the new step config.
            this.formatConfig(config);
            // Set it in local storage.
            this.stepsStateMachine({ event: 'set', type: 'inputs' });
          });
        }
      }
    })
      .catch((err) => {
      this.isLoadingPOST = false;
      console.error(err);
    }).finally(() => {
      this.isLoadingPOST = false;
    });
  }
  setRegister() {
    this.isLoading = true;
    this.registerErrors = false;
    const url = new URL(`${this.endpoint}/v1/player/legislation/register`);
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    const options = {
      method: 'PUT',
      body: JSON.stringify({ registrationId: this.registrationID }),
      headers
    };
    fetch(url.href, options)
      .then((res) => {
      if (!res.ok) {
        this.registerErrors = true;
        return res.json().then(error => {
          this.errorCode = error.thirdPartyResponse.errorCode;
          // Show the idomsoft error if it is the case
          if (this.errorCode == 'GmErr_BadRequest_IdomsoftVerification_ShouldRetry') {
            this.errorMessage = error.thirdPartyResponse.message;
          }
          else if (this.errorCode == 'GmErr_BadRequest') {
            this.errorMessage = error.thirdPartyResponse.message;
          }
          else {
            this.errorMessage = translate(`${this.errorCode}`, this.language) || translate(`generalError`, this.language);
          }
          window.postMessage({ type: 'registrationFailed', errorMessage: error === null || error === void 0 ? void 0 : error.thirdPartyResponse.message }, window.location.href);
          window.postMessage({ type: 'WidgetNotification', data: {
              type: 'error',
              message: this.errorMessage
            } }, window.location.href);
        });
      }
      return res.json();
    })
      .then((data) => {
      this.isLoading = false;
      if (!this.registerErrors) {
        window.postMessage({ type: 'registrationSuccessful', userId: data === null || data === void 0 ? void 0 : data.userId }, window.location.href);
        window.postMessage({ type: 'WidgetNotification', data: {
            type: 'success',
            message: translate('successMessage', this.language)
          } }, window.location.href);
      }
    })
      .catch((err) => {
      this.isLoading = false;
      console.error(err);
    })
      .finally(() => {
      this.isLoading = false;
    });
  }
  formatConfig(config) {
    // Populate the list of inputs
    this.listOfInputs = config.content.fields.flatMap((field) => {
      // Special case for inputs that need to be duplicated.
      const duplicateInputRule = field.validate.custom.find(customRule => customRule.rule === 'duplicate-input');
      const inputElement = Object.assign({}, field);
      if (duplicateInputRule) {
        const duplicateInput = Object.assign(Object.assign({}, field), { name: `${field.name}Duplicate`, displayName: duplicateInputRule.displayName, isDuplicateInput: true });
        return [inputElement, duplicateInput];
      }
      else {
        return [inputElement];
      }
    });
    this.listOfInputValidity = this.listOfInputs.reduce((acc, field) => {
      var _a;
      // If the field is a togglecheckbox, add its subfields
      if (((_a = field.inputType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "togglecheckbox") {
        field.data.subFields.forEach(subfield => {
          acc.push({
            name: subfield.name,
            isValid: this.setInitialValidStatus(subfield)
          });
        });
      }
      else {
        acc.push({
          name: field.name,
          isValid: this.setInitialValidStatus(field)
        });
      }
      return acc;
    }, []);
    this.listOfInputValues = this.listOfInputs.reduce((acc, field) => {
      var _a, _b, _c;
      // If the field type is a 'togglecheckbox', add its subfields
      if (((_a = field.inputType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "togglecheckbox") {
        field.data.subFields.forEach(subfield => {
          var _a, _b;
          acc.push({
            name: subfield.name,
            value: ((_a = subfield.inputType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == 'checkbox' ? 'false' : null,
            isDuplicate: subfield.isDuplicateInput || false,
            type: ((_b = field.inputType) === null || _b === void 0 ? void 0 : _b.toLowerCase()) == 'togglecheckbox'
              ? 'togglecheckbox'
              : null
          });
        });
      }
      else {
        acc.push({
          name: field.name,
          value: ((_b = field.inputType) === null || _b === void 0 ? void 0 : _b.toLowerCase()) == 'checkbox' ? 'false' : null,
          isDuplicate: field.isDuplicateInput || false,
          type: ((_c = field.inputType) === null || _c === void 0 ? void 0 : _c.toLowerCase()) == 'checkboxgroup' ? 'checkboxgroup' : null
        });
      }
      return acc;
    }, []);
    if (this.btag)
      this.addBtagValue();
    // Set the list of actions
    this.listOfActions = config.content.actions.map(action => action);
    this.registrationID = config.content.registrationID;
    this.registrationStep = config.content.step;
    if (this.listOfActions.some(action => action == '/register')) {
      this.lastStep = this.registrationStep;
    }
    // The translations for fields happens here. 
    if (this.translationUrl) {
      getTranslations(this.translationUrl).then(() => {
        this.listOfInputs.forEach(field => {
          var _a, _b;
          this.addTranslation(field);
          // Logic for field types that have subfields
          if (((_a = field.inputType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'togglecheckbox') {
            field.data.subFields.forEach(subField => this.addTranslation(subField));
          }
          if (((_b = field.inputType) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'checkboxgroup') {
            this.addTranslation(field);
            field.data.subFields.forEach(subField => this.addTranslation(subField));
          }
          return field;
        });
      })
        .catch((error) => {
        console.error('Failed to fetch translations:', error);
      }).finally(() => {
        this.forms = [...this.forms, { [this.registrationStep]: this.listOfInputs }];
      });
    }
    else {
      this.forms = [...this.forms, { [this.registrationStep]: this.listOfInputs }];
    }
    // Add the step to the registrationStepsData
    this.registrationStepsState.regId = this.registrationID;
    if (!this.registrationStepsState[this.registrationStep]) {
      this.registrationStepsState[this.registrationStep] = {
        fields: [],
        fieldsValidity: [],
        registerUserData: {},
        actions: []
      };
    }
  }
  addBtagValue() {
    const btagField = this.listOfInputs.find(input => input.name.toLowerCase() === 'btag');
    if (btagField) {
      btagField.defaultValue = this.btag;
    }
    const btagValue = this.listOfInputValues.find(input => input.name.toLowerCase() === 'btag');
    if (btagValue) {
      btagValue.value = this.btag;
    }
  }
  addTranslation(field) {
    if (TRANSLATIONS[this.language][field.name]) {
      Object.keys(TRANSLATIONS[this.language][field.name]).forEach((key) => {
        field[key] = TRANSLATIONS[this.language][field.name][key];
      });
    }
  }
  setInitialValidStatus(field) {
    var _a, _b;
    // Input type checkbox, with no validation are valid
    if (((_a = field.inputType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == 'checkbox' && ((_b = field.validate) === null || _b === void 0 ? void 0 : _b.mandatory) == false) {
      return true;
    }
    //Inputs that have default value are valid.
    if (field.defaultValue !== null) {
      return true;
    }
    return false;
  }
  stepChange(action) {
    const stepNum = parseInt(this.registrationStep.replace('Step', ''));
    if (action === 'increment') {
      return 'Step' + (stepNum + 1);
    }
    if (action === 'decrement') {
      return 'Step' + (stepNum - 1);
    }
  }
  getInvalidStatus(listOfInputs) {
    return listOfInputs.filter(input => input.isValid == false).length > 0;
  }
  renderForm() {
    return this.forms.map((form, index) => {
      return h("form", { action: '.', id: `RegistrationForm${this.registrationStep}`, class: `registration__form ${this.registrationStep !== `Step${index + 1}` ? 'hidden' : ''}`, ref: el => this.form = el }, form[this.registrationStep] && form[this.registrationStep].map(input => h("general-input", { type: input.inputType, name: input.name, displayName: input.displayName, validation: input.validate, action: input.action || null, options: input.data
          ? (input.inputType.toLowerCase() == 'checkboxgroup' || input.inputType.toLowerCase() == 'togglecheckbox')
            ? input.data.subFields
            : input.data.values
          : [], defaultValue: input.defaultValue, autofilled: input.autofill, emitValue: this.emitValue, language: this.language, isDuplicateInput: input.isDuplicateInput, "client-styling": this.clientStyling, tooltip: input.tooltip, placeholder: input.placeholder == null ? '' : input.placeholder, dateFormat: this.dateFormat, "translation-url": this.translationUrl })), this.buttonInsideForm && this.renderButtons(), h("div", { class: 'registration__wrapper--flex' }, h("p", { class: 'registration__error-message', innerHTML: this.errorMessage })));
    });
  }
  ;
  renderButtons() {
    return (h("div", { class: `registration__buttons-wrapper ${this.autofilled ? 'registration__buttons-wrapper--autofilled' : ''}` }, this.isLoadingPOST
      && h("slot", { name: 'spinner' })
      && h("svg", { class: "spinner", viewBox: "0 0 50 50" }, h("circle", { class: "path", cx: "25", cy: "25", r: "20", fill: "none", "stroke-width": "5" })), !this.isLoadingPOST && h("button", { class: `registration__button registration__button--next ${this.isFormValid ? '' : 'registration__button--disabled'}`, type: 'submit', form: `RegistrationForm${this.registrationStep}`, onClick: (e) => this.nextHandler(e), disabled: !this.isFormValid }, this.lastStep === this.registrationStep ? translate('doneButton', this.language) : translate('nextButton', this.language)), h("button", { class: `registration__button registration__button--back ${this.registrationStep == 'Step1' ? 'registration__button--first-step' : ''}`, onClick: (e) => this.backHandler(e) }, translate('backButton', this.language))));
  }
  render() {
    if (this.isLoading) {
      return h("p", null, "Please wait, loading ...");
    }
    return (h("div", { class: `registration  registration__${this.registrationStep}` }, this.renderForm(), !this.buttonInsideForm && this.renderButtons()));
  }
  get host() { return this; }
  static get watchers() { return {
    "registrationStep": ["sendStep"],
    "forms": ["setFormValidity"],
    "btag": ["addBtag"]
  }; }
  static get style() { return generalRegistrationCss; }
}, [1, "general-registration", {
    "endpoint": [513],
    "language": [513],
    "clientStyling": [1537, "client-styling"],
    "clientStylingUrl": [513, "client-styling-url"],
    "translationUrl": [513, "translation-url"],
    "dateFormat": [513, "date-format"],
    "buttonInsideForm": [516, "button-inside-form"],
    "btag": [513],
    "errorMessage": [32],
    "isFormValid": [32],
    "isLoading": [32],
    "isLoadingPOST": [32],
    "registrationStep": [32],
    "forms": [32],
    "limitStylingAppends": [32],
    "autofilled": [32]
  }, [[0, "sendValidityState", "checkInputsValidityHandler"], [0, "sendInputValue", "getInputsValueHandler"]]]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["general-registration", "checkbox-group-input", "checkbox-input", "date-input", "email-input", "general-input", "number-input", "password-input", "radio-input", "select-input", "tel-input", "text-input", "toggle-checkbox-input"];
  components.forEach(tagName => { switch (tagName) {
    case "general-registration":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, GeneralRegistration$1);
      }
      break;
    case "checkbox-group-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "checkbox-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "date-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "email-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "general-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "number-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "password-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "radio-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "select-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "tel-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "text-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "toggle-checkbox-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}

const GeneralRegistration = GeneralRegistration$1;
const defineCustomElement = defineCustomElement$1;

export { GeneralRegistration, defineCustomElement };
