(function () {
  'use strict';
  const root = document.querySelector('[data-idr-root]');
  if (!root) return;

  const search = document.querySelector('[data-idr-search]');
  const status = document.querySelector('[data-idr-status]');
  const rows = Array.from(document.querySelectorAll('[data-idr-row]'));
  const visibleCount = document.querySelector('[data-idr-visible-count]');
  const totalCount = document.querySelector('[data-idr-total-count]');
  const showAllButton = document.querySelector('[data-idr-show-all]');
  const initialLimit = Math.max(1, parseInt(root.dataset.initialLimit || '5', 10));
  let expanded = false;

  function applyFilters() {
    const term = (search && search.value ? search.value : '').trim().toLowerCase();
    const selectedStatus = status ? status.value : 'all';
    const matchedRows = [];

    rows.forEach(function (row) {
      const matchesText = !term || (row.dataset.search || '').indexOf(term) !== -1;
      const matchesStatus = selectedStatus === 'all' || row.dataset.status === selectedStatus;
      const matched = matchesText && matchesStatus;
      row.hidden = !matched;
      row.classList.remove('idr-row-hidden-by-limit');
      if (matched) matchedRows.push(row);
    });

    const shouldLimit = !expanded && !term && selectedStatus === 'all';
    if (shouldLimit) {
      matchedRows.forEach(function (row, index) {
        if (index >= initialLimit) row.classList.add('idr-row-hidden-by-limit');
      });
    }

    const shown = shouldLimit ? Math.min(initialLimit, matchedRows.length) : matchedRows.length;
    if (visibleCount) visibleCount.textContent = String(shown);
    if (totalCount) totalCount.textContent = String(matchedRows.length);
    if (showAllButton) {
      showAllButton.hidden = expanded || !!term || selectedStatus !== 'all' || matchedRows.length <= initialLimit;
    }
  }

  if (search) search.addEventListener('input', applyFilters);
  if (status) status.addEventListener('change', applyFilters);
  if (showAllButton) {
    showAllButton.addEventListener('click', function () {
      expanded = true;
      applyFilters();
    });
  }
  applyFilters();
})();
