

/// some script

$(document).ready(function () {
  // Get the current URL path and split it
  var path = window.location.pathname.split("/").pop();

  // Default to 'index.php' if path is empty (assuming home page)
  if (path === "") {
    path = "index.php";
  }

  // Check if the current path matches any of the navigation links
  $(".navbar-nav a").each(function () {
    var href = $(this).attr("href");
    // Adjust the condition to handle both '/' and 'index.php' for home
    if (
      href === path ||
      (href === "/" && (path === "index.php" || path === ""))
    ) {
      $(this).addClass("active");
    } else {
      $(this).removeClass("active");
    }
  });
});
function toggleDropdownCSS() {
  const cssRule = document.getElementById("dropdown-css");
  if (window.innerWidth < 992) {
    if (cssRule) cssRule.parentNode.removeChild(cssRule);
  } else {
    if (!cssRule) {
      const style = document.createElement("style");
      style.id = "dropdown-css";
      style.innerHTML =
        ".navbar-expand-lg .nav-item:hover .dropdown-menu { display: block; }";
      document.head.appendChild(style);
    }
  }
}

window.addEventListener("resize", toggleDropdownCSS);
window.addEventListener("load", toggleDropdownCSS);



const counters = document.querySelectorAll(".counter");

counters.forEach((counter) => {
  counter.innerText = "0";
  const updateCounter = () => {
    const target = +counter.getAttribute("data-target");
    const count = +counter.innerText;
    const increment = target / 400;
    if (count < target) {
      counter.innerText = `${Math.ceil(count + increment)}`;
      setTimeout(updateCounter, 1);
    } else counter.innerText = target;
  };
  updateCounter();
});

$(".opensidepopup").on("click", function () {
  $(".floatbutton").toggleClass("active");
  var packagename = $(this).attr("rel");
  $(".packagename").val(packagename);
  $(".packagenametext").text(packagename);
});

$("#entry-box_close").click(function () {
  $("#entry-popup").fadeOut();
}),
  $(".popup-open").click(function () {
    $("#entry-popup").css("display", "flex").fadeIn();
  }),
  function popupFunc() {
    setTimeout(function () {
      $("#entry-popup").css("display", "flex").fadeIn();
    }, 3e4);
  };

// window.addEventListener("load", function(){
//   setTimeout(
//       function open(event){
//           document.querySelector("#entry-popup").style.display = "flex";
//       },
//       20000
//   )
// });

// $('.open_popup').click(function () {
// $("#popup_form").css('display', 'flex');
// });

$(".popup-open").click(function () {
  var priceText = $(this).parents(".package-box").find(".packg-price").text();
  var titleText = $(this).parents(".package-box").find(".packg-hd").text();

  $('#entry-popup input[name="price"]').val(priceText);
  $('#entry-popup input[name="title"]').val(titleText);
  // $('#entry-popup').css('display', 'block');
});



//table-sec

let data = [];
let totalResults = 0;

let urlParams = new URLSearchParams(window.location.search);
let searchedValue = urlParams.get("text");

function getTrademarkData(page = 1) {
  $.ajax({
    url: `https://innova-labs.net:9094/trademarks/search?name=${searchedValue}&page=${page}&count=10`,
    method: "GET",
    dataType: "json",
    success: function (response) {
      if (response.elements && Array.isArray(response.elements)) {
        data = response.elements.map((item) => ({
          trademark: item.markIdentification,
          owner: item.owners.length > 0 ? item.owners[0].partyName : undefined,
          serial: item.serialNumber,
          date: item.filingDate,
          status: item.liveOrDeadStatus,
        }));
      } else {
        console.warn("No 'elements' array found in response");
        data = [];
      }

      totalResults = response.totalResults;

      const tableBody = document.getElementById("table-body");

      displayTable(data, tableBody, rowsPerPage, page);
      setupPagination(data, document.getElementById("page-numbers"));
    },
    error: function (xhr, status, error) {
      console.error("AJAX Error:", error);
    },
  });
}

let currentPage = 1;
const rowsPerPage = 10;

function displayTable(data, wrapper, rowsPerPage, page) {
  if (!wrapper) {
    console.log("Wrapper element not found.");
    return;
  }
  wrapper.innerHTML = "";
  page--;
  console.log(data);
  const start = page * rowsPerPage;
  const end = start + rowsPerPage;
  const paginatedItems = data;
  console.log(paginatedItems);
  for (let item of paginatedItems) {
    const row = `<tr class="table-results">
                    <td class="title">${item.trademark}</td>
                    <td class="owner">${item.owner}</td>
                    <td>${item.serial}</td>
                    <td>${item.date}</td>
                    <td><span class="status ${item.status.toLowerCase()}">${item.status
      }</span></td>  
        </tr>`;
    wrapper.innerHTML += row;
  }
  updateDisplayInfo(start + 1, Math.min(end, data.length), totalResults);
}

function setupPagination(data, wrapper) {
  if (!wrapper) {
    console.log("Pagination wrapper not found!");
    return;
  }
  wrapper.innerHTML = "";

  const pageCount = Math.ceil(totalResults / rowsPerPage);
  for (let i = 1; i <= pageCount; i++) {
    const btn = document.createElement("button");
    btn.innerText = i;
    btn.classList.add("page-num");
    if (i === currentPage) btn.style.backgroundColor = "#dfe6f0";

    btn.addEventListener("click", function () {
      currentPage = i;
      displayTable(
        data,
        document.getElementById("table-body"),
        rowsPerPage,
        currentPage
      );
      setupPagination(data, wrapper);
    });

    wrapper.appendChild(btn);
  }
}

function updateDisplayInfo(start, end, total) {
  document.getElementById(
    "display-info"
  ).innerText = `Displaying  ${start} to ${end} of ${total} entries`;
}

function updateDisplayInfo(start, end, total) {
  const info = `
    <span class="display-text">Displaying mark</span> 
    <span class="display-count">${start} to ${end}</span> 
    <span class="display-text">of</span> 
    <span class="display-count">${total}</span> 
    <span class="display-text">entries</span>
  `;
  document.getElementById("display-info").innerHTML = info;
}

function prevPage() {
  if (currentPage > 1) {
    currentPage--;
    getTrademarkData(currentPage);
    // displayTable(data, document.getElementById("table-body"), rowsPerPage, currentPage);
    // setupPagination(data, document.getElementById("page-numbers"));
  }
}

function nextPage() {
  if (currentPage < Math.ceil(totalResults / rowsPerPage)) {
    currentPage++;
    getTrademarkData(currentPage);
    // displayTable(data, document.getElementById("table-body"), rowsPerPage, currentPage);
    // setupPagination(data, document.getElementById("page-numbers"));
  }
}

window.onload = function () {
  getTrademarkData(currentPage);

  // displayTable(data, document.getElementById("table-body"), rowsPerPage, currentPage);
  // setupPagination(data, document.getElementById("page-numbers"));
};
//trademark-registration form

const checkboxes = document.querySelectorAll(
  'input[type="checkbox"][name="option"]'
);
const inputField = document.getElementById("inputField");
const inputLabel = document.getElementById("inputLabel");

const labels = {
  Name: "Enter the name you wish to protect",
  Slogan: "Enter the slogan you wish to protect",
  Logo: "Please provide a complete and accurate description of your logo, including any words that may appear in the logo. An example of a description is: ‘a red cat wrapped around a blue outline of a globe’. Leave out the colors if you want to protect your logo in all colors",
};

const placeholders = {
  Name: "Enter the name you wish to protect",
  Slogan: "Enter the slogan you wish to protect",
  Logo: "", // Empty placeholder for logo
};

checkboxes.forEach((checkbox) => {
  checkbox.addEventListener("change", () => {
    // Only one checkbox active
    checkboxes.forEach((cb) => (cb.checked = false));
    checkbox.checked = true;

    const selected = checkbox.value;
    inputField.placeholder = placeholders[selected];
    inputLabel.textContent = labels[selected];
  });
});

// Set default on load
window.addEventListener("DOMContentLoaded", () => {
  const defaultChecked = document.querySelector('input[name="option"]:checked');
  if (defaultChecked) {
    inputField.placeholder = placeholders[defaultChecked.value];
    inputLabel.textContent = labels[defaultChecked.value];
  }
});

document.addEventListener("DOMContentLoaded", function () {
  const yesInfo = document.getElementById("yesInfo");
  const noInput = document.getElementById("noInput");
  //   const yesInfoLinving = document.getElementById('nested-fields');
  //   const noInfoLinving = document.getElementById('noInfoLinving');

  function toggleLogoColorInfo(value) {
    if (value === "yes") {
      yesInfo.style.display = "block";
      noInput.style.display = "none";
    } else if (value === "no") {
      yesInfo.style.display = "none";
      noInput.style.display = "block";
    }
  }

  // Attach change event to all radio buttons
  const radiosLogos = document.querySelectorAll(
    'input[name="protect_logo_colors"]'
  );
  radiosLogos.forEach((radio) => {
    radio.addEventListener("change", function () {
      toggleLogoColorInfo(this.value);
    });
  });

  // Initial state on load
  const selected = document.querySelector(
    'input[name="protect_logo_colors"]:checked'
  );
  if (selected) {
    toggleLogoColorInfo(selected.value);
  }
});

const nameSloganField = document.getElementById("nameSloganField");
const logoFields = document.getElementById("logoFields");

checkboxes.forEach((cb) => {
  cb.addEventListener("change", () => {
    // Uncheck all
    checkboxes.forEach((c) => (c.checked = false));
    cb.checked = true;

    const selected = cb.value;

    if (selected === "Logo") {
      logoFields.classList.remove("hidden");
      nameSloganField.classList.remove("hidden");
      inputLabel.textContent = labels[selected];
      inputField.placeholder = "";
    } else {
      logoFields.classList.add("hidden");
      nameSloganField.classList.remove("hidden");
      inputLabel.textContent = labels[selected];
      inputField.placeholder = placeholders[selected];
    }
  });
});

// Initial setup on page load
window.addEventListener("DOMContentLoaded", () => {
  const checked = document.querySelector(".option-checkbox:checked");
  if (checked && checked.value === "Logo") {
    logoFields.classList.remove("hidden");
    nameSloganField.classList.remove("hidden");
    inputLabel.textContent = labels.Logo;
    inputField.placeholder = "";
  }
});

const nestedFields = document.getElementById("nested-fields");

const radiosnestedFields = document.querySelectorAll(
  'input[name="living_person_name"]'
);

function toggleNestedFields() {
  const selected = document.querySelector(
    'input[name="living_person_name"]:checked'
  );

  if (selected && selected.value === "yes") {
    nestedFields.classList.remove("hidden");
  } else {
    nestedFields.classList.add("hidden");
  }
}

// Attach event listener to all "living_person_name" radio buttons
radiosnestedFields.forEach((radio) => {
  radio.addEventListener("change", toggleNestedFields);
});

// On page load
window.addEventListener("DOMContentLoaded", toggleNestedFields);

const isNameNotShow = document.getElementById("isNameNotShow");
const extraInput = document.getElementById("extra-input"); // Correct ID here
const isYourNameRadios = document.querySelectorAll(
  'input[name="is_your_name"]'
);

function toggleExtraInput() {
  const selected = document.querySelector('input[name="is_your_name"]:checked');
  if (selected && selected.value === "yes") {
    extraInput.classList.remove("hidden");
    isNameNotShow.classList.add("hidden");
  } else {
    extraInput.classList.add("hidden");
    isNameNotShow.classList.remove("hidden");
  }
}

// Event listeners
isYourNameRadios.forEach((radio) => {
  radio.addEventListener("change", toggleExtraInput);
});

// Run on page load
window.addEventListener("DOMContentLoaded", toggleExtraInput);

document.addEventListener("DOMContentLoaded", function () {
  const yourNameRadios = document.querySelectorAll(
    'input[name="is_your_name"]'
  );
  const otherPersonRadios = document.querySelectorAll(
    'input[name="other_person_name"]'
  );

  const extraInput1 = document.getElementById("extra-input"); // Your legal name
  const extraInput2 = document.getElementById("extra-input02"); // Other person's name
  const isNameNotShow = document.getElementById("isNameNotShow"); // Second question block

  function toggleFirstCondition() {
    const selected = document.querySelector(
      'input[name="is_your_name"]:checked'
    );

    if (selected.value === "yes") {
      extraInput1.classList.remove("hidden"); // Show legal name field
      isNameNotShow.classList.add("hidden"); // Hide second question
      extraInput2.classList.add("hidden"); // Hide 2nd input just in case
    } else {
      extraInput1.classList.add("hidden"); // Hide legal name field
      isNameNotShow.classList.remove("hidden"); // Show second question
      toggleSecondCondition(); // Run nested check in case user already selected "yes"
    }
  }

  function toggleSecondCondition() {
    const selected = document.querySelector(
      'input[name="other_person_name"]:checked'
    );
    if (selected && selected.value === "yes") {
      extraInput2.classList.remove("hidden"); // Show name of other person
    } else {
      extraInput2.classList.add("hidden"); // Hide it
    }
  }

  // Add listeners to all relevant radios
  yourNameRadios.forEach((radio) => {
    radio.addEventListener("change", toggleFirstCondition);
  });

  otherPersonRadios.forEach((radio) => {
    radio.addEventListener("change", toggleSecondCondition);
  });

  // Run both checks once on page load
  toggleFirstCondition();
  toggleSecondCondition();
});

// 1. Use unique variable name to avoid conflict
const useTrademarkRadios = document.querySelectorAll(
  'input[name="currently_using_trademark"]'
);
const anywhereDate = document.getElementById("anywhere_date_field");
const commerceDate = document.getElementById("commerce_date_field");

// 2. Function to toggle date fields
function toggleDateFields() {
  const selected = document.querySelector(
    'input[name="currently_using_trademark"]:checked'
  );
  if (selected && selected.value === "yes") {
    anywhereDate.classList.remove("hidden");
    commerceDate.classList.remove("hidden");
  } else {
    anywhereDate.classList.add("hidden");
    commerceDate.classList.add("hidden");
  }
}

// 3. Attach listener to each radio
useTrademarkRadios.forEach((radio) => {
  radio.addEventListener("change", toggleDateFields);
});

// 4. Run once on page load
window.addEventListener("DOMContentLoaded", toggleDateFields);

function populateDatePickers(prefix) {
  const daySelect = document.getElementById(`${prefix}_day`);
  const monthSelect = document.getElementById(`${prefix}_month`);
  const yearSelect = document.getElementById(`${prefix}_year`);

  // Populate day
  for (let i = 1; i <= 31; i++) {
    let option = document.createElement("option");
    option.value = i;
    option.text = i;
    daySelect.appendChild(option);
  }

  // Populate month
  const monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];
  monthNames.forEach((month, index) => {
    let option = document.createElement("option");
    option.value = index + 1;
    option.text = month;
    monthSelect.appendChild(option);
  });

  // Populate year
  const currentYear = new Date().getFullYear();
  for (let i = currentYear - 100; i <= currentYear + 20; i++) {
    let option = document.createElement("option");
    option.value = i;
    option.text = i;
    yearSelect.appendChild(option);
  }

  daySelect.addEventListener("change", handlePlaceholderColor);
  monthSelect.addEventListener("change", handlePlaceholderColor);
  yearSelect.addEventListener("change", handlePlaceholderColor);

  // Adjust day count when month/year changes
  monthSelect.addEventListener("change", () => adjustDays(prefix));
  yearSelect.addEventListener("change", () => adjustDays(prefix));
}

// function adjustDays(prefix) {
//   const daySelect = document.getElementById(`${prefix}_day`);
//   const monthSelect = document.getElementById(`${prefix}_month`);
//   const yearSelect = document.getElementById(`${prefix}_year`);

//   const selectedMonth = parseInt(monthSelect.value);
//   const selectedYear = parseInt(yearSelect.value);
//   const daysInMonth = new Date(selectedYear, selectedMonth, 0).getDate();
//   const currentDay = parseInt(daySelect.value);

//   // Clear existing options
//   // while (daySelect.firstChild) {
//   //   daySelect.removeChild(daySelect.firstChild);
//   // }

//   // // Placeholder
//   // let placeholderOption = document.createElement("option");
//   // placeholderOption.value = "";
//   // placeholderOption.disabled = true;
//   // placeholderOption.text = "Day";
//   // daySelect.appendChild(placeholderOption);

//   // Populate days
//   // for (let i = 1; i <= daysInMonth; i++) {
//   //   let option = document.createElement("option");
//   //   option.value = i;
//   //   option.text = i;
//   //   daySelect.appendChild(option);
//   // }

//   // Restore previously selected value
//   if (currentDay && currentDay <= daysInMonth) {
//     daySelect.value = currentDay;
//   } else {
//     daySelect.selectedIndex = 0; // Select placeholder
//   }

//   handlePlaceholderColor({ target: daySelect });
// }

function handlePlaceholderColor(event) {
  if (event.target.value === "") {
    event.target.classList.add("placeholder");
  } else {
    event.target.classList.remove("placeholder");
  }
}

document.addEventListener("DOMContentLoaded", () => {
  populateDatePickers("anywhere");
  populateDatePickers("commerce");
});

//payment-page


document.addEventListener("DOMContentLoaded", () => {
  const cardNumberInput = document.getElementById("cardNumber");
  const expirationMonthSelect = document.getElementById("expirationMonth");
  const expirationYearSelect = document.getElementById("expirationYear");
  const cvcInput = document.getElementById("cvc");
  const cvcInfoToggle = document.getElementById("cvcInfoToggle");
  const cvcInfoBox = document.getElementById("cvcInfoBox");
  const cvcError = document.getElementById("cvcError");
  const termsAcceptedCheckbox = document.getElementById("termsAccepted");
  const paymentForm = document.getElementById("paymentForm");

  // Function to format card number with spaces
  const formatCardNumber = (value) => {
    return value
      .replace(/\s?/g, "")
      .replace(/(\d{4})/g, "$1 ")
      .trim();
  };

  // Handle card number input
  document.addEventListener("input", function (e) {
    if (e.target && e.target.id === "card-number") {
      const { value } = e.target;
      if (/^[\d\s]*$/.test(value)) {
        e.target.value = formatCardNumber(value);
      }
    }
  });

  // Populate expiration months
  const months = [
    { value: "01", label: "January" },
    { value: "02", label: "February" },
    { value: "03", label: "March" },
    { value: "04", label: "April" },
    { value: "05", label: "May" },
    { value: "06", label: "June" },
    { value: "07", label: "July" },
    { value: "08", label: "August" },
    { value: "09", label: "September" },
    { value: "10", label: "October" },
    { value: "11", label: "November" },
    { value: "12", label: "December" },
  ];
  if (expirationMonthSelect) {
    months.forEach((month) => {
      const option = document.createElement("option");
      option.value = month.value;
      option.textContent = month.label;
      expirationMonthSelect.appendChild(option);
    });
  }

  // Populate expiration years
  if (expirationYearSelect) {
    const currentYear = new Date().getFullYear();
    for (let i = 0; i < 10; i++) {
      const year = currentYear + i;
      const option = document.createElement("option");
      option.value = year;
      option.textContent = year;
      expirationYearSelect.appendChild(option);
    }
  }

  // Handle CVC input
  if (cvcInput) {
    cvcInput.addEventListener("input", (e) => {
      const { value } = e.target;
      if (!/^\d*$/.test(value)) {
        e.target.value = value.replace(/\D/g, "");
      }
      if (e.target.value.length > 0 && e.target.value.length < 3) {
        cvcError.classList.remove("hidden");
      } else {
        cvcError.classList.add("hidden");
      }
    });
  }

  // Toggle CVC info box
  if (cvcInfoToggle && cvcInfoBox) {
    cvcInfoToggle.addEventListener("click", () => {
      cvcInfoBox.classList.toggle("show");
    });
  }

  // Hide CVC info box when clicking outside
  document.addEventListener("click", (e) => {
    if (cvcInfoBox && cvcInfoToggle) {
      if (!cvcInfoBox.contains(e.target) && !cvcInfoToggle.contains(e.target)) {
        cvcInfoBox.classList.remove("show");
      }
    }
  });

  // Custom alert/message box function
  const showMessage = (message) => {
    const modalOverlay = document.createElement("div");
    modalOverlay.classList.add("modal-overlay");

    const modalContent = document.createElement("div");
    modalContent.classList.add("modal-content");
    modalContent.innerHTML = `
                    <p>${message}</p>
                    <button id="modalCloseButton">OK</button>
                `;

    modalOverlay.appendChild(modalContent);
    document.body.appendChild(modalOverlay);

    document
      .getElementById("modalCloseButton")
      .addEventListener("click", () => {
        document.body.removeChild(modalOverlay);
      });
  };

  // Handle form submission
  if (paymentForm) {
    paymentForm.addEventListener("submit", (e) => {
      e.preventDefault();

      const cardNumber = cardNumberInput.value.replace(/\s/g, ""); // Remove spaces for validation
      const expirationMonth = expirationMonthSelect.value;
      const expirationYear = expirationYearSelect.value;
      const cvc = cvcInput.value;
      const termsAccepted = termsAcceptedCheckbox.checked;

      if (!cardNumber || cardNumber.length < 16) {
        showMessage("Please enter a valid card number.");
        return;
      }
      if (!expirationMonth || !expirationYear) {
        showMessage("Please select the expiration date.");
        return;
      }
      if (!cvc || cvc.length < 3) {
        showMessage("Please enter a valid CVC.");
        return;
      }
      if (!termsAccepted) {
        showMessage("Please accept the terms and conditions.");
        return;
      }

      // In a real application, you would send this data to a payment gateway
      showMessage("Payment submitted successfully! (This is a demo)");
      console.log({
        cardNumber,
        expirationMonth,
        expirationYear,
        cvc,
        termsAccepted,
      });
    });
  }
});

// registration-trademark-search

// Get references to the checkboxes and form sections
const individualCheckbox = document.getElementById("individualCheckbox");
const organizationCheckbox = document.getElementById("organizationCheckbox");
const individualForm = document.getElementById("individualForm");
const organizationForm = document.getElementById("organizationForm");
const contactInfoForm = document.getElementById("contactInfoForm"); // This form is always visible

// Function to update form visibility based on checkbox state
function updateFormVisibility() {
  if (organizationCheckbox.checked) {
    organizationForm.classList.remove("hidden");
    individualForm.classList.add("hidden");
    // Ensure individual checkbox is unchecked if organization is checked
    individualCheckbox.checked = false;
  } else if (individualCheckbox.checked) {
    individualForm.classList.remove("hidden");
    organizationForm.classList.add("hidden");
    // Ensure organization checkbox is unchecked if individual is checked
    organizationCheckbox.checked = false;
  } else {
    // If neither is checked, hide both specific forms (though one should always be checked)
    individualForm.classList.add("hidden");
    organizationForm.classList.add("hidden");
  }
}

// Add event listeners to the checkboxes
individualCheckbox.addEventListener("change", function () {
  if (this.checked) {
    organizationCheckbox.checked = false; // Uncheck organization if individual is checked
  } else {
    // If individual is unchecked, and organization is also unchecked,
    // re-check organization to maintain at least one selection
    if (!organizationCheckbox.checked) {
      organizationCheckbox.checked = true;
    }
  }
  updateFormVisibility();
});

organizationCheckbox.addEventListener("change", function () {
  if (this.checked) {
    individualCheckbox.checked = false; // Uncheck individual if organization is checked
  } else {
    // If organization is unchecked, and individual is also unchecked,
    // re-check individual to maintain at least one selection
    if (!individualCheckbox.checked) {
      individualCheckbox.checked = true;
    }
  }
  updateFormVisibility();
});

// Initial call to set the correct visibility on page load
// Since individualCheckbox is checked by default in HTML, this will show individual form.
updateFormVisibility();

function saveStep1() {
  localStorage.setItem(
    "name",
    document.getElementById("search_availability").value
  );
  window.location.href = "trademark-registration.php";
  console.log("..");
}

const tabs = document.querySelectorAll(".tab");

tabs.forEach((tab) => {
  tab.addEventListener("click", function () {
    // Remove active class from all tabs
    tabs.forEach((t) => t.classList.remove("active"));

    // Add active class to clicked tab
    this.classList.add("active");
  });
});

// clone card good

// document.addEventListener('DOMContentLoaded', function () {
//   const addClassBtn = document.getElementById('addClassBtn');
//   const container = addClassBtn.parentNode;

//   // ✅ Init Select2 on first section
//   $('select').select2();

//   function updateRemoveButtons() {
//     const sections = container.querySelectorAll('.form-section');
//     sections.forEach((section) => {
//       const removeBtn = section.querySelector('.remove-class');
//       removeBtn.style.display = sections.length > 1 ? 'inline-block' : 'none';
//     });

//     // Also re-check add button state
//     disableAddButtonIfLimitReached();
//   }

//   function resetInputs(section) {
//     const uniqueSuffix = Date.now() + '_' + Math.floor(Math.random() * 1000);

//     section
//       .querySelectorAll('input[type="checkbox"]')
//       .forEach((input) => (input.checked = false));
//     section
//       .querySelectorAll('select')
//       .forEach((select) => (select.selectedIndex = 0));
//     section
//       .querySelectorAll('input[type="text"]')
//       .forEach((input) => (input.value = ''));

//     section.querySelectorAll('[id]').forEach(el => {
//     const oldId = el.id;
//     const newId = `${oldId}_${uniqueSuffix}`;
//     el.id = newId;

//     // Update name (optional but recommended)
//     if (el.name) {
//       el.name = `${el.name}_${uniqueSuffix}`;
//     }

//     // Update label's for attribute
//     const label = section.querySelector(`label[for="${oldId}"]`);
//       if (label) {
//         label.setAttribute('for', newId);
//       }
//     });
//   }

//   function bindRemoveButton(section) {
//     const removeBtn = section.querySelector('.remove-class');
//     removeBtn.addEventListener('click', function () {
//       section.remove();
//       updateRemoveButtons();
//     });
//   }

//   function reinitSelect2(section) {
//     // Destroy any cloned select2 DOM elements
//     $(section)
//       .find('select.select2-hidden-accessible')
//       .each(function () {
//         $(this).select2('destroy');
//       });

//     // Remove select2 DOM wrappers (important to avoid duplicated DOM)
//     $(section).find('.select2').remove();

//     // Re-initialize select2 on new selects
//     $(section).find('select').select2();
//   }

//   function disableAddButtonIfLimitReached() {
//     const sections = container.querySelectorAll('.form-section');
//     if (sections.length >= 2) {
//       addClassBtn.style.backgroundColor = '#ccc';
//       addClassBtn.style.pointerEvents = 'none';
//       addClassBtn.style.cursor = 'not-allowed';
//     } else {
//       addClassBtn.style.backgroundColor = '';
//       addClassBtn.style.pointerEvents = 'auto';
//       addClassBtn.style.cursor = 'pointer';
//     }
//   }

//   addClassBtn.addEventListener('click', function () {
//     const lastSection = container.querySelector('.form-section:last-of-type');

//     // Destroy Select2 on last section before cloning
//     $(lastSection)
//       .find('select.select2-hidden-accessible')
//       .each(function () {
//         $(this).select2('destroy');
//       });
//     $(lastSection).find('.select2').remove();

//     // Clone the section
//     const clonedSection = lastSection.cloneNode(true);

//     // ✅ Clear previously added dynamic inputs
//     const dynamicInputs = clonedSection.querySelector('.dynamic-inputs');
//     if (dynamicInputs) {
//       dynamicInputs.innerHTML = '';
//     }

//     // Reset checkbox, select and text inputs
//     resetInputs(clonedSection);

//     // Bind remove button to new section
//     bindRemoveButton(clonedSection);

//     // Insert the cloned section before the Add button
//     container.insertBefore(clonedSection, addClassBtn);

//     // Re-init Select2 on both the cloned and the original
//     reinitSelect2(clonedSection);
//     $(lastSection).find('select').select2();

//     updateRemoveButtons();
//     disableAddButtonIfLimitReached();
//   });

//   const firstSection = container.querySelector('.form-section');
//   bindRemoveButton(firstSection);
//   updateRemoveButtons();
//   disableAddButtonIfLimitReached(); // run on load
// });

// Select options for dynamic inputs

$(document).on("change", ".form-section select", function () {
  const section = $(this).closest(".form-section");
  const selectedText = $(this).find("option:selected").text();

  const matches = selectedText.match(/{(.*?)}/g);
  const dynamicInputsContainer = section.find(".dynamic-inputs");
  dynamicInputsContainer.empty();

  if (matches) {
    matches.forEach((match, index) => {
      const label = `Please indicate ${match.replace(/[{}]/g, "")}`;
      const inputHTML = `
                    <label>${label}</label>
                    <input type="text" name="curly_input_${index}" placeholder="${label}" class="form-control mb-2" required />
                `;
      dynamicInputsContainer.append(inputHTML);
    });
  }
});
