<template>
    <NuxtLayout :name="device" :config="config">
        <main class="search-product">
            <SearchBrand v-if="data.brand" />
            <AppBreadcrumbs v-else-if="device == 'desktop'" :items="breadcrumbs" />
            <SearchWrapper />
            <HomeProducers v-if="data.brand" :title="$t('otherProducers')" />
        </main>
    </NuxtLayout>
</template>

<script setup>
import init from '../../initialize/search'

const config = reactive({
    mobile: { header: { search: true, menu: true } },
})

const { device, t } = inject('service')
const breadcrumbs = reactive([
    { name: t('asanMarket'), link: '/' },
    { name: t('products'), link: '/search' }
])

const route = useRoute()
const { page = 1, sort = 'mostVisited', ...filters } = route.query

const { status, data, error } = await useFetch(`/api/products/search/${page}`, {
    params: { sort, filters }
})

if (status.value == 'success') {
    if (filters.category) {
        const temp = []
        const func = (items) => {
            let finded = false
            items.forEach((item) => {
                if (!finded) {
                    if (item.link == filters.category) {
                        temp.unshift(Object.assign({}, item))
                        finded = true
                    } else {
                        finded = func(item.sub ?? [])
                        if (finded) {
                            temp.unshift(Object.assign({}, item))
                        }
                    }
                }
            })
            return finded
        }

        const categories = useCategoriesStore()
        func(categories.items)

        const items = temp.map((item) => {
            item.link = '/search?category=' + item.link
            return item
        })
        breadcrumbs.push(...items)
    }

    if (filters.q)
        breadcrumbs.push({ name: filters.q, link: route.path })


    provide('data', data.value)

    route.meta.init = init()
    provide('init', route.meta.init)

} else throw createError(error.value)
</script>

<style lang="scss">
.search-product {
    @apply flex flex-col mb-[6.8rem] bg-white;

    .breadcrumbs {
        @apply px-3 justify-start mt-8 mb-2.5 max-lg:hidden;
    }


}
</style>
