<script setup>
import CollectionToolbar from '@/views/CollectionView/CollectionToolbar.vue'
import CollectionMerchCard from '@/views/CollectionView/CollectionMerchCard.vue'
import { computed, onMounted, ref } from 'vue'
import { useMerchApi } from '@/api/merch.js'
import ScrollToTopButton from '@/components/ScrollToTopButton.vue'

const merchList = ref(null)
const loading = ref(true)
const error = ref(null)

const { getMerchList } = useMerchApi()

const fetchMerch = async () => {
  try {
    const response = await getMerchList()
    if (!response.ok) throw new Error('Network error')
    merchList.value = await response.data
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchMerch()
})

const searchQuery = ref('')

const filteredMerch = computed(() => {
  if (!searchQuery.value.trim()) {
    return merchList.value
  }
  const q = searchQuery.value.toLowerCase()
  return merchList.value.filter((item) => item.name.toLowerCase().includes(q))
})
</script>

<template>
  <div class="sticky-search-container">
    <CollectionToolbar v-model="searchQuery" />
  </div>
  <n-grid responsive="screen" cols="2 s:3 m:4 l:5 xl:6 2xl:7" class="grid-main">
    <n-gi class="grid-item" v-for="item in filteredMerch" :key="item.merch_uuid">
      <router-link :to="`/details/${item.merch_uuid}`" class="card-link">
        <CollectionMerchCard :merch="item" />
      </router-link>
    </n-gi>
  </n-grid>
  <ScrollToTopButton />
</template>

<style scoped></style>
