/**
 * Renders removable pill chips for currently active grid filters.
 */
const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ({
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;'
}[char]));

export function initActiveFilterChips(options = {}) {
  const {
    container,
    removeButtonLabel = 'Remove filter',
    clearAllLabel = 'Clear all filters',
    onRemove = null,
    onClearAll = null
  } = options;

  const root = typeof container === 'string' ? document.querySelector(container) : container;
  if (!(root instanceof HTMLElement)) {
    return null;
  }

  const abortController = new AbortController();
  const { signal } = abortController;

  root.addEventListener('click', (event) => {
    const target = event.target instanceof HTMLElement ? event.target : null;
    if (!target) {
      return;
    }

    const removeButton = target.closest('[data-active-filter-remove]');
    if (removeButton instanceof HTMLElement) {
      if (typeof onRemove !== 'function') {
        return;
      }
      onRemove({
        id: removeButton.dataset.activeFilterId || '',
        param: removeButton.dataset.activeFilterParam || '',
        value: removeButton.dataset.activeFilterValue || '',
        valueType: removeButton.dataset.activeFilterValueType || 'scalar',
        meta: removeButton.dataset.activeFilterMeta || ''
      });
      return;
    }

    const clearButton = target.closest('[data-active-filter-clear]');
    if (clearButton instanceof HTMLElement && typeof onClearAll === 'function') {
      onClearAll();
    }
  }, { signal });

  const render = (chips = []) => {
    if (!Array.isArray(chips) || chips.length === 0) {
      root.innerHTML = '';
      root.hidden = true;
      return;
    }
    root.hidden = false;

    const list = chips.map((chip) => {
      const id = String(chip?.id ?? '');
      const param = String(chip?.param ?? '');
      const value = String(chip?.value ?? '');
      const valueType = String(chip?.valueType ?? 'scalar');
      const label = String(chip?.label ?? '');
      const meta = String(chip?.meta ?? '');
      return `<li>
        <button type="button" class="app-filter-chip" data-active-filter-remove data-active-filter-id="${escapeHtml(id)}" data-active-filter-param="${escapeHtml(param)}" data-active-filter-value="${escapeHtml(value)}" data-active-filter-value-type="${escapeHtml(valueType)}" data-active-filter-meta="${escapeHtml(meta)}" aria-label="${escapeHtml(removeButtonLabel)}">
          <span>${escapeHtml(label)}</span>
          <i class="bi bi-x-lg" aria-hidden="true"></i>
        </button>
      </li>`;
    }).join('');

    const clearChip = `<li>
      <button type="button" class="app-filter-chip app-filter-chip-clear" data-active-filter-clear aria-label="${escapeHtml(clearAllLabel)}">
        <span>${escapeHtml(clearAllLabel)}</span>
        <i class="bi bi-x-lg" aria-hidden="true"></i>
      </button>
    </li>`;

    root.innerHTML = `<div class="app-active-filters-inner"><ul class="app-filter-chip-list">${list}${clearChip}</ul></div>`;
  };

  const destroy = () => {
    abortController.abort();
  };

  return { render, destroy };
}
