import Image from 'next/image'
import Link from 'next/link'
import { getLocale, getTranslations } from 'next-intl/server'
import { ArrowUpRight, Star, Sparkles } from 'lucide-react'
import Container from '@/components/frontend/Container'
import HeroSlider from '@/components/frontend/home/blocks/HeroSlider'
import BannerFill from '@/components/frontend/home/blocks/BannerFill'
import HeroFallback from '@/components/frontend/home/blocks/HeroFallback'
import PriceTag from './PriceTag'
import { getProductCatalog } from '@/lib/db/queries/getProductCatalog'
import { getStoreStats } from '@/lib/db/queries/getStoreStats'
import { isOptimizableImage } from '@/lib/cloudinary'
import type { HomeBanner } from '@/lib/db/queries/getHeroBanners'

const compact = (locale: string, n: number) => new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 1 }).format(n)

// "Premium" hero: a deep, full-width band (brand glow on the dark theme
// color) with the admin's hero slider in a large rounded frame, and beside
// it a spotlight on one real featured product plus live store numbers.
export default async function HeroPremium({ slides }: { slides: HomeBanner[] }) {
  const locale = await getLocale()
  const [t, tHero, stats, featured] = await Promise.all([
    getTranslations('HomeDesigns'),
    getTranslations('Hero'),
    getStoreStats(),
    getProductCatalog(locale, { featuredOnly: true, sort: 'popular', page: 1, perPage: 1 }),
  ])
  const spotlight =
    featured.products[0] ?? (await getProductCatalog(locale, { sort: 'popular', page: 1, perPage: 1 })).products[0]

  const statItems = [
    { value: compact(locale, stats.products), label: t('premium.statProducts') },
    { value: compact(locale, stats.categories), label: t('premium.statCategories') },
    stats.brands > 0 ? { value: compact(locale, stats.brands), label: t('premium.statBrands') } : null,
    stats.reviews > 0 ? { value: `${stats.averageRating}★`, label: t('premium.statRating', { count: stats.reviews }) } : null,
  ].filter((s): s is { value: string; label: string } => s !== null && s.value !== '0')

  const frame = 'h-[380px] sm:h-[500px] lg:h-[600px] rounded-[2rem]'

  return (
    <section className="relative overflow-hidden bg-dark-bg text-white">
      <div aria-hidden className="pointer-events-none absolute -top-40 -start-40 h-[520px] w-[520px] rounded-full bg-primary/30 blur-[140px]" />
      <div aria-hidden className="pointer-events-none absolute -bottom-48 end-0 h-[480px] w-[480px] rounded-full bg-secondary/25 blur-[140px]" />
      <div aria-hidden className="pointer-events-none absolute inset-0 opacity-[0.04] [background-image:linear-gradient(white_1px,transparent_1px),linear-gradient(90deg,white_1px,transparent_1px)] [background-size:48px_48px]" />

      <Container className="relative py-5 sm:py-8">
        <div className="grid gap-4 sm:gap-5 lg:grid-cols-12">
          <div className="lg:col-span-8">
            {slides.length > 0 ? (
              <HeroSlider
                labels={{
                  previous: tHero('carousel.previous'),
                  next: tHero('carousel.next'),
                  carousel: t('hero.carousel'),
                  slide: slides.map((_, i) => t('hero.slideOf', { number: i + 1, total: slides.length })),
                }}
                className={`${frame} bg-white/5 ring-1 ring-white/10 shadow-2xl shadow-black/40`}
                controls="bars"
                controlsPosition="bottom-start"
              >
                {slides.map((banner, i) => (
                  <BannerFill
                    key={banner.id}
                    banner={banner}
                    eager={i === 0}
                    sizes="(max-width: 1024px) 100vw, 66vw"
                    overlaySize="hero"
                  />
                ))}
              </HeroSlider>
            ) : (
              <HeroFallback className={frame} />
            )}
          </div>

          <div className="grid gap-4 sm:gap-5 sm:grid-cols-2 lg:col-span-4 lg:grid-cols-1 lg:grid-rows-[1fr_auto]">
            {spotlight && (
              <Link
                href={`/product/${spotlight.slug}`}
                className="group relative flex flex-col overflow-hidden rounded-[2rem] bg-white/[0.06] p-5 ring-1 ring-white/10 backdrop-blur transition-colors hover:bg-white/[0.09]"
              >
                <div className="flex items-center justify-between">
                  <span className="inline-flex items-center gap-1.5 rounded-full bg-white/10 px-3 py-1 text-[11px] font-bold uppercase tracking-[0.18em] text-white/85">
                    <Sparkles size={12} className="text-primary-light" /> {t('premium.spotlight')}
                  </span>
                  <span className="flex h-10 w-10 items-center justify-center rounded-full bg-white text-gray-900 transition-transform duration-300 group-hover:rotate-45">
                    <ArrowUpRight size={18} className="rtl:-scale-x-100" />
                  </span>
                </div>
                <div className="relative my-4 aspect-[4/3] lg:aspect-auto lg:flex-1 lg:min-h-[180px] overflow-hidden rounded-2xl bg-white">
                  {spotlight.imageUrl ? (
                    <Image
                      src={spotlight.imageUrl}
                      alt={spotlight.title}
                      fill
                      sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 30vw"
                      unoptimized={!isOptimizableImage(spotlight.imageUrl)}
                      className="object-cover text-transparent transition-transform duration-700 group-hover:scale-105"
                    />
                  ) : null}
                </div>
                {spotlight.brand && (
                  <span className="text-[11px] font-semibold uppercase tracking-[0.2em] text-white/55">{spotlight.brand.name}</span>
                )}
                <div className="mt-1 flex items-end justify-between gap-3">
                  <p className="text-lg font-bold leading-snug line-clamp-2">{spotlight.title}</p>
                  <PriceTag price={spotlight.price} oldPrice={spotlight.oldPrice} tone="dark" />
                </div>
              </Link>
            )}

            {statItems.length > 0 && (
              <div className="grid grid-cols-2 gap-px overflow-hidden rounded-[2rem] bg-white/10 ring-1 ring-white/10">
                {statItems.map((s) => (
                  <div key={s.label} className="bg-dark-bg/60 px-5 py-4 backdrop-blur">
                    <p className="text-2xl sm:text-3xl font-black tracking-tight">{s.value}</p>
                    <p className="mt-0.5 text-xs text-white/60 flex items-center gap-1">
                      {s.value.endsWith('★') && <Star size={11} className="fill-yellow-400 text-yellow-400" />}
                      {s.label}
                    </p>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </Container>
    </section>
  )
}
