// resources/assets/ts/ContactsPage/utils/filterHandlers.ts
import { Option } from '../types';

/**
 * Handle checkbox changes in filter dropdowns
 * - If "Alle" is clicked: toggle all other options
 * - If any other option is clicked: uncheck "Alle"
 */
export const handleCheckboxChange = (
  options: Option[],
  setOptions: (opts: Option[]) => void,
  clickedValue: number | string | 'all',
  newChecked: boolean
) => {
  if (clickedValue === 'all') {
    // Toggle all options to match "Alle"
    setOptions(options.map((opt) => ({ ...opt, checked: newChecked })));
  } else {
    // Uncheck "Alle" when any specific option is clicked
    const updated = options.map((opt) => {
      if (opt.value === 'all') return { ...opt, checked: false };
      if (opt.value === clickedValue) return { ...opt, checked: newChecked };
      return opt;
    });

    // If all specific options are checked, also check "Alle"
    const allSpecificChecked = updated
      .filter((opt) => opt.value !== 'all')
      .every((opt) => opt.checked);

    if (allSpecificChecked) {
      setOptions(updated.map((opt) => (opt.value === 'all' ? { ...opt, checked: true } : opt)));
    } else {
      setOptions(updated);
    }
  }
};

/**
 * Get array of checked labels (excluding "Alle")
 */
export const getCheckedLabels = (options: Option[]): string[] => {
  return options.filter((opt) => opt.checked && opt.value !== 'all').map((opt) => opt.label);
};

/**
 * Check if only "Alle" is selected (all filters active)
 */
export const isOnlyAlleSelected = (options: Option[]): boolean => {
  const alleOpt = options.find((opt) => opt.value === 'all');
  const otherOpts = options.filter((opt) => opt.value !== 'all');
  
  // "Alle" is checked AND all other options are also checked
  return Boolean(alleOpt?.checked && otherOpts.every((opt) => opt.checked));
};