{{ header }}
<div id="account-register" class="container-xl flex-grow-1">
  <nav aria-label="breadcrumb">
    <ul class="breadcrumb pr-breadcrumb fsz-12">
      {% for breadcrumb in breadcrumbs %}
        {% if loop.last %}
          <li class="breadcrumb-item pr-breadcrumb-item">{{ breadcrumb.text }}</li>
        {% else %}
          <li class="breadcrumb-item pr-breadcrumb-item"><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
        {% endif %}
      {% endfor %}
    </ul>
  </nav>
  <main>
    <div class="content-top-box">{{ content_top }}</div>
    {% if error_warning %}
      <script>
        prNotify('danger', '{{ error_warning }}');
      </script>
    {% endif %}
    <div class="row g-3 g-xxl-4 pr-account">
      {{ column_left }}
      {% if column_left and column_right %}
        {% set class = 'col-xl-6' %}
      {% elseif column_left or column_right %}
        {% set class = 'col-xl-9' %}
      {% else %}
        {% set class = 'col-xl-12' %}
      {% endif %}
      <div id="content" class="{{ class }}">
        <div class="content-block pr-account-page">
          <form id="register_form" action="{{ action }}" method="post" class="form-horizontal" novalidate>
            <fieldset class="p-0">
              <div class="pr-page-title mb-3 mb-xl-4 pb-3 pb-xl-4 border-bottom d-flex align-items-center gap-3">
                <h1>{{ heading_title }}</h1>
              </div>
              <div class="row g-3 g-md-4 register_block">
                {% if not user_logged %}
                  <div class="form-group col-lg-12">
                    <div class="d-flex align-items-center alert alert-info py-3 px-4 mb-0 br-8 fsz-14">
                      {{ text_have_account }} <a onclick="octPopupLogin();" class="blue-link ms-2 fsz-14 fw-300">{{ heading_login_block }}</a>
                    </div>
                  </div>
                {% endif %}
                {% if customer_group_status and customer_groups %}
                  <div class="form-group col-lg-12">
                    <legend class="h4 mt-1 mb-2">{{ entry_customer_group }}</legend>
                    <div class="d-flex flex-wrap gap-3">
                      {% for customer_group in customer_groups %}
                        <div class="form-check d-flex align-items-center mb-0 gap-1">
                          <input type="radio" name="customer_group_id" id="customer_group_{{ customer_group.customer_group_id }}" value="{{ customer_group.customer_group_id }}" class="form-check-input"{% if customer_group.customer_group_id == customer_group_id %} checked="checked"{% endif %} />
                          <label class="form-check-label" for="customer_group_{{ customer_group.customer_group_id }}">{{ customer_group.name }}</label>
                        </div>
                      {% endfor %}
                    </div>
                  </div>
                {% endif %}
                {% for key, field in fields %}
                  {% if key == 'telephone' %}
                    <div class="form-floating col-lg-6">
                      <input type="tel"
                        inputmode="numeric"
                        placeholder=""
                        class="form-control"
                        id="{{ key }}"
                        name="mask_{{ key }}_display"
                        value="{{ field.value }}"
                        {% if field.required %} required aria-required="true" {% endif %}>
                      <input type="hidden" id="full_{{ key }}" name="{{ key }}" value="{{ field.value }}">
                    </div>
                  {% else %}
                    <div class="form-floating col-lg-6">
                      <input type="{{ field.type }}"
                        placeholder="{% if field.localization[language_id].placeholder is not empty %}{{ field.localization[language_id].placeholder }}{% elseif attribute(_context, 'entry_' ~ key) is not empty %}{{ attribute(_context, 'entry_' ~ key) }}{% endif %}"
                        class="form-control"
                        id="{{ key }}"
                        name="{{ key }}"
                        value="{{ field.value }}"
                        {% if field.required %} required aria-required="true" {% endif %}>
                      <label class="px-3 secondary-text fsz-14" for="{{ key }}">
                        {% if field.required %}<span class="required">*</span>{% endif %}
                        {% if field.localization[language_id].name is not empty %}
                          {{ field.localization[language_id].name }}
                        {% elseif attribute(_context, 'entry_' ~ key) is not empty %}
                          {{ attribute(_context, 'entry_' ~ key) }}
                        {% else %}
                          {{ field.name }}
                        {% endif %}
                      </label>
                    </div>
                  {% endif %}
                {% endfor %}
              </div>
              {% if newsletter_status %}
                <legend class="h4 mt-3 mb-2">{{ text_newsletter }}</legend>
                <div class="form-group mb-2">
                  <div class="d-flex">
                    {% if newsletter %}
                      <div class="form-check d-flex align-items-center mb-0 gap-1">
                        <input type="radio" name="newsletter" id="checkYes" value="1" class="form-check-input" checked="checked" />
                        <label class="form-check-label" for="checkYes">{{ text_yes }}</label>
                      </div>
                      <div class="form-check d-flex align-items-center my-0 ms-3 gap-1">
                        <input type="radio" name="newsletter" id="checkNo" value="0" class="form-check-input" />
                        <label class="form-check-label" for="checkNo">{{ text_no }}</label>
                      </div>
                    {% else %}
                      <div class="form-check d-flex align-items-center mb-0 gap-1">
                        <input type="radio" name="newsletter" id="checkYes" value="1" class="form-check-input" />
                        <label class="form-check-label" for="checkYes">{{ text_yes }}</label>
                      </div>
                      <div class="form-check d-flex align-items-center my-0 ms-3 gap-1">
                        <input type="radio" name="newsletter" id="checkNo" value="0" class="form-check-input" checked="checked" />
                        <label class="form-check-label" for="checkNo">{{ text_no }}</label>
                      </div>
                    {% endif %}
                  </div>
                </div>
              {% endif %}
            </fieldset>
            <div class="form-group col-md-12 register-form">
              <div class="row">
                <label class="col-md-12 dark-text fsz-14 fw-500 mb-1 mt-2" for="password">
                  <span class="required">*</span> {{ entry_password }}
                </label>
                <div class="col-md-6">
                  <div class="input-group password-input-group">
                    <span class="input-group-text">
                      <button type="button" class="no-btn button-show position-absolute" onclick="togglePasswordVisibility();return false;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="19" height="16" viewBox="0 0 19 16" fill="none" role="img">
                          <title>{{ entry_show_hide_password }}</title>
                          <path d="M18.0244 6.22877C16.8124 4.199 14.0921 0.793945 9.5 0.793945C4.90786 0.793945 2.18755 4.199 0.975598 6.22877C0.341467 7.28842 0.341467 8.60571 0.975598 9.66629C2.18755 11.6961 4.90786 15.1011 9.5 15.1011C14.0921 15.1011 16.8124 11.6961 18.0244 9.66629C18.6585 8.60571 18.6585 7.28934 18.0244 6.22877ZM16.8363 8.95553C15.7748 10.7333 13.4091 13.7165 9.5 13.7165C5.59091 13.7165 3.22515 10.7342 2.16366 8.95553C1.79259 8.3334 1.79259 7.56076 2.16366 6.93863C3.22515 5.16085 5.59091 2.17761 9.5 2.17761C13.4091 2.17761 15.7748 5.15992 16.8363 6.93863C17.2083 7.56168 17.2083 8.3334 16.8363 8.95553ZM9.5 4.0246C7.33639 4.0246 5.57707 5.78484 5.57707 7.94753C5.57707 10.1102 7.33639 11.8705 9.5 11.8705C11.6636 11.8705 13.4229 10.1102 13.4229 7.94753C13.4229 5.78484 11.6636 4.0246 9.5 4.0246ZM9.5 10.4859C8.09974 10.4859 6.96163 9.34778 6.96163 7.94753C6.96163 6.54727 8.09974 5.40916 9.5 5.40916C10.9003 5.40916 12.0384 6.54727 12.0384 7.94753C12.0384 9.34778 10.9003 10.4859 9.5 10.4859Z" fill="var(--pr-black-color)"></path>
                        </svg>
                      </button>
                    </span>
                    <input type="password"
                      name="password"
                      oninput="updateStrengthIndicator(this.value)"
                      value="{{ password }}"
                      placeholder="{{ entry_password }}"
                      id="password"
                      class="form-control"
                      required aria-required="true">
                    <input type="number" class="d-none" id="length" value="12" min="8" max="24">
                    <button type="button" class="no-btn button-copy position-absolute" onclick="copyToClipboard();return false;">
                      <svg width="18" height="21" viewBox="0 0 18 21" fill="none" xmlns="http://www.w3.org/2000/svg" role="img">
                        <title>{{ entry_copy_password }}</title>
                        <path d="M17.7863 6.06681L12.9083 1.18876C12.7707 1.0512 12.5853 0.974121 12.3911 0.974121H7.90325C5.95008 0.974121 4.83017 2.09412 4.83017 4.04729V4.87656H4.00081C2.04764 4.87656 0.927734 5.99655 0.927734 7.94973V17.901C0.927734 19.8532 2.04764 20.9741 4.00081 20.9741H11.0244C12.9776 20.9741 14.0975 19.8541 14.0975 17.901V17.0717H14.9269C16.88 17.0717 18 15.9517 18 13.9985V6.58388C18.0009 6.38973 17.9239 6.20339 17.7863 6.06681ZM13.1229 3.47266L15.5023 5.85217H14.8302C13.6009 5.85217 13.1229 5.37315 13.1229 4.14485V3.47266ZM12.6351 17.901C12.6351 19.059 12.1834 19.5107 11.0254 19.5107H4.00176C2.84274 19.5107 2.3921 19.059 2.3921 17.901V7.94973C2.3921 6.79168 2.84371 6.33997 4.00176 6.33997H4.83113V13.9985C4.83113 15.9507 5.95103 17.0717 7.9042 17.0717H12.636V17.901H12.6351ZM14.9278 15.6083H7.9042C6.74518 15.6083 6.29454 15.1566 6.29454 13.9985V4.04729C6.29454 2.88924 6.74615 2.43754 7.9042 2.43754H11.6604V4.14485C11.6604 6.18973 12.7862 7.31558 14.8311 7.31558H16.5384V13.9985C16.5375 15.1566 16.0859 15.6083 14.9278 15.6083Z" fill="var(--pr-black-color)"/>
                      </svg>
                    </button>
                  </div>
                  <div id="strengthIndicator" class="strength-indicator mb-2"></div>
                </div>
                <div class="col-md-6 align-self-stretch">
                  <button type="button" class="button button-light button-generate py-3 w-100 fsz-14 mt-2 mb-3 m-md-0" onclick="generatePassword(); return false;">{{ text_generate_password }}</button>
                </div>
              </div>
            </div>
            <div class="d-none">
              <input type="text" name="email_check_confirm" value="" />
            </div>
            {% if captcha %}
              <div class="pt-3">{{ captcha }}</div>
            {% endif %}
            {% if text_agree %}
              <div class="form-check d-flex align-items-center gap-2 mb-3">
                {% if agree %}
                  <input type="checkbox" name="agree" id="registerAgree" value="1" class="form-check-input" checked="checked" />
                {% else %}
                  <input type="checkbox" name="agree" id="registerAgree" value="1" class="form-check-input" />
                {% endif %}
                <label class="form-check-label fsz-12 dark-text" for="registerAgree">{{ text_agree }}</label>
              </div>
            {% endif %}
            <input type="hidden" name="csrf_reg_token" value="{{ csrf_reg_token }}" />
            <button type="submit" class="button button-secondary button-large" id="button-reg">{{ button_continue }}</button>
          </form>
        </div>
      </div>
      {{ column_right }}
    </div>
    {{ content_bottom }}
  </main>
</div>

<div class="modal fade" id="smsVerificationModal" tabindex="-1" aria-labelledby="smsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header p-4 bg-grey">
        <h5 class="modal-title fsz-20 fw-700 d-flex align-items-center justify-content-between dark-text" id="smsModalLabel">{{ text_sms_verify_title }}</h5>
        <button type="button" class="btn-close br-8 bg-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="mb-3 dark-text">{{ text_sms_verify_desc }}</p>
        <div class="mb-3">
          <input type="text" 
            id="sms-code-input" 
            class="form-control text-center fs-4" 
            maxlength="4" 
            placeholder="0000" 
            inputmode="numeric" 
            pattern="[0-9]*" 
            autocomplete="one-time-code"
            aria-label="{{ text_sms_code }}">
        </div>
        <div id="sms-error" class="alert alert-danger d-none"></div>
        <div id="sms-timer" class="text-center grey-text fsz-14 mb-3">
          {{ text_resend_in }} <span id="timer-seconds" class="fw-600 text-danger mx-1">60</span> {{ text_seconds }}
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="button button-primary button-large w-100 py-3 fsz-14" id="btn-verify-sms">{{ button_verify }}</button>
        <button type="button" class="button button-secondary w-100 mt-2" id="btn-resend-sms" disabled>{{ button_resend }}</button>
      </div>
    </div>
  </div>
</div>

<script>
  let smsTimerInterval;

  function startSmsTimer(seconds, isBlocking = false) {
    clearInterval(smsTimerInterval);
    let remaining = seconds;

    if (isBlocking) {
      $('#sms-timer').hide();
      $('#btn-verify-sms').prop('disabled', true);
      $('#btn-resend-sms').prop('disabled', true);
      $('#sms-code-input').prop('disabled', true).val('');
      $('#sms-error').removeClass('d-none alert-danger').addClass('alert-warning');
    }

    smsTimerInterval = setInterval(function() {
      if (isBlocking) {
        $('#sms-error').html('{{ error_sms_max_attempts|escape('js') }}'.replace('%s', '<strong>' + remaining + '</strong>'));
      } else {
        $('#timer-seconds').text(remaining);
      }
      
      remaining--;

      if (remaining <= 0) {
        clearInterval(smsTimerInterval);
        smsTimerInterval = null;
        
        if (isBlocking) {
          $('#sms-error').addClass('d-none');
        } else {
          $('#sms-timer').hide();
          $('#sms-error').addClass('d-none');
        }
        
        $('#btn-resend-sms').prop('disabled', false);
        $('#btn-verify-sms').prop('disabled', false);
        $('#sms-code-input').prop('disabled', false).val('').focus();
      }
    }, 1000);
  }

  $('#smsVerificationModal').on('shown.bs.modal', function() {
    $('#sms-code-input').val('').prop('disabled', false);
    $('#btn-verify-sms').prop('disabled', false);
    $('#sms-error').addClass('d-none');
    
    setTimeout(function() {
      const input = document.getElementById('sms-code-input');
      if (input) {
        input.focus();
        if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
          input.setSelectionRange(0, 0);
        }
      }
    }, 400);
  });

  $('#smsVerificationModal').on('hidden.bs.modal', function () {
    clearInterval(smsTimerInterval);
    smsTimerInterval = null;
  });

  $(document).on('click', '#btn-verify-sms', function() {
    const code = $('#sms-code-input').val().trim();
    
    if (code.length !== 4) {
      $('#sms-error').removeClass('d-none alert-warning').addClass('alert-danger').text('{{ error_sms_code_length|escape('js') }}');
      return;
    }
    
    $.ajax({
      url: 'index.php?route=account/oct_smart_register/verifySmsCode',
      type: 'post',
      data: {
        sms_code: code,
        csrf_reg_token: $('input[name="csrf_reg_token"]').val()
      },
      dataType: 'json',
      beforeSend: function() {
        $('#btn-verify-sms').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
      },
      success: function(json) {
        $('#btn-verify-sms').html('{{ button_verify|escape('js') }}');
        
        if (json.error) {
          if (json.attempts_exceeded && json.retry_after) {
            startSmsTimer(json.retry_after, true);
          } else {
            $('#btn-verify-sms').prop('disabled', false);
            $('#sms-error').removeClass('d-none alert-warning').addClass('alert-danger').text(json.error);
          }
          return;
        }
        
        if (json.redirect) {
          $('#btn-verify-sms').prop('disabled', false);
          $('#smsVerificationModal').modal('hide');
          window.location.href = json.redirect;
        }
      }
    });
  });

  $(document).on('click', '#btn-resend-sms', function() {
    $.ajax({
      url: 'index.php?route=account/oct_smart_register/resendSmsCode',
      type: 'post',
      data: {
        csrf_reg_token: $('input[name="csrf_reg_token"]').val()
      },
      dataType: 'json',
      beforeSend: function() {
        $('#btn-resend-sms').prop('disabled', true);
      },
      success: function(json) {
        if (json.error) {
          $('#sms-error').removeClass('d-none').addClass('alert-danger').text(json.error);
          $('#btn-resend-sms').prop('disabled', false);
          return;
        }
        
        if (json.success) {
          $('#sms-error').addClass('d-none');
          $('#sms-code-input').val('').focus();
          prNotify('success', json.success);
          startSmsTimer(60, false);
        }
      }
    });
  });

  $(document).on('input', '#sms-code-input', function() {
    this.value = this.value.replace(/[^0-9]/g, '');
    
    if (this.value.length === 4) {
      setTimeout(function() {
        $('#btn-verify-sms').trigger('click');
      }, 300);
    }
  });

  function generatePassword() {
    const length = document.getElementById('length').value;
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]:;?><,./-=";
    let password = "";
    const lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
    const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const numbers = "0123456789";
    const specialChars = "!@#$%^&*()_+~`|}{[]:;?><,./-=";
    password += lowercaseLetters.charAt(Math.floor(Math.random() * lowercaseLetters.length));
    password += uppercaseLetters.charAt(Math.floor(Math.random() * uppercaseLetters.length));
    password += numbers.charAt(Math.floor(Math.random() * numbers.length));
    password += specialChars.charAt(Math.floor(Math.random() * specialChars.length));
    for (let i = password.length; i < length; i++) {
      password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    password = shuffle(password);
    document.getElementById('password').value = password;
    updateStrengthIndicator(password);
  }

  function shuffle(string) {
    const array = string.split('');
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array.join('');
  }

  function togglePasswordVisibility() {
    const passwordInput = document.getElementById('password');
    const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
    passwordInput.setAttribute('type', type);
  }

  function copyToClipboard() {
    const passwordInput = document.getElementById('password');
    const currentType = passwordInput.getAttribute('type');
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(passwordInput.value).then(() => {
        prNotify('success', '{{ text_copy_success }}');
      }).catch(() => {
        prNotify('warning', 'Copy failed.');
      });
    } else {
      passwordInput.setAttribute('type', 'text');
      passwordInput.select();
      document.execCommand('copy');
      prNotify('success', '{{ text_copy_success }}');
    }
    passwordInput.setAttribute('type', currentType);
  }

  function evaluatePasswordStrength(password) {
    let strengthPoints = 0;
    const diversityFactors = [
      { regex: /[a-z]/, points: 1 },
      { regex: /[A-Z]/, points: 1 },
      { regex: /[0-9]/, points: 1 },
      { regex: /[^a-zA-Z0-9]/, points: 1 }
    ];
    diversityFactors.forEach(factor => {
      if (factor.regex.test(password)) {
        strengthPoints += factor.points;
      }
    });
    const lengthPoints = Math.min(Math.floor(password.length / 4), 5);
    strengthPoints += lengthPoints;
    return strengthPoints;
  }

  function updateStrengthIndicator(password) {
    const strengthPoints = evaluatePasswordStrength(password);
    const strengthIndicator = document.getElementById('strengthIndicator');
    let backgroundColor;
    let width;
    if (strengthPoints >= 7) {
      backgroundColor = 'green';
      width = '100%';
    } else if (strengthPoints >= 4) {
      backgroundColor = 'orange';
      width = `${(strengthPoints / 7) * 100}%`;
    } else {
      backgroundColor = 'red';
      width = `${(strengthPoints / 7) * 100}%`;
    }
    strengthIndicator.style.width = width;
    strengthIndicator.style.backgroundColor = backgroundColor;
  }

  $(document).ready(function() {
    $('#smsVerificationModal').appendTo('body');
    
    $('#register_form').submit(function(e) {
      e.preventDefault();
      var form = $(this);
      var url = form.attr('action');
      $.ajax({
        type: "POST",
        beforeSend: function () {
          $('#button-reg').button('loading');
          masked('body', true);
          $('#button-reg').data('original-content', $('#button-reg').html());
          $('#button-reg').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> &nbsp;{{ text_loading }}').prop('disabled', true);
        },
        complete: function () {
          $('#button-reg').button('reset');
          masked('body', false);
          setTimeout(function () {
            $('#button-reg').html($('#button-reg').data('original-content')).prop('disabled', false);
          }, 600);
        },
        url: url,
        data: form.serialize(),
        success: function(data) {
          if (data.sms_required || data.show_sms_modal) {
            const timerValue = data.timer || 60;
            
            $('#timer-seconds').text(timerValue);
            $('#sms-timer').show();
            $('#sms-code-input').val('').prop('disabled', false);
            $('#btn-verify-sms').prop('disabled', false);
            $('#btn-resend-sms').prop('disabled', true);
            $('#sms-error').addClass('d-none');
            
            startSmsTimer(timerValue, false);
            
            if (data.message) {
              prNotify('success', data.message);
            }
            
            $('#smsVerificationModal').modal('show');
            
            setTimeout(function() {
              const input = document.getElementById('sms-code-input');
              if (input) {
                input.focus();
                if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
                  input.setSelectionRange(0, 0);
                }
              }
            }, 400);
            
            return;
          }
          
          if (data['error']) {
            var errorMessages = '';
            for (var key in data['error']) {
              if (data['error'].hasOwnProperty(key)) {
                // Спеціальна обробка для телефону (ITI поле)
                if (key === 'telephone') {
                  const telInput = document.querySelector('#telephone');
                  if (telInput) telInput.classList.add('error_style');
                } else {
                  $('input[name="' + key + '"]').addClass('error_style');
                }
                errorMessages += '<p class="mb-2">' + data['error'][key] + '</p>\n';
              }
            }
            scrollToItem('.error_style');
            prNotify('danger', errorMessages);
            if (data['error']['warning_agree'] !== undefined) {
              $('#registerAgree').addClass('error_style');
            }
            if (data['error']['logged']) {
              location = '{{ account_url }}';
            }
          }
          if (data['redirect']) {
            window.location.href = data['redirect'];
          }
          if (data['warning']) {
            prNotify('warning', data['warning']);
          }
        },
        error: function() {
          console.log('An error occurred while processing your request.');
        }
      });
    });
    
    $(document).on('input', 'input', function() {
      $(this).removeClass('error_style');
      $(this).next('.error_message').remove();
    });
  });

  function scrollToItem(selector, shipping = false) {
    const element = document.querySelector(selector);
    if (element) {
      if (shipping) {
        element.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
        return;
      }
      const rect = element.getBoundingClientRect();
      window.scrollTo({
        top: rect.top + window.scrollY - (window.innerHeight / 2),
        behavior: 'smooth'
      });
    }
  }

</script>

<link rel="stylesheet" href="catalog/view/theme/oct_promo/stylesheet/intlTelInput.css" />
<script src="catalog/view/theme/oct_promo/js/intlTelInput.min.js"></script>

<script>
// ITI Variables
if (typeof registerIti === 'undefined') {
  var registerIti = null;
}
if (typeof defaultRegisterCountry === 'undefined') {
  var defaultRegisterCountry = '{{ default_phone_country|default("ua") }}';
}

if (typeof registerPhoneMasks === 'undefined') {
  var registerPhoneMasks = {};
  try {
    const phoneMasksJson = {{ phone_masks|raw }};
    if (phoneMasksJson && typeof phoneMasksJson === 'object') {
      registerPhoneMasks = phoneMasksJson;
    }
  } catch (e) {
    console.warn('Failed to parse phone masks:', e);
  }
}

if (typeof registerAllowedCountries === 'undefined') {
  var registerAllowedCountries = [];
  try {
    const allowedCountriesJson = {{ allowed_countries|raw }};
    if (allowedCountriesJson && Array.isArray(allowedCountriesJson)) {
      registerAllowedCountries = allowedCountriesJson;
    }
  } catch (e) {
    console.warn('Failed to parse allowed countries:', e);
  }
}

// Helper function to get full phone number with country code
if (typeof getRegisterFullPhoneNumber === 'undefined') {
  function getRegisterFullPhoneNumber() {
    if (!registerIti) return '';
    
    const telInput = document.querySelector('#telephone');
    if (!telInput) return '';
    
    const selectedCountryData = registerIti.getSelectedCountryData();
    const dialCode = selectedCountryData.dialCode || '';
    let rawValue = telInput.value.replace(/\D/g, '');
    
    if (rawValue.length > 15) {
      rawValue = rawValue.substring(0, 15);
    }
    
    return rawValue ? '+' + dialCode + rawValue : '';
  }
}

// Helper function to update hidden phone field
if (typeof updateRegisterHiddenPhoneField === 'undefined') {
  function updateRegisterHiddenPhoneField() {
    const fullNumber = getRegisterFullPhoneNumber();
    const hiddenField = document.querySelector('#full_telephone');
    if (hiddenField) {
      hiddenField.value = fullNumber;
    }
    return fullNumber;
  }
}

// Initialize ITI for register form
if (typeof initRegisterIntlTelInput === 'undefined') {
  function initRegisterIntlTelInput() {
    const telInput = document.querySelector('#telephone');
    if (telInput && !telInput.classList.contains('iti__tel-input')) {
      if (registerIti) {
        registerIti.destroy();
      }

      const itiOptions = {
        initialCountry: defaultRegisterCountry,
        geoIpLookup: function(callback) {
          callback(defaultRegisterCountry);
        },
        separateDialCode: true,
        nationalMode: true,
        formatOnDisplay: false,
        strictMode: false,
        allowDropdown: true,
        useFullscreenPopup: false,
        containerClass: "input-group"
      };

      if (registerAllowedCountries.length > 0) {
        itiOptions.onlyCountries = registerAllowedCountries;
        
        if (registerAllowedCountries.length === 1) {
          itiOptions.allowDropdown = false;
        }
      }

      registerIti = window.intlTelInput(telInput, itiOptions);

      const applyRegisterInputMask = function() {
        if (typeof $.fn.inputmask === 'undefined') {
          console.warn('Inputmask not loaded yet');
          return;
        }
        
        const countryData = registerIti.getSelectedCountryData();
        let maskData = registerPhoneMasks[countryData.iso2];
        let mask = null;
        
        if (maskData && typeof maskData === 'object' && maskData.mask) {
          mask = maskData.mask;
        } else if (typeof maskData === 'string') {
          mask = maskData;
        }
        
        if (!mask) {
          const defaultMasks = {
            'ua': '99 999 99 99',
            'pl': '999 999 999',
            'us': '(999) 999-9999',
            'ca': '(999) 999-9999',
            'gb': '99999 999999',
            'de': '9999 99999999',
            'fr': '9 99 99 99 99',
            'it': '999 999 9999',
            'es': '999 99 99 99',
            'ru': '(999) 999-99-99',
            'by': '(99) 999-99-99',
          };
          mask = defaultMasks[countryData.iso2];
        }
        
        if (!mask) {
          const dialCodeLength = countryData.dialCode.length;
          if (dialCodeLength === 1) {
            mask = '(999) 999-9999';
          } else if (dialCodeLength === 2) {
            mask = '99 999 99 99';
          } else {
            mask = '999 999 9999';
          }
        }
        
        if ($(telInput).inputmask) {
          $(telInput).inputmask('remove');
        }
        
        $(telInput).inputmask({
          mask: mask,
          clearMaskOnLostFocus: false,
          showMaskOnHover: false,
          placeholder: '_',
          onincomplete: function() {
            updateRegisterHiddenPhoneField();
          },
          oncomplete: function() {
            updateRegisterHiddenPhoneField();
          },
          oncleared: function() {
            updateRegisterHiddenPhoneField();
          }
        });
        
        const placeholderText = mask.replace(/9/g, '_');
        telInput.setAttribute('placeholder', placeholderText);
      };
      
      setTimeout(function() {
        applyRegisterInputMask();
      }, 300);

      telInput.addEventListener('input', function(e) {
        updateRegisterHiddenPhoneField();
      });

      telInput.addEventListener('paste', function(e) {
        setTimeout(function() {
          updateRegisterHiddenPhoneField();
        }, 10);
      });

      telInput.addEventListener('countrychange', function() {
        applyRegisterInputMask();
        updateRegisterHiddenPhoneField();
      });

      telInput.addEventListener('blur', function() {
        updateRegisterHiddenPhoneField();
      });
    }
  }
}

// Initialize ITI when document is ready
$(document).ready(function() {
  setTimeout(initRegisterIntlTelInput, 500);
});

// Also initialize if modal is shown (in case form is in modal)
$(document).on('shown.bs.modal', function() {
  setTimeout(initRegisterIntlTelInput, 300);
});

// Remove error style on input
$("#telephone").on("change paste keyup", function() {
  $(this).removeClass('error_style');
});

// Загальна обробка для всіх інпутів
$(document).on('input', 'input', function() {
  $(this).removeClass('error_style');
  $(this).next('.error_message').remove();
});

// Update hidden field before form submission
$('#register_form').on('submit', function(e) {
  if (registerIti) {
    updateRegisterHiddenPhoneField();
  }
});
</script>
{{ footer }}