export interface TrendPopupOption {
  label: string;
  value: string;
}

export interface TrendTableColumn {
  dataIndex: string;
  key: string;
  title: string;
  width?: number;
}

export interface TrendTableOption extends TrendPopupOption {
  [key: string]: unknown;
}

export function normalizeTrendOptionValue(value?: string | string[]): string[] {
  if (Array.isArray(value)) return value.filter(Boolean);
  return value ? [value] : [];
}

export function filterTrendOptions(options: TrendPopupOption[], keyword: string): TrendPopupOption[] {
  const normalizedKeyword = keyword.trim().toLocaleLowerCase();
  if (!normalizedKeyword) return options;
  return options.filter(({ label, value }) => `${label}\n${value}`.toLocaleLowerCase().includes(normalizedKeyword));
}

export function filterTrendTableOptions<T extends TrendPopupOption>(options: T[], keyword: string, columnKeys: string[]): T[] {
  const normalizedKeyword = keyword.trim().toLocaleLowerCase();
  if (!normalizedKeyword) return options;
  return options.filter((option) => {
    const row = option as Record<string, unknown> & TrendPopupOption;
    return [option.label, option.value, ...columnKeys.map((key) => row[key])]
      .filter((value) => value !== undefined && value !== null)
      .some((value) => String(value).toLocaleLowerCase().includes(normalizedKeyword));
  });
}

export function getTrendOptionSummary(value: string | string[] | undefined, options: TrendPopupOption[]): string {
  const labelMap = new Map(options.map((option) => [option.value, option.label]));
  return normalizeTrendOptionValue(value)
    .map((key) => labelMap.get(key) || key)
    .join(', ');
}
