$(document).ready(function () {
  $("#krfs_plugin_activation_form").submit(function (e) {
    e.preventDefault();
    let form = $(this);
    let name = form.find('input[name="name"]').val();
    let company_name = form.find('input[name="company_name"]').val();
    let email = form.find('input[name="email"]').val();
    let dial_code = form.find('input[name="dial_code"]').val();
    let phone_number = form.find('input[id="temp_phone_krfs_act"]').val();
    let phone = `${dial_code}-${phone_number}`; 
    form.find('input[name="phone"]').val(phone);
    let country = form.find('input[name="country"]').val();

    let data = {
      name: name,
      company_name: company_name,
      email: email,
      phone: phone,
      country: country,
      website_url: form.find('input[name="hidden_site_url"]').val(),
    };

    let isValid = true;
    $(".krfs_err_lbl").remove();
    $.each(data, function (key, value) {
      if (value.length == 0) {
        isValid = false;
        form
          .find(`input[name="${key}"]`)
          .after(
            '<span class="krfs_err_lbl text-required">' +
              '<img src="data:image/svg+xml;utf8,' +
              encodeURIComponent(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="rgba(0,0,134,1)"><path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM11 15V17H13V15H11ZM11 7V13H13V7H11Z"></path></svg>'
              ) +
              '" alt="Error"width="24" height="24" style="margin-right:5px;">' +
              "Required</span>"
          );
      } else if (key == "email") {
        let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
        if (!emailRegex.test(value)) {
          isValid = false;
          form
            .find(`input[name="${key}"]`)
            .after(
              '<span class="krfs_err_lbl text-required">' +
                '<img src="data:image/svg+xml;utf8,' +
                encodeURIComponent(
                  '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="rgba(0,0,134,1)"><path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM11 15V17H13V15H11ZM11 7V13H13V7H11Z"></path></svg>'
                ) +
                '" alt="Error"width="24" height="24" style="margin-right:5px;">' +
                "Invalid</span>"
            );
        }
      } else if (key == "website_url" && !value.startsWith("http")) {
        isValid = false;
        form
          .find(`input[name="${key}"]`)
          .after(
            '<span class="krfs_err_lbl text-required">Invalid website  url</span>'
          );
      } else if (key === "phone") {
        let phoneInput = form.find('input[id="temp_phone_krfs_act"]').val();

        if (phoneInput.length === 0) {
          isValid = false;
          $(".phone-error-container").append(
            '<span class="krfs_err_lbl text-required">' +
              '<img src="data:image/svg+xml;utf8,' +
              encodeURIComponent(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="rgba(0,0,134,1)"><path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM11 15V17H13V15H11ZM11 7V13H13V7H11Z"></path></svg>'
              ) +
              '" alt="Error" width="24" height="24" style="margin-right:5px;">' +
              "Required</span>"
          );
        }
      } else if (key === "country") {
        if (value.length === 0) {
          form
            .find(`input[name="${key}"]`)
            .after(
              $(".country-error-container").append(
                '<span class="krfs_err_lbl text-required">' +
                  '<img src="data:image/svg+xml;utf8,' +
                  encodeURIComponent(
                    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="rgba(0,0,134,1)"><path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM11 15V17H13V15H11ZM11 7V13H13V7H11Z"></path></svg>'
                  ) +
                  '" alt="Error"width="24" height="24" style="margin-right:5px;">' +
                  "Required</span>"
              )
            );
        }
      }
    });

    if (!isValid) {
      return;
    }
    // disable the form and submit button
    form.find('button[type="submit"]').attr("disabled", "disabled");

    krfs_activation_sidebar_toggle(false);
    form.unbind("submit").submit();
  });

  $(".krfs_active_form").click(() => {
    krfs_activation_sidebar_toggle(true);
  });
  $("#krfs_activation_form_overlay").click(() => {
    krfs_activation_sidebar_toggle(false);
    closesliderLang();
  });

  function update_phone() {
    let dial_code = $("#krfs_plugin_activation_form")
      .find('input[name="dial_code"]')
      .val();
    let phone = $("#krfs_plugin_activation_form")
      .find('input[id="temp_phone_krfs_act"]')
      .val();
    $("#krfs_plugin_activation_form")
      .find('input[name="phone"]')
      .val(`${dial_code}-${phone}`);
  }

  $("#temp_phone_krfs_act").change(function(){
    update_phone();
  });
  $(".krfs_phone_number_dropdown_content div").click(function(){
    setTimeout(() => {
      update_phone();
    },100);
  });


  document.querySelectorAll(".dropdown-number").forEach((dropdown) => {
    const dropdownContent = dropdown.querySelector(".number-dropdown-content");
    const arrowIcon = dropdown.querySelector(".arrowIcon");
    const selectedSpan = dropdown.querySelector(".dropdown-selected");
    const data_id = dropdown.getAttribute("data-id");

    // Toggle the dropdown on click
    dropdown.addEventListener("click", function (e) {
      e.stopPropagation(); // Prevent the event from bubbling up to the window

      let active_element = $(dropdown)
        .find(".number-dropdown-content")
        .find(".active");

      setTimeout(() => {
        $(dropdownContent).scrollTop(
          $(active_element).offset().top -
            $(dropdownContent).offset().top +
            $(dropdownContent).scrollTop()
        );
      }, 50);

      // Close any other open dropdowns
      document
        .querySelectorAll(".number-dropdown-content")
        .forEach((content) => {
          if (content !== dropdownContent) {
            content.classList.remove("show");
          }
        });
      document.querySelectorAll(".arrowIcon").forEach((icon) => {
        if (icon !== arrowIcon) {
          icon.classList.remove("rotate");
        }
      });

      // Toggle the clicked dropdown
      dropdownContent.classList.toggle("show");
      arrowIcon.classList.toggle("rotate");
    });

    // Handle item selection
    dropdown.querySelectorAll(".number-item").forEach((item) => {
      item.addEventListener("click", function (e) {
        e.stopPropagation(); // Prevent the dropdown from toggling back open

        const selectedCode = this.getAttribute("data-code");
        selectedSpan.textContent = selectedCode;

        $(dropdown).find(".number-item").removeClass("active");
        $(this).addClass("active");
        $('#country-search').val('');

        $("#krfs_plugin_activation_form")
          .find(`input[name="${data_id}"]`)
          .val(selectedCode);

        // Close the dropdown after selection
        dropdownContent.classList.remove("show");
        arrowIcon.classList.remove("rotate");

        let idx = $(this).attr("data-idx");
        let dynamic_class = "";
        let related_field_name = "";

        if (data_id == "country") {
          dynamic_class = "krfs_phone_number_dropdown_content";
          related_field_name = "dial_code";
        } else {
          dynamic_class = "krfs_country_dropdown_content";
          related_field_name = "country";
        }

        $(`.${dynamic_class} > div`).removeClass("active");
        $(`.${dynamic_class}`)
          .children(`div[data-idx="${idx}"]`)
          .addClass("active");
        let related_field_content = $(`.${dynamic_class}`)
          .children(`div[data-idx="${idx}"]`)
          .attr("data-code");
        $(`.${dynamic_class.replace("_content", "")}`)
          .find(".dropdown-selected")
          .html(related_field_content);
        $("#krfs_plugin_activation_form")
          .find(`input[name="${related_field_name}"]`)
          .val(related_field_content);
      });
    });
  });

  // Close the dropdown if clicked outside
  window.addEventListener("click", function () {
    document.querySelectorAll(".number-dropdown-content").forEach((content) => {
      content.classList.remove("show");
    });
    document.querySelectorAll(".arrowIcon").forEach((icon) => {
      icon.classList.remove("rotate");
    });
  });
});

  // Registration Form Country Search Bar
  $("#country-search").on("keydown", function (e) {
    if (e.key === "Enter") {
      e.preventDefault();
    }
  });

  $("#country-search").on("click", function (event) {
    event.stopPropagation();
  });

  // Country Filter Functionality
  $("#country-search").on("keyup", function () {
    let searchTerm = $(this).val().toLowerCase();
    let countryFound = false;
    $("#country-list div").each(function () {
      let countryName = $(this).text().toLowerCase();
      if (countryName.includes(searchTerm)) {
        $(this).show();
        countryFound = true;
      } else {
        $(this).hide();
      }
    });
    // Response body if no country found
    if (!countryFound) {
      $("#krfs-no-results").show();
    } else {
      $("#krfs-no-results").hide();
    }
  });

  // Phone number validation in activation form
  $('.krfs-input-number').on('input', function(){
    this.value = this.value.replace(/[^0-9]/g, '');
    if($(this).val().length > 15) {
      $(this).val($(this).val().slice(0, 15))
    }
  })

// Right Sidebar opening Function
const krfs_activation_sidebar_toggle = (toggle) => {
  if (toggle) {
    $("#rightSidebar").addClass("open");
    $("#krfs_activation_form_overlay").addClass("visible");
    $("body").addClass("no-scroll");
  } else {
    $("#rightSidebar").removeClass("open");
    $("#krfs_activation_form_overlay").removeClass("visible");
    $("body").removeClass("no-scroll");
  }
};

$(".krfs-admin-edit-contact-info-btn").click(() => {
  krfs_activation_sidebar_toggle(true);
});

$("#krfs_activation_form_overlay").click(() => {
  krfs_activation_sidebar_toggle(false);
});

// Eye View Change Function
function krfsEyeView(eyeImageId, dataChange, dataValue) {
  $('#' + eyeImageId).on('click', function () {
    let svgPath = $(this).find('path'); 
        let currentFill = svgPath.attr('fill');
        let newFill = currentFill === 'var(--krfs-primary-color)' ? 'black' : 'var(--krfs-primary-color)';
        svgPath.attr('fill', newFill);

      $('[data-change="' + dataChange + '"]').each(function () {
          let textChangeElement = $(this); 
          let newChangeElement = $(this).siblings('[data-value="' + dataValue + '"]'); 
          let swapText = textChangeElement.html(); 
          textChangeElement.html(newChangeElement.html()); 
          newChangeElement.html(swapText); 
      })
  });
}

krfsEyeView('view-engagement-ring-style', 'engagement-ring-style-text-change', 'engagement-ring-style-new-change');
krfsEyeView('view-engagement-ring-side-stone', 'engagement-ring-stone-text-change', 'engagement-ring-stone-new-change');
krfsEyeView('wedding-ring-men-ring-style', 'wedding-ring-men-text-change', 'wedding-ring-men-new-change');
krfsEyeView('wedding-ring-women-ring-style', 'wedding-ring-women-text-change', 'wedding-ring-women-new-change');
krfsEyeView('common-metal-type', 'common-metal-type-text-change', 'common-metal-type-new-change');
krfsEyeView('common-diamond-shape', 'common-diamond-shape-text-change', 'common-diamond-shape-new-change');

// Pricing Tab Section Dropdown
$(".plan-dropdown-heading").click(function () {
  const content = $(this).next();
  const arrowIcon = $(this).find(".arrow-icon");

  // Toggle visibility of the content
  if (content.css("display") === "block") {
    $(content).hide(200);
    arrowIcon.removeClass("rotate");
  } else {
    $(content).show(200);
    arrowIcon.addClass("rotate");
  }
});