(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.fwc_form = {
    attach: function (context, settings) {
      if ($('input[name="code_validation"]').length) {
        $('input[name="code_validation"]').once('codeValidation').on('keyup change', function () {
          if ($(this).val().length === 6) {
            $('.webform-submission-fwc-code-validation-form input.webform-button--submit').click().hide();
          }
        })
      }

      if ($('input[name="phone_number"]').length) {
        let selected_code = '';
        setTimeout(function() {
          selected_code = $( '.iti__country-list .iti__active');
          selected_code = selected_code.data('dial-code');
        }, 100);

        $('input[name="phone_number"]').once('countryCode').on('keyup change focus', function () {
          let tel = $(this);
          setTimeout(function() {
            let selected = $('.iti__country-list .iti__active');
            let code = selected.data('dial-code');
            if (code !== undefined) {
              if (tel.val().length <= 1) {
                tel.val('+' );
                tel.attr('placeholder','+' );
              }
            }

          }, 100);

        })
      }
    }
  }

  Drupal.behaviors.otp_sms = {
    attach: function (context, settings) {

      if ($('input[autocomplete="one-time-code"]').length) {
        if ('OTPCredential' in window) {
          window.addEventListener('DOMContentLoaded', e => {
            const input = document.querySelector('input[autocomplete="one-time-code"]');
            if (!input) return;
            // Cancel the WebOTP API if the form is submitted manually.
            const ac = new AbortController();
            const form = input.closest('form');
            if (form) {
              form.addEventListener('submit', e => {
                // Cancel the WebOTP API.
                ac.abort();
              });
            }
            // Invoke the WebOTP API
            navigator.credentials.get({
              otp: {transport: ['sms']},
              signal: ac.signal
            }).then(otp => {
              input.value = otp.code;
              // Automatically submit the form when an OTP is obtained.
              //if (form) form.submit();
            }).catch(err => {
              console.log(err);
            });
          });
        }
      }
    }
  }

  Drupal.behaviors.process_messages = {
    attach: function (context, settings) {
      if ($('.alert-error.alert-danger').length && $('.form-header-text').length) {
        $('.alert-error.alert-danger').insertAfter('.form-header-text');
      }
    }
  }

  //alert-error alert-danger

})(jQuery, Drupal, drupalSettings);