<template>
    <div class="error-page">
        <!-- newmobilebanking 導轉中遮罩 -->
        <div v-if="isRedirecting" class="error-redirect-overlay">
            <div class="error-redirect-overlay__spinner"></div>
        </div>

        <!-- 正常錯誤頁面 -->
        <template v-else>
            <Header />
            <main data-scroll-container>
                <div class="container">
                    <div class="error-page__content">
                        <h1>{{ errorTitle }}</h1>
                        <p>{{ errorMessage }}</p>
                        <NuxtLink to="/" class="error-page__link">返回首頁</NuxtLink>
                        <!-- <pre>{{ error }}</pre> -->
                    </div>

                    <div class="error-page__test">
                        <ElementsButton
                            :data="{
                                text: 'Client 測試呼叫 API 資料',
                                style: 'success'
                            }"
                            @click="testApi"
                        />
                        <ElementsButton
                            :data="{
                                text: 'Server 測試呼叫 API 資料',
                                style: 'danger'
                            }"
                            @click="testServerApi"
                        />
                    </div>
                </div>
            </main>
            <Footer />
        </template>
    </div>
</template>
<script setup lang="ts">
    const props = defineProps({
        error: {
            type: Object,
            required: true
        }
    })
    const pageloaded = usePageLoaded()

    // newmobilebanking 導轉邏輯
    // 當 stock 頁面無資料且可能為 newmobilebanking 時，isRedirecting = true
    // 此時 error.vue 顯示遮罩，等待 kony callback 確認後導轉到 ETF 頁
    const isRedirecting = useIsRedirecting()
    const userAgentInfo = useUserAgentInfo()
    const route = useRoute()

    if (isRedirecting.value && import.meta.client) {
        const KONY_MAX_WAIT_MS = 3500
        let handled = false
        let stopWatchFn: (() => void) | undefined
        let timer: ReturnType<typeof setTimeout> | undefined

        // 從目前 route 取得產品 ID（如 /stock/product/VT → 'VT'）
        const productId = Array.isArray(route.params.id)
            ? route.params.id[0]
            : (route.params.id || route.path.split('/').pop() || '')

        const doHandle = (ua: string) => {
            if (handled) return
            handled = true
            stopWatchFn?.()
            clearTimeout(timer)

            if (ua === 'newmobilebanking') {
                navigateTo(`/etf/product/${productId}`)
            } else {
                // 確認非 newmobilebanking，顯示正常錯誤頁
                isRedirecting.value = false
            }
        }

        const currentUA = userAgentInfo.value
        if (currentUA === 'newmobilebanking') {
            doHandle('newmobilebanking')
        } else {
            const maxWait = (window as any).kony ? KONY_MAX_WAIT_MS : 400
            stopWatchFn = watch(userAgentInfo, (val: string) => {
                if (val === 'newmobilebanking') doHandle(val)
            })
            timer = setTimeout(() => doHandle(userAgentInfo.value), maxWait)
        }
    }

    const errorTitle = computed(() => {
        switch(props.error?.statusCode) {
            case 400:
                return '請求錯誤'
            case 401:
                return '未經授權'
            case 403: 
                return '拒絕訪問'
            case 404:
                return '找不到你要找的頁面。'
            case 500:
                return '伺服器錯誤'
            case 502:
                return '網關錯誤'
            case 503:
                return '服務暫時無法使用'
            case 504:
                return '網關超時'
            default:
                return '發生未知錯誤'
        }
    })

    const errorMessage = computed(() => {
        switch(props.error?.statusCode) {
            case 400:
                return '請求錯誤'
            case 401:
                return '未經授權'
            case 403: 
                return '拒絕訪問'
            case 404:
                return '抱歉，我們找不到你要找的頁面。你可以返回我們的首頁重新開始。'
            case 500:
                return '伺服器錯誤'
            case 502:
                return '網關錯誤'
            case 503:
                return '服務暫時無法使用'
            case 504:
                return '網關超時'
            default:
                return props.error?.statusMessage || '發生未知錯誤'
        }
    })

    const testApi = async () => {
        try {
            const data = await $fetch('/api/get_single_type?id=main_menu')
            console.log('Client 測試呼叫 API 資料', data)
        } catch (error) {
            console.log('Client 測試呼叫 API 錯誤', error)
        }
    }

    const testServerApi = async () => {
        try {
            const response = await $fetch('/api/servertest');
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            console.log('Server 測試呼叫 API 資料', response);
            
        } catch (error) {
            console.error('Server 測試呼叫 API 錯誤', 
                'status: ' + error.status,
                'message: ' + error.message,
                'stack: ' + error.stack,
                'code: ' + error.code
            );
            console.error(error.data);
        }
    }

    useHead({
        title: '發生錯誤' + props.error?.statusCode,
        meta: [
            { name: 'description', content: '發生錯誤' }
        ]
    })

    onMounted(() => {
        setTimeout(() => {
            pageloaded.value = true
            document.body.classList.remove('is-loading')
            document.body.classList.add('is-loaded')
        }, 600)
    })

</script>
<style lang="scss">
    .error-redirect-overlay {
        position: fixed;
        inset: 0;
        z-index: 99999;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;

        &__spinner {
            width: 2.4rem;
            height: 2.4rem;
            border: 3px solid #e0e0e0;
            border-top-color: #333;
            border-radius: 50%;
            animation: error-redirect-spin 0.7s linear infinite;
        }
    }
    @keyframes error-redirect-spin {
        to { transform: rotate(360deg); }
    }

    $class-name: error-page;
    .#{$class-name} {
        min-height: 100vh;
        display: flex;
        flex-direction: column;

        main {
            flex: 1;
            display: flex;
            align-items: center;

            pre {
                margin: 2rem 0;
                text-align: left;
            }
        }

        &__test,
        &__content {
            text-align: center;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            padding-left: 10rem;
            gap: 1rem;

            @include media-breakpoint-down(medium) {
                padding-left: 0;
            }

            h1 {
                @include typo('head', 44);
                margin-bottom: 1.6rem;

                @include media-breakpoint-down(medium) {
                    @include typo('head', 24);
                }
            }

            p {
                margin-bottom: 2rem;
                text-align: left;
            }
        }

        &__test {
            padding-top: 3rem;
            flex-direction: row;
            display: none;
        }

        &__link {
            display: inline-block;
            margin-top: 2rem;
            padding: 1rem 2rem;
            background-color: map-get($colors, black-1);
            color: #fff;
            border-radius: .4rem;
            transition: background-color .3s;

            &:hover {
                background-color: map-get($colors, red-50);
            }
        }
    }
</style>