export type Locale = 'zh-CN' | 'zh-TW' | 'en'; export const locales: Locale[] = ['zh-CN', 'zh-TW', 'en']; export const defaultLocale: Locale = 'zh-CN'; export const languages = [ { code: 'zh-CN' as Locale, name: '简体中文', flag: '🇨🇳' }, { code: 'zh-TW' as Locale, name: '繁體中文', flag: '🇹🇼' }, { code: 'en' as Locale, name: 'English', flag: '🇺🇸' }, ]; export async function getTranslations(locale: Locale, namespace: string) { // Validate inputs if (!locales.includes(locale) || !namespace || namespace.includes('.')) { console.warn(`Invalid locale or namespace: ${locale}/${namespace}`); return {}; } try { const translations = await import(`../data/locales/${locale}/${namespace}.json`); return translations.default; } catch (error) { console.warn(`Failed to load translations for ${locale}/${namespace}:`, error); // Fallback to default locale if (locale !== defaultLocale) { try { const fallbackTranslations = await import( `../data/locales/${defaultLocale}/${namespace}.json` ); return fallbackTranslations.default; } catch (fallbackError) { console.error( `Failed to load fallback translations for ${defaultLocale}/${namespace}:`, fallbackError, ); return {}; } } return {}; } } export function getLocaleFromPath(pathname: string): Locale { const segments = pathname.split('/').filter(Boolean); const firstSegment = segments[0]; if (locales.includes(firstSegment as Locale)) { return firstSegment as Locale; } return defaultLocale; } export function removeLocaleFromPath(pathname: string): string { const segments = pathname.split('/').filter(Boolean); const firstSegment = segments[0]; if (locales.includes(firstSegment as Locale)) { return '/' + segments.slice(1).join('/'); } return pathname; } export function addLocaleToPath(pathname: string, locale: Locale): string { if (locale === defaultLocale) { return pathname; } const cleanPath = removeLocaleFromPath(pathname); return `/${locale}${cleanPath === '/' ? '' : cleanPath}`; } export function generateLocalizedPath(path: string, locale: Locale): string { // Remove leading slash if present const cleanPath = path.startsWith('/') ? path.slice(1) : path; if (locale === defaultLocale) { return `/${cleanPath}`; } return `/${locale}/${cleanPath}`; } export function getNavigationPaths(locale: Locale) { const basePaths = [ { key: 'home', path: '' }, { key: 'products', path: 'products' }, { key: 'news', path: 'news' }, { key: 'support', path: 'support' }, { key: 'about', path: 'about' }, ]; return basePaths.map((item) => ({ key: item.key, path: generateLocalizedPath(item.path, locale), })); }