(function () {
  'use strict';

  // Client-side live filter for tables with data-filter="true" attribute.
  // Filters rows by matching input value against all cell text.
  function initLiveFilter(inputId, tableId) {
    var input = document.getElementById(inputId);
    var table = document.getElementById(tableId);
    if (!input || !table) return;

    input.addEventListener('input', function () {
      var query = input.value.toLowerCase().trim();
      var rows = table.querySelectorAll('tbody tr');
      rows.forEach(function (row) {
        var text = row.textContent.toLowerCase();
        row.style.display = (!query || text.includes(query)) ? '' : 'none';
      });
    });
  }

  // Client-side column sort for a table.
  function initSort(tableId) {
    var table = document.getElementById(tableId);
    if (!table) return;

    var headers = table.querySelectorAll('thead th[data-sort]');
    headers.forEach(function (th, colIdx) {
      th.style.cursor = 'pointer';
      th.addEventListener('click', function () {
        sortTable(table, colIdx, th);
      });
    });
  }

  function sortTable(table, colIdx, th) {
    var asc = th.dataset.sortDir !== 'asc';
    th.dataset.sortDir = asc ? 'asc' : 'desc';

    var tbody = table.querySelector('tbody');
    var rows = Array.from(tbody.querySelectorAll('tr'));

    rows.sort(function (a, b) {
      var aText = cellText(a, colIdx);
      var bText = cellText(b, colIdx);
      var aNum = parseFloat(aText);
      var bNum = parseFloat(bText);
      if (!isNaN(aNum) && !isNaN(bNum)) {
        return asc ? aNum - bNum : bNum - aNum;
      }
      return asc
        ? aText.localeCompare(bText)
        : bText.localeCompare(aText);
    });

    rows.forEach(function (r) { tbody.appendChild(r); });
  }

  function cellText(row, idx) {
    var cells = row.querySelectorAll('td');
    return cells[idx] ? cells[idx].textContent.trim().toLowerCase() : '';
  }

  // Expose helpers for inline use in page scripts.
  window.TableHelpers = { initLiveFilter: initLiveFilter, initSort: initSort };
})();
