import { STORAGE } from '@/core/constants/storage-keys'

/** @typedef {{ code: string, text: string }} LocaleOption */

/**
 * @param {(key: string) => string} t
 * @returns {LocaleOption[]}
 */
export function buildLocaleOptions(t) {
	return [
		{ code: 'auto', text: t('locale.auto') },
		{ code: 'en', text: t('locale.en') },
		{ code: 'en-SG', text: t('locale.en-sg') },
		{ code: 'en-MY', text: t('locale.en-my') },
		{ code: 'zh-cn', text: t('locale.zh-hans') },
		{ code: 'zh-Hant', text: t('locale.zh-hant') }
	]
}

export function getStoredLocaleCode() {
	const saved = uni.getStorageSync(STORAGE.language)
	if (saved) return saved
	const current = uni.getLocale()
	return current || 'auto'
}

/**
 * @param {LocaleOption[]} options
 * @param {string} code
 */
export function localeLabelForCode(options, code) {
	const hit = options.find((item) => item.code === code)
	if (hit) return hit.text
	return code
}

/**
 * @param {string} storedCode
 * @param {object} i18n VueI18n instance
 */
export function applyLocaleChange(storedCode, i18n) {
	uni.setStorageSync(STORAGE.language, storedCode)
	uni.setLocale(storedCode)
	if (storedCode === 'auto') {
		i18n.locale = uni.getLocale()
	} else {
		i18n.locale = storedCode
	}
}

export function isAndroidPlatform() {
	try {
		return uni.getSystemInfoSync().platform.toLowerCase() === 'android'
	} catch (_) {
		return false
	}
}
