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) {
    return null;
  }

  const bindEvents = () => {
    const removeButtons = Array.from(root.querySelectorAll('[data-active-filter-remove]'));
    removeButtons.forEach((button) => {
      if (button.dataset.bound === '1') {return;}
      button.dataset.bound = '1';
      button.addEventListener('click', () => {
        if (typeof onRemove !== 'function') {return;}
        onRemove({
          id: button.dataset.activeFilterId || '',
          param: button.dataset.activeFilterParam || '',
          value: button.dataset.activeFilterValue || '',
          valueType: button.dataset.activeFilterValueType || 'scalar',
          meta: button.dataset.activeFilterMeta || ''
        });
      });
    });

    const clearButton = root.querySelector('[data-active-filter-clear]');
    if (clearButton && clearButton.dataset.bound !== '1') {
      clearButton.dataset.bound = '1';
      clearButton.addEventListener('click', () => {
        if (typeof onClearAll === 'function') {
          onClearAll();
        }
      });
    }
  };

  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>`;
    bindEvents();
  };

  return { render };
}
