import { warnOnce } from '../core/app-dom.js';

const getEmptyValues = (field) => {
  const own = field?.dataset?.filterEmpty || '';
  const parent = field?.closest?.('[data-filter-empty]')?.dataset?.filterEmpty || '';
  return [own, parent]
    .filter(Boolean)
    .join(',')
    .split(',')
    .map((value) => value.trim())
    .filter(Boolean);
};

const isFieldActive = (field) => {
  if (!field) {return false;}
  if (field.disabled) {return false;}
  if (field.type === 'hidden') {return false;}
  if (field.type === 'checkbox') {return field.checked;}
  if (field.tagName === 'SELECT' && field.multiple) {
    return Array.from(field.selectedOptions || []).some((option) => option.value);
  }
  if (field.tagName === 'SELECT') {
    const value = String(field.value || '').trim();
    const empty = new Set(['', 'all', ...getEmptyValues(field)]);
    return value !== '' && !empty.has(value);
  }
  return String(field.value || '').trim() !== '';
};

const isOptionalActive = (item) => {
  const fields = item.matches('input, select, textarea')
    ? [item]
    : Array.from(item.querySelectorAll('input, select, textarea'));
  return fields.some(isFieldActive);
};

export function initFilterOverflow(root = document) {
  const toolbars = root.querySelectorAll('[data-filter-overflow]');
  toolbars.forEach((toolbar) => {
    if (toolbar.dataset.filterOverflowBound === '1') {return;}
    toolbar.dataset.filterOverflowBound = '1';

    const optional = Array.from(toolbar.querySelectorAll('[data-filter-optional]'));
    if (!optional.length) {return;}

    const toggle = toolbar.querySelector('[data-filter-toggle]');
    if (!toggle) {
      warnOnce('UI_EL_MISSING', 'Missing filter overflow toggle', { module: 'filter-overflow' });
      return;
    }

    const setExpanded = (expanded) => {
      optional.forEach((item) => {
        item.hidden = !expanded;
      });
      toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
    };

    const hasActiveOptional = optional.some(isOptionalActive);
    setExpanded(hasActiveOptional);

    toggle.addEventListener('click', () => {
      const expanded = toggle.getAttribute('aria-expanded') === 'true';
      setExpanded(!expanded);
    });
  });
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => initFilterOverflow());
} else {
  initFilterOverflow();
}
