/**
 * 보조지표 설정 목록 — Main 탭 지표 우선 + 전체 registry, 검색 필터
 */
import { INDICATOR_REGISTRY } from './indicatorRegistry';
import { getIndicatorDef } from './indicatorRegistry';
import { MAIN_INDICATOR_TYPES, MAIN_INDICATOR_LABELS, isMainIndicatorType } from './indicatorMainTab';

const MAIN_SET = new Set<string>(MAIN_INDICATOR_TYPES);

/** 설정 UI에서 제외 (Psychological 과 동일) */
const EXCLUDED_TYPES = new Set(['NewPsychological']);

/** Main 탭 지표 + 그 외 모든 보조지표 type (순서 고정, Main 항목은 하단 registry 에서 제외) */
export function getSettingsIndicatorTypes(): string[] {
  const rest = INDICATOR_REGISTRY
    .map(d => d.type)
    .filter(t => !MAIN_SET.has(t) && !EXCLUDED_TYPES.has(t));
  return [...MAIN_INDICATOR_TYPES, ...rest];
}

export function isSettingsMainSection(type: string): boolean {
  return isMainIndicatorType(type);
}

export function getIndicatorListLabels(type: string): { ko: string; en: string } {
  const def = getIndicatorDef(type);
  const main = MAIN_INDICATOR_LABELS[type];
  return {
    ko: main?.ko ?? def?.description ?? def?.koreanName ?? type,
    en: main?.en ?? def?.name ?? type,
  };
}

/** 지표 추가 팝업과 동일 — 이름·약어·한글명·설명 검색 */
export function matchIndicatorSearch(type: string, query: string): boolean {
  const q = query.trim().toLowerCase();
  if (!q) return true;
  const def = getIndicatorDef(type);
  if (!def) return type.toLowerCase().includes(q);
  const main = MAIN_INDICATOR_LABELS[type];
  const hay = [
    type,
    def.name,
    def.koreanName,
    def.shortName,
    def.description ?? '',
    main?.ko ?? '',
    main?.en ?? '',
  ].join(' ').toLowerCase();
  return hay.includes(q);
}

export function filterSettingsIndicatorTypes(types: readonly string[], query: string): string[] {
  return types.filter(t => matchIndicatorSearch(t, query));
}

export function partitionFilteredTypes(filtered: string[]): { main: string[]; other: string[] } {
  const main: string[] = [];
  const other: string[] = [];
  for (const t of filtered) {
    if (isSettingsMainSection(t)) main.push(t);
    else other.push(t);
  }
  return { main, other };
}
