/**
 * Multi-step "get in touch" qualification form.
 */
(function () {
  "use strict";

  var form = document.getElementById("contact-form");
  if (!form || !form.classList.contains("quiz-form")) return;

  var steps = Array.prototype.slice.call(form.querySelectorAll(".quiz-step"));
  var total = steps.length;
  var current = 0;

  var progressFill = form.querySelector(".quiz-progress__fill");
  var progressCurrent = form.querySelector(".quiz-progress__current");

  function showStep(index) {
    steps.forEach(function (step, i) {
      step.classList.toggle("active", i === index);
    });
    if (progressFill) {
      progressFill.style.width = Math.round(((index + 1) / total) * 100) + "%";
    }
    if (progressCurrent) {
      progressCurrent.textContent = index + 1;
    }
  }

  function updateSelectedState(optionEls) {
    optionEls.forEach(function (option) {
      var input = option.querySelector("input");
      option.classList.toggle("is-selected", !!(input && input.checked));
    });
  }

  function stepIsValid(step) {
    var radios = Array.prototype.slice.call(step.querySelectorAll('input[type="radio"]'));
    if (radios.length) {
      var groups = {};
      radios.forEach(function (radio) {
        groups[radio.name] = groups[radio.name] || false;
        if (radio.checked) groups[radio.name] = true;
      });
      return Object.keys(groups).every(function (name) {
        return groups[name];
      });
    }

    var requiredFields = Array.prototype.slice.call(step.querySelectorAll("[required]"));
    for (var i = 0; i < requiredFields.length; i++) {
      if (!requiredFields[i].checkValidity()) {
        requiredFields[i].reportValidity();
        return false;
      }
    }
    return true;
  }

  steps.forEach(function (step) {
    var optionEls = Array.prototype.slice.call(step.querySelectorAll(".quiz-option"));
    optionEls.forEach(function (option) {
      var input = option.querySelector("input");
      if (!input) return;
      input.addEventListener("change", function () {
        updateSelectedState(optionEls);
        var error = step.querySelector(".quiz-step__error");
        if (error) error.classList.remove("visible");
      });
    });

    var nextBtn = step.querySelector(".quiz-next");
    if (nextBtn) {
      nextBtn.addEventListener("click", function () {
        if (!stepIsValid(step)) {
          var error = step.querySelector(".quiz-step__error");
          if (error) error.classList.add("visible");
          return;
        }
        if (current < total - 1) {
          current++;
          showStep(current);
        }
      });
    }

    var backBtn = step.querySelector(".quiz-back");
    if (backBtn) {
      backBtn.addEventListener("click", function () {
        if (current > 0) {
          current--;
          showStep(current);
        }
      });
    }
  });

  form.addEventListener("keydown", function (e) {
    if (e.key === "Enter" && current < total - 1) {
      e.preventDefault();
    }
  });

  var progressWrap = form.querySelector(".quiz-progress");
  var quizResult = document.getElementById("quiz-result");
  var quizProcessing = document.getElementById("quiz-processing");
  var quizSuccess = document.getElementById("quiz-success");
  var quizError = document.getElementById("quiz-error");
  var quizErrorText = document.getElementById("quiz-error-text");

  function showResultState(state) {
    [quizProcessing, quizSuccess, quizError].forEach(function (el) {
      if (el) el.classList.toggle("is-active", el === state);
    });
  }

  function showQuiz() {
    if (quizResult) quizResult.classList.remove("is-active");
    if (progressWrap) progressWrap.style.display = "";
    steps.forEach(function (step, i) {
      step.classList.toggle("active", i === current);
    });
  }

  var retryBtn = quizError ? quizError.querySelector(".quiz-retry") : null;
  if (retryBtn) {
    retryBtn.addEventListener("click", showQuiz);
  }

  form.addEventListener("submit", function (e) {
    e.preventDefault();

    if (progressWrap) progressWrap.style.display = "none";
    steps.forEach(function (step) {
      step.classList.remove("active");
    });
    if (quizResult) quizResult.classList.add("is-active");
    showResultState(quizProcessing);

    fetch(form.getAttribute("action"), {
      method: "POST",
      body: new FormData(form),
      headers: { "X-Requested-With": "XMLHttpRequest" }
    })
      .then(function (response) {
        return response.json().then(function (data) {
          return { ok: response.ok, data: data };
        });
      })
      .then(function (result) {
        if (result.ok && result.data && result.data.success) {
          showResultState(quizSuccess);
          setTimeout(function () {
            window.location.href = "deposit.php";
          }, 1800);
        } else {
          if (quizErrorText && result.data && result.data.message) {
            quizErrorText.textContent = result.data.message;
          }
          showResultState(quizError);
        }
      })
      .catch(function () {
        if (quizErrorText) {
          quizErrorText.textContent = "We couldn't reach the server. Please check your connection and try again.";
        }
        showResultState(quizError);
      });
  });

  showStep(current);
})();
