<template>
    <!-- Google Tag Manager (noscript) -->
    <noscript>
        <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-NFZC9B8M"
                height="0" width="0" style="display:none;visibility:hidden"></iframe>
    </noscript>
    <!-- End Google Tag Manager (noscript) -->
    
    <div v-if="isRedirecting" class="redirect-overlay">
        <div class="redirect-overlay__spinner"></div>
    </div>
    <Header />
    <main data-scroll-container>
        <NuxtPage />
        <NuxtLink class="search" :to="searchLink" v-if="userAgentInfo && userAgentInfo !== 'web'">
            <NuxtIcon name="search" />
        </NuxtLink>
        <!-- <div class="test-popup" v-if="messageActive" data-lenis-prevent>
            <div class="test-popup-content">
                <p v-text="message"></p>
                <button @click="messageActive = false">關閉</button>
            </div>
        </div> -->
    </main>
        
</template>
<script setup>
    const isMobile = useMobileDevice()
    const userAgentInfo = useUserAgentInfo()
    const isRedirecting = useIsRedirecting()
    const siteInfoData = useSiteInfoData()
    const { data } = await useAsyncData('siteInfoData', () => $fetch('/api/get_site_info'))
    siteInfoData.value = data.value

    const route = useRoute()

    // 每次路由切換完成後清除導轉遮罩
    watch(() => route.fullPath, () => {
        isRedirecting.value = false
    })

    const message = ref('')
    const messageActive = ref(true)
    const ibmbToken = useIBMBToken()
    ibmbToken.value = route?.query?.IBMBToken || ''

    const pathTypeMap = [
        { prefix: '/stock', type: 'stock' },
        { prefix: '/fund',  type: 'fund'  },
        { prefix: '/etf',   type: 'etf'   },
        { prefix: '/bond',  type: 'bond'  },
    ]
    const searchLink = computed(() => {
        const match = pathTypeMap.find(({ prefix }) => route.path.startsWith(prefix))
        return match ? `/search?from=${match.type}` : '/search'
    })

    function getUserAgentInfo() {
        var arr = []
        kony.evaluateJavaScriptInNativeContext("userAgent", JSON.stringify(arr))
    }

    function UserAgentCallBack(param) {
        const decodedParam = decodeURIComponent(param)
        alert("UserAgent: " + decodedParam)
        
        // 判斷是否被新網銀內嵌，檢查結果是否含有 newmobilebanking
        if (decodedParam && decodedParam.indexOf('newmobilebanking') > -1) {
            userAgentInfo.value = 'newmobilebanking'
        }
    }

    onMounted(() => {
        fetch('/api/get_config')
            .then(res => res.json())
            .then(config => {
                if (config?.ENV) {
                    window.ENV = config.ENV
                    window.DMP = {
                        serverUrl: config.DMP_SERVER_URL,
                        sdkUrl: config.DMP_SDK_URL,
                        heatmapUrl: config.DMP_HEATMAP_URL
                    }
                    document.documentElement.classList.add(config.ENV)
                    console.log('window.ENV', window.ENV)

                    message.value = `
                        用戶代理: ${navigator.userAgent}\n
                        用戶代理資訊: ${userAgentInfo.value}\n
                        是否為行動裝置: ${isMobile.value}\n
                        目前網域: ${window.location.hostname}\n
                        目前網址: ${window.location.pathname}\n
                        SERVER_URL: ${config.DMP_SERVER_URL}\n
                        SDK_URL: ${config.DMP_SDK_URL}\n
                        HEATMAP_URL: ${config.DMP_HEATMAP_URL}\n
                        ENV: ${config.ENV}\n
                    `
                }
            })
            .catch(err => {
                console.error('Failed to load config:', err)
            })

        ESinit()
        useUpdateViewport()
        // 確認有 IBMBToken，再呼叫 getUserAgentInfo()
        if (ibmbToken.value) {
            // getUserAgentInfo()
        }

        // 測試模式：模擬不同的 App 環境
        // userAgentInfo.value = 'dawho-iphone'        // DAWHO iPhone App
        // userAgentInfo.value = 'dawho-android'       // DAWHO Android App
        // userAgentInfo.value = 'mobilebanking-iphone' // 永豐行動銀行 iPhone App
        // userAgentInfo.value = 'mobilebanking-android' // 永豐行動銀行 Android App
        // userAgentInfo.value = 'web'                   // 一般網頁
        // userAgentInfo.value = 'newmobilebanking'
    })

</script>
<style>
    .redirect-overlay {
        position: fixed;
        inset: 0;
        z-index: 99999;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .redirect-overlay__spinner {
        width: 2.4rem;
        height: 2.4rem;
        border: 3px solid #e0e0e0;
        border-top-color: #333;
        border-radius: 50%;
        animation: redirect-spin 0.7s linear infinite;
    }
    @keyframes redirect-spin {
        to { transform: rotate(360deg); }
    }

    main {
        position: relative;
        z-index: 1;
        background-color: #fff;
        min-height: 80vh;
        
        @include media-breakpoint-down(medium) {
            min-height: 100dvh;
        }
    }
    footer {
        position: relative;
        z-index: 0;
    }

    .search {
        width: 3.6rem;
        height: 3.6rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 10rem;
        box-shadow: 0 0 10px 0 rgba(0, 8, 15, 0.15);
        position: absolute;
        right: 2.4rem;
        top: 2.4rem;
        z-index: 10;
        background-color: #fff;
    }

    .test-popup {
        position: fixed;
        top: 6rem;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 10000;
        display: flex;
    }

    .test-popup-content {
        background-color: #fff;
        padding: 1rem;
        margin: 1rem;
        border-radius: 1rem;
        max-width: 100vw;
        width: 100vw;
        max-height: calc(100dvh - 8rem);
        white-space: pre-line;
        overflow: scroll;
        word-break: break-all;
    }

    .test-popup-content button {
        width: 100%;
        padding: 1rem;
        border-radius: .6rem;
        background-color: black;
        color: #fff;
    }
</style>