<template>
    <div class="search-input">
        <form class="search-input__form" @submit.prevent="submitSearch">
            <div class="search-input__form-input" :class="{ '-focus': isFocused }">
                <nuxt-icon name="search" />
                <input 
                    ref="inputRef" 
                    type="text" 
                    v-model="searchText"
                    name="keyword" 
                    :placeholder="template.placeholder || '請輸入關鍵字'" 
                    @focus="handleFocus" 
                    @blur="isFocused = false" 
                    autocomplete="off"
                >
                <ElementsButton
                    :data="{
                        submit: true,
                        text: template.buttonText || 'GO',
                    }"
                />
            </div>
            <div 
                class="search-input__form-suggestion"
                @mousedown.prevent
                v-if="isFocused && filteredSuggestions.length > 0"
            >
                <div>
                    <ul 
                        v-if="!searchText" 
                        class="search-input__form-suggestion-default"
                    >
                        <span>快速搜尋</span>
                        <li
                            v-for="text in recommendSearchText"
                            :key="text.key"
                            @click="handleSuggestionClick(text.sentence)"
                        >
                            <nuxt-icon name="arrow_forward" />{{ text.sentence }}
                        </li>
                    </ul>
                    <!-- <ul 
                        v-else-if="filteredSuggestions.length > 0"
                        class="search-input__form-suggestion-real"
                    > -->
                    
                    <ul 
                        v-else-if="filteredSuggestions.length > 0"
                        class="search-input__form-suggestion-real"
                    >
                        <span>推薦搜尋</span>
                        <li
                            v-for="text in filteredSuggestions.slice(0, 6)"
                            :key="text.key"
                            @click="handleSuggestionClick(text.sentence)"
                        >
                            <nuxt-icon name="arrow_forward" />{{ text.sentence }}
                        </li>
                    </ul>

                    <!-- <div 
                        v-else
                        class="search-input__form-suggestion-nofound"
                    >
                        沒有符合「 {{ searchText }} 」的建議選項
                    </div> -->
                </div>
            </div>
        </form>
    </div>
</template>

<script setup>
const props = defineProps({
    template: {
        type: Object,
        default: () => ({
            placeholder: '請輸入關鍵字',
            buttonText: 'GO',
            redirectPath: '/search/result'
        }),
    },
})

const isFocused = ref(false)
const inputRef = ref(null)
const searchText = ref('')
const btnTags = ref([])
const recommendSearchText = ref([])

const handleFocus = async () => {
    isFocused.value = true
    if (!btnTags.value.length) {
        // 在這裡獲取推薦搜尋詞
        const { data } = await useFetch('/api/get_single_type?id=search')
        btnTags.value = data.value.blocks[2].fields.suggested_sentence
        recommendSearchText.value = data.value.blocks[1].fields.search_sentence
    }
}

const route = useRoute()

// 從當前路徑偵測商品類別，帶入搜尋結果頁作為預設分類
const pathTypeMap = [
    { prefix: '/stock', type: 'stock' },
    { prefix: '/fund',  type: 'fund'  },
    { prefix: '/etf',   type: 'etf'   },
    { prefix: '/bond',  type: 'bond'  },
]
const getProductTypeFromPath = () => {
    const match = pathTypeMap.find(({ prefix }) => route.path.startsWith(prefix))
    return match?.type ?? null
}

const buildSearchUrl = (keyword) => {
    const base = `${props.template.redirectPath}?keyword=${encodeURIComponent(keyword)}`
    const fromType = getProductTypeFromPath()
    return fromType ? `${base}&from=${fromType}` : base
}

const handleSuggestionClick = (text) => {
    searchText.value = text
    isFocused.value = false
    navigateTo(buildSearchUrl(text))
}

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

const submitSearch = () => {
    if (!searchText.value) return
    navigateTo(buildSearchUrl(searchText.value))
}
</script>

<style lang="scss">
$class-name: search-input;
.#{$class-name} {
    &__form {
        position: relative;

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

            .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);

                ul {
                    > span {
                        @include typo('head', 14);
                        color: map-get($colors, gray-1);
                        padding-bottom: 1.2rem;
                    }
                    li {
                        cursor: pointer;
                        padding: .6rem 0;
                        transition: opacity .3s;

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

        &-input {
            &.-focus + .search-input__form-suggestion {
                display: block;
            }
        }
    }
}
</style>