(function () {
  var y = document.getElementById('year');
  if (y) y.textContent = String(new Date().getFullYear());

  var overlayIds = ['privacy-policy', 'terms-of-use'];
  var overlays = overlayIds
    .map(function (id) {
      return document.getElementById(id);
    })
    .filter(Boolean);

  function isOverlayHash(hash) {
    return overlayIds.indexOf(String(hash || '').replace('#', '')) !== -1;
  }

  function setOverlayOpen(isOpen) {
    if (!overlays.length) return;
    if (isOpen) {
      overlays.forEach(function (ov) {
        ov.classList.add('is-open');
        ov.setAttribute('aria-hidden', 'false');
      });
      document.body.classList.add('overlay-open');
    } else {
      overlays.forEach(function (ov) {
        ov.classList.remove('is-open');
        ov.setAttribute('aria-hidden', 'true');
      });
      document.body.classList.remove('overlay-open');
    }
  }

  function setActiveOverlayFromHash() {
    if (!overlays.length) return;
    var activeId = String(window.location.hash || '').replace('#', '');
    overlays.forEach(function (ov) {
      var active = ov.id === activeId;
      if (active) {
        ov.classList.add('is-open');
        ov.setAttribute('aria-hidden', 'false');
      } else {
        ov.classList.remove('is-open');
        ov.setAttribute('aria-hidden', 'true');
      }
    });
    if (isOverlayHash(window.location.hash)) {
      document.body.classList.add('overlay-open');
    } else {
      document.body.classList.remove('overlay-open');
    }
  }

  function clearHash() {
    try {
      if (history && typeof history.replaceState === 'function') {
        history.replaceState(null, document.title, window.location.pathname + window.location.search);
      } else {
        window.location.hash = '';
      }
    } catch (e) {
      window.location.hash = '';
    }
  }

  function closeOverlay() {
    if (!isOverlayHash(window.location.hash)) return;
    try {
      window.location.hash = '#start';
    } catch (e) {
      clearHash();
    }
  }

  setActiveOverlayFromHash();
  window.addEventListener('hashchange', setActiveOverlayFromHash);

  document.addEventListener('click', function (e) {
    var el = e.target;
    if (!el) return;
    var closeBtn = el.closest && el.closest('[data-overlay-close]');
    if (!closeBtn) return;
    e.preventDefault();
    closeOverlay();
  });

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
      closeOverlay();
    }
  });

  var chips = document.querySelectorAll('.chips .chip');
  chips.forEach(function (chip) {
    chip.setAttribute('aria-pressed', chip.classList.contains('is-active') ? 'true' : 'false');
    chip.addEventListener('click', function (e) {
      e.preventDefault();
      var active = chip.classList.toggle('is-active');
      chip.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
  });

  var successModal = document.getElementById('itr-success-modal');
  function openSuccessModal() {
    if (!successModal) return;
    successModal.classList.add('is-open');
    successModal.setAttribute('aria-hidden', 'false');
    document.body.classList.add('modal-open');
  }

  function closeSuccessModal() {
    if (!successModal) return;
    successModal.classList.remove('is-open');
    successModal.setAttribute('aria-hidden', 'true');
    document.body.classList.remove('modal-open');
  }

  document.addEventListener('click', function (e) {
    if (!successModal) return;
    var el = e.target;
    if (!el) return;
    var close = el.closest && el.closest('[data-modal-close]');
    if (!close) return;
    e.preventDefault();
    closeSuccessModal();
  });

  var items = document.querySelectorAll('.faq-item');
  items.forEach(function (item) {
    var q = item.querySelector('.faq-q');
    var a = item.querySelector('.faq-a');
    if (!q || !a) return;

    q.addEventListener('click', function () {
      var expanded = q.getAttribute('aria-expanded') === 'true';
      q.setAttribute('aria-expanded', expanded ? 'false' : 'true');
      a.hidden = expanded;
      var icon = q.querySelector('.faq-icon');
      if (icon) icon.textContent = expanded ? '+' : '−';
    });
  });

  var leadForm = document.querySelector('form.lead-form');
  if (leadForm) {
    function setFieldError(fieldName, message) {
      var el = leadForm.querySelector('[data-error-for="' + fieldName + '"]');
      if (!el) return;
      el.textContent = message || '';
    }

    function clearAllErrors() {
      var els = leadForm.querySelectorAll('.field-error[data-error-for]');
      Array.prototype.forEach.call(els, function (e) {
        e.textContent = '';
      });
    }

    function validateLeadForm() {
      clearAllErrors();
      var firstInvalid = null;

      var nameInput = leadForm.querySelector('input[name="name"]');
      if (!nameInput || String(nameInput.value || '').trim() === '') {
        setFieldError('name', 'Please enter your name.');
        firstInvalid = firstInvalid || nameInput;
      }

      var taxpayerSelect = leadForm.querySelector('select[name="taxpayer_type"]');
      if (!taxpayerSelect || String(taxpayerSelect.value || '').trim() === '') {
        setFieldError('taxpayer_type', 'Please select your taxpayer type.');
        firstInvalid = firstInvalid || taxpayerSelect;
      }

      var filingChecked = leadForm.querySelector('input[name="filing_when"]:checked');
      if (!filingChecked) {
        setFieldError('filing_when', 'Please choose when you need to file.');
        firstInvalid = firstInvalid || leadForm.querySelector('input[name="filing_when"]');
      }

      var phoneInput = leadForm.querySelector('input[name="phone"]');
      var phoneVal = phoneInput ? String(phoneInput.value || '').trim() : '';
      if (!phoneInput || phoneVal === '') {
        setFieldError('phone', 'Please enter your phone number.');
        firstInvalid = firstInvalid || phoneInput;
      } else if (!/^[0-9+()\-\s]{8,20}$/.test(phoneVal)) {
        setFieldError('phone', 'Please enter a valid phone number.');
        firstInvalid = firstInvalid || phoneInput;
      }

      if (firstInvalid && typeof firstInvalid.focus === 'function') {
        firstInvalid.focus();
      }

      return !firstInvalid;
    }

    leadForm.addEventListener('input', function (e) {
      var t = e.target;
      if (!t || !t.name) return;
      if (t.name === 'name' || t.name === 'phone') {
        setFieldError(t.name, '');
      }
    });

    leadForm.addEventListener('change', function (e) {
      var t = e.target;
      if (!t || !t.name) return;
      if (t.name === 'taxpayer_type' || t.name === 'filing_when') {
        setFieldError(t.name, '');
      }
    });

    leadForm.addEventListener('submit', function (e) {
      e.preventDefault();

      if (!validateLeadForm()) {
        return;
      }

      var submitBtn = leadForm.querySelector('button[type="submit"]');
      if (!submitBtn) return;

      if (submitBtn.classList.contains('is-loading')) return;

      var originalHtml = submitBtn.innerHTML;
      submitBtn.classList.add('is-loading');
      submitBtn.innerHTML = '<span class="btn-spinner" aria-hidden="true"></span><span>Sending.. Please wait</span>';

      var incomeInput = leadForm.querySelector('input[name="income_components"]');
      if (incomeInput) {
        var selected = Array.prototype.slice
          .call(leadForm.querySelectorAll('.chips .chip.is-active'))
          .map(function (c) {
            return (c.textContent || '').trim();
          })
          .filter(Boolean);
        incomeInput.value = selected.join(', ');
      }

      var minDelayMs = 3500;
      var startedAt = Date.now();
      var formData = new FormData(leadForm);

      fetch('itr_submit.php', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
        .then(function (res) {
          return res
            .json()
            .catch(function () {
              return { ok: false, message: 'Unexpected server response.' };
            })
            .then(function (data) {
              return { status: res.status, data: data };
            });
        })
        .then(function (payload) {
          var elapsed = Date.now() - startedAt;
          var waitMore = Math.max(0, minDelayMs - elapsed);
          window.setTimeout(function () {
            if (payload && payload.data && payload.data.ok) {
              submitBtn.classList.remove('is-loading');
              submitBtn.innerHTML = originalHtml;
              try {
                leadForm.reset();
              } catch (err) {}
              clearAllErrors();
              openSuccessModal();
            } else {
              var msg =
                (payload && payload.data && payload.data.message) ||
                'Failed to send. Please try again.';
              submitBtn.classList.remove('is-loading');
              submitBtn.innerHTML = msg;
              window.setTimeout(function () {
                submitBtn.innerHTML = originalHtml;
              }, 2500);
            }
          }, waitMore);
        })
        .catch(function () {
          var elapsed = Date.now() - startedAt;
          var waitMore = Math.max(0, minDelayMs - elapsed);
          window.setTimeout(function () {
            submitBtn.classList.remove('is-loading');
            submitBtn.innerHTML = 'Network error. Please try again.';
            window.setTimeout(function () {
              submitBtn.innerHTML = originalHtml;
            }, 2500);
          }, waitMore);
        });
    });
  }
})();
