// Shared CSS filter manager — allows contrast and grayscale to compose rather than clobber.
// Each caller passes its own key and filter value; the combined result is written as a
// single CSS rule so only one `filter` declaration ever exists on <html>.
const activeFilters: Record<string, string> = {};
let el: HTMLStyleElement | null = null;

export function setFilter(key: string, value: string | null): void {
  if (value) {
    activeFilters[key] = value;
  } else {
    delete activeFilters[key];
  }

  el?.remove();
  const filters = Object.values(activeFilters);
  if (!filters.length) { el = null; return; }

  el = document.createElement('style');
  el.id = 'accessmate-filters';

  let css = `html{filter:${filters.join(' ')}!important}`;
  // When contrast (invert) is active, double-invert media so images look natural.
  if (activeFilters['contrast']) {
    css += `img,video,canvas,svg{filter:invert(1) hue-rotate(180deg)!important}`;
  }
  el.textContent = css;
  document.head.appendChild(el);
}
