import { translations, type LanguageCode } from './header-data';

export const PROFILE_MENU_KEYS = {
  accountSetting: 'account_setting',
  notificationSetting: 'notification_setting',
  myOrganization: 'my_organization',
  downloadApp: 'download_app',
  language: 'language',
  logout: 'logout',
} as const;
export type ProfileMenuKey = keyof typeof PROFILE_MENU_KEYS;

export function resolveProfileMenuLabels(language: LanguageCode, dictionary: Record<string, string>) {
  return Object.fromEntries(Object.entries(PROFILE_MENU_KEYS).map(([key, apiKey]) => {
    const value = dictionary[apiKey];
    return [key, typeof value === 'string' && value.trim() ? value : translations[language][key as ProfileMenuKey]];
  })) as Record<ProfileMenuKey, string>;
}

export async function fetchProfileMenuDictionary(language: LanguageCode, signal?: AbortSignal) {
  return fetchSharedDictionary('profile_menu', language, signal);
}

export async function fetchSharedDictionary(page: string, language: LanguageCode, signal?: AbortSignal) {
  const base = (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1').replace(/\/$/, '');
  const query = new URLSearchParams({ module: 'shared', page, language: language === 'kh' ? 'km' : 'en' });
  const response = await fetch(`${base}/translations/dictionary?${query}`, { cache: 'no-store', credentials: 'include', signal });
  if (!response.ok) throw new Error('Could not load shared translations');
  let value: unknown = await response.json();
  for (let depth = 0; depth < 5 && value && typeof value === 'object'; depth++) {
    const record = value as Record<string, unknown>;
    if (record.translations && typeof record.translations === 'object') {
      return Object.fromEntries(Object.entries(record.translations).filter(
        (entry): entry is [string, string] => typeof entry[1] === 'string' && !!entry[1].trim(),
      ));
    }
    value = record.data;
  }
  return {};
}
