<template>
  <section class="container-page py-10">
    <div class="grid gap-8 lg:grid-cols-[280px_1fr]">
      <DashboardSidebar />

      <div>
        <div class="mb-8">
          <h1 class="text-3xl font-extrabold">Barang Tersimpan</h1>
          <p class="mt-2 text-slate-600">Barang yang kamu simpan dari marketplace.</p>
        </div>

        <div v-if="loading" class="card p-10 text-center">
          <h2 class="text-xl font-extrabold">Memuat barang tersimpan...</h2>
        </div>

        <div v-else-if="savedProducts.length" class="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          <ProductCard
            v-for="product in savedProducts"
            :key="product.id"
            :product="product"
            :saved="true"
            @toggle-save="toggleSave"
          />
        </div>

        <div v-else class="card p-10 text-center">
          <h2 class="text-xl font-extrabold">Belum ada barang tersimpan</h2>
          <p class="mt-2 text-slate-600">Simpan barang yang menarik dari marketplace.</p>
          <RouterLink to="/marketplace" class="btn-primary mt-5">Lihat Marketplace</RouterLink>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from "vue"
import DashboardSidebar from "../components/DashboardSidebar.vue"
import ProductCard from "../components/ProductCard.vue"
import { products as defaultProducts } from "../data/products"
import { fetchProducts, getSavedProducts, setSavedProducts } from "../utils"

const saved = ref(getSavedProducts())
const products = ref([])
const loading = ref(true)

const savedProducts = computed(() => {
  return products.value.filter((product) => saved.value.includes(product.id))
})

function toggleSave(id) {
  saved.value = saved.value.filter((item) => item !== id)
  setSavedProducts(saved.value)
}

async function loadProducts() {
  loading.value = true
  try {
    const data = await fetchProducts()
    products.value = data.products
  } catch {
    products.value = defaultProducts
  } finally {
    loading.value = false
  }
}

onMounted(loadProducts)
</script>
