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

export default async function AdvertBannerSection() {
  const items = await getAdvertBanners()
  const now = Date.now()
  const banner = items.find(item => {
    const start = item.data.start_date ? new Date(item.data.start_date as string).getTime() : 0
    const end   = item.data.end_date   ? new Date(item.data.end_date   as string).getTime() : Infinity
    return now >= start && now <= end
  }) ?? items[0]

  if (!banner) return null

  const { headline, subheadline, cta_text, cta_url, image } = banner.data as {
    headline: string; subheadline?: string; cta_text?: string; cta_url?: string; image?: string
  }

  return (
    <section className="relative w-full overflow-hidden rounded-2xl my-8 mx-auto max-w-7xl px-4">
      {image ? (
        <div className="relative h-64 md:h-80 w-full">
          <Image src={image} alt={headline} fill className="object-cover rounded-2xl" />
          <div className="absolute inset-0 bg-black/45 rounded-2xl" />
          <div className="absolute inset-0 flex flex-col items-center justify-center text-center px-6 gap-3">
            <h2 className="text-2xl md:text-4xl font-bold text-white drop-shadow">{headline}</h2>
            {subheadline && <p className="text-sm md:text-base text-white/90">{subheadline}</p>}
            {cta_text && cta_url && (
              <Link href={cta_url} className="mt-2 inline-block bg-white text-black font-semibold px-6 py-2 rounded-full hover:bg-primary hover:text-white transition-colors text-sm">
                {cta_text}
              </Link>
            )}
          </div>
        </div>
      ) : (
        <div className="flex flex-col items-center justify-center gap-3 py-16 px-6 text-center bg-primary/10 rounded-2xl">
          <h2 className="text-2xl md:text-3xl font-bold">{headline}</h2>
          {subheadline && <p className="text-muted-foreground">{subheadline}</p>}
          {cta_text && cta_url && (
            <Link href={cta_url} className="inline-block bg-primary text-white font-semibold px-6 py-2 rounded-full hover:bg-primary/80 transition-colors text-sm">
              {cta_text}
            </Link>
          )}
        </div>
      )}
    </section>
  )
}
