export const INTEREST_CATEGORY_CODE = "interest";
export const MAX_INTEREST_LABELS = 8;

export type DictItem = { id: number; name: string; code?: string };
export type DictCategory = { id: number; name: string; code?: string; items: DictItem[] };

export function normalizeDictionaryCategories(dict: any): DictCategory[] {
  return (Array.isArray(dict?.categories) ? dict.categories : [])
    .map((cat: any) => ({
      id: Number(cat?.id),
      name: String(cat?.name || ""),
      code: String(cat?.code || ""),
      items: (Array.isArray(cat?.items) ? cat.items : [])
        .map((item: any) => ({
          id: Number(item?.id),
          name: String(item?.name || ""),
          code: String(item?.code || "")
        }))
        .filter((item: DictItem) => Number.isFinite(item.id) && item.name)
    }))
    .filter((cat: DictCategory) => cat.name && cat.items.length > 0);
}

export function interestItems(dict: any) {
  return normalizeDictionaryCategories(dict).find((cat) => cat.code === INTEREST_CATEGORY_CODE)?.items || [];
}

export function professionalCategories(dict: any) {
  return normalizeDictionaryCategories(dict).filter((cat) => cat.code !== INTEREST_CATEGORY_CODE);
}

export function selectedInterestIds(mine: any) {
  return selectedItems(mine)
    .filter((item) => String(item?.category_code || "") === INTEREST_CATEGORY_CODE)
    .map((item) => Number(item?.id))
    .filter((id) => Number.isFinite(id));
}

export function selectedProfessionalIds(mine: any) {
  return selectedItems(mine)
    .filter((item) => String(item?.category_code || "") !== INTEREST_CATEGORY_CODE)
    .map((item) => Number(item?.id))
    .filter((id) => Number.isFinite(id));
}

export function selectedInterestNames(mine: any) {
  return selectedItems(mine)
    .filter((item) => String(item?.category_code || "") === INTEREST_CATEGORY_CODE)
    .map((item) => String(item?.label_name || item?.name || "").trim())
    .filter(Boolean);
}

export function selectedProfessionalNames(mine: any) {
  return selectedItems(mine)
    .filter((item) => String(item?.category_code || "") !== INTEREST_CATEGORY_CODE)
    .map((item) => String(item?.label_name || item?.name || "").trim())
    .filter(Boolean);
}

export function selectedCustomLabels(mine: any) {
  return (Array.isArray(mine?.customLabels) ? mine.customLabels : [])
    .map((x: any) => String(x || "").trim())
    .filter(Boolean);
}

export function dedupe(values: string[]) {
  const seen = new Set<string>();
  return values.filter((v) => {
    const key = v.trim();
    if (!key || seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

function selectedItems(mine: any) {
  return Array.isArray(mine?.items) ? mine.items : Array.isArray(mine) ? mine : [];
}
