document.addEventListener("DOMContentLoaded", () => {
  const steps = [
    document.querySelectorAll(".step-main.step-1"),
    document.querySelectorAll(".step-main.step-2"),
    document.querySelectorAll(".step-main.step-3"),
  ];
  const progressTracker = document.querySelector(".progress-tracker .progress");
  const nextButtons = document.querySelectorAll(".buttons button:not(.empty)"); // All "Next" buttons
  const backButtons = document.querySelectorAll(".buttons .empty"); // All "Back" buttons

  let currentStep = 0;

  // Function to display the current step
  function showStep(stepIndex) {
    steps.forEach((stepElements, index) => {
      stepElements.forEach((element) => {
        element.classList.toggle("active", index === stepIndex);
      });
    });
    updateProgress(stepIndex);
  }

  // Function to update progress bar and tracker
  function updateProgress(stepIndex) {
    const progressPercentage = ((stepIndex + 1) / steps.length) * 100;
    progressTracker.style.width = `${progressPercentage}%`;

    const stepLabels = document.querySelectorAll(".progress-tracker .step");
    stepLabels.forEach((label, index) => {
      label.classList.toggle("active", index === stepIndex);
    });
  }

  // Function to validate the current step
  function validateStep(stepIndex) {
    const currentStepElements = steps[stepIndex];
    let isValid = true;

    currentStepElements.forEach((element) => {
      const requiredInputs = element.querySelectorAll("input[required]");

      requiredInputs.forEach((input) => {
        let errorContainer = input.nextElementSibling;

        // If there's no error container, create one
        if (!errorContainer || !errorContainer.classList.contains("alert")) {
          errorContainer = document.createElement("p");
          errorContainer.className = "alert";
          errorContainer.style.color = "red"; // Example style, change as needed
          input.parentNode.insertBefore(errorContainer, input.nextSibling);
        }

        // Check if input is valid
        if (
          (input.type === "checkbox" && !input.checked) ||
          (input.type === "text" && input.value.trim() === "")
        ) {
          showError(errorContainer, "This field is required.");
          isValid = false;
        } else {
          hideError(errorContainer);
        }
      });
    });

    return isValid;
  }

  // Show error message in a p tag with alert class
  function showError(container, message) {
    if (!container) return;
    container.textContent = message;
    container.classList.add("alert");
  }

  // Hide error message
  function hideError(container) {
    if (!container) return;
    container.textContent = "";
    container.classList.remove("alert");
  }

  // Check the URL hash and parameters on page load
  function goToStepFromHash() {
    const hash = window.location.hash.substring(1); // Remove the '#' symbol
    const urlParams = new URLSearchParams(window.location.search);
    const discordID = urlParams.get("discordID"); // Get the discordID parameter

    // Debug: Log the full URL parts
    console.log("Hash:", hash);
    console.log("Discord ID:", discordID);

    // Log discordID to console if it exists
    if (discordID) {
      console.log("Discord ID:", discordID);
    }

    // Set currentStep based on the hash
    if (hash === "step1") currentStep = 0;
    else if (hash === "step2") currentStep = 1;
    else if (hash === "step3") currentStep = 2;

    showStep(currentStep);
  }

nextButtons.forEach((button) => {
    button.addEventListener("click", (event) => {
        if (validateStep(currentStep)) {
            if (currentStep === 1) {
                // Force Discord authentication before moving to Step 3
                const urlParams = new URLSearchParams(window.location.search);
                const discordID = urlParams.get("discordID");
                
                if (!discordID) {
                   
                    window.location.href = 'https://hashcoinw.co.uk/discordConnect/login.php';
                } else {
                    currentStep++;
                    showStep(currentStep);
                    window.location.hash = `step${currentStep + 1}`;
                }
            } else if (currentStep < steps.length - 1) {
                currentStep++;
                showStep(currentStep);
                window.location.hash = `step${currentStep + 1}`;
            }
        } else {
            event.preventDefault();
        }
    });
});


  // "Back" button click event
  backButtons.forEach((button) => {
    button.addEventListener("click", (event) => {
      if (currentStep > 0) {
        currentStep--;
        showStep(currentStep);
        window.location.hash = `step${currentStep + 1}`; // Update hash in URL
      }
      event.preventDefault();
    });
  });

  // Remove error message when input changes
  document.querySelectorAll("input[required]").forEach((input) => {
    input.addEventListener("input", (event) => {
      const errorContainer = event.target.nextElementSibling;
      if (
        (input.type === "checkbox" && input.checked) ||
        (input.type === "text" && input.value.trim() !== "")
      ) {
        hideError(errorContainer);
      }
    });
  });
  function goToStepFromHash() {
    const hash = window.location.hash.substring(1); // Remove the '#' symbol
    const urlParams = new URLSearchParams(window.location.search);
    const discordID = urlParams.get("discordID"); // Get the discordID parameter

    // Only allow Step 3 if discordID is present
    if (hash === "step3" && !discordID) {
        // Redirect to Step 2 for Discord authentication if discordID is missing
       
        showDiscordAlertModal(); // Show modal instead of alert
        window.location.hash = "step2";
        currentStep = 1;
    } else {
        // Set currentStep based on the hash
        if (hash === "step1") currentStep = 0;
        else if (hash === "step2") currentStep = 1;
        else if (hash === "step3" && discordID) currentStep = 2;
    }

    showStep(currentStep);
}

function showDiscordAlertModal() {
  const modal = document.getElementById("discordAlertModal");
  modal.style.display = "flex";
}

function hideDiscordAlertModal() {
  const modal = document.getElementById("discordAlertModal");
  modal.style.display = "none";
}

// Close modal when the close button is clicked
document.getElementById("closeDiscordAlert").addEventListener("click", hideDiscordAlertModal);




  // Run on initial load to jump to the hash-specified step if it exists
  goToStepFromHash();
});
