import Link from 'next/link'

const VULA_CMS_URL    = process.env.VULA_CMS_URL || 'https://ide.vulai.co.za'
const VULA_PROJECT_ID = process.env.VULA_CMS_PROJECT_ID || ''

interface VulaCategory { id: string; name: string; handle: string }

async function getCategories(): Promise<VulaCategory[]> {
  if (!VULA_PROJECT_ID) return []
  try {
    const r = await fetch(
      `${VULA_CMS_URL}/api/store/${VULA_PROJECT_ID}/categories`,
      { next: { revalidate: 300 } }
    )
    if (!r.ok) return []
    const data = await r.json() as { product_categories?: VulaCategory[] }
    return data.product_categories ?? []
  } catch {
    return []
  }
}

export default async function BrandCarouselSection() {
  const categories = await getCategories()
  if (!categories.length) return null

  return (
    <section className="py-10 px-4">
      <div className="max-w-7xl mx-auto">
        <h2 className="text-xl font-bold mb-5">Shop by Category</h2>
        <div className="flex gap-4 overflow-x-auto pb-3 scrollbar-hide snap-x snap-mandatory">
          {categories.map(cat => (
            <Link
              key={cat.id}
              href={`/products?categoryId=${cat.id}`}
              className="flex-none snap-start w-36 group"
            >
              <div className="relative h-36 w-36 rounded-2xl overflow-hidden bg-muted mb-2 group-hover:shadow-md transition-shadow flex items-center justify-center">
                <span className="text-3xl font-bold text-primary/30 uppercase">{cat.name.slice(0, 2)}</span>
              </div>
              <p className="text-xs font-medium text-center line-clamp-2 group-hover:text-primary transition-colors">{cat.name}</p>
            </Link>
          ))}
        </div>
      </div>
    </section>
  )
}
