jQuery(document).ready(function ($) {
  localBuyersLightBox();
  const forms = document.querySelectorAll('[id^="blueprintdigital-form"]');

  const setTotalSections = (form, form_id) => {
    const counterTotalElement = document.querySelector(
      ".bp-counter-total-" + form_id
    );
    const formStepElements = form.querySelectorAll(".form-step");
    counterTotalElement.innerHTML = formStepElements.length;
  };

  const createTrustedFormScript = () => {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.src = `${document.location.protocol === "https:" ? "https" : "http"
      }://api.trustedform.com/trustedform.js?field=xxTrustedFormCertUrl&ping_field=xxTrustedFormPingUrl&l=${new Date().getTime()}${Math.random()}`;
    document
      .getElementsByTagName("script")[0]
      .parentNode.insertBefore(
        script,
        document.getElementsByTagName("script")[0]
      );
  };

  const createJornayeLeadScript = () => {
    (function () {
      var s = document.createElement("script");
      s.id = "LeadiDscript_campaign";
      s.type = "text/javascript";
      s.async = true;
      s.src =
        "https://create.lidstatic.com/campaign/2fcd30e3-5e74-5fff-7ace-ad5e299554e8.js?snippet_version=2";
      var LeadiDscript = document.getElementById("LeadiDscript");
      LeadiDscript.parentNode.insertBefore(s, LeadiDscript);
    })();
  };

  for (const form of forms) {
    const form_id = form.id.substring(0 + "blueprintdigital-form-".length);
    validateFieldsByDependentChild(form);
    if (document.querySelector(".bp-form-header-stepper")) {
      setTotalSections(form, form_id);
      isFirstSection(form);
      initLastSectionBtn(form, form_id);

      const progressBarFill = document.querySelector(".bp-bar-fill-" + form_id);
      const formStepElements = form.querySelectorAll(".form-step");

      document
        .querySelectorAll(".btn-navigate-back")
        .forEach((formNavigationBtn, iter) => {
          formNavigationBtn.addEventListener("click", (e) => {
            let stepNumber = parseInt(
              formNavigationBtn.getAttribute("step_number")
            );

            navigateToPreviousStep(form, stepNumber);
          });
        });

      progressBarFill.style.width = `${(100 / formStepElements.length) * 1}%`;

      document
        .querySelectorAll("#btn-navigate-form-step-" + form_id)
        .forEach((formNavigationBtn, iter) => {
          formNavigationBtn.addEventListener("click", (e) => {
            const stepNumber = parseInt(
              formNavigationBtn.getAttribute("step_number")
            );
            var step_all = form.querySelectorAll(".bp-counter");
            var current_step = step_all[iter].getAttribute("step_number");
            var totalSteps = step_all[iter].getAttribute("steps");
            validateStep = parseInt(
              formNavigationBtn.getAttribute("current_step_btn")
            );

            if (checkForRequiredFields(form, validateStep)) {
              if (current_step == totalSteps) {
                form
                  .querySelector(".bp-submit-section")
                  .classList.remove("bp-d-none");
                jQuery("#btn-navigate-form-step-" + form_id).addClass(
                  "bp-d-none"
                );
                form.querySelectorAll(".bp-button-container").forEach((elm) => {
                  elm.style.display = "none";
                });
              }
              navigateToFormStep(form, stepNumber);
            }
          });
        });

      jQuery(form).find("section").length > 0
        ? form
          .querySelector("#btn-last-section-" + form_id)
          .addEventListener("click", (e) => {
            navigateToPreviousStep(
              form,
              jQuery("#btn-last-section-" + form_id).attr("current_step_btn")
            );
            jQuery(form).find(".bp-submit-section").addClass("bp-d-none");
            let clearBtnContainer = jQuery(form).find(
              "section:visible .bp-clear-btn"
            );
            let clearBtn = jQuery(form).find(
              "section:visible .bp-button-container"
            );

            if (
              parseInt(
                jQuery(form).find("section:visible").prop("id").split("-")[1]
              ) != 1
            ) {
              clearBtnContainer.css("display", "");
            }
            clearBtn.css("display", "");
          })
        : "";
    }

    document.addEventListener("submit", function (event) {
      event.preventDefault();
      service = jQuery("#service_type").val();
      url = event.target.action;
      const niche = url.split("?")[1].split("&")[0].split("=")[1];
      if (("mold remediation" == decodeURI(niche)) && (service == "Mold Testing Only")) {
        new_niche = encodeURI("mold inspection");
        url = url + "&niche_specific=" + niche;
        url = url.replace(niche, new_niche);
      }
      else if (("mold inspection" == decodeURI(niche)) && ((service == "Mold Testing and Removal") || (service == "Mold Removal Only"))) {
        new_niche = encodeURI("mold remediation");
        url = url + "&niche_specific=" + niche;
        url = url.replace(niche, new_niche);
      }
      const type = event.target.method;
      if (validateBlueForm(form_id)) {
        form.querySelector(`#btn-submit-${form_id}`).value = "Processing...";

        verticalSubmission(url, type, form);
      } else {
        form.querySelector(`#btn-submit-${form_id}`).value = "Submit";
      }
    });
  }

  createTrustedFormScript();
  createJornayeLeadScript();

  function fetchAndCacheIp() {
    fetch("https://api.ipify.org?format=json")
      .then((response) => response.json())
      .then((data) => {
        const { ip } = data;
        // Store the IP in LocalStorage for later use
        localStorage.setItem("cachedIp", ip);
        localStorage.setItem("lastCachedTime", new Date().getTime());
      })
      .catch((error) => {
        console.error(error);
      });
  }

  function verticalSubmission(url, type, form) {
    tcpa_text = $('.bp-chk-text').text();
    $('#tcpa_language').val(tcpa_text);
    form_id = form.id.substring(0 + "blueprintdigital-form-".length);
    $.ajax({
      url: url,
      crossDomain: true,
      headers: {
        accept: "application/json",
        "Access-Control-Allow-Origin": "*",
        IP: localStorage.getItem("cachedIp") || fetchAndCacheIp(),
      },
      type: "POST",
      dataType: "json",
      data: jQuery(form).serialize(),
      success: function (response) {
        redirectPPC(response)
      },
      error: function (data) {
        var messageColor = 'style="color:white;"',
          errMessage;
        if (data.responseJSON) {
          errMessage = data.responseJSON.message;
        } else if (data.responseText) {
          errMessage = data.responseText;
        } else {
          errMessage = "Process Failed, Kindly Contact Administrator.";
        }
        $(".error_msg-" + form_id).html(
          '<i class="bp-text-center" ' +
          messageColor +
          " >" +
          errMessage +
          "</i>"
        );

        jQuery(".bp-card-" + form_id).hide();
        jQuery(".error_msg-" + form_id).focus();
        jQuery(".error_msg-" + form_id + ".bp-alert-danger").show();
      },
    });
  }

  function redirectPPC(response) {

      pageExists("/thank-you")
        .then(exists => {
          if (exists) {
            window.location.href = "/thank-you";
          } else {
            let responseMessageColor =
              response.status == 200
                ? 'style="color:white;"'
                : 'style="color:green; background: yellow;"';
            $(".success_msg-" + form_id).html(
              '<i class="bp-text-center" ' +
              responseMessageColor +
              " >" +
              response.message +
              "</i>"
            );
            jQuery(".bp-card-" + form_id).hide();
            jQuery(".success_msg-" + form_id).focus();
            jQuery(".success_msg-" + form_id + ".bp-alert-success").show();
          }
        });
  }

  function pageExists(url) {
    return new Promise((resolve, reject) => {
      jQuery.ajax({
        url: url,
        type: "HEAD",
        success: function () {
          resolve(true);
        },
        error: function () {
          resolve(false);
        }
      });
    });
  }


  function incrementBarOnNext(form, sectionNumber) {
    form_id = form.id.substring(0 + "blueprintdigital-form-".length);
    document.querySelector(
      ".bp-counter-current-screen-" +
      form.id.substring(0 + "blueprintdigital-form-".length)
    ).innerHTML = sectionNumber;
    const progressBarFill = document.querySelector(".bp-bar-fill-" + form_id);
    const formStepElements = form.querySelectorAll(".form-step");
    progressBarFill.style.width = `${(100 / (formStepElements.length / sectionNumber)) * 1
      }%`;
  }

  function decrementBarOnPrevious(form, sectionNumber) {
    form_id = form.id.substring(0 + "blueprintdigital-form-".length);
    document.querySelector(
      ".bp-counter-current-screen-" +
      form.id.substring(0 + "blueprintdigital-form-".length)
    ).innerHTML = sectionNumber;
    const progressBarFill = document.querySelector(".bp-bar-fill-" + form_id);
    const formStepElements = form.querySelectorAll(".form-step");
    progressBarFill.style.width = `${(100 / (formStepElements.length / sectionNumber)) * 1
      }%`;
  }

  function checkForRequiredFields(form, stepNumber) {
    var result = true;
    var formElems = form
      .querySelector("#step-" + stepNumber)
      .querySelectorAll("input, select");

    for (let i = 0; i < formElems.length; i++) {
      if (!formElems[i].checkValidity()) {
        formElems[i].parentElement.classList.add("bp-input-err");
        result = false;
      } else {
        formElems[i].parentElement.classList.remove("bp-input-err");
      }
    }
    return result;
  }

  const navigateToFormStep = (form, stepNumber) => {
    incrementBarOnNext(form, stepNumber);
    form.querySelectorAll(".form-step").forEach((formStepElement) => {
      formStepElement.classList.add("bp-d-none");
    });
    form.querySelector("#step-" + stepNumber).classList.remove("bp-d-none");
    isFirstSection(form);
    isLastSection(form);
  };

  const navigateToPreviousStep = (form, stepNumber) => {
    decrementBarOnPrevious(form, stepNumber);
    form.querySelectorAll(".form-step").forEach((formStepElement) => {
      formStepElement.classList.add("bp-d-none");
    });

    form.querySelector("#step-" + stepNumber).classList.remove("bp-d-none");
    isFirstSection(form);
    isLastSection(form);
  };
});

function localBuyersLightBox() {
  jQuery(".view-buyers-list").on("click", function () {
    console.log("Fetching Buyers...");
    jQuery.ajax({
      url: "https://bpdmonitors.com/webhooks/read_buyers",
      type: "GET",
      dataType: "json",
      success: function (response) {
        var tableHtml = '<table class="table table-bordered">';
        for (var i = 0; i < response.length; i += 4) {
          tableHtml += '<tr class="lh-1">';

          for (var j = i; j < i + 4 && j < response.length; j++) {
            tableHtml += '<td class="small">' + response[j] + '</td>';
          }

          tableHtml += '</tr>';
        }

        tableHtml += '</table>';

        jQuery(".modal-body").html(tableHtml);
      },
      error: function (data) {
        console.log(data);
      }
    });
  });
}

function validateBlueForm(form_id) {
  const forms = document.querySelectorAll('[id^="blueprintdigital-form"]');
  const formIndex = Array.from(forms).findIndex(
    (form) => form.id === "blueprintdigital-form-" + form_id
  );

  let isValid = true;
  const termsCheckbox = document.querySelector(
    "#term_and_conditions-" + form_id
  );
  const errorContainer = document.querySelector(
    "#bp-error-checkbox-" + form_id
  );

  if (!termsCheckbox.checked) {
    errorContainer.innerHTML = "Kindly, check on Terms and Conditions.";
    isValid = false;
  }

  const recaptchaResponse = grecaptcha.getResponse(formIndex);
  const recaptchaErrorContainer = document.getElementById(
    "rcaptcha-" + form_id
  );

  if (recaptchaResponse.length == 0) {
    recaptchaErrorContainer.innerHTML = "You can't leave Captcha Code empty";
    isValid = false;
  } else {
    recaptchaErrorContainer.innerHTML = "Captcha completed";
  }

  grecaptcha.reset(formIndex);
  return isValid;
}

const isFirstSection = (form) => {
  form = jQuery(form);
  const clearBtnContainer = form.find("section:visible .bp-clear-btn")[0];
  const clearBtn = form.find("section:visible .bp-button-container")[0];
  const visibleSection = form.find("section:visible");
  if (visibleSection.length > 0) {
    const sectionId = visibleSection[0].id;
    const sectionNumber = parseInt(sectionId.split("-")[1]);
    if (sectionNumber !== 1) {
      clearBtnContainer.style.display = "";
      clearBtn.style.display = "";
    } else {
      clearBtn.style.display = "";
    }
  }
};

const isLastSection = (form) => {
  form = jQuery(form);
  const clearBtnContainer = form.find("section:visible .bp-clear-btn");
  const clearBtn = form.find("section:visible .bp-button-container");
  const visibleSection = form.find("section:visible");

  if (
    parseInt(visibleSection.prop("id").split("-")[1]) ==
    parseInt(form.find(".form-step").length)
  ) {
    clearBtnContainer.css("display", "none");
    clearBtn.css("display", "none");
    jQuery(
      "#btn-last-section-" +
      form[0].id.substring(0 + "blueprintdigital-form-".length)
    ).removeClass("bp-d-none");
  }
};

function initLastSectionBtn(form, formId) {
  const lastSectionBtn = document.querySelector(`#btn-last-section-${formId}`);
  const formSteps = form.querySelectorAll(".form-step");
  lastSectionBtn.setAttribute("current_step_btn", formSteps.length - 1);
  lastSectionBtn.setAttribute("step_number", formSteps.length);
}

document.addEventListener("DOMContentLoaded", function (event) {
  let observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
      toggleSpinner();
      populateJornayaId();
    });
  });
  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });
});

function toggleSpinner() {
  const spinnerForms = document.querySelectorAll(".bpd-spinner-card");
  for (const form of spinnerForms) {
    const formCert = form.querySelector('input[name="xxTrustedFormToken"]');
    const spinner = form.querySelector(".bpd-spinner");
    const mainForm = spinner.parentElement;
    const method = formCert ? "remove" : "add";
    jQuery(mainForm).toggleClass("disable-form", method === "add");
    spinner.style.display = method === "remove" ? "none" : "flex";
  }
}

function populateJornayaId() {
  if (document.querySelector("#leadid_token").value) {
    document
      .querySelectorAll('[name="universal_leadid"]')
      .forEach((element) => {
        element.value = document.querySelector("#leadid_token").value;
      });
  }
}

function validateFieldsByDependentChild(form) {
  var all_elemes = form.querySelectorAll("input, select");
  all_elemes.forEach(function (v) {
    let eventType = v.tagName.toLowerCase() != "select" ? "input" : "change";
    toggleRequiredAttribute(v, eventType, form);
  });
}

function toggleRequiredAttribute(input, eventType, form) {
  input.addEventListener(eventType, function () {
    let elem = form.querySelector(
      '[name="' + input.getAttribute("data-child") + '"]'
    );
    if (elem) {
      elem.required = this.value === input.getAttribute("data-requirement");
    }
  });
}
window.onload = function () {
  jQuery("div p img").removeAttr("srcset");
}