<template>
    <div class="pc-translate-button">
        <div class="pc-translate-trigger-group">
            <button type="button" class="pc-translate-trigger-key-btn" :title="t('翻译')" @click="handleTriggerKeyClick">
                {{ selectedLanguage }}
            </button>
            <button type="button" :class="['pc-translate-trigger-arrow-btn', { 'is-open': showLanguagePanel }]"
                :title="t('翻译')" @click="toggleLanguagePanel">
                <span class="pc-translate-trigger-arrow"></span>
            </button>
        </div>

        <div v-if="showLanguagePanel" ref="panelRef" class="pc-translation-language-panel" @click.stop>
            <div class="pc-translation-language-panel-title">{{ t('将输入内容翻译成') }}</div>
            <div class="pc-translation-language-panel-list">
                <button v-for="item in languageOptions" :key="item.key" type="button"
                    :class="['pc-translation-language-item', { 'is-active': item.key === selectedLanguage }]"
                    @click="handleSelectLanguage(item.key)">
                    <span class="pc-translation-language-item-key">{{ item.key }}</span>
                    <span class="pc-translation-language-item-label">{{ item.label }}</span>
                    <span v-if="item.key === selectedLanguage" class="pc-translation-language-item-check">✓</span>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance, { StoreName } from '@tencentcloud/ai-desk-core';
import toast from '../../../../../utils/toast';

interface LanguageOption {
    key: string;
    label: string;
}

const props = defineProps<{ sessionId: string; getSourceText: () => string }>();
const emit = defineEmits<{
    (e: 'open'): void;
    (e: 'translated', text: string): void;
}>();

const { t } = useI18n();

const selectedLanguage = ref('zh');
const showLanguagePanel = ref(false);
const panelRef = ref<HTMLDivElement | null>(null);

const languageOptions = computed<LanguageOption[]>(() => [
    { key: 'zh', label: t('中文') },
    { key: 'zh-TW', label: t('繁体中文') },
    { key: 'en', label: t('英文') },
    { key: 'ja', label: t('日语') },
    { key: 'ko', label: t('韩语') },
    { key: 'fr', label: t('法语') },
    { key: 'es', label: t('西班牙语') },
    { key: 'de', label: t('德语') },
    { key: 'ru', label: t('俄语') },
    { key: 'pt', label: t('葡萄牙语') },
    { key: 'vi', label: t('越南语') },
    { key: 'id', label: t('印尼语') },
    { key: 'th', label: t('泰语') },
    { key: 'ms', label: t('马来语') },
    { key: 'ar', label: t('阿拉伯语') },
]);

const runTranslate = async () => {
    const sourceText = props.getSourceText();
    if (!sourceText.trim()) {
        toast.info(t('没有文本'));
        return;
    }

    try {
        const result = await AIDeskCoreInstance.chatService.translateText({
            sourceTextList: [sourceText],
            targetLanguage: selectedLanguage.value,
        });
        emit('translated', result[0] ?? '');
    } catch (error) {
        console.error(error);
        toast.error(t('翻译失败'));
    }
};

const toggleLanguagePanel = async () => {
    showLanguagePanel.value = !showLanguagePanel.value;
    if (showLanguagePanel.value) {
        emit('open');
        await nextTick();
        bindOutsideClick();
    } else {
        unbindOutsideClick();
    }
};

const close = () => {
    if (!showLanguagePanel.value) return;
    showLanguagePanel.value = false;
    unbindOutsideClick();
};

const handleSelectLanguage = (languageKey: string) => {
    selectedLanguage.value = languageKey;
    AIDeskCoreInstance.userInfoService.updateSeatMesssageTranslateTargetLanguage(props.sessionId, languageKey);
    close();
};

// 点击外部关闭
const onDocumentClick = (event: MouseEvent) => {
    if (!panelRef.value) return;
    const target = event.target as Node;
    if (panelRef.value.contains(target)) return;
    // 点击到触发按钮时由 toggleLanguagePanel 处理，不重复关闭
    const rootEl = panelRef.value.parentElement as HTMLElement | null;
    if (rootEl && rootEl.contains(target)) return;
    close();
};

const bindOutsideClick = () => {
    document.addEventListener('mousedown', onDocumentClick, true);
};

const unbindOutsideClick = () => {
    document.removeEventListener('mousedown', onDocumentClick, true);
};

onBeforeUnmount(() => {
    unbindOutsideClick();
});

const handleTriggerKeyClick = async () => {
    await runTranslate();
};

const onSeatMessageTranslateTargetLanguage = (data: Record<string, string>) => {
    if (!props.sessionId) {
        selectedLanguage.value = 'zh';
        return;
    }
    selectedLanguage.value = data?.[props.sessionId] || 'zh';
};

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        seatMesssageTranslateTargetLanguage: onSeatMessageTranslateTargetLanguage,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        seatMesssageTranslateTargetLanguage: onSeatMessageTranslateTargetLanguage,
    });
});

defineExpose({ close });
</script>

<style scoped>
.pc-translate-button {
    position: relative;
    display: inline-flex;
}

.pc-translate-trigger-group {
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.pc-translate-trigger-key-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 34px;
    height: 24px;
    padding: 0 8px;
    border: 1px solid #E4E6EB;
    border-radius: 6px;
    background: #fff;
    color: #676A70;
    font-size: 12px;
    line-height: 18px;
    cursor: pointer;
    transition: border-color 0.2s;
}

.pc-translate-trigger-key-btn:hover {
    border-color: #B7BAC0;
}

.pc-translate-trigger-arrow-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 24px;
    padding: 0;
    border: none;
    background: transparent;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.2s;
}

.pc-translate-trigger-arrow-btn:hover,
.pc-translate-trigger-arrow-btn.is-open {
    background: #F0F2F7;
}

.pc-translate-trigger-arrow {
    width: 0;
    height: 0;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-top: 5px solid #676A70;
}

.pc-translation-language-panel {
    position: absolute;
    left: 0;
    bottom: calc(100% + 8px);
    z-index: 7;
    width: 220px;
    max-height: 320px;
    padding: 8px 0;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.pc-translation-language-panel-title {
    padding: 6px 16px 8px;
    color: #B7BAC0;
    font-size: 13px;
    line-height: 20px;
    text-align: center;
}

.pc-translation-language-panel-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 8px;
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.15) transparent;
}

.pc-translation-language-panel-list::-webkit-scrollbar {
    width: 4px;
}

.pc-translation-language-panel-list::-webkit-scrollbar-track {
    background: transparent;
    border: none;
}

.pc-translation-language-panel-list::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    border: none;
}

.pc-translation-language-panel-list::-webkit-scrollbar-thumb:hover {
    background: rgba(0, 0, 0, 0.25);
}

.pc-translation-language-item {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    height: 36px;
    padding: 0 8px;
    border: none;
    border-radius: 8px;
    background: transparent;
    color: #222;
    font-size: 13px;
    line-height: 20px;
    cursor: pointer;
    text-align: left;
}

.pc-translation-language-item:hover {
    background: #F5F6F8;
}

.pc-translation-language-item.is-active {
    background: #F0F2F7;
}

.pc-translation-language-item-key {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 34px;
    height: 20px;
    padding: 0 6px;
    border: 1px solid #E4E6EB;
    border-radius: 4px;
    background: #fff;
    color: #676A70;
    font-size: 12px;
    line-height: 18px;
}

.pc-translation-language-item-label {
    flex: 1;
    color: #222;
}

.pc-translation-language-item-check {
    color: #1677FF;
    font-size: 14px;
    font-weight: 600;
}
</style>
