// modules/datatable_filter.js
export function bindDatatableFilters(tableId, callback) {
  const container = document.getElementById(`${tableId}_wrapper`) || document;
  
  container.querySelectorAll(".datatable-filter").forEach((filter) => {
    filter.addEventListener("change", () => {
      const filters = Array.from(
        container.querySelectorAll(".datatable-filter")
      ).map((el) => ({
        name: el.dataset.filter,
        value: el.value,
      }));
      callback(filters);
    });
  });

  // Tambahan: jika ada input text search
  container.querySelectorAll(".datatable-search").forEach((input) => {
    input.addEventListener("input", debounce(() => {
      const filters = Array.from(
        container.querySelectorAll(".datatable-filter, .datatable-search")
      ).map((el) => ({
        name: el.dataset.filter || "search",
        value: el.value,
      }));
      callback(filters);
    }, 400));
  });
}

function debounce(fn, delay = 400) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}
