import i18n from '../i18n'

export type I18nString = string | { [key: string]: string }

/**
 * Safely extracts the translated string from a value that could be a string or an I18nString object.
 * @param value The value to translate (string or object with language keys)
 * @returns The translated string for the current language, or fallback to English/first available
 */
export const getTranslatedText = (value: I18nString | undefined | null): string => {
    if (!value) return ''

    // If it's already a string, return it
    if (typeof value === 'string') return value

    // If it's an object, try to get the current language
    const currentLang = i18n.language || 'en'

    // 1. Try current language
    if (value[currentLang]) return value[currentLang]

    // 2. Try English fallback
    if (value['en']) return value['en']

    // 3. Return the first available key
    const firstKey = Object.keys(value)[0]
    if (firstKey) return value[firstKey]

    // 4. Fallback empty
    return ''
}
