<template>
	<view class="selectorWrapper">
		<view class="selector" @click="toggleOptionsVisible">
			<image src="/static/nvue/global2.png" mode="aspectFit" style="width: 18px; height: 18px;margin-right: 10px;"></image>
			<view class="selectorLabel">
				<text style="margin-right: auto;">{{ t('locale.current') }}</text>
				<image src="/static/downArrow.png" mode="aspectFit" style="width: 14px; height: 8px"></image>
			</view>
		</view>
		<view ref="languageSelector" :class="['optionsWrapper', { visible: optionsVisible }]">
			<text
				:class="['option', locale === language.value ? 'active' : '']"
				:style="{'text-align': language.value=='ar-SA'?'right':'left'}"
				v-for="(language, index) in languageOptions"
				:key="language.value"
				@click="changeLanguage(language)"
			>
				{{ language.label }}
			</text>
		</view>
	</view>
</template>

<script>
import { setLocale } from '@/utils/const.ts';
import { setLoveLanguage } from '@/services/user.ts';
import { languages } from '@/utils/const.ts';
import { i18n } from '@/locale/index.ts';
export default {
	name: 'MenuLanguageSelector',
	data() {
		return {
			local: undefined,
			optionsVisible: false,
			languageOptions: [
				{ label: 'العربية', value: 'ar-SA' },
				{ label: 'English', value: 'en-US' },
				{ label: 'Spanish', value: 'es-ES' },
				{ label: 'हिंदी', value: 'hi-IN' },
				{ label: '한국어', value: 'ko-KR' },
				{ label: 'ภาษาไทย', value: 'th-TH' },
				{ label: 'Tiếng Việt', value: 'vi-VN' },
				{ label: '简体中文', value: 'zh-CN' },
				{ label: '繁體中文', value: 'zh-TW' },
				{ label: 'Indonesia', value: 'in-ID' }
			],
			t: i18n.global.t
		};
	},
	methods: {
		toggleOptionsVisible() {
			this.optionsVisible = !this.optionsVisible;
		},
		async changeLanguage(language) {
			// #ifndef H5
			uni.showModal({
				content: this.t('modal.changeLanguage') + this.t(`locale.${language.value}`) + ',' + this.t('locale.languageChangeConfirm'),
				confirmColor: '#4DC0E5',
				success: async (res) => {
					if (res.confirm) {
						await setLoveLanguage({ qcc_language: languages[language.value] ?? 'en_US' });
						setLocale(language.value);
					}
				}
			});
			// #endif

			// #ifdef H5
			await setLoveLanguage({ qcc_language: languages[language.value] ?? 'en_US' });
			setLocale(language.value);
			// #endif
		}
	},
	created() {
		this.locale = uni.getLocale();
	}
};
</script>

<style scoped>
@import './index.css';
</style>
