"use client";

import { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import Image from "next/image";
import Link from "next/link";
import {
  Star,
  Heart,
  GitCompare,
  Car as CarIcon,
  MapPin,
  Settings2,
  Users,
  Gauge,
  Fuel,
  Check,
  X as XIcon,
  ChevronRight,
  Phone,
  ChevronLeft,
  ChevronDown,
  ChevronUp,
  Sparkles,
  Loader2,
  Shield,
  Clock,
  Download,
  Wrench,
  Award,
  TrendingUp,
  AlertCircle,
  Zap,
  HelpCircle,
  MonitorSmartphone,
  SunMedium,
  Wind,
  Wifi,
  Camera,
  Navigation2,
  Bell,
  BellRing,
} from "lucide-react";
import BrandLogo from "@/components/brand/BrandLogo";
import BodyTypeSilhouette from "@/components/ui/BodyTypeSilhouette";
import CarImagePlaceholder from "@/components/ui/CarImagePlaceholder";
import PriceHistoryChart from "@/components/cars/PriceHistoryChart";
import { fetchPriceHistory, fetchRivals, fetchCityPricing, fetchOffers, fetchWaitingPeriod, trackCarEvent, toggleWatch, checkWatching, fetchCarReviews } from "@/lib/api";
import type { CarPriceHistory, CarRivals, CityPriceBreakdown, CarDiscounts, WaitingPeriod, CarReview } from "@/lib/types";

import { motion, useReducedMotion } from "framer-motion";

import type { Car } from "@/lib/types";
import { formatPrice, cn } from "@/lib/utils";
import { resolveUploadUrl } from "@/lib/uploadUrl";
import { resolveCarHeroImage } from "@/lib/carImage";
import { primaryCarField } from "@/lib/carFieldUtils";
import CarFieldBadges from "@/components/cars/CarFieldBadges";
import ReviewCard from "@/components/cars/ReviewCard";

import { useWishlistStore } from "@/store/useWishlistStore";
import { useCarStore } from "@/store/useCarStore";
import { useRecentlyViewedStore } from "@/store/useRecentlyViewedStore";
import { useOwnedCarsStore } from "@/store/useOwnedCarsStore";
import { useNotificationStore } from "@/store/useNotificationStore";

// Lazy-load heavy components
const EMICalculator = dynamic(() => import("@/components/cars/EMICalculator"), {
  loading: () => <div className="rounded-[28px] bg-white border border-gray-200/60 h-[72px] animate-pulse" />,
  ssr: false,
});
const AISummaryCard = dynamic(() => import("@/components/cars/AISummaryCard"), {
  loading: () => null,
  ssr: false,
});
const SimilarCars = dynamic(() => import("@/components/cars/SimilarCars"), {
  loading: () => null,
  ssr: false,
});
const OnRoadPriceModal = dynamic(() => import("@/components/leads/OnRoadPriceModal"), {
  ssr: false,
});
const RivalsSection = dynamic(() => import("@/components/cars/RivalsSection"), {
  loading: () => null,
  ssr: false,
});
const CityPricingSection = dynamic(() => import("@/components/cars/CityPricingSection"), {
  loading: () => null,
  ssr: false,
});
const OwnershipCostSection = dynamic(() => import("@/components/cars/OwnershipCostSection"), {
  loading: () => null,
  ssr: false,
});

const SECTION_TABS = [
  "Variants",
  "Specifications",
  "Features",
  "Safety",
  "Colors",
  "Pros & Cons",
  "Overview",
  "FAQs",
] as const;

/* ── Helper: FAQ accordion ── */
function FAQAccordion({ faqs }: { faqs: { question: string; answer: string }[] }) {
  const [open, setOpen] = useState<number | null>(null);
  return (
    <div className="divide-y divide-gray-100">
      {faqs.map((faq, i) => (
        <div key={i}>
          <button
            onClick={() => setOpen(open === i ? null : i)}
            className="w-full flex items-center justify-between px-6 py-5 text-left hover:bg-gray-50 transition-colors"
          >
            <span className="font-semibold text-gray-800 pr-4 leading-snug">{faq.question}</span>
            {open === i
              ? <ChevronUp className="w-5 h-5 text-gray-400 shrink-0" />
              : <ChevronDown className="w-5 h-5 text-gray-400 shrink-0" />
            }
          </button>
          {open === i && (
            <div className="px-6 pb-6 text-sm text-gray-600 leading-7 bg-gray-50/50">
              {faq.answer}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

/* ── Helper: boolean badge ── */
function BoolBadge({ value, label }: { value?: boolean; label: string }) {
  if (value === undefined || value === null) return null;
  return (
    <div className={cn(
      "flex items-center gap-2.5 rounded-2xl border px-4 py-3",
      value
        ? "bg-green-50 border-green-200 text-green-700"
        : "bg-gray-50 border-gray-200 text-gray-400"
    )}>
      {value
        ? <Check className="w-4 h-4 text-green-500 shrink-0" />
        : <XIcon className="w-4 h-4 text-gray-300 shrink-0" />
      }
      <span className="text-sm font-semibold">{label}</span>
    </div>
  );
}

export default function CarDetailClient({ car }: { car: Car }) {
  const [activeImg, setActiveImg]       = useState(0);
  const [activeTab, setActiveTab]       = useState<typeof SECTION_TABS[number]>("Variants");
  const [showAllSpecs, setShowAllSpecs] = useState(false);

  const [wishLoading,    setWishLoading]    = useState(false);
  const [compareLoading, setCompareLoading] = useState(false);
  const [watchLoading,   setWatchLoading]   = useState(false);
  const [isWatching,     setIsWatching]     = useState(false);
  const [showPriceModal, setShowPriceModal] = useState(false);
  const [priceHistory,   setPriceHistory]   = useState<CarPriceHistory | null>(null);
  const [rivals,         setRivals]         = useState<CarRivals | null>(null);
  const [cityPrices,     setCityPrices]     = useState<CityPriceBreakdown[]>([]);
  const [discounts,      setDiscounts]      = useState<CarDiscounts | null>(null);
  const [waitingPeriod,  setWaitingPeriod]  = useState<WaitingPeriod | null>(null);
  const [reviews,        setReviews]        = useState<CarReview[]>([]);
  const [reviewsLoading, setReviewsLoading] = useState(false);

  const prefersReducedMotion = useReducedMotion();

  const { toggle, has }                  = useWishlistStore();
  const { addToCompare, removeFromCompare, compareList } = useCarStore();
  const { addViewed }                    = useRecentlyViewedStore();
  const { add: addOwned, remove: removeOwned, has: isOwned } = useOwnedCarsStore();
  const { sessionId } = useNotificationStore();

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => { addViewed(car); }, [car.id]);

  // ── F48: Check if user is watching this car ─────────────────────────────
  useEffect(() => {
    if (!sessionId) return;
    checkWatching(sessionId, car.id).then(setIsWatching);
  }, [car.id, sessionId]);

  useEffect(() => {
    fetchPriceHistory(car.id).then(setPriceHistory);
  }, [car.id]);

  // ── F47: Track car view (once per browser session per car) ─────────────
  useEffect(() => {
    if (typeof window === "undefined") return;
    const key = `dh_viewed_${car.id}`;
    if (!sessionStorage.getItem(key)) {
      sessionStorage.setItem(key, "1");
      trackCarEvent(car.id, "view");
    }
  }, [car.id]);

  useEffect(() => {
    fetchRivals(car.id).then(setRivals);
  }, [car.id]);

  useEffect(() => {
    fetchCityPricing(car.id).then(setCityPrices);
    fetchOffers(car.id).then(setDiscounts);
    fetchWaitingPeriod(car.id).then(setWaitingPeriod);
  }, [car.id]);

  useEffect(() => {
    setReviewsLoading(true);
    fetchCarReviews(car.id)
      .then((data) => setReviews(data.reviews))
      .catch(() => setReviews([]))
      .finally(() => setReviewsLoading(false));
  }, [car.id]);

  const isWished    = has(car.id);
  const isComparing = compareList.some((c) => c.id === car.id);
  const owned       = isOwned(car.id);

  /**
   * Prefer Phase-13 imageGallery (media-library backed) when available.
   * Fall back to legacy CarImage[] from the scraper / AI seed.
   * Normalise to a unified shape so the JSX below is unchanged.
   */
  const images = (() => {
    const gallery = car.imageGallery ?? [];
    if (gallery.length > 0) {
      return gallery
        .slice()
        .sort((a, b) => {
          // primary first, then by order
          if (a.isPrimary && !b.isPrimary) return -1;
          if (!a.isPrimary && b.isPrimary) return 1;
          return a.order - b.order;
        })
        .map((g) => ({ url: resolveUploadUrl(g.url), alt: g.alt || car.name, isPrimary: g.isPrimary, category: g.category }));
    }
    // Legacy: use primaryImage as first item if gallery is empty
    if (car.primaryImage) {
      const legacy = car.images ?? [];
      const hasPrimary = legacy.some((i) => i.url === car.primaryImage);
      if (!hasPrimary) {
        return [{ url: resolveUploadUrl(car.primaryImage), alt: car.name, isPrimary: true, category: "exterior" }, ...legacy.map((i) => ({ ...i, url: resolveUploadUrl(i.url) }))];
      }
    }
    const legacyImages = (car.images ?? []).map((i) => ({ ...i, url: resolveUploadUrl(i.url) }));
    if (legacyImages.length > 0) return legacyImages;
    const hero = resolveCarHeroImage(car);
    if (hero) {
      return [{ url: hero, alt: car.name, isPrimary: true, category: "exterior" }];
    }
    return [];
  })();

  function handleWishlist() {
    setWishLoading(true);
    toggle(car);
    setTimeout(() => setWishLoading(false), 400);
  }
  function handleCompare() {
    setCompareLoading(true);
    if (isComparing) {
      removeFromCompare(car.id);
    } else {
      addToCompare(car);
      trackCarEvent(car.id, "compare"); // F47 — track compare event
    }
    setTimeout(() => setCompareLoading(false), 400);
  }
  async function handleWatch() {
    if (!sessionId || watchLoading) return;
    setWatchLoading(true);
    const result = await toggleWatch(sessionId, car.id);
    setIsWatching(result.watching);
    setWatchLoading(false);
  }

  const fuelDisplay = car.fuelTypes?.length ? car.fuelTypes : car.fuelType;
  const transDisplay = car.availableTransmissions?.length ? car.availableTransmissions : car.transmission;
  const bodyDisplay = car.availableBodyTypes?.length ? car.availableBodyTypes : car.bodyType;

  const keySpecs = [
    { icon: Fuel,      label: "Fuel Type",    value: primaryCarField(fuelDisplay) },
    { icon: Settings2, label: "Transmission", value: primaryCarField(transDisplay) },
    { icon: Users,     label: "Seating",      value: car.specs?.seatingCapacity ? `${car.specs.seatingCapacity} Persons` : "—" },
    { icon: Gauge,     label: "Mileage",      value: car.specs?.mileage ?? "—" },
  ];

  const allSpecRows = [
    {
      group: "Engine & Performance",
      rows: [
        ["Engine",           car.specs?.engine],
        ["Displacement",     car.specs?.displacement],
        ["Cylinders",        car.specs?.cylinders ? String(car.specs.cylinders) : null],
        ["Max Power",        car.specs?.maxPower],
        ["Max Torque",       car.specs?.maxTorque],
        ["Top Speed",        car.specs?.topSpeed],
        ["0-100 kmph",       car.specs?.acceleration],
        ["Drive Type",       car.specs?.driveType],
        ["Turbocharger",     car.specs?.turbocharger != null ? (car.specs.turbocharger ? "Yes" : "No") : null],
        ["Steering Type",    car.specs?.steeringType],
      ],
    },
    {
      group: "Fuel & Efficiency",
      rows: [
        ["Fuel Type",  primaryCarField(fuelDisplay)],
        ["Mileage",    car.specs?.mileage],
        ["Fuel Tank",  car.specs?.fuelTankCapacity],
      ],
    },
    {
      group: "Dimensions",
      rows: [
        ["Length",           car.specs?.length],
        ["Width",            car.specs?.width],
        ["Height",           car.specs?.height],
        ["Wheelbase",        car.specs?.wheelbase],
        ["Ground Clearance", car.specs?.groundClearance],
        ["Boot Space",       car.specs?.bootSpace],
      ],
    },
    {
      group: "Comfort & Convenience",
      rows: [
        ["Seating Capacity", car.specs?.seatingCapacity ? `${car.specs.seatingCapacity} Persons` : null],
        ["Front Brakes",     car.specs?.frontBrakes],
        ["Rear Brakes",      car.specs?.rearBrakes],
      ],
    },
  ];

  const visibleSpecs = showAllSpecs ? allSpecRows : allSpecRows.slice(0, 2);

  // Derived safety flags
  const hasSafetyData = car.specs && (
    car.specs.airbags != null ||
    car.specs.abs != null ||
    car.specs.EBD != null ||
    car.specs.ESC != null ||
    car.specs.tractionControl != null ||
    car.specs.ADAS != null ||
    car.specs.ncapRating
  );

  const hasColors = (car.colors && car.colors.length > 0) || (car.color && car.color.length > 0);

  const hasFeatureFlags = car.features && Object.values(car.features).some((v) => v !== undefined && v !== null && v !== false);
  const hasFeatureGroups = car.featureGroups && Object.keys(car.featureGroups).length > 0;
  const hasFeatures = hasFeatureFlags || hasFeatureGroups;
  const hasEVSpecs  = car.evSpecs && Object.values(car.evSpecs).some((v) => v !== undefined && v !== null && v !== false);
  const hasFAQs     = car.faqs && car.faqs.length > 0;

  const hasProsOrCons = !!(car.pros?.length || car.cons?.length);
  const hasOverview   = !!(car.overview?.trim());

  // Visible tabs: filter out tabs with no data
  const visibleTabs = SECTION_TABS.filter((tab) => {
    if (tab === "Safety")    return hasSafetyData;
    if (tab === "Colors")    return hasColors;
    if (tab === "Features")  return hasFeatures;
    if (tab === "FAQs")      return hasFAQs;
    if (tab === "Pros & Cons") return hasProsOrCons;
    if (tab === "Overview")  return hasOverview;
    return true;
  });

  const hasOwnership = car.ownership && (
    car.ownership.serviceCost || car.ownership.warranty ||
    car.ownership.maintenance || car.ownership.resaleValue
  );

  return (
    <div className="min-h-screen bg-[#f5f7fb] pb-20">
      {/* ─── BREADCRUMB ─────────────────────────────────────────────────────── */}
      <div className="border-b border-white/30 bg-white/70 backdrop-blur-2xl sticky top-0 z-30">
        <div className="max-w-[1280px] mx-auto px-4 py-3 flex items-center gap-1 text-xs text-gray-500 overflow-x-auto scrollbar-none">
          <Link href="/" className="hover:text-blue-600 transition-colors">Home</Link>
          <ChevronRight className="w-3 h-3 text-gray-300" />
          <Link href="/cars" className="hover:text-blue-600 transition-colors">New Cars</Link>
          <ChevronRight className="w-3 h-3 text-gray-300" />
          <Link href={`/cars?brand=${car.brand}`} className="hover:text-blue-600 transition-colors whitespace-nowrap">
            {car.brand}
          </Link>
          <ChevronRight className="w-3 h-3 text-gray-300" />
          <span className="font-semibold text-gray-800 whitespace-nowrap">{car.name}</span>
        </div>
      </div>

      <div className="max-w-[1280px] mx-auto px-4 pt-6">
        {/* ─── TOP SECTION: Gallery + Sidebar ──────────────────────────────── */}
        <div className="flex flex-col lg:flex-row gap-6 mb-6">
          {/* LEFT — image gallery */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4 }}
            className="flex-1 min-w-0"
          >
            <div className="relative overflow-hidden rounded-[32px] bg-white border border-gray-200/60 shadow-[0_10px_40px_rgba(0,0,0,0.06)]">
              <div className="relative w-full aspect-[16/9]">
                {images[activeImg] ? (
                  <Image
                    src={images[activeImg].url}
                    alt={images[activeImg].alt || `${car.name} — view ${activeImg + 1}`}
                    fill priority fetchPriority="high"
                    className="object-cover transition-transform duration-700 hover:scale-105"
                    sizes="(max-width: 1024px) 100vw, 65vw"
                  />
                ) : (
                  <CarImagePlaceholder
                    bodyType={car.bodyType}
                    carName={car.name}
                    brand={car.brand}
                    size="lg"
                  />
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-black/30 via-transparent to-transparent" />

                {/* Badges */}
                <div className="absolute top-5 left-5 flex flex-col gap-2">
                  {car.isUpcoming && (
                    <div className="flex items-center gap-1.5 bg-purple-600 text-white px-3 py-1.5 rounded-2xl text-xs font-bold shadow-xl">
                      <Clock className="w-3 h-3" />
                      Upcoming
                      {car.launchDate && <span className="opacity-80 text-[10px]">· {car.launchDate}</span>}
                    </div>
                  )}
                  {car.badge && !car.isUpcoming && (
                    <div className="flex items-center gap-2 bg-gradient-to-r from-red-500 to-pink-500 text-white px-4 py-2 rounded-2xl text-xs font-bold shadow-xl">
                      <Sparkles className="w-3 h-3" />
                      {car.badge}
                    </div>
                  )}
                </div>

                {images.length > 0 && (
                  <div className="absolute bottom-5 right-5 bg-black/50 backdrop-blur-xl text-white px-3 py-1.5 rounded-xl text-xs font-semibold">
                    {activeImg + 1} / {images.length}
                  </div>
                )}

                {images.length > 1 && (
                  <>
                    <motion.button
                      whileTap={prefersReducedMotion ? undefined : { scale: 0.9 }}
                      onClick={() => setActiveImg((i) => (i - 1 + images.length) % images.length)}
                      aria-label="Previous image"
                      className="absolute left-5 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-white/80 backdrop-blur-xl shadow-xl flex items-center justify-center"
                    >
                      <ChevronLeft className="w-5 h-5 text-gray-700" />
                    </motion.button>
                    <motion.button
                      whileTap={prefersReducedMotion ? undefined : { scale: 0.9 }}
                      onClick={() => setActiveImg((i) => (i + 1) % images.length)}
                      aria-label="Next image"
                      className="absolute right-5 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-white/80 backdrop-blur-xl shadow-xl flex items-center justify-center"
                    >
                      <ChevronRight className="w-5 h-5 text-gray-700" />
                    </motion.button>
                  </>
                )}
              </div>
            </div>

            {/* Thumbnails */}
            {images.length > 1 && (
              <div className="flex gap-2 sm:gap-3 overflow-x-auto scrollbar-none pt-4 max-w-full">
                {images.map((img, idx) => (
                  <motion.button
                    whileHover={prefersReducedMotion ? undefined : { y: -3 }}
                    key={idx}
                    onClick={() => setActiveImg(idx)}
                    aria-label={`View image ${idx + 1}`}
                    aria-pressed={idx === activeImg}
                    className={cn(
                      "relative shrink-0 w-[72px] h-[52px] sm:w-[100px] sm:h-[68px] rounded-2xl overflow-hidden border-2 transition-all duration-300",
                      idx === activeImg
                        ? "border-blue-500 shadow-xl shadow-blue-100"
                        : "border-transparent hover:border-gray-300"
                    )}
                  >
                    <Image src={img.url} alt={img.alt || `View ${idx + 1}`} fill className="object-cover" sizes="100px" />
                  </motion.button>
                ))}
              </div>
            )}
          </motion.div>

          {/* RIGHT — price card + actions + EMI */}
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4 }}
            className="w-full lg:w-[360px] shrink-0 self-start lg:sticky lg:top-[88px] flex flex-col gap-4"
          >
            <div className="rounded-[32px] bg-white border border-gray-200/60 p-6 shadow-[0_10px_40px_rgba(0,0,0,0.06)]">
              {/* Brand */}
              <div className="flex items-center gap-2.5 mb-3">
                <BrandLogo brand={car.brand} size={32} />
                <p className="text-xs uppercase tracking-[0.2em] text-blue-600 font-black">{car.brand}</p>
              </div>

              <h1 className="text-2xl sm:text-3xl font-black text-gray-900 leading-tight mb-1 break-words">{car.name}</h1>
              {car.year && (
                <p className="text-sm text-gray-400 mb-4">{car.year} Model</p>
              )}

              {/* Ratings row */}
              {(car.rating > 0 || (car.expertRating ?? 0) > 0) && (
                <div className="flex items-center gap-3 mb-5 flex-wrap">
                  {car.rating > 0 && (
                    <div className="flex items-center gap-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white text-xs font-bold px-3 py-1 rounded-xl shadow-md">
                      <Star className="w-3 h-3 fill-current" />
                      {car.rating.toFixed(1)}
                    </div>
                  )}
                  {car.rating > 0 && car.reviewCount > 0 && (
                    <span className="text-sm text-gray-500">
                      ⭐ {car.rating.toFixed(1)}/5 · {car.reviewCount.toLocaleString()} User Reviews
                    </span>
                  )}
                  {(car.expertRating ?? 0) > 0 && (
                    <div className="flex items-center gap-1 bg-amber-50 border border-amber-200 text-amber-700 text-xs font-bold px-3 py-1 rounded-xl">
                      <Award className="w-3 h-3" />
                      Expert: {car.expertRating}/10
                    </div>
                  )}
                  {/* F41 Confidence badge */}
                  {car.confidenceLevel && (
                    <div className={`flex items-center gap-1 text-xs font-bold px-3 py-1 rounded-xl border ${
                      car.confidenceLevel === "verified"     ? "bg-green-50 border-green-200 text-green-700" :
                      car.confidenceLevel === "high"         ? "bg-blue-50 border-blue-200 text-blue-700" :
                      car.confidenceLevel === "medium"       ? "bg-amber-50 border-amber-200 text-amber-700" :
                                                               "bg-red-50 border-red-200 text-red-600"
                    }`}>
                      <Shield className="w-3 h-3" />
                      {car.confidenceLevel === "verified"     ? "Verified Data" :
                       car.confidenceLevel === "high"         ? "High Confidence" :
                       car.confidenceLevel === "medium"       ? "Medium Confidence" :
                                                                "Data Under Review"}
                    </div>
                  )}
                </div>
              )}

              {/* Price */}
              <div className="mb-5">
                <div className="flex flex-wrap items-end gap-2">
                  <span className="text-3xl sm:text-4xl font-black text-gray-900">{formatPrice(car.priceMin)}</span>
                  {car.priceMax > car.priceMin && (
                    <span className="text-lg text-gray-500 font-semibold">– {formatPrice(car.priceMax)}</span>
                  )}
                  {car.priceChangeType && car.priceChangeType !== "initial" && car.priceChangePct != null && (
                    <span className={`self-end mb-1 text-xs font-black px-2 py-1 rounded-xl ${
                      car.priceChangeType === "decrease"
                        ? "bg-green-100 text-green-700"
                        : "bg-red-100 text-red-600"
                    }`}>
                      {car.priceChangeType === "decrease" ? "↓" : "↑"} {Math.abs(car.priceChangePct).toFixed(1)}%
                    </span>
                  )}
                </div>
                <p className="text-sm text-gray-400 mt-1">Ex-showroom Price</p>
              </div>

              {/* Key specs */}
              <div className="grid grid-cols-2 gap-2 sm:gap-3 mb-5">
                {keySpecs.map(({ icon: Icon, label, value }) => (
                  <div key={label} className="rounded-2xl border border-gray-100 bg-gradient-to-br from-white to-gray-50 p-3 sm:p-4 min-w-0">
                    <Icon className="w-4 h-4 text-blue-500 mb-2" />
                    <p className="text-[10px] sm:text-[11px] uppercase tracking-wide text-gray-400 font-bold mb-1">{label}</p>
                    <p className="text-xs sm:text-sm font-bold text-gray-800 break-words">{value ?? "—"}</p>
                  </div>
                ))}
              </div>

              {/* Tags */}
              <div className="flex flex-wrap gap-2 mb-5">
                <CarFieldBadges value={fuelDisplay} kind="fuel" />
                <CarFieldBadges value={transDisplay} kind="transmission" />
                <CarFieldBadges value={bodyDisplay} kind="body" />
                {car.specs?.ADAS && (
                  <span className="px-3 py-1.5 rounded-xl text-xs font-bold bg-teal-50 text-teal-700 border border-teal-200 flex items-center gap-1">
                    <Shield className="w-3 h-3" />ADAS
                  </span>
                )}
              </div>

              {car.city?.length > 0 && (
                <div className="flex items-start gap-2 text-sm text-gray-500 mb-6">
                  <MapPin className="w-4 h-4 mt-0.5 text-gray-400 shrink-0" />
                  <span>
                    Available in {car.city.slice(0, 3).join(", ")}
                    {car.city.length > 3 && ` +${car.city.length - 3} more`}
                  </span>
                </div>
              )}

              {/* CTA buttons */}
              <div className="space-y-3">
                <motion.button
                  whileHover={prefersReducedMotion ? undefined : { scale: 1.02 }}
                  whileTap={prefersReducedMotion ? undefined : { scale: 0.98 }}
                  onClick={() => setShowPriceModal(true)}
                  className="w-full bg-gradient-to-r from-blue-600 to-cyan-500 text-white font-bold py-4 rounded-2xl shadow-xl shadow-blue-100 flex items-center justify-center gap-2 transition-all"
                >
                  <Phone className="w-4 h-4" />
                  Get On-Road Price
                </motion.button>

                <div className="grid grid-cols-2 gap-3">
                  <motion.button
                    whileHover={prefersReducedMotion ? undefined : { y: -2 }}
                    onClick={handleWishlist}
                    disabled={wishLoading}
                    aria-pressed={isWished}
                    className={cn(
                      "flex items-center justify-center gap-2 rounded-2xl py-3 border font-semibold transition-all duration-300",
                      isWished
                        ? "bg-red-50 border-red-200 text-red-600"
                        : "bg-white border-gray-200 text-gray-700 hover:border-red-200 hover:text-red-500"
                    )}
                  >
                    {wishLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Heart className="w-4 h-4" fill={isWished ? "currentColor" : "none"} />}
                    {isWished ? "Saved" : "Save"}
                  </motion.button>

                  <motion.button
                    whileHover={prefersReducedMotion ? undefined : { y: -2 }}
                    onClick={handleCompare}
                    disabled={compareLoading}
                    aria-pressed={isComparing}
                    className={cn(
                      "flex items-center justify-center gap-2 rounded-2xl py-3 border font-semibold transition-all duration-300",
                      isComparing
                        ? "bg-blue-50 border-blue-200 text-blue-600"
                        : "bg-white border-gray-200 text-gray-700 hover:border-blue-200 hover:text-blue-600"
                    )}
                  >
                    {compareLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <GitCompare className="w-4 h-4" />}
                    {isComparing ? "Added" : "Compare"}
                  </motion.button>
                </div>

                {/* I Own This toggle */}
                <motion.button
                  whileHover={prefersReducedMotion ? undefined : { y: -2 }}
                  onClick={() => owned ? removeOwned(car.id) : addOwned(car)}
                  aria-pressed={owned}
                  className={cn(
                    "w-full flex items-center justify-center gap-2 rounded-2xl py-3 border font-semibold transition-all duration-300 text-sm",
                    owned
                      ? "bg-blue-50 border-blue-200 text-blue-700"
                      : "bg-white border-gray-200 text-gray-700 hover:border-blue-200 hover:text-blue-600"
                  )}
                >
                  <CarIcon className="w-4 h-4" fill={owned ? "currentColor" : "none"} />
                  {owned ? "✓ In My Garage" : "I Own This Car"}
                </motion.button>

                {/* Watch Car toggle — F48 */}
                <motion.button
                  whileHover={prefersReducedMotion ? undefined : { y: -2 }}
                  onClick={handleWatch}
                  disabled={watchLoading}
                  aria-pressed={isWatching}
                  className={cn(
                    "w-full flex items-center justify-center gap-2 rounded-2xl py-3 border font-semibold transition-all duration-300 text-sm",
                    isWatching
                      ? "bg-amber-50 border-amber-200 text-amber-700"
                      : "bg-white border-gray-200 text-gray-700 hover:border-amber-200 hover:text-amber-600"
                  )}
                >
                  {watchLoading ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : isWatching ? (
                    <BellRing className="w-4 h-4" />
                  ) : (
                    <Bell className="w-4 h-4" />
                  )}
                  {isWatching ? "✓ Watching Alerts" : "Watch Car"}
                </motion.button>

                {/* Brochure download */}
                {car.brochureUrl && (
                  <a
                    href={car.brochureUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-full flex items-center justify-center gap-2 py-3 rounded-2xl border border-gray-200 text-gray-700 hover:border-blue-200 hover:text-blue-600 font-semibold transition-all duration-300 text-sm"
                  >
                    <Download className="w-4 h-4" />
                    Download Brochure
                  </a>
                )}
              </div>
            </div>

            <EMICalculator carPrice={car.priceMin} />
          </motion.div>
        </div>

        {/* ─── HIGHLIGHTS STRIP ───────────────────────────────────────────── */}
        {car.highlights && car.highlights.length > 0 && (
          <div className="rounded-[28px] bg-gradient-to-r from-blue-600 to-indigo-600 p-5 mb-6 shadow-lg">
            <p className="text-[10px] uppercase tracking-[0.2em] text-blue-200 font-black mb-3">Why Buy This Car</p>
            <div className="flex flex-wrap gap-2">
              {car.highlights.map((h, i) => (
                <div key={i} className="flex items-center gap-2 bg-white/15 backdrop-blur rounded-2xl px-4 py-2">
                  <Check className="w-3.5 h-3.5 text-green-300 shrink-0" />
                  <span className="text-sm font-semibold text-white">{h}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ─── TABS ─────────────────────────────────────────────────────────── */}
        <div className="rounded-[32px] overflow-hidden bg-white border border-gray-200/60 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6">
          <div
            role="tablist"
            aria-label="Car information sections"
            className="flex overflow-x-auto scrollbar-none border-b border-gray-100 bg-white/80 backdrop-blur-xl"
          >
            {visibleTabs.map((tab) => (
              <button
                key={tab}
                role="tab"
                aria-selected={activeTab === tab}
                onClick={() => setActiveTab(tab)}
                className={cn(
                  "relative px-6 py-5 text-sm font-bold whitespace-nowrap transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-blue-500",
                  activeTab === tab ? "text-blue-600" : "text-gray-500 hover:text-gray-800"
                )}
              >
                {tab}
                {activeTab === tab && (
                  <motion.div
                    layoutId="activeTab"
                    className="absolute left-0 bottom-0 w-full h-[3px] bg-gradient-to-r from-blue-600 to-cyan-500 rounded-full"
                  />
                )}
              </button>
            ))}
          </div>

          {/* VARIANTS */}
          {activeTab === "Variants" && (
            <div className="overflow-x-auto">
              {car.variants && car.variants.length > 0 ? (
                <table className="w-full min-w-[640px]">
                  <thead className="bg-gradient-to-r from-gray-50 to-blue-50 border-b border-gray-100">
                    <tr>
                      {["Variant", "Fuel", "Transmission", "Mileage", "Price"].map((head) => (
                        <th key={head} className={cn(
                          "px-6 py-4 text-xs uppercase tracking-wider text-gray-500 font-black",
                          head === "Price" ? "text-right" : "text-left"
                        )}>
                          {head}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {car.variants.map((v, i) => (
                      <tr key={i} className="border-b border-gray-100 hover:bg-blue-50/40 transition-colors">
                        <td className="px-6 py-5">
                          <div>
                            <p className="font-bold text-gray-800">{v.name}</p>
                            {v.engine && <p className="text-xs text-gray-400 mt-0.5">{v.engine}</p>}
                          </div>
                        </td>
                        <td className="px-6 py-5 text-gray-600">{v.fuelType}</td>
                        <td className="px-6 py-5 text-gray-600">{v.transmission}</td>
                        <td className="px-6 py-5 text-gray-600">{v.mileage ?? "—"}</td>
                        <td className="px-6 py-5 text-right font-black text-gray-900">{formatPrice(v.price)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <p className="p-8 text-gray-500">No variants available.</p>
              )}
            </div>
          )}

          {/* SPECIFICATIONS */}
          {activeTab === "Specifications" && (
            <div className="divide-y divide-gray-100">
              {visibleSpecs.map(({ group, rows }) => {
                const filtered = rows.filter(([, val]) => val);
                if (filtered.length === 0) return null;
                return (
                  <div key={group}>
                    <div className="px-6 py-4 bg-gradient-to-r from-gray-50 to-blue-50">
                      <h3 className="text-xs uppercase tracking-[0.2em] text-gray-600 font-black">{group}</h3>
                    </div>
                    {filtered.map(([label, value]) => (
                      <div key={label} className="flex flex-col sm:flex-row sm:items-center px-6 py-4 hover:bg-gray-50 transition-colors">
                        <span className="w-full sm:w-1/2 text-sm text-gray-500 font-medium">{label}</span>
                        <span className="w-full sm:w-1/2 text-sm font-bold text-gray-800 mt-1 sm:mt-0">{String(value)}</span>
                      </div>
                    ))}
                  </div>
                );
              })}
              <button
                onClick={() => setShowAllSpecs(!showAllSpecs)}
                className="w-full py-5 flex items-center justify-center gap-2 text-sm font-bold text-blue-600 hover:bg-blue-50 transition-colors"
              >
                {showAllSpecs ? "Show Less" : "Show All Specifications"}
                {showAllSpecs ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </button>
            </div>
          )}

          {/* FEATURES */}
          {activeTab === "Features" && hasFeatures && (
            <div className="p-8">
              {/* ── Raw CarWale feature groups (when available) ────────────── */}
              {hasFeatureGroups && (
                <div className="mb-8">
                  {Object.entries(car.featureGroups!).map(([groupName, items]) => (
                    <div key={groupName} className="mb-6">
                      <h3 className="text-sm font-black uppercase tracking-wider text-gray-500 mb-3">
                        {groupName}
                      </h3>
                      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2">
                        {items.map((item) => (
                          <div key={item} className="flex items-center gap-2.5 rounded-xl border border-blue-100 bg-blue-50 px-3 py-2.5">
                            <Check className="w-3.5 h-3.5 text-blue-500 shrink-0" />
                            <span className="text-sm text-gray-700">{item}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                  {hasFeatureFlags && (
                    <div className="border-t border-gray-100 pt-6 mb-2">
                      <p className="text-xs uppercase tracking-wider text-gray-400 font-bold mb-4">Feature Highlights</p>
                    </div>
                  )}
                </div>
              )}
              {hasFeatureFlags && [
                {
                  icon: SunMedium, label: "Comfort & Luxury", color: "amber",
                  items: [
                    { key: "sunroof",          label: "Sunroof" },
                    { key: "panoramicSunroof", label: "Panoramic Sunroof" },
                    { key: "ventilatedSeats",  label: "Ventilated Seats" },
                    { key: "heatedSeats",      label: "Heated Seats" },
                    { key: "climateControl",   label: "Climate Control" },
                    { key: "rearAC",           label: "Rear AC" },
                    { key: "ambientLighting",  label: "Ambient Lighting" },
                    { key: "powerTailgate",    label: "Power Tailgate" },
                  ],
                },
                {
                  icon: MonitorSmartphone, label: "Technology & Connectivity", color: "blue",
                  items: [
                    { key: "touchscreenSize",  label: car.features?.touchscreenSize ? `${car.features.touchscreenSize} Touchscreen` : "Touchscreen" },
                    { key: "digitalCluster",   label: "Digital Cluster" },
                    { key: "connectedCar",     label: "Connected Car" },
                    { key: "appleCarPlay",     label: "Apple CarPlay" },
                    { key: "androidAuto",      label: "Android Auto" },
                    { key: "wirelessCharger",  label: "Wireless Charging" },
                    { key: "HUD",              label: "Head-Up Display (HUD)" },
                  ],
                },
                {
                  icon: Camera, label: "Cameras & Parking", color: "violet",
                  items: [
                    { key: "camera360",           label: "360° Camera" },
                    { key: "rearCamera",          label: "Rear Camera" },
                    { key: "frontParkingSensors", label: "Front Parking Sensors" },
                    { key: "rearParkingSensors",  label: "Rear Parking Sensors" },
                  ],
                },
                {
                  icon: Navigation2, label: "Driver Assistance", color: "teal",
                  items: [
                    { key: "cruiseControl",        label: "Cruise Control" },
                    { key: "adaptiveCruiseControl",label: "Adaptive Cruise Control" },
                    { key: "laneDepartureWarning", label: "Lane Departure Warning" },
                    { key: "blindSpotMonitoring",  label: "Blind Spot Monitoring" },
                    { key: "autoParking",          label: "Auto Parking" },
                  ],
                },
                {
                  icon: Wifi, label: "Convenience", color: "green",
                  items: [
                    { key: "keylessEntry",    label: "Keyless Entry" },
                    { key: "pushButtonStart", label: "Push Button Start" },
                  ],
                },
              ].map(({ icon: Icon, label, color, items }) => {
                const present = items.filter(({ key }) => {
                  const val = (car.features as Record<string, unknown> | undefined)?.[key];
                  return val === true || (typeof val === "string" && val);
                });
                if (present.length === 0) return null;
                return (
                  <div key={label} className="mb-8">
                    <div className={`flex items-center gap-2 mb-4 text-${color}-600`}>
                      <Icon className="w-5 h-5" />
                      <h3 className="text-sm font-black uppercase tracking-wider">{label}</h3>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
                      {present.map(({ label: fl }) => (
                        <div key={fl} className="flex items-center gap-3 rounded-2xl border border-green-100 bg-green-50 px-4 py-3">
                          <Check className="w-4 h-4 text-green-500 shrink-0" />
                          <span className="text-sm font-semibold text-gray-800">{fl}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* SAFETY */}
          {activeTab === "Safety" && hasSafetyData && (
            <div className="p-8">
              {/* NCAP Rating */}
              {car.specs?.ncapRating && (
                <div className="mb-8 p-5 rounded-[24px] bg-gradient-to-r from-green-50 to-emerald-50 border border-green-100">
                  <div className="flex items-center gap-3 mb-2">
                    <div className="w-12 h-12 rounded-2xl bg-green-100 flex items-center justify-center">
                      <Award className="w-6 h-6 text-green-600" />
                    </div>
                    <div>
                      <p className="text-xs uppercase tracking-wider text-green-600 font-black">Global NCAP</p>
                      <p className="text-2xl font-black text-gray-900">{car.specs.ncapRating}</p>
                    </div>
                  </div>
                  <p className="text-sm text-gray-500">Independent crash-test safety rating</p>
                </div>
              )}

              {/* Airbags */}
              {car.specs?.airbags != null && (
                <div className="mb-8 p-5 rounded-[24px] bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-100">
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 rounded-2xl bg-blue-100 flex items-center justify-center">
                      <Shield className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <p className="text-xs uppercase tracking-wider text-blue-600 font-black">Airbags</p>
                      <p className="text-2xl font-black text-gray-900">{car.specs.airbags}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Boolean safety features */}
              <h3 className="text-sm font-black uppercase tracking-wider text-gray-500 mb-4">Safety Systems</h3>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <BoolBadge value={car.specs?.abs} label="ABS (Anti-lock Braking)" />
                <BoolBadge value={car.specs?.EBD} label="EBD (Electronic Brakeforce)" />
                <BoolBadge value={car.specs?.ESC} label="ESC (Electronic Stability)" />
                <BoolBadge value={car.specs?.tractionControl} label="Traction Control" />
                <BoolBadge value={car.specs?.ADAS} label="ADAS (Driver Assistance)" />
              </div>
            </div>
          )}

          {/* COLORS */}
          {activeTab === "Colors" && hasColors && (
            <div className="p-8">
              <h3 className="text-lg font-black text-gray-900 mb-6">Available Colors</h3>

              {car.colors && car.colors.length > 0 ? (
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                  {car.colors.map((c) => (
                    <div key={c.name} className="group rounded-[20px] border border-gray-100 hover:border-blue-200 hover:shadow-lg p-4 transition-all duration-300 cursor-default flex flex-col items-center gap-3">
                      {c.imageUrl ? (
                        <div className="relative w-full aspect-[4/3] rounded-2xl overflow-hidden bg-gray-50">
                          <Image src={c.imageUrl} alt={c.name} fill className="object-cover" sizes="200px" />
                        </div>
                      ) : (
                        <div
                          className="w-14 h-14 rounded-2xl border-2 border-white shadow-md"
                          style={{ backgroundColor: c.hex ?? "#e5e7eb" }}
                        />
                      )}
                      <p className="text-sm font-semibold text-gray-700 text-center leading-tight">{c.name}</p>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex flex-wrap gap-3">
                  {car.color.map((c) => (
                    <div key={c} className="px-4 py-2 rounded-2xl bg-gradient-to-r from-gray-100 to-gray-50 border border-gray-200 text-sm font-semibold text-gray-700">
                      {c}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* PROS & CONS */}
          {activeTab === "Pros & Cons" && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8 p-8">
              <div className="rounded-[28px] bg-green-50 border border-green-100 p-6">
                <h3 className="flex items-center gap-3 text-lg font-black text-green-700 mb-5">
                  <div className="w-10 h-10 rounded-2xl bg-green-100 flex items-center justify-center">
                    <Check className="w-5 h-5 text-green-600" />
                  </div>
                  What&apos;s Good
                </h3>
                <div className="space-y-4">
                  {car.pros && car.pros.length > 0 ? (
                    car.pros.map((p, i) => (
                      <div key={i} className="flex items-start gap-3">
                        <Check className="w-4 h-4 text-green-500 mt-1 shrink-0" />
                        <p className="text-sm text-gray-700 leading-relaxed">{p}</p>
                      </div>
                    ))
                  ) : (
                    <p className="text-sm text-gray-400">Not available</p>
                  )}
                </div>
              </div>

              <div className="rounded-[28px] bg-red-50 border border-red-100 p-6">
                <h3 className="flex items-center gap-3 text-lg font-black text-red-700 mb-5">
                  <div className="w-10 h-10 rounded-2xl bg-red-100 flex items-center justify-center">
                    <XIcon className="w-5 h-5 text-red-600" />
                  </div>
                  What&apos;s Not
                </h3>
                <div className="space-y-4">
                  {car.cons && car.cons.length > 0 ? (
                    car.cons.map((c, i) => (
                      <div key={i} className="flex items-start gap-3">
                        <XIcon className="w-4 h-4 text-red-500 mt-1 shrink-0" />
                        <p className="text-sm text-gray-700 leading-relaxed">{c}</p>
                      </div>
                    ))
                  ) : (
                    <p className="text-sm text-gray-400">Not available</p>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* OVERVIEW */}
          {activeTab === "Overview" && (
            <div className="p-8">
              <div className="max-w-4xl">
                <p className="text-gray-700 leading-8 text-[15px]">
                  {car.overview || "Overview not available."}
                </p>
              </div>
            </div>
          )}

          {/* FAQs */}
          {activeTab === "FAQs" && hasFAQs && (
            <FAQAccordion faqs={car.faqs!} />
          )}
        </div>

        {/* ─── KEY HIGHLIGHTS ──────────────────────────────────────────────── */}
        <div className="rounded-[32px] bg-white border border-gray-200/60 p-5 sm:p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6 overflow-hidden">
          <h2 className="text-xl sm:text-2xl font-black text-gray-900 mb-6 sm:mb-8 break-words">{car.name} — Key Highlights</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-5">
            {[
              { label: "Starting Price",   value: formatPrice(car.priceMin) },
              { label: "Engine",           value: car.specs?.engine ?? "—" },
              { label: "Mileage",          value: car.specs?.mileage ?? "—" },
              { label: "Seating",          value: car.specs?.seatingCapacity ? `${car.specs.seatingCapacity} Persons` : "—" },
              { label: "Body Type",        value: primaryCarField(bodyDisplay) },
              { label: "Transmission",     value: primaryCarField(transDisplay) },
              { label: "Ground Clearance", value: car.specs?.groundClearance ?? "—" },
              { label: "Boot Space",       value: car.specs?.bootSpace ?? "—" },
            ].map(({ label, value }) => (
              <motion.div
                whileHover={{ y: -4 }}
                key={label}
                className="rounded-[24px] bg-gradient-to-br from-white to-gray-50 border border-gray-100 p-4 sm:p-5 hover:shadow-xl hover:shadow-blue-100/30 transition-all duration-300 min-w-0"
              >
                <p className="text-[10px] sm:text-[11px] uppercase tracking-[0.15em] text-gray-400 font-black mb-2">{label}</p>
                <p className="text-sm sm:text-base font-black text-gray-900 leading-snug break-words">{value}</p>
              </motion.div>
            ))}
          </div>
        </div>

        {/* ─── EXPERT REVIEW ──────────────────────────────────────────────── */}
        {(car.expertRating ?? 0) > 0 && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-5 sm:p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6 overflow-hidden">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-amber-100 flex items-center justify-center shrink-0">
                <Award className="w-6 h-6 text-amber-600" />
              </div>
              <div className="min-w-0">
                <p className="text-[10px] uppercase tracking-[0.2em] text-amber-600 font-black">Editorial</p>
                <h2 className="text-xl font-black text-gray-900">Expert Rating</h2>
              </div>
            </div>
            <div className="flex flex-col sm:flex-row sm:items-center gap-4 sm:gap-6">
              <div className="text-5xl sm:text-6xl font-black text-gray-900 shrink-0">
                {car.expertRating!.toFixed(1)}
                <span className="text-2xl text-gray-400">/10</span>
              </div>
              <div className="flex-1 min-w-0">
                <div className="h-3 bg-gray-100 rounded-full overflow-hidden">
                  <motion.div
                    initial={{ width: 0 }}
                    animate={{ width: `${(car.expertRating! / 10) * 100}%` }}
                    transition={{ duration: 1, ease: "easeOut" }}
                    className="h-full bg-gradient-to-r from-amber-400 to-orange-500 rounded-full"
                  />
                </div>
                <div className="flex justify-between text-xs text-gray-400 mt-1.5 font-medium">
                  <span>0</span>
                  <span className="text-amber-600 font-bold">
                    {car.expertRating! >= 8 ? "Excellent" : car.expertRating! >= 6 ? "Good" : "Average"}
                  </span>
                  <span>10</span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ─── CUSTOMER REVIEWS ───────────────────────────────────────────── */}
        {(car.rating > 0 || reviews.length > 0) && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-5 sm:p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6 overflow-hidden">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-green-100 flex items-center justify-center shrink-0">
                <Star className="w-6 h-6 text-green-600 fill-green-600" />
              </div>
              <div className="min-w-0">
                <p className="text-[10px] uppercase tracking-[0.2em] text-green-600 font-black">Users</p>
                <h2 className="text-xl font-black text-gray-900">Customer Reviews</h2>
              </div>
            </div>
            <div className="flex flex-col md:flex-row md:items-start gap-6 md:gap-8 mb-8">
              <div className="text-center md:text-left shrink-0">
                <div className="text-5xl sm:text-6xl font-black text-gray-900">
                  {car.rating.toFixed(1)}
                  <span className="text-xl sm:text-2xl text-gray-400">/5</span>
                </div>
                <div className="flex items-center justify-center md:justify-start gap-1 mt-2">
                  {[1, 2, 3, 4, 5].map((s) => (
                    <Star
                      key={s}
                      className={cn(
                        "w-4 h-4 sm:w-5 sm:h-5",
                        s <= Math.round(car.rating)
                          ? "text-yellow-400 fill-yellow-400"
                          : "text-gray-200 fill-gray-200"
                      )}
                    />
                  ))}
                </div>
                <p className="text-sm text-gray-500 mt-1">
                  Based on {(car.reviewCount || reviews.length).toLocaleString()} user reviews
                </p>
              </div>
            </div>

            {reviewsLoading ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="w-6 h-6 text-green-500 animate-spin" />
              </div>
            ) : reviews.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {reviews.map((review) => (
                  <ReviewCard key={review.id} review={review} />
                ))}
              </div>
            ) : null}
          </div>
        )}

        {/* ─── OWNERSHIP COST ─────────────────────────────────────────────── */}
        {hasOwnership && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-blue-100 flex items-center justify-center">
                <Wrench className="w-6 h-6 text-blue-600" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-blue-600 font-black">Cost of Ownership</p>
                <h2 className="text-xl font-black text-gray-900">Running Costs</h2>
              </div>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {car.ownership!.serviceCost && (
                <div className="rounded-[20px] bg-blue-50 border border-blue-100 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-blue-500 font-black mb-2">Service Cost</p>
                  <p className="text-sm font-bold text-gray-800">{car.ownership!.serviceCost}</p>
                </div>
              )}
              {car.ownership!.warranty && (
                <div className="rounded-[20px] bg-green-50 border border-green-100 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-green-500 font-black mb-2">Warranty</p>
                  <p className="text-sm font-bold text-gray-800">{car.ownership!.warranty}</p>
                </div>
              )}
              {car.ownership!.maintenance && (
                <div className={cn(
                  "rounded-[20px] border p-4",
                  car.ownership!.maintenance.toLowerCase() === "low" ? "bg-green-50 border-green-100" :
                  car.ownership!.maintenance.toLowerCase() === "high" ? "bg-red-50 border-red-100" :
                  "bg-amber-50 border-amber-100"
                )}>
                  <p className="text-[11px] uppercase tracking-wider text-gray-500 font-black mb-2">Maintenance</p>
                  <p className="text-sm font-bold text-gray-800">{car.ownership!.maintenance}</p>
                </div>
              )}
              {car.ownership!.resaleValue && (
                <div className="rounded-[20px] bg-violet-50 border border-violet-100 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-violet-500 font-black mb-2">Resale Value</p>
                  <p className="text-sm font-bold text-gray-800">{car.ownership!.resaleValue}</p>
                </div>
              )}
            </div>
          </div>
        )}

        {/* ─── EV SPECS ───────────────────────────────────────────────────── */}
        {hasEVSpecs && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-emerald-100 flex items-center justify-center">
                <Zap className="w-6 h-6 text-emerald-600" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-emerald-600 font-black">Electric Vehicle</p>
                <h2 className="text-xl font-black text-gray-900">EV Specifications</h2>
              </div>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              {[
                { label: "Battery Capacity",  value: car.evSpecs?.batteryCapacity },
                { label: "Range",             value: car.evSpecs?.range },
                { label: "Charging Time",     value: car.evSpecs?.chargingTime },
                { label: "Fast Charge Time",  value: car.evSpecs?.fastChargingTime },
                { label: "Charging Type",     value: car.evSpecs?.chargingType },
                { label: "Charger Port",      value: car.evSpecs?.chargerPortType },
                { label: "Running Cost",      value: car.evSpecs?.runningCost },
                { label: "Battery Warranty",  value: car.evSpecs?.batteryWarranty },
                { label: "Motor Type",        value: car.evSpecs?.motorType },
                { label: "Motor Power",       value: car.evSpecs?.motorPower },
                { label: "Fast Charging",     value: car.evSpecs?.fastCharging != null ? (car.evSpecs.fastCharging ? "Yes" : "No") : undefined },
                { label: "Regen Braking",     value: car.evSpecs?.regenerativeBraking != null ? (car.evSpecs.regenerativeBraking ? "Yes" : "No") : undefined },
              ].filter(({ value }) => value).map(({ label, value }) => (
                <div key={label} className="rounded-[20px] bg-emerald-50 border border-emerald-100 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-emerald-500 font-black mb-2">{label}</p>
                  <p className="text-sm font-bold text-gray-800">{value}</p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ─── CITY PRICING, OFFERS & WAITING PERIOD ──────────────────────── */}
        {(cityPrices.length > 0 || discounts || waitingPeriod) && (
          <CityPricingSection
            carId={car.id}
            carName={car.name}
            prices={cityPrices}
            discounts={discounts}
            waiting={waitingPeriod}
          />
        )}

        {/* ─── OWNERSHIP COST (F46) ───────────────────────────────────────── */}
        <OwnershipCostSection carId={car.id} fuelType={car.fuelType} />

        {/* ─── PRICE HISTORY ──────────────────────────────────────────────── */}
        {priceHistory && (
          <PriceHistoryChart data={priceHistory} />
        )}

        {/* ─── VEHICLE SCORES (F29) ───────────────────────────────────────── */}
        {car.vehicleScores && (car.vehicleScores.overall ?? 0) > 0 && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-purple-100 flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-purple-600" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-purple-600 font-black">Expert Analysis</p>
                <h2 className="text-xl font-black text-gray-900">Vehicle Scores</h2>
              </div>
              <div className="ml-auto text-right">
                <div className="text-3xl font-black text-gray-900">
                  {car.vehicleScores.overall?.toFixed(1)}
                  <span className="text-base text-gray-400">/10</span>
                </div>
                <p className="text-xs text-gray-400 font-semibold">Overall</p>
              </div>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {[
                { key: "performance",   label: "Performance",     color: "from-red-500 to-orange-500" },
                { key: "comfort",       label: "Comfort",          color: "from-blue-500 to-cyan-500" },
                { key: "features",      label: "Features",         color: "from-violet-500 to-purple-500" },
                { key: "safety",        label: "Safety",           color: "from-green-500 to-emerald-500" },
                { key: "mileage",       label: "Mileage",          color: "from-amber-500 to-yellow-500" },
                { key: "ownership",     label: "Ownership Cost",   color: "from-teal-500 to-cyan-600" },
                { key: "reliability",   label: "Reliability",      color: "from-indigo-500 to-blue-600" },
                { key: "valueForMoney", label: "Value For Money",  color: "from-pink-500 to-rose-500" },
              ].map(({ key, label, color }) => {
                const score = car.vehicleScores![key as keyof typeof car.vehicleScores] as number | undefined;
                if (!score) return null;
                return (
                  <div key={key} className="rounded-[20px] border border-gray-100 p-4">
                    <p className="text-[11px] uppercase tracking-wider text-gray-400 font-black mb-3">{label}</p>
                    <div className="flex items-end justify-between mb-2">
                      <span className="text-2xl font-black text-gray-900">{score.toFixed(1)}</span>
                      <span className="text-xs text-gray-400">/10</span>
                    </div>
                    <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                      <motion.div
                        initial={{ width: 0 }}
                        animate={{ width: `${(score / 10) * 100}%` }}
                        transition={{ duration: 0.8, ease: "easeOut" }}
                        className={`h-full bg-gradient-to-r ${color} rounded-full`}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* ─── AI SAFETY CONTENT (F31) ────────────────────────────────────── */}
        {car.safety?.safetyOverview && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-green-100 flex items-center justify-center">
                <Shield className="w-6 h-6 text-green-600" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-green-600 font-black">Safety Analysis</p>
                <h2 className="text-xl font-black text-gray-900">Safety Report</h2>
              </div>
              {(car.safety.safetyRating ?? 0) > 0 && (
                <div className="ml-auto flex items-center gap-1">
                  {Array.from({ length: 5 }).map((_, i) => (
                    <div key={i} className={`w-3 h-3 rounded-full ${i < (car.safety!.safetyRating ?? 0) ? "bg-green-500" : "bg-gray-200"}`} />
                  ))}
                </div>
              )}
            </div>
            <p className="text-gray-700 leading-7 text-[15px] mb-4">{car.safety.safetyOverview}</p>
            {car.safety.crashRatingSummary && (
              <div className="rounded-2xl bg-green-50 border border-green-100 px-5 py-4 mb-4">
                <p className="text-sm font-semibold text-green-700">{car.safety.crashRatingSummary}</p>
              </div>
            )}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {car.safety.airbagInfo && (
                <div className="rounded-2xl border border-gray-100 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-gray-400 font-black mb-1">Airbags</p>
                  <p className="text-sm text-gray-700">{car.safety.airbagInfo}</p>
                </div>
              )}
              {car.safety.childSafetyNotes && (
                <div className="rounded-2xl border border-gray-100 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-gray-400 font-black mb-1">Child Safety</p>
                  <p className="text-sm text-gray-700">{car.safety.childSafetyNotes}</p>
                </div>
              )}
            </div>
            {(car.safety.adasFeatures?.length ?? 0) > 0 && (
              <div className="mt-4">
                <p className="text-[11px] uppercase tracking-wider text-gray-400 font-black mb-3">ADAS Features</p>
                <div className="flex flex-wrap gap-2">
                  {car.safety.adasFeatures!.map((f, i) => (
                    <span key={i} className="px-3 py-1.5 rounded-xl bg-green-50 border border-green-100 text-xs font-semibold text-green-700">{f}</span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* ─── AI EV OWNERSHIP GUIDE (F32) ────────────────────────────────── */}
        {car.evContent?.evOverview && (
          <div className="rounded-[32px] bg-gradient-to-br from-emerald-900 to-teal-800 text-white p-8 shadow-[0_10px_40px_rgba(0,0,0,0.15)] mb-6">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-12 h-12 rounded-2xl bg-white/10 flex items-center justify-center">
                <Zap className="w-6 h-6 text-emerald-300" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-emerald-300 font-black">EV Guide</p>
                <h2 className="text-xl font-black">EV Ownership Guide</h2>
              </div>
            </div>
            <p className="text-emerald-100 leading-7 text-[15px] mb-6">{car.evContent.evOverview}</p>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6">
              {[
                { label: "Real World Range",  value: car.evContent.realWorldRange },
                { label: "Charging Cost",     value: car.evContent.chargingCostEstimate },
                { label: "Running Cost",      value: car.evContent.totalCostOfOwnership ? "See below" : undefined },
              ].filter(({ value }) => value).map(({ label, value }) => (
                <div key={label} className="rounded-2xl bg-white/10 p-4">
                  <p className="text-[11px] uppercase tracking-wider text-emerald-300 font-black mb-1">{label}</p>
                  <p className="text-sm font-semibold">{value}</p>
                </div>
              ))}
            </div>
            {car.evContent.evOwnershipGuide && (
              <p className="text-emerald-200 text-sm leading-6">{car.evContent.evOwnershipGuide}</p>
            )}
            {(car.evContent.publicChargingNetworks?.length ?? 0) > 0 && (
              <div className="mt-4">
                <p className="text-[11px] uppercase tracking-wider text-emerald-300 font-black mb-2">Charging Networks</p>
                <div className="flex flex-wrap gap-2">
                  {car.evContent.publicChargingNetworks!.map((n, i) => (
                    <span key={i} className="px-3 py-1 rounded-xl bg-white/10 text-xs font-semibold">{n}</span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* ─── AI SUMMARY ─────────────────────────────────────────────────── */}
        <AISummaryCard carId={car.id} carName={car.name} />

        {/* ─── RIVALS ─────────────────────────────────────────────────────── */}
        {rivals && (
          <RivalsSection
            rivals={rivals}
            currentCarId={car.id}
            currentCarName={car.name}
          />
        )}

        {/* ─── SIMILAR CARS ───────────────────────────────────────────────── */}
        <div className="mt-6 mb-8">
          <SimilarCars currentCarId={car.id} brand={car.brand} bodyType={car.bodyType} />
        </div>
      </div>

      {/* ─── ON-ROAD PRICE MODAL ─────────────────────────────────────────── */}
      <OnRoadPriceModal
        car={{ id: car.id, name: car.name, variants: car.variants }}
        isOpen={showPriceModal}
        onClose={() => setShowPriceModal(false)}
      />
    </div>
  );
}
