<template>
  <section class="bg-gradient-to-br from-brand-50 via-white to-slate-100">
    <div class="container-page grid min-h-[560px] items-center gap-10 py-16 lg:grid-cols-2">
      <div>
        <ShinyText
          text="SecondTech"
          className="text-1xl font-extrabold tracking-tight sm:text-1xl lg:text-2xl"
          :color="'#1c4ed9'"
          :shineColor="'#e0e7ff'"
          :spread="45"
          :speed="1"
          :delay="2"
          :direction="'left'"
          :pauseOnHover="true"
          :yoyo="true"
        />

        <div>
          <TextType
            as="h2"
            className="mt-6 text-3xl font-extrabold tracking-tight text-zinc-950 sm:text-6xl lg:text-5xl"
            :text="['Menjual Barang Bekas, yang kamu butuhkan, di satu tempat.']"
            :typingSpeed="75"
            :pauseDuration="1500"
            :showCursor="false"
            :textColors="['var(--hero-title-color)']"
            cursorCharacter="|"
          />
        </div>

        <p class="mt-6 max-w-xl text-lg leading-8 text-slate-600">
          Temukan laptop bekas, PC, monitor, keyboard, router, switch, access point, dan server bekas untuk berbagai kebutuhan.
        </p>

        <div class="mt-8 flex flex-wrap gap-3">
          <RouterLink to="/jual" class="btn-primary">Jual Barang Sekarang</RouterLink>
          <RouterLink to="/marketplace" class="btn-secondary">Lihat Marketplace</RouterLink>
        </div>
      </div>

      <div class="relative">
        <div class="absolute -inset-4 rounded-[2rem] bg-brand-100 blur-2xl"></div>
        <img
          class="relative aspect-[4/3] w-full rounded-[2rem] object-cover shadow-2xl"
          src="/Hero.jpeg"
          alt="Tech marketplace"
        />
      </div>
    </div>
  </section>

  <section class="container-page py-14">
    <div class="mb-8 flex items-end justify-between gap-4">
      <div>
        <h2 class="text-2xl font-extrabold">Kategori Populer</h2>
        <p class="mt-2 text-slate-600">Fokus ke perangkat teknologi dan jaringan.</p>
      </div>
      <RouterLink to="/marketplace" class="text-sm font-bold text-brand-700">
        Lihat semua
      </RouterLink>
    </div>

    <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
      <div
        v-for="cat in categoryList"
        :key="cat.name"
        class="card p-5 text-center transition hover:-translate-y-1 hover:shadow-md"
      >
        <div class="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-700">
          <component :is="iconMap[cat.icon]" :size="22" />
        </div>

        <p class="font-bold">{{ cat.name }}</p>
      </div>
    </div>
  </section>

  <section class="bg-white py-14">
    <div class="container-page">
      <div class="mb-8 flex items-end justify-between gap-4">
        <div>
          <h2 class="text-2xl font-extrabold">Produk Terbaru</h2>
          <p class="mt-2 text-slate-600">Barang terbaru yang tersedia di marketplace.</p>
        </div>
      </div>

      <div v-if="latestProducts.length" class="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
        <ProductCard
          v-for="product in latestProducts"
          :key="product.id"
          :product="product"
          :saved="saved.includes(product.id)"
          @toggle-save="toggleSave"
        />
      </div>

      <div v-else class="card p-10 text-center">
        <h3 class="text-xl font-extrabold">Belum ada produk</h3>
        <p class="mt-2 text-slate-600">Produk terbaru akan muncul setelah barang diposting.</p>
      </div>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from "vue"
import { Boxes, Keyboard, Laptop, Monitor, Network, PcCase, Router, Server, Wifi } from "lucide-vue-next"
import ProductCard from "../components/ProductCard.vue"
import { categoryOptions, products as defaultProducts } from "../data/products"
import { fetchProducts, getSavedProducts, setSavedProducts } from "../utils"
import ShinyText from "../vuebits/ShinyText/ShinyText.vue"
import TextType from "../vuebits/TextType/TextType.vue"

const saved = ref(getSavedProducts())
const products = ref(defaultProducts)

const categoryList = categoryOptions
  .filter((category) => category.name !== "Semua")
  .slice(0, 6)

const latestProducts = computed(() => {
  return [...products.value]
    .sort((a, b) => {
      const dateA = new Date(a.created_at || 0).getTime()
      const dateB = new Date(b.created_at || 0).getTime()

      if (dateA !== dateB) return dateB - dateA
      return Number(b.id) - Number(a.id)
    })
    .slice(0, 4)
})

const iconMap = {
  Boxes,
  Laptop,
  PcCase,
  Monitor,
  Keyboard,
  Router,
  Network,
  Server,
  Wifi
}

function toggleSave(id) {
  if (saved.value.includes(id)) {
    saved.value = saved.value.filter((item) => item !== id)
  } else {
    saved.value.push(id)
  }

  setSavedProducts(saved.value)
}

async function loadLatestProducts() {
  try {
    const data = await fetchProducts()
    products.value = data.products?.length ? data.products : defaultProducts
  } catch {
    products.value = defaultProducts
  }
}

onMounted(loadLatestProducts)
</script>
