<template>
    <div v-if="visible" class="guide-overlay">
        <div class="guide-mask"></div>
        <div class="guide-popup" :style="popupStyle">
            <div class="guide-content">
                <span style="font-size: 17px; font-weight: bold">{{ title }}</span>
                <span style="font-size: 12px; font-weight: 400;margin-top: 6px;margin-bottom: 10px;">
                    <template v-if="step === 1">
                        {{ beforeIconText }}
                        <SvgIcon icon="mcp-switch" :style="{'fill': 'var(--uosai-color-flat-btn-icon)', 'width': '13.54px', 'height': '12.77px', 'margin-right': '2px', 'margin-left': '2px', 'display': 'inline', 'vertical-align': 'middle'}"/>
                        {{ afterIconText }}
                    </template>
                    <template v-else>
                        {{ content }}
                    </template>
                </span>
                <span style="font-size: 12px; font-weight: 400;margin-bottom: 15px;color: var(--uosai-guide-popup-contentText-color);">{{ contentText }}</span>
                <div class="guide-btn-group">
                    <span class="close-btn" @click="closeGuide(false)" style="color: var(--uosai-guide-popup-trylater-color)">{{ useLaterText }}</span>
                    <span class="close-btn" @click="activeBtn">{{ activeText }}</span>
                </div>
            </div>
            <div class="guide-arrow" :style="arrayStyle"></div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useGlobalStore } from "@/store/global";
import SvgIcon from "@/components/svgIcon/svgIcon.vue" // 确保导入 SvgIcon 组件

const store = useGlobalStore()

const props = defineProps({
    targetRef: Object, // 传入SwitchModel的ref或DOM节点
    visible: Boolean
})
const emit = defineEmits(['close', 'install'])
const popupStyle = ref({})
const arrayStyle = ref({})
const popup = ref(null)

const updatePosition = () => {
    const el = props.targetRef
    if (!el || typeof el.getBoundingClientRect !== 'function' || el.nodeType !== 1) {
        return
    }
    const rect = el.getBoundingClientRect()
    // 弹窗高度假设为120px，箭头高度10px，弹窗底部对齐targetRef顶部
    // 获取guide-popup的DOM元素
    let popupDom = document.querySelector('.guide-popup')
    let popupWidth = 280 // 默认宽度
    let popupHeight = 120 // 默认高度
    let arrowHeight = 10 // 箭头高度
    if (popupDom) {
        popupWidth = popupDom.offsetWidth
        popupHeight = popupDom.offsetHeight
    }

    let left = rect.left  + rect.width - popupWidth
    if (left < 0) {
        left = 40
    }
    popupStyle.value = {
        position: 'fixed',
        left: `${left}px`,
        top: `${rect.top - popupHeight - arrowHeight*2 }px`,
        zIndex: 10001
    }

    // 计算目标元素的中心点
    const targetCenter = rect.left + rect.width / 2
    // 计算弹出框的左边界
    const popupLeft = left
    // 计算箭头应该在弹出框中的位置（减去箭头宽度的一半：8px）
    const arrowPosition = targetCenter - popupLeft - 8
    
    // 确保箭头不会太靠近弹出框边缘
    const minArrowPosition = 10 // 距离左边至少10px
    const maxArrowPosition = popupWidth - 10 // 距离右边至少10px
    
    const finalArrowPosition = Math.min(Math.max(arrowPosition, minArrowPosition), maxArrowPosition)
    
    arrayStyle.value = {
        left: `${finalArrowPosition}px`,
        right: 'auto'
    }
}

const closeGuide = (isActive) => {
    emit('close', isActive)
    // 把目标元素的层级设置为1
    props.targetRef.style.zIndex = 1 
    // 把目标元素的pointerEvents属性设置为auto
    props.targetRef.style.pointerEvents = 'auto'
}

const showBtn = (isAllowClick) => {
    const el = props.targetRef
    if (!el || typeof el.getBoundingClientRect !== 'function' || el.nodeType !== 1) {
        return
    }

    // 设置目标元素的pointerEvents属性,是否可以点击
    if (isAllowClick) {
        props.targetRef.style.pointerEvents = 'auto'
    } else {
        props.targetRef.style.pointerEvents = 'none'
    }
    // 把目标元素的层级设置为10001
    props.targetRef.style.zIndex = 10001
}

const step = ref(0)  //判断当前步骤
const title = ref('')
const content = ref('')
const contentText = ref('')
const useLaterText = ref('')
const activeText = ref('')
const beforeIconText = ref('')
const afterIconText = ref('')

const activeBtn = () => {
    if (step.value === 0) {
        title.value = store.loadTranslations['Enable MCP Server']
        // 拆分文本，插入图标
        beforeIconText.value = store.loadTranslations['After installing the MCP environment \"UOS AI Agent\", click the ']
        afterIconText.value = store.loadTranslations[' and select \"uos-mcp\" in the MCP server list.']

        contentText.value = store.loadTranslations['Try saying: \"Change system to dark mode\".']
        useLaterText.value = store.loadTranslations['Use later']
        activeText.value = store.loadTranslations['Try it now']
        step.value = 1
        nextTick(() => {
            updatePosition()  //高度变化，重新计算位置
        }, 10)
        emit('install')
        showBtn(true)//显示按钮,让按钮可以点击

    } else if (step.value === 1) {
        closeGuide(true)
    } 
}

// 初始化翻译文本的函数
const initializeTranslations = () => {
    if (store.loadTranslations && Object.keys(store.loadTranslations).length > 0) {
        title.value = store.loadTranslations['Add Mcp Server[GuidePage]'].replace('[GuidePage]', '')
        content.value = store.loadTranslations['Automate multi-file and multi-app tasks with one command using MCP Service. Try it now!']
        contentText.value = store.loadTranslations['First-time users: Install MCP environment \"UOS AI Agent\" via App Store.']
        useLaterText.value = store.loadTranslations['Use later']
        activeText.value = store.loadTranslations['Install Now']
    }
    
}

onMounted(() => {
    // 如果翻译已经加载，直接初始化
    initializeTranslations()
    
    window.addEventListener('resize', updatePosition)
    window.addEventListener('scroll', updatePosition)
})

// 监听翻译数据的变化
watch(() => store.loadTranslations, (newTranslations) => {
    if (newTranslations && Object.keys(newTranslations).length > 0) {
        initializeTranslations()
    }
}, { immediate: true, deep: true })

onUnmounted(() => {
    window.removeEventListener('resize', updatePosition)
    window.removeEventListener('scroll', updatePosition)
})

// 监听visible，显示时再定位
watch(() => props.visible, (val) => {
    if (val) {
        nextTick(() => {
            updatePosition()
            showBtn(false)
        }, 10)
    }
})
</script>

<style lang="scss" scoped>
.guide-overlay {
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    z-index: 10000;
    pointer-events: auto;
}
.guide-mask {
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background-color: var(--uosai-history-list-mask-bg); 
    z-index: 10000;
}
.guide-popup {
    width: 280px;
    background-color: var(--uosai-guide-popup-bg);
    border-radius: 10px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 4px 24px rgba(0,0,0,0.18);
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 16px;
    position: fixed;
    z-index: 10001;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.guide-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    color: var(--uosai-guide-popup-font-color);
    width: 100%;
}

.guide-btn-group {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
}

.close-btn {
    margin-top: 0;
    margin-left: 16px;
    color: var(--activityColor);
    border-radius: 4px;
    cursor: pointer;
}
.guide-arrow {
    width: 0;
    height: 0;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-top: 10px solid rgba(0, 0, 0, 0.05);
    border-bottom: 0;
    margin: 0;
    position: absolute;
    bottom: 0;
    transform: translateY(100%);
    z-index: 10002;

    &::after {
        content: '';
        position: absolute;
        width: 0;
        height: 0;
        border-left: 8px solid transparent;
        border-right: 8px solid transparent;
        border-top: 10px solid var(--uosai-guide-popup-bg);
        left: -8px;
        top: -11px;
    }
}
</style> 