// Query Params
function buildQueryParams(obj) {
  return Object.keys(obj)
    .map((key) => key + "=" + obj[key])
    .join("&");
}

// Update the activation button link with the current page URL
function updatedActivateBtnLink() {
  const linkElement = document.getElementById("activateBtn");
  if (linkElement) {
    const systemURL = linkElement.href;
    const queryParams = buildQueryParams(wdesAdminAjaxLicenseActivation);
    const newUrl = `${systemURL}?${queryParams}`;
    activateBtn.href = newUrl;
  }
}

document.addEventListener("DOMContentLoaded", updatedActivateBtnLink);

// Submit Form with selected plugins
const loader = document.querySelector(
  ".wdes-panel-plugins-list-item-status-loader"
);
const nextStep = document.querySelector(".wdes-panel-plugins-next-step");
const submitBtn = document.getElementById("plugins-form-submit-btn");
const errorMsg = document.querySelector(".wdes-error-msg");

if (submitBtn) {
  document
    .getElementById("wdes-form-plugins")
    .addEventListener("submit", async function (event) {
      event.preventDefault();

      // Get all selected plugins
      var selectedValues = [];
      var checkboxes = document.querySelectorAll(
        'input[name="plugins"]:checked'
      );
      checkboxes.forEach(function (checkbox) {
        selectedValues.push(checkbox.value);
      });

      // success counter
      let successCounter = 0;

      // submit each selected plugin
      async function submitPlugin(slug, isLast) {
        // Find Element using attr data-id
        let element = document.querySelector(`[data-id="${slug}"]`);
        let status = element.querySelector(
          ".wdes-panel-plugins-list-item-status"
        );

        // Change status to loading
        status.innerHTML =
          'Loading<div class="wdes-panel-plugins-list-item-status-loader"></div>';
        status.classList.add("wdes-panel-plugins-list-item-status--loading");

        // Disable the submit button and replace it's content with a loader
        submitBtn.classList.add("disabled");

        let url =
          window.location.origin +
          window.ajaxurl +
          `?action=wdes_wizard_plugins&_wpnonce=${wdesAdminAjaxLicenseActivation?.["plugins-nonce"]}&slug=${slug}`;

        try {
          let response = await fetch(url, { method: "GET" });
          let data = await response.json();

          // Change Status to Done
          if (data?.success) {
            status.innerHTML = "Done";
            status.classList.remove(
              "wdes-panel-plugins-list-item-status--loading"
            );
            status.classList.add("wdes-panel-plugins-list-item-status--done");

            if (isLast) {
              // Hide the submit button
              submitBtn.classList.add("hidden");
            }

            successCounter++;
          } else {
            // Show Error Message
            errorMsg.classList.remove("hidden");
            errorMsg.innerHTML = "Something went wrong";
            status.classList.remove(
              "wdes-panel-plugins-list-item-status--loading"
            );
            status.classList.add("wdes-panel-plugins-list-item-status--error");
            status.innerHTML = "Error";
            // Hide the submit button
            submitBtn.classList.add("hidden");
          }

          // Handle success
        } catch (error) {
          // Show Error Message
          errorMsg.classList.remove("hidden");
          errorMsg.innerHTML = error.message;
        }
      }

      // Loop through each selected plugin and submit the form in series
      for (let i = 0; i < selectedValues.length; i++) {
        let slug = selectedValues[i];
        let isLast = i === selectedValues.length - 1;
        await submitPlugin(slug, isLast);
      }

      if (successCounter === selectedValues.length) {
        nextStep.classList.remove("hidden");
      }
    });
}
