import Image from 'next/image'
import Link from 'next/link'
import { getProductCarousels } from '@/lib/cms'

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 VulaProduct {
  id: string; title: string; thumbnail: string | null
  variants?: Array<{ prices?: Array<{ amount: number; currency_code: string }> }>
}

const CURRENCY_SYMBOLS: Record<string, string> = { zar: 'R', usd: '$', eur: '€', gbp: '£', kes: 'KSh', ngn: '₦', ghs: '₵' }
const fmt = (amount: number, code?: string) =>
  `${CURRENCY_SYMBOLS[(code ?? '').toLowerCase()] ?? (code?.toUpperCase() ?? '')}${amount.toFixed(2)}`

async function fetchProductsByIds(ids: string[]): Promise<VulaProduct[]> {
  if (!ids.length) return []
  try {
    const query = ids.map(id => `id[]=${id}`).join('&')
    const res = await fetch(
      `${VULA_CMS_URL}/api/store/${VULA_PROJECT_ID}/products?${query}&limit=${ids.length}`,
      { next: { revalidate: 300 } }
    )
    if (!res.ok) return []
    const data = await res.json() as { products?: VulaProduct[] }
    return data.products ?? []
  } catch { return [] }
}

export default async function ProductCarouselSection() {
  const carousels = await getProductCarousels()
  if (!carousels.length) return null

  const sections = await Promise.all(
    carousels.map(async c => {
      const ids   = Array.isArray(c.data.product_ids) ? (c.data.product_ids as string[]) : []
      const prods = await fetchProductsByIds(ids)
      return { title: c.data.title as string, products: prods }
    })
  )

  return (
    <>
      {sections.filter(s => s.products.length > 0).map(section => (
        <section key={section.title} className="py-8 px-4">
          <div className="max-w-7xl mx-auto">
            <h2 className="text-xl font-bold mb-5">{section.title}</h2>
            <div className="flex gap-4 overflow-x-auto pb-3 scrollbar-hide snap-x snap-mandatory">
              {section.products.map(product => {
                const variant = product.variants?.[0]
                const price   = variant?.prices?.[0]
                return (
                  <Link
                    key={product.id}
                    href={`/products/${product.id}`}
                    className="flex-none snap-start w-44 group"
                  >
                    <div className="relative h-44 w-44 rounded-xl overflow-hidden bg-muted mb-2 group-hover:shadow-md transition-shadow">
                      {product.thumbnail ? (
                        <Image src={product.thumbnail} alt={product.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-muted-foreground text-xs">No image</div>
                      )}
                    </div>
                    <p className="text-xs font-medium line-clamp-2 group-hover:text-primary transition-colors mb-1">{product.title}</p>
                    {price?.amount && (
                      <p className="text-xs font-bold text-primary">{fmt(price.amount, price.currency_code)}</p>
                    )}
                  </Link>
                )
              })}
            </div>
          </div>
        </section>
      ))}
    </>
  )
}
