import type { LocaleCode } from '../i18n/messages';

type LocalizedRecord = Record<string, string | null | undefined>;

function pickLocalizedValue(record: LocalizedRecord, locale: LocaleCode): string | null {
  if (typeof record[locale] === 'string' && record[locale]) {
    return record[locale] as string;
  }

  if (typeof record.de === 'string' && record.de) {
    return record.de as string;
  }

  if (typeof record.en === 'string' && record.en) {
    return record.en as string;
  }

  const firstValue = Object.values(record).find((value) => typeof value === 'string' && value);
  return (firstValue as string | undefined) ?? null;
}

export function localizeTaskLabel(
  raw: string | LocalizedRecord | null | undefined,
  locale: LocaleCode,
): string | null {
  if (!raw) {
    return null;
  }

  if (typeof raw === 'object') {
    return pickLocalizedValue(raw, locale);
  }

  const trimmed = raw.trim();
  if (!trimmed) {
    return null;
  }

  if (trimmed.startsWith('{')) {
    try {
      const parsed = JSON.parse(trimmed);
      if (parsed && typeof parsed === 'object') {
        return pickLocalizedValue(parsed as LocalizedRecord, locale) ?? trimmed;
      }
    } catch {
      return trimmed;
    }
  }

  return trimmed;
}
