<template>
    <div 
        class="page-search"
        :class="{'-height': menuData?.blocks?.[1]?.fields?.event_list?.length > 0}"
    >
        <!-- <ElementsBack /> -->
        <ElementsHome />
        <section class="container page-search__section-1">
            <h1 v-text="pageData.default.title"></h1>
            <p v-text="pageData.blocks[0].fields.description"></p>

            <form class="page-search__form" @submit.prevent="submitSearch">
                <div class="page-search__form-input" :class="{ '-focus': isFocused }">
                    <nuxt-icon name="search" />
                    <input 
                        ref="inputRef" 
                        type="text" 
                        v-model="searchText"
                        name="keyword" 
                        placeholder="請輸入關鍵字" 
                        @focus="isFocused = true" 
                        @blur="isFocused = false" 
                        autocomplete="off"
                    >
                    <ElementsButton
                        :data="{
                            submit: true,
                            text: 'GO',
                        }"
                    />
                </div>
                
                <div 
                    class="page-search__form-suggestion"
                    @mousedown.prevent
                    v-if="isFocused && filteredSuggestions.length > 0"
                >
                    <div>
                        <!-- 沒有輸入時顯示預設建議 -->
                        <ul 
                            v-if="!searchText" 
                            class="page-search__form-suggestion-default"
                        >
                            <span>快速搜尋</span>
                            <li
                                v-for="(text, index) in recommendSearchText"
                                :key="text.key"
                                @click="handleSuggestionClick(text?.sentence, text?.category)"
                            >
                                <nuxt-icon name="arrow_forward" />{{ text.sentence }}
                            </li>
                        </ul>
                        
                        <!-- 有搜尋結果時顯示篩選建議 -->
                        <ul 
                            v-else-if="filteredSuggestions.length > 0"
                            class="page-search__form-suggestion-real"
                        >
                            <span>推薦搜尋</span>
                            <li
                                v-for="(text, index) in filteredSuggestions.slice(0, 6)"
                                :key="text.key"
                                @click="handleSuggestionClick(text.sentence)"
                            >
                                <nuxt-icon name="arrow_forward" />{{ text.sentence }}
                            </li>
                        </ul>
                        <!-- 搜尋功能完善前不顯示，問題清單 P9，要改回來記得最上面的 v-if="isFocused && filteredSuggestions.length > 0" 要改成 v-if="isFocused" -->
                        <!-- 沒有搜尋結果時顯示提示 -->
                        <!-- <div 
                            v-else
                            class="page-search__form-suggestion-nofound"
                        >
                            沒有符合「 {{ searchText }} 」的建議選項
                        </div> -->
                    </div>
                </div>
            </form>
        </section>
        <section class="page-search__section-2">
            <div class="container">
                <h2>為你的下一次投資尋找靈感</h2>
                <!-- 只顯示前 20 個 -->
                <div class="page-search__tags">
                    <ElementsButton
                        v-for="tag in btnTags.slice(0, 20)"
                        :key="tag.key"
                        :data="{ 
                            text: tag.sentence,
                            style: 'border',
                            to: `/search/result?type=${tag?.category}&keyword=${tag?.sentence}`,
                        }"
                    />
                </div>
            </div>
        </section>
        <Footer />
    </div>
</template>
<script setup>

    const pageloaded = usePageLoaded()
    const route = useRoute()
    const isFocused = ref(false)
    const inputRef = ref(null)
    const searchText = ref('')

    onMounted(() => {
        inputRef.value?.focus()
    })
    const { data: config } = await useFetch('/api/get_config')

    const fromType = route.query.from || null

    const buildResultUrl = (keyword, cat) => {
        const params = new URLSearchParams({ keyword: keyword.trim() })
        if (cat) params.set('type', cat)
        else if (fromType) params.set('from', fromType)
        return `/search/result?${params.toString()}`
    }

    const handleSuggestionClick = (text, cat) => {
        searchText.value = text
        isFocused.value = false
        navigateTo(buildResultUrl(text, cat))
    }

    const filteredSuggestions = computed(() => {
        if (!searchText.value) return btnTags.value
        
        return btnTags.value
            .filter(tag => 
                tag.sentence.toLowerCase().includes(searchText.value.toLowerCase())
            )
    })

    const { data: pageData } = await useAsyncData('pageData', () => {
        return $fetch('/api/get_single_type?id=search')
    })

    if (pageData.value) {
        pageloaded.value = true
    }

    const submitSearch = () => {
        if (!searchText.value) return
        navigateTo(buildResultUrl(searchText.value))
    }

    const btnTags = ref([])
    const recommendSearchText = ref([])
    btnTags.value = pageData.value.blocks[2].fields.suggested_sentence
    recommendSearchText.value = pageData.value.blocks[1].fields.search_sentence

    // SEO 區域
    const siteInfoData = useSiteInfoData()
    const seoDefault = siteInfoData?.value?.seo
    const menuData = computed(() => siteInfoData.value.header)

    // 取得 OG 圖片
    const ogImage = ref(
        pageData.value?.seo?.og_image?.[0] ?
        pageData.value?.seo?.og_image?.[0] :
        seoDefault?.site_img
    )
    if (ogImage.value) {
        ogImage.value = `/images/${ogImage.value?._id}.${ogImage.value?.fileType}`
    }
    // 設定 SEO
    useHead({
        title: pageData.value?.seo?.og_title || seoDefault?.site_name,
        meta: useMetaReturn({
            title: pageData.value?.seo?.og_title || seoDefault?.site_name,
            description: pageData.value?.seo?.og_description || seoDefault?.description,
            image: ogImage.value,
            url: config.value?.SITE_URL + route?.fullPath || 'https://wm.sinopac.com' + route?.fullPath
        })
    })
</script>
<style lang="scss">
    $class-name: page-search;
    .#{$class-name} {
        padding: 12rem 0 0;

        @include media-breakpoint-down(medium) {
            padding-top: 16.2rem;
        }

        &.-height {
            padding-top: 18rem;
        }

        section {
            h1 {
                @include typo('head', 44);
                margin-bottom: 2rem;
    
                @include media-breakpoint-down(tablet) {
                    @include typo('head', 32);
                    margin-bottom: 1.6rem;
                }
            }
            p {
                margin-bottom: 4rem;
    
                @include media-breakpoint-up(tablet) {
                    max-width: 50%;
                }
            }
        }
            

        &__section {
            &-2 {
                padding: 6rem 0;
                background-color: map-get($colors, gray-3);

                @include media-breakpoint-down(tablet) {
                    padding: 4.8rem 0;
                }
                h2 {
                    @include typo('head', 36);
                    margin-bottom: 6rem;

                    @include media-breakpoint-down(tablet) {
                        @include typo('head', 24);
                        margin-bottom: 2rem;
                    }
                }
            }
        }

        &__form {
            margin-bottom: 8rem;
            position: relative;

            @include media-breakpoint-down(tablet) {
                margin-bottom: 4.8rem;
            }

            &-input {
                display: flex;
                gap: 2.4rem;
                position: relative;

                @include media-breakpoint-down(tablet) {
                    gap: 1.2rem;
                }

                .nuxt-icon {
                    font-size: 3rem;
                    position: absolute;
                    left: 1.6rem;
                    top: 50%;
                    transform: translateY(-50%);
                }
                input {
                    font-size: 1.6rem;
                    padding: 1.6rem 3.2rem 1.6rem 5.6rem;
                    line-height: 1;
                    background-color: map-get($colors, gray-3);
                    border: 1px solid map-get($colors, gray-3);
                    border-radius: .4rem;
                    transition: border-color .3s;

                    &::placeholder {
                        color: map-get($colors, gray-1);
                    }

                    &:hover,
                    &:focus {
                        border-color: map-get($colors, black-1);
                    }
                }
                button {
                    height: 100%;
                }
            }

            &-suggestion {
                position: absolute;
                padding-top: 2.4rem;
                width: 100%;
                display: none;
                animation: fadeInDown .2s both;

                > div {
                    padding: 2rem 4rem;
                    background-color: #fff;
                    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);

                    @include media-breakpoint-down(tablet) {
                        padding: 1.6rem;
                    }

                    ul {
                        > span {
                            @include typo('head', 14);
                            color: map-get($colors, gray-1);
                            padding-bottom: 1.2rem;

                            @include media-breakpoint-down(tablet) {
                                @include typo('head', 12);
                            }
                        }
                        li {
                            cursor: pointer;
                            padding: .6rem 0;
                            transition: opacity .3s;

                            @include media-breakpoint-down(tablet) {
                                @include typo('head', 14);

                                padding: .4rem 0;
                            }

                            &:hover {
                                opacity: .5;
                            }
                        }
                    }
                }
            }

            &-input {
                &.-focus + .page-search__form-suggestion {
                    display: block;
                }
            }
        }

        &__tags {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;

            @include media-breakpoint-down(tablet) {
                gap: .8rem;
            }

            button, a {
                background-color: #fff;
                border-radius: 4rem;
                padding: .8rem 1.6rem;
            }
        }
    }
</style>