'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'

interface MedusaCollection { id: string; title: string; handle: string; metadata?: { image?: string } }

export default function BrandCarouselSection() {
  const [collections, setCollections] = useState<MedusaCollection[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/medusa/store/collections?limit=20')
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(d => { setCollections(d.collections ?? []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [])

  if (loading || collections.length === 0) 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 Collection</h2>
        <div className="flex gap-4 overflow-x-auto pb-3 scrollbar-hide snap-x snap-mandatory">
          {collections.map(col => (
            <Link
              key={col.id}
              href={`/products?collection=${col.handle}`}
              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">
                {col.metadata?.image ? (
                  <Image src={col.metadata.image} alt={col.title} fill className="object-cover group-hover:scale-105 transition-transform duration-300" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-3xl font-bold text-primary/30 uppercase">
                    {col.title.slice(0, 2)}
                  </div>
                )}
              </div>
              <p className="text-xs font-medium text-center line-clamp-2 group-hover:text-primary transition-colors">{col.title}</p>
            </Link>
          ))}
        </div>
      </div>
    </section>
  )
}
