/**
 * DriveHub Home Page — Production-grade streaming architecture.
 *
 * Rendering strategy:
 *  • Critical path  : Hero slider (fetchActiveBanners only) → renders in ~100-200ms
 *  • First stream   : Trust stats  → Suspense boundary
 *  • Second stream  : Popular brands → Suspense boundary
 *  • Third stream   : All car rows + ads → single Suspense boundary
 *
 * Each section component uses React.cache() so identical fetch calls
 * inside the same request are automatically deduplicated.
 */

import type { Metadata } from "next";
import { Suspense, cache } from "react";
import Link from "next/link";
import Image from "next/image";
import {
  ChevronRight, Star, TrendingUp, Zap, Shield, IndianRupee, Clock,
} from "lucide-react";
import dynamic from "next/dynamic";

import CarListCard          from "@/components/cars/CarListCard";
import BrandLogo            from "@/components/brand/BrandLogo";
import BodyTypeSilhouette   from "@/components/ui/BodyTypeSilhouette";
import HeroBannerSlider     from "@/components/ui/HeroBannerSlider";
import HeroSearchOverlay    from "@/components/ui/HeroSearchOverlay";
import AdBanner             from "@/components/ui/AdBanner";
import {
  HomeStatsSkeleton,
  HomeBrandsSkeleton,
  HomeAllSectionsSkeleton,
} from "@/components/ui/Skeletons";
import {
  fetchHomepageData, fetchBrands, fetchStats, fetchBrandCounts,
  fetchActiveBanners,
} from "@/lib/api";
import type { Car } from "@/lib/types";
import { formatPrice, FUEL_COLOR_MAP, cn } from "@/lib/utils";
import { resolveCarHeroImage } from "@/lib/carImage";
import { CAR_CARD_BLUR, LOGO_BLUR } from "@/lib/blurPlaceholder";

// RecentlyViewed uses localStorage — client only, load lazily
const RecentlyViewed = dynamic(() => import("@/components/cars/RecentlyViewed"), { ssr: false });

// ── Metadata ──────────────────────────────────────────────────────────────────

export const metadata: Metadata = {
  title: "DriveHub — New Cars, Prices, Reviews & Comparisons in India",
  description:
    "Find new cars in India. Compare prices, specs, reviews, mileage & expert insights. Get the best deals on your dream car.",
  openGraph: {
    title: "DriveHub — New Cars, Prices, Reviews & Comparisons in India",
    description: "India's smartest car marketplace. Live prices, AI-powered search, side-by-side comparison for 500+ cars.",
    type: "website",
  },
};

// Page-level ISR: re-generate every 5 minutes
export const revalidate = 300;

// ── React.cache() deduplicated fetchers ──────────────────────────────────────

const getStats = cache(async () => {
  try { return await fetchStats(); }
  catch { return { totalCars: 500, totalBrands: 30, totalCities: 50 }; }
});

const getBrandsData = cache(async () => {
  try {
    const { brands } = await fetchBrands();
    const top = brands.slice(0, 16);
    const brandCounts = await fetchBrandCounts(top).catch(() => ({} as Record<string, number>));
    return { brands, brandCounts };
  } catch {
    return { brands: [] as string[], brandCounts: {} as Record<string, number> };
  }
});

const getHomepageData = cache(async () => {
  try { return await fetchHomepageData(); }
  catch { return null; }
});

// ── Static config ─────────────────────────────────────────────────────────────

const BODY_TYPES_CONFIG = [
  { type: "SUV",       color: "text-orange-500", bgColor: "bg-orange-50"  },
  { type: "Sedan",     color: "text-blue-500",   bgColor: "bg-blue-50"    },
  { type: "Hatchback", color: "text-teal-500",   bgColor: "bg-teal-50"    },
  { type: "MUV",       color: "text-purple-500", bgColor: "bg-purple-50"  },
  { type: "Coupe",     color: "text-rose-500",   bgColor: "bg-rose-50"    },
];

const BUDGET_RANGES = [
  { label: "Under ₹5 Lakh",  sub: "Best for first-time buyers",   min: 0,  max: 5,   accent: "from-green-400 to-emerald-500",  textAccent: "text-emerald-600", bgAccent: "bg-emerald-50" },
  { label: "₹5L – ₹10L",     sub: "Popular segment",              min: 5,  max: 10,  accent: "from-blue-400 to-cyan-500",      textAccent: "text-blue-600",    bgAccent: "bg-blue-50"    },
  { label: "₹10L – ₹20L",    sub: "Premium hatchbacks & sedans",  min: 10, max: 20,  accent: "from-violet-400 to-purple-500",  textAccent: "text-violet-600",  bgAccent: "bg-violet-50"  },
  { label: "Above ₹20 Lakh", sub: "Luxury & performance",         min: 20, max: 200, accent: "from-amber-400 to-orange-500",   textAccent: "text-amber-600",   bgAccent: "bg-amber-50"   },
];

// ── Small horizontal-scroll car card ─────────────────────────────────────────

function SmallCarCard({ car, upcoming = false }: { car: Car; upcoming?: boolean }) {
  const heroSrc = resolveCarHeroImage(car);
  return (
    <Link
      href={`/cars/${car.id}`}
      className="group shrink-0 w-[200px] sm:w-[210px] rounded-2xl bg-white border border-gray-100 overflow-hidden hover:border-blue-200 hover:-translate-y-1.5 hover:shadow-xl hover:shadow-blue-100/40 transition-all duration-300 active:scale-95"
    >
      <div className="relative w-full h-[120px] sm:h-[130px] bg-gradient-to-br from-gray-100 to-gray-50 overflow-hidden">
        {heroSrc ? (
          <Image
            src={heroSrc}
            alt={car.name}
            fill
            loading="lazy"
            placeholder="blur"
            blurDataURL={CAR_CARD_BLUR}
            quality={70}
            sizes="210px"
            className="object-cover group-hover:scale-105 transition-transform duration-500"
          />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center p-4">
            <BodyTypeSilhouette type={car.bodyType} className="w-full h-full text-gray-300" />
          </div>
        )}
        {upcoming ? (
          <div className="absolute top-2 left-2">
            <span className="bg-purple-500 text-white text-[9px] font-black px-2 py-1 rounded-lg shadow-md flex items-center gap-1">
              <Clock className="w-2.5 h-2.5" />
              {car.launchDate ? `Launch: ${car.launchDate}` : "Upcoming"}
            </span>
          </div>
        ) : car.badge ? (
          <div className="absolute top-2 left-2">
            <span className="bg-gradient-to-r from-red-500 to-pink-500 text-white text-[9px] font-black px-2 py-1 rounded-lg shadow-md">
              {car.badge}
            </span>
          </div>
        ) : null}
        {car.rating > 0 && !upcoming && (
          <div className="absolute top-2 right-2 flex items-center gap-0.5 bg-black/60 backdrop-blur text-white text-[9px] font-black px-1.5 py-0.5 rounded-lg">
            <Star className="w-2.5 h-2.5 fill-current text-yellow-400" />
            {car.rating.toFixed(1)}
          </div>
        )}
      </div>

      <div className="p-3">
        <div className="flex items-center gap-1.5 mb-1">
          <BrandLogo brand={car.brand} size={14} showWhiteBg={false} />
          <p className="text-[9px] uppercase tracking-[0.15em] text-blue-600 font-black">{car.brand}</p>
        </div>
        <p className="text-sm font-black text-gray-900 leading-tight line-clamp-1 group-hover:text-blue-600 transition-colors mb-1">
          {car.name}
        </p>
        <span className={cn(
          "inline-block px-1.5 py-0.5 rounded-md text-[9px] font-bold border mb-1.5",
          FUEL_COLOR_MAP[car.fuelType] ?? "bg-gray-50 text-gray-600 border-gray-200"
        )}>
          {car.fuelType}
        </span>
        <p className="text-sm font-black text-gray-900">
          {upcoming
            ? (car.priceMin > 0 ? `~${formatPrice(car.priceMin)}` : "Price TBA")
            : formatPrice(car.priceMin)}
        </p>
        {!upcoming && <p className="text-[9px] text-gray-400 mt-0.5">onwards*</p>}
      </div>
    </Link>
  );
}

// ── Reusable horizontal car section ──────────────────────────────────────────

function CarSection({
  label, title, subtitle, cars, href,
  accentColor = "text-blue-600", bgClass = "bg-white", upcoming = false,
}: {
  label: string; title: string; subtitle?: string; cars: Car[];
  href?: string; accentColor?: string; bgClass?: string; upcoming?: boolean;
}) {
  if (!cars?.length) return null;
  return (
    <section className={cn("py-12 md:py-14", bgClass)}>
      <div className="max-w-[1280px] mx-auto px-4">
        <div className="flex items-end justify-between mb-6 md:mb-8">
          <div>
            <p className={cn("font-bold text-xs md:text-sm uppercase tracking-wider mb-1.5", accentColor)}>{label}</p>
            <h2 className="text-2xl md:text-3xl font-black text-gray-900">{title}</h2>
            {subtitle && <p className="text-gray-500 mt-1.5 text-sm">{subtitle}</p>}
          </div>
          {href && (
            <Link href={href} className="hidden md:flex items-center gap-1 text-sm font-semibold text-blue-600 hover:gap-2 transition-all shrink-0">
              View All <ChevronRight className="w-4 h-4" />
            </Link>
          )}
        </div>
        <div className="flex gap-3 overflow-x-auto pb-3 scrollbar-none -mx-4 px-4 md:mx-0 md:px-0">
          {cars.slice(0, 10).map((car) => (
            <SmallCarCard key={car.id} car={car} upcoming={upcoming} />
          ))}
        </div>
        {href && (
          <div className="md:hidden mt-4 text-center">
            <Link href={href} className="inline-flex items-center gap-1.5 text-sm font-bold text-blue-600 border border-blue-200 px-4 py-2 rounded-xl hover:bg-blue-50 transition-colors">
              View All <ChevronRight className="w-4 h-4" />
            </Link>
          </div>
        )}
      </div>
    </section>
  );
}

// ══════════════════════════════════════════════════════════════════════════════
// Async streaming section components
// ══════════════════════════════════════════════════════════════════════════════

async function TrustStatsSection() {
  const stats = await getStats();
  return (
    <section className="py-8">
      <div className="max-w-[1100px] mx-auto px-4">
        <div className="bg-white/90 backdrop-blur-xl border border-white/50 rounded-3xl shadow-[0_8px_40px_rgba(0,0,0,0.06)] p-5 md:p-8">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
            {[
              { icon: TrendingUp, val: `${stats.totalCars}+`, label: "Cars Listed",    color: "text-blue-600",   bg: "from-blue-50 to-cyan-50"     },
              { icon: Star,       val: `${stats.totalBrands}+`, label: "Brands",       color: "text-violet-600", bg: "from-violet-50 to-purple-50" },
              { icon: Shield,     val: "Live Data",             label: "Updated Daily", color: "text-green-600", bg: "from-green-50 to-emerald-50" },
              { icon: Zap,        val: `${stats.totalCities}+`, label: "Cities",       color: "text-amber-600",  bg: "from-amber-50 to-orange-50"  },
            ].map(({ icon: Icon, val, label, color, bg }) => (
              <div key={label} className="text-center group">
                <div className={cn("w-12 h-12 md:w-14 md:h-14 rounded-2xl bg-gradient-to-br flex items-center justify-center mx-auto mb-2 md:mb-3 group-hover:scale-110 transition-transform duration-300", bg)}>
                  <Icon className={cn("w-5 h-5 md:w-6 md:h-6", color)} />
                </div>
                <div className="text-xl md:text-3xl font-black text-gray-900">{val}</div>
                <div className="text-xs md:text-sm text-gray-500 font-medium mt-1">{label}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

async function PopularBrandsSection() {
  const { brands, brandCounts } = await getBrandsData();
  if (!brands.length) return null;

  return (
    <section className="py-12 md:py-14 bg-white">
      <div className="max-w-[1280px] mx-auto px-4">
        <div className="flex items-end justify-between mb-6 md:mb-8">
          <div>
            <p className="text-blue-600 font-bold text-xs md:text-sm uppercase tracking-wider mb-1.5">Explore Brands</p>
            <h2 className="text-2xl md:text-3xl font-black text-gray-900">Popular Car Brands</h2>
          </div>
          <Link href="/brands" className="hidden md:flex items-center gap-1 text-sm font-semibold text-blue-600 hover:gap-2 transition-all">
            All Brands <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
        <div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8 gap-3 md:gap-4">
          {brands.slice(0, 16).map((brand) => {
            const count = brandCounts[brand];
            return (
              <Link
                key={brand}
                href={`/cars?brand=${encodeURIComponent(brand)}`}
                className="group flex flex-col items-center gap-2 bg-white border border-gray-100 hover:border-blue-200 rounded-2xl p-3 md:p-4 transition-all duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-blue-100/40 active:scale-95"
              >
                <BrandLogo brand={brand} size={44} className="group-hover:scale-110 transition-transform duration-300" />
                <p className="text-[10px] md:text-[11px] font-bold text-center text-gray-700 leading-tight group-hover:text-blue-600 transition-colors line-clamp-2">
                  {brand}
                </p>
                {count !== undefined && count > 0 && (
                  <span className="text-[9px] font-black bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded-full">{count}</span>
                )}
              </Link>
            );
          })}
        </div>
        <div className="md:hidden mt-4 text-center">
          <Link href="/brands" className="inline-flex items-center gap-1.5 text-sm font-bold text-blue-600 border border-blue-200 px-4 py-2 rounded-xl hover:bg-blue-50 transition-colors">
            View All Brands <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      </div>
    </section>
  );
}

async function AllCarSections() {
  const [hp, stats] = await Promise.all([getHomepageData(), getStats()]);

  const featured          = hp?.featured          ?? [];
  const newLaunches       = hp?.newLaunches        ?? [];
  const topRated          = hp?.topRated           ?? [];
  const popularSUVs       = hp?.popularSUVs        ?? [];
  const popularHatchbacks = hp?.popularHatchbacks  ?? [];
  const popularSedans     = hp?.popularSedans      ?? [];
  const electricCars      = hp?.electricCars       ?? [];
  const budgetCars        = hp?.budgetCars         ?? [];
  const upcomingCars      = hp?.upcomingCars       ?? [];

  return (
    <>
      <CarSection label="Fresh Off the Floor" title="New Launches"
        subtitle="Latest cars added to our database" cars={newLaunches}
        href="/cars?sortBy=year&sortOrder=-1" accentColor="text-green-600" bgClass="bg-[#f6f8fc]" />

      <CarSection label="Expert Picks" title="Top Rated Cars"
        subtitle="Highest rated by users & experts" cars={topRated}
        href="/cars?sortBy=rating&sortOrder=-1" accentColor="text-amber-600" bgClass="bg-white" />

      {/* AD: Between popular cars */}
      <div className="bg-white border-t border-gray-50">
        <div className="max-w-[1280px] mx-auto px-4">
          <AdBanner slot="between-popular" />
        </div>
      </div>

      {/* Cars by Budget */}
      <section className="py-12 md:py-14 bg-gradient-to-b from-white to-[#f3f7fd]">
        <div className="max-w-[1280px] mx-auto px-4">
          <div className="mb-6 md:mb-8">
            <p className="text-blue-600 font-bold text-xs md:text-sm uppercase tracking-wider mb-1.5">Smart Budget</p>
            <h2 className="text-2xl md:text-3xl font-black text-gray-900">Cars by Budget</h2>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 md:gap-5">
            {BUDGET_RANGES.map(({ label, sub, min, max, accent, textAccent, bgAccent }) => (
              <Link key={label} href={`/cars?priceMin=${min}&priceMax=${max}`}
                className="group relative overflow-hidden rounded-2xl md:rounded-[28px] bg-white border border-gray-100 p-5 md:p-6 hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-blue-100/30 transition-all duration-300 active:scale-95"
              >
                <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500">
                  <div className={cn("absolute top-0 right-0 w-28 h-28 rounded-full blur-3xl opacity-20 bg-gradient-to-br", accent)} />
                </div>
                <div className="relative">
                  <div className={cn("w-12 h-12 rounded-2xl flex items-center justify-center mb-4", bgAccent)}>
                    <IndianRupee className={cn("w-6 h-6", textAccent)} />
                  </div>
                  <h3 className="text-base md:text-lg font-black text-gray-900 mb-1 group-hover:text-blue-600 transition-colors">{label}</h3>
                  <p className="text-sm text-gray-400 mb-3">{sub}</p>
                  <p className="text-sm text-blue-600 font-semibold flex items-center gap-1">
                    Explore <ChevronRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                  </p>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </section>

      <CarSection label="Future of Mobility" title="Electric Cars"
        subtitle="Zero emissions, maximum performance" cars={electricCars}
        href="/cars?fuelType=Electric" accentColor="text-green-600"
        bgClass="bg-gradient-to-b from-green-50/30 to-white border-t border-green-100/60" />

      {/* AD: Between Electric */}
      <div className="bg-white">
        <div className="max-w-[1280px] mx-auto px-4">
          <AdBanner slot="between-electric" />
        </div>
      </div>

      <CarSection label="Most Searched" title="Popular SUVs"
        subtitle="India's most loved SUV segment" cars={popularSUVs}
        href="/cars?bodyType=SUV" accentColor="text-orange-600" bgClass="bg-white" />

      <CarSection label="Budget Favourites" title="Popular Hatchbacks"
        subtitle="Best value hatchbacks in India" cars={popularHatchbacks}
        href="/cars?bodyType=Hatchback" accentColor="text-teal-600" bgClass="bg-[#fafbff]" />

      {featured.length > 0 && (
        <section className="py-12 md:py-14 bg-white border-t border-gray-100">
          <div className="max-w-[1280px] mx-auto px-4">
            <div className="flex items-end justify-between mb-6 md:mb-8">
              <div>
                <p className="text-blue-600 font-bold text-xs md:text-sm uppercase tracking-wider mb-1.5">Trending Cars</p>
                <h2 className="text-2xl md:text-3xl font-black text-gray-900">Popular New Cars</h2>
                <p className="text-gray-500 mt-1.5 text-sm">Top picks this month</p>
              </div>
              <Link href="/cars" className="hidden md:flex items-center gap-1 text-sm font-semibold text-blue-600 hover:gap-2 transition-all">
                View All <ChevronRight className="w-4 h-4" />
              </Link>
            </div>
            <div className="space-y-4 md:space-y-5">
              {featured.slice(0, 5).map((car) => (
                <div key={car.id} className="rounded-2xl md:rounded-[30px] overflow-hidden">
                  <CarListCard car={car} />
                </div>
              ))}
            </div>
            <div className="text-center mt-8 md:mt-10">
              <Link href="/cars"
                className="inline-flex items-center gap-2 bg-gradient-to-r from-blue-600 to-cyan-500 text-white font-bold px-6 md:px-8 py-3.5 md:py-4 rounded-2xl shadow-lg shadow-blue-200 hover:scale-105 transition-all duration-300 active:scale-95"
              >
                View All {stats.totalCars}+ Cars <ChevronRight className="w-5 h-5" />
              </Link>
            </div>
          </div>
        </section>
      )}

      {/* AD: After news */}
      <div className="bg-gray-50 border-t border-gray-100">
        <div className="max-w-[1280px] mx-auto px-4">
          <AdBanner slot="between-news" />
        </div>
      </div>

      {/* Compare CTA */}
      <section className="py-12 md:py-16 relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-r from-[#0f172a] via-[#172554] to-[#0f766e]" />
        <div className="absolute top-0 right-0 w-[350px] h-[350px] bg-cyan-500/15 rounded-full blur-3xl pointer-events-none" />
        <div className="relative max-w-[1280px] mx-auto px-4">
          <div className="bg-white/10 backdrop-blur-2xl border border-white/10 rounded-3xl md:rounded-[36px] p-6 md:p-12 flex flex-col md:flex-row items-center justify-between gap-6 md:gap-8">
            <div className="max-w-2xl text-center md:text-left">
              <p className="text-cyan-300 font-bold text-xs md:text-sm uppercase tracking-wider mb-2 md:mb-3">Compare Smartly</p>
              <h2 className="text-2xl md:text-4xl font-black text-white leading-tight mb-3 md:mb-4">Compare Cars Side by Side</h2>
              <p className="text-white/70 text-sm md:text-base leading-relaxed">
                Compare specifications, prices, mileage, features &amp; performance of up to 4 cars together.
              </p>
            </div>
            <Link href="/compare"
              className="shrink-0 inline-flex items-center gap-2 bg-white text-[#172554] font-black px-6 md:px-8 py-3.5 md:py-4 rounded-xl md:rounded-2xl hover:scale-105 transition-all duration-300 shadow-2xl active:scale-95 whitespace-nowrap"
            >
              Compare Now <ChevronRight className="w-5 h-5" />
            </Link>
          </div>
        </div>
      </section>

      {upcomingCars.length > 0 && (
        <CarSection label="Coming Soon" title="Upcoming Cars"
          subtitle="Pre-launch reveals & expected launches" cars={upcomingCars}
          href="/cars?isUpcoming=true" accentColor="text-purple-600"
          bgClass="bg-gradient-to-b from-[#f3f0ff] to-white border-t border-purple-100/60" upcoming />
      )}

      {/* Browse by Type */}
      <section className="py-12 md:py-14 bg-white border-t border-gray-100">
        <div className="max-w-[1280px] mx-auto px-4">
          <div className="mb-6 md:mb-8">
            <p className="text-blue-600 font-bold text-xs md:text-sm uppercase tracking-wider mb-1.5">Explore Categories</p>
            <h2 className="text-2xl md:text-3xl font-black text-gray-900">Cars by Body Type</h2>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-5 gap-3 md:gap-4">
            {BODY_TYPES_CONFIG.map(({ type, color, bgColor }) => (
              <Link key={type} href={`/cars?bodyType=${type}`}
                className="group bg-white border border-gray-100 rounded-2xl p-4 md:p-5 flex flex-col items-center justify-center hover:border-blue-200 hover:-translate-y-1.5 hover:shadow-xl hover:shadow-blue-100/40 transition-all duration-300 active:scale-95"
              >
                <div className={cn("w-full max-w-[80px] aspect-[2/1] rounded-xl flex items-center justify-center mb-3 p-2 group-hover:scale-110 transition-transform duration-300", bgColor)}>
                  <BodyTypeSilhouette type={type} className={cn("w-full h-full", color)} />
                </div>
                <span className="text-sm font-bold text-gray-700 group-hover:text-blue-600 transition-colors text-center">{type}</span>
              </Link>
            ))}
          </div>
        </div>
      </section>

      <CarSection label="Executive Class" title="Popular Sedans"
        subtitle="Elegant sedans for every occasion" cars={popularSedans}
        href="/cars?bodyType=Sedan" accentColor="text-blue-600" bgClass="bg-[#f6f8fc]" />

      <CarSection label="Smart Savings" title="Cars Under ₹8 Lakh"
        subtitle="Affordable yet feature-packed options" cars={budgetCars}
        href="/cars?priceMax=8" accentColor="text-violet-600" bgClass="bg-white border-t border-gray-100" />
    </>
  );
}

// ══════════════════════════════════════════════════════════════════════════════
// Root — Streaming architecture: hero renders instantly, rest streams in
// ══════════════════════════════════════════════════════════════════════════════

export default async function HomePage() {
  // Only block on banners — hero renders in ~100-200ms
  const { banners } = await fetchActiveBanners().catch(() => ({
    banners: [] as Awaited<ReturnType<typeof fetchActiveBanners>>["banners"],
  }));

  return (
    <div className="bg-[#f6f8fc] overflow-x-hidden">

      {/* TOP LEADERBOARD AD — client auto-fetches, shows placeholder until loaded */}
      <div className="bg-white border-b border-gray-100">
        <div className="max-w-[1280px] mx-auto px-4">
          <AdBanner slot="leaderboard-top" />
        </div>
      </div>

      {/* HERO SLIDER — renders with banner data immediately */}
      <HeroBannerSlider banners={banners} interval={5000} />

      {/*
        Search card — 40 px overlap with the banner bottom edge.
        Using -mt-10 (negative margin) keeps the card in normal flow:
        no absolute positioning, no spacer div, no CLS.
        relative z-10 ensures the card paints above the slider.
      */}
      <div className="relative z-10 -mt-10">
        <div className="max-w-[1000px] mx-auto px-4 sm:px-6">
          <HeroSearchOverlay />
        </div>
      </div>

      {/* TRUST STATS — streams in first (~fast) */}
      <Suspense fallback={<HomeStatsSkeleton />}>
        <TrustStatsSection />
      </Suspense>

      {/* POPULAR BRANDS — streams independently */}
      <Suspense fallback={<HomeBrandsSkeleton />}>
        <PopularBrandsSection />
      </Suspense>

      {/* ALL CAR SECTIONS + ADS — streams from homepage API */}
      <Suspense fallback={<HomeAllSectionsSkeleton />}>
        <AllCarSections />
      </Suspense>

      {/* RECENTLY VIEWED — client only (localStorage), no SSR */}
      <RecentlyViewed />

      {/* BOTTOM AD */}
      <div className="bg-gray-50">
        <div className="max-w-[1280px] mx-auto px-4">
          <AdBanner slot="between-news" />
        </div>
      </div>
    </div>
  );
}
