<script setup>
import { onMounted, ref } from 'vue'
import { useChartsApi } from '@/api/charts.js'
import PeriodSelector from '@/components/PeriodSelector.vue'
import ChartsCard from '@/views/ChartsView/ChartsCard.vue'
import router from '@/router/index.js'


const { getChartsPrices } = useChartsApi()

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

const fetchPrices = async (days = 7) => {
  loading.value = true
  error.value = null
  try {
    const response = await getChartsPrices(days)

    if (response.status === 400) {
      router.push({ name: 'collection' })
      return
    }

    pricesList.value = response.data
  } catch (err) {
    error.value = err.message || 'Fetch data error'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchPrices(7)
})

function handleSelectDays(days) {
  fetchPrices(days)
}
</script>

<template>
  <PeriodSelector @days="handleSelectDays" />
  <n-grid responsive="screen" cols="1 s:1 m:1 l:2 xl:2 2xl:2" class="grid-main">
    <n-gi class="grid-item" v-for="item in pricesList" :key="item.merch_uuid">
      <router-link :to="`/details/${item.merch_uuid}`" class="card-link">
        <ChartsCard :chartsData="item" />
      </router-link>
    </n-gi>
  </n-grid>
</template>

<style scoped>

</style>
