const steps = document.querySelectorAll(".step");
const nextBtn = document.getElementById("nextBtn");
const prevBtn = document.getElementById("prevBtn");
const submitBtn = document.getElementById("submitBtn");
const progressBar = document.getElementById("progressBar");
const progressBarText = document.getElementById("progressText");

let formRequestData = [];
let currentStep = 0;
// Track if validation has been attempted for each step
const stepTried = Array(steps.length).fill(false);

function updateForm() {
  steps.forEach((step, index) => {
    step.classList.toggle("active", index === currentStep);
  });

  

  // Update buttons
  prevBtn.style.display = currentStep === 0 ? "none" : "inline-block";
  nextBtn.style.display =
    currentStep === steps.length - 1 ? "none" : "inline-block";
  submitBtn.style.display =
    currentStep === steps.length - 1 ? "inline-block" : "none";

  // Update progress bar
  const progress = Math.round(((currentStep + 1) / steps.length) * 100);
  progressBar.style.width = progress + "%";
  progressBarText.textContent = progress + "%";
  progressBarText.style.left = progress + "%";


  // Always clear errors when showing a new step
  clearStepErrors();
}

function clearStepErrors() {
  const currentInputs = steps[currentStep].querySelectorAll(
    "input, textarea, select"
  );
  const processedGroups = new Set();
  currentInputs.forEach((input) => {
    if (input.type === "checkbox" || input.type === "radio") {
      if (processedGroups.has(input.name)) return;
      processedGroups.add(input.name);
      let groupContainer = input.closest(
        ".checkbox-group, .radio-group, .checkboxes__item"
      );
      if (!groupContainer) groupContainer = input.parentElement;
      if (groupContainer) groupContainer.classList.remove("group-invalid");
      const feedback = groupContainer
        ? groupContainer.querySelector(".invalid-feedback")
        : null;
      if (feedback) feedback.style.display = "none";
      const group = steps[currentStep].querySelectorAll(
        `input[name='${input.name}']`
      );
      group.forEach((i) => i.classList.remove("is-invalid"));
    } else {
      input.classList.remove("is-invalid");
      const feedback =
        input.parentElement.querySelector(".invalid-feedback") ||
        input.nextElementSibling;
      if (feedback && feedback.classList.contains("invalid-feedback"))
        feedback.style.display = "none";
    }
  });
}

function validateCurrentStep(showErrors = false) {
  const currentInputs = steps[currentStep].querySelectorAll(
    "input, textarea, select"
  );
  let isValid = true;
  let firstInvalid = null;
  const processedGroups = new Set();

  currentInputs.forEach((input) => {
    if (input.offsetParent === null) return;
    if ((input.type === "checkbox" || input.type === "radio") && input.name) {
      if (processedGroups.has(input.name)) return;
      processedGroups.add(input.name);
      const group = steps[currentStep].querySelectorAll(
        `input[name='${input.name}']`
      );
      let groupValid = false;
      group.forEach((i) => {
        if (i.checked) groupValid = true;
      });
      let groupContainer = input.closest(
        ".checkbox-group, .radio-group, .checkboxes__item"
      );
      if (!groupContainer) groupContainer = input.parentElement;
      if (!groupValid) {
        if (showErrors) {
          group.forEach((i) => i.classList.add("is-invalid"));
          if (groupContainer) groupContainer.classList.add("group-invalid");
          const feedback = groupContainer
            ? groupContainer.querySelector(".invalid-feedback")
            : null;
          if (feedback) feedback.style.display = "block";
        }
        if (!firstInvalid) firstInvalid = input;
        isValid = false;
      } else {
        group.forEach((i) => i.classList.remove("is-invalid"));
        if (groupContainer) groupContainer.classList.remove("group-invalid");
        const feedback = groupContainer
          ? groupContainer.querySelector(".invalid-feedback")
          : null;
        if (feedback) feedback.style.display = "none";
      }
    } else if (input.type !== "checkbox" && input.type !== "radio") {
      if (!input.checkValidity()) {
        if (showErrors) {
          input.classList.add("is-invalid");
          const feedback =
            input.parentElement.querySelector(".invalid-feedback") ||
            input.nextElementSibling;
          if (feedback && feedback.classList.contains("invalid-feedback"))
            feedback.style.display = "block";
        }
        if (!firstInvalid) firstInvalid = input;
        isValid = false;
      } else {
        input.classList.remove("is-invalid");
        const feedback =
          input.parentElement.querySelector(".invalid-feedback") ||
          input.nextElementSibling;
        if (feedback && feedback.classList.contains("invalid-feedback"))
          feedback.style.display = "none";
      }
    }
  });

  if (showErrors && firstInvalid) {
    firstInvalid.scrollIntoView({
      behavior: "smooth",
      block: "center",
    });
  }

  return isValid;
}

nextBtn.addEventListener("click", () => {
  document.getElementById("loader-new").style.display = "flex";
  // Only mark this step as tried and show errors if not valid
  if (!validateCurrentStep(true)) {
    stepTried[currentStep] = true;
    return;
  }
  // If valid, move to next step and clear errors
  currentStep++;
  setTimeout(() => {
    updateForm();

    document.getElementById("loader-new").style.display = "none";
  }, 1000);
});

prevBtn.addEventListener("click", () => {
  if (currentStep > 0) {
    currentStep--;
    updateForm();
  }
});

document
  .getElementById("multiStepForm")
  .addEventListener("submit", function (e) {
    e.preventDefault();
    if (!validateCurrentStep(true)) {
      stepTried[currentStep] = true;
      return;
    }
    alert("Form submitted successfully!");
    this.reset(); // optional: reset the form
    currentStep = 0;
    stepTried.fill(false);
    updateForm();
  });

// Initial display
updateForm();

let sectionCounter = 1;

// Mock API data - replace with actual API calls
const mockGoodsData = [
  { id: 1, name: "Clothing and Apparel" },
  { id: 2, name: "Jewelry and Watches" },
  { id: 3, name: "Electronics and Computers" },
  { id: 4, name: "Food and Beverages" },
  { id: 5, name: "Automotive Products" },
];

const mockServicesData = [
  { id: 1, name: "Business and Management Services" },
  { id: 2, name: "Financial Services" },
  { id: 3, name: "Legal Services" },
  { id: 4, name: "Educational Services" },
  { id: 5, name: "Entertainment Services" },
];

// Real API call
function fetchDropdownData(type) {
  const apiUrl = `https://innova-labs.net:9094/trademarks/categories?search=&isGoods=${type}&page=1&count=10`;

  return new Promise((resolve, reject) => {
    $.ajax({
      url: apiUrl,
      method: "GET",
      dataType: "json",
      success: function (response) {
        console.log("API Response:", response);

        if (response && response.elements) {
          // Transform API response to match expected format
          const transformedData = response.elements.map((item) => ({
            id: item.id || item.ID, // Adjust based on your API response structure
            name: item.name || item.description || item.title, // Adjust field names as needed
          }));
          resolve(transformedData);
        } else {
          resolve([]);
        }
      },
      error: function (xhr, status, error) {
        console.error("API Error:", error);
        reject(error);
      },
    });
  });
}

// Handle checkbox changes
function handleCheckboxChange(sectionId) {
  const section = document.querySelector(`[data-section="${sectionId}"]`);
  if (!section) {
    console.warn(`Section with ID ${sectionId} not found.`);
    return;
  }
  const goodsCheckbox = section.querySelector(".goodsCheckbox");
  const servicesCheckbox = section.querySelector(".servicesCheckbox");
  const dropdown = section.querySelector(".goodsoption");
  const inputWrapper = section.querySelector(".inputWrapper");

  // Ensure only one checkbox is selected at a time
  if (goodsCheckbox.checked && servicesCheckbox.checked) {
    if (event.target === goodsCheckbox) {
      servicesCheckbox.checked = false;
    } else {
      goodsCheckbox.checked = false;
    }
  }

  // Update dropdown based on selection
  if (goodsCheckbox.checked || servicesCheckbox.checked) {
    const selectedType = goodsCheckbox.checked ? "Goods" : "Services";
    populateDropdown(dropdown, selectedType);
    inputWrapper.classList.remove("hidden");
  } else {
    dropdown.innerHTML =
      '<option value="">Please select Goods or Services first</option>';
    dropdown.disabled = true;
    dropdown.classList.add("dropdown-disabled");
    inputWrapper.classList.add("hidden");
  }
}

// Populate dropdown with API data
async function populateDropdown(dropdown, type) {
  dropdown.innerHTML = '<option value="">Loading...</option>';
  dropdown.disabled = true;
  dropdown.classList.add("dropdown-disabled");

  try {
    const data = await fetchDropdownData(type);
    console.log(data);

    dropdown.innerHTML = `<option value="">Select ${type.toLowerCase()}</option>`;

    if (data && data.length > 0) {
      data.forEach((item) => {
        const option = document.createElement("option");
        option.value = item.id;
        option.textContent = item.name;
        dropdown.appendChild(option);
      });
    } else {
      dropdown.innerHTML = `<option value="">No ${type.toLowerCase()} available</option>`;
    }

    dropdown.disabled = false;
    dropdown.classList.remove("dropdown-disabled");
  } catch (error) {
    dropdown.innerHTML = '<option value="">Error loading data</option>';
    dropdown.disabled = false;
    dropdown.classList.remove("dropdown-disabled");
    console.error("Error fetching dropdown data:", error);
  }
}

// Add new section
function addSection() {
  sectionCounter++;
  const newSection = createSection(sectionCounter);

  const addButton = document.getElementById("addClassBtn");
  addButton.parentNode.insertBefore(newSection, addButton);
}

// Create new section
function createSection(sectionId) {
  const sectionDiv = document.createElement("div");
  sectionDiv.className = "form-section";
  sectionDiv.setAttribute("data-section", sectionId);

  sectionDiv.innerHTML = `
        <h3>Do you sell, or intend to sell, a goods or service?</h3>
        <div class="checkbox-group checkboxes__item">
            <label class="checkbox style-b">
                <input type="checkbox" name="goods_services_${sectionId}" value="Goods" class="checkbox goodsCheckbox" data-section="${sectionId}">
                <div class="checkbox__checkmark"></div>
                <div class="checkbox__body">Goods</div>
            </label>
            <label class="checkbox style-b">
                <input type="checkbox" name="goods_services_${sectionId}" value="Services" class="checkbox servicesCheckbox" data-section="${sectionId}">
                <div class="checkbox__checkmark"></div>
                <div class="checkbox__body">Services</div>
            </label>
            <span class="invalid-feedback">Please select at least one option.</span>
        </div>
        <div class="goods-opt">
            <label>GOODS/SERVICES - Which of these categories best describes the industry or way in which you will use your mark?</label>
            <select class="goodsoption" name="goods_services_dropdown_${sectionId}" data-section="${sectionId}" disabled>
                <option value="">Please select Goods or Services first</option>
            </select>
        </div>
        <div class="dynamic-inputs mt-3"></div>
        <div class="inputWrapper hidden">
            <label class="dynamic-label">Enter the name you wish to protect</label>
            <input type="text" name="protect_name_${sectionId}" placeholder="Enter the name you wish to protect" required minlength="2">
            <span class="invalid-feedback">Please enter the name you wish to protect.</span>
        </div>
        <button type="button" class="remove-class" onclick="removeSection(${sectionId})">Remove Class</button>
    `;

  // Add event listeners to new checkboxes
  const checkboxes = sectionDiv.querySelectorAll('input[type="checkbox"]');
  checkboxes.forEach((checkbox) => {
    checkbox.addEventListener("change", () => handleCheckboxChange(sectionId));
  });

  return sectionDiv;
}

// Remove section
function removeSection(sectionId) {
  const section = document.querySelector(`[data-section="${sectionId}"]`);
  if (section) {
    section.remove();
  }
}

// Initialize event listeners for the first section
document.addEventListener("DOMContentLoaded", function () {
  const checkboxes = document.querySelectorAll('input[type="checkbox"]');
  checkboxes.forEach((checkbox) => {
    checkbox.addEventListener("change", () => {
      const sectionId = checkbox.getAttribute("data-section");
      handleCheckboxChange(sectionId);
    });
  });
});


