import { CheckboxFilterInputOption } from '../core';

/**
 * Filters checkbox options recursively by label text
 * @param options - The checkbox options to filter
 * @param query - The search query to filter by
 * @returns Filtered options that match the query or have matching children
 */
export const filterCheckboxOptionsHelper = (
  options: CheckboxFilterInputOption[],
  query: string,
): CheckboxFilterInputOption[] => {
  if (!query) {
    return options;
  }

  const lowercaseQuery = query.toLowerCase();

  return options.reduce((filtered, option) => {
    // Check if current option label matches
    const labelMatches = option.label?.toLowerCase().includes(lowercaseQuery);

    // If parent matches, keep all children; otherwise filter children recursively
    const filteredChildren = option.values
      ? labelMatches
        ? option.values // Keep all children when parent matches
        : filterCheckboxOptionsHelper(option.values, query) // Only filter children if parent doesn't match
      : undefined;

    // Include option if:
    // 1. Its label matches the query, OR
    // 2. It has children that match (keep parent for context)
    if (labelMatches || (filteredChildren && filteredChildren.length > 0)) {
      filtered.push({
        ...option,
        values: filteredChildren,
      });
    }

    return filtered;
  }, [] as CheckboxFilterInputOption[]);
};
