import Image from 'next/image'
import Link from 'next/link'
import { getLocale, getTranslations } from 'next-intl/server'
import { getBrandList, type BrandListItem } from '@/lib/db/queries/getBrandDetail'
import SectionHeading from './SectionHeading'
import { isOptimizableImage } from '@/lib/cloudinary'

function BrandTile({ brand }: { brand: BrandListItem }) {
  return (
    <Link
      href={`/brand/${brand.slug}`}
      title={brand.name}
      className="group flex h-20 w-40 sm:h-24 sm:w-48 shrink-0 items-center justify-center rounded-2xl border border-gray-100 bg-white px-6 transition-all duration-300 hover:border-primary/30 hover:shadow-lg"
    >
      {brand.logoUrl ? (
        <span className="relative block h-full w-full">
          <Image
            src={brand.logoUrl}
            alt={brand.altText || brand.name}
            fill
            sizes="176px"
            unoptimized={!isOptimizableImage(brand.logoUrl)}
            className="object-contain p-3 transition-all duration-300"
          />
        </span>
      ) : (
        <span
          className="truncate text-lg font-extrabold tracking-tight transition-colors text-dark group-hover:text-primary"
        >
          {brand.name}
        </span>
      )}
    </Link>
  )
}

// Brands with at least one browsable product (getBrandList). Enough brands
// → an endless marquee (pauses on hover); a few → a simple centered row.
export default async function BrandsShowcase({ variant }: { variant: 'modern' | 'premium' }) {
  const locale = await getLocale()
  const [t, brands] = await Promise.all([getTranslations('HomeDesigns'), getBrandList(locale)])
  if (brands.length === 0) return null

  const marquee = brands.length >= 5

  return (
    <section className="home-reveal">
      <SectionHeading
        variant={variant}
        eyebrow={t('brands.eyebrow')}
        title={t('brands.title')}
        action={{ href: '/brands', label: t('brands.viewAll') }}
      />
      {marquee ? (
        <div className="home-marquee-pause relative overflow-hidden [mask-image:linear-gradient(to_right,transparent,black_8%,black_92%,transparent)]">
          <div
            className="home-marquee gap-4 sm:gap-6"
            style={{ ['--marquee-duration' as string]: `${Math.max(brands.length * 4, 25)}s` }}
          >
            {[...brands, ...brands].map((brand, i) => (
              // The second copy is decorative (it only makes the loop seamless).
              <div key={`${brand.id}-${i}`} aria-hidden={i >= brands.length} className="shrink-0">
                <BrandTile brand={brand} />
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="flex flex-wrap justify-center gap-4 sm:gap-6">
          {brands.map((brand) => (
            <BrandTile key={brand.id} brand={brand} />
          ))}
        </div>
      )}
    </section>
  )
}
