'use client';

import React, { useEffect, useState, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useAuth } from '@/context/AuthContext';
import api from '@/lib/api';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { ProductCard } from '@/components/ProductCard';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import { trackViewItem } from '@/lib/analytics';
import {
  ShoppingCart, ShoppingBag, Heart, Truck, ShieldCheck, ArrowLeft,
  Loader2, Check, Star, Phone, MessageCircle, ChevronRight,
  Package, RotateCcw, BadgeCheck, Minus, Plus, ZoomIn, X, ChevronLeft,
  ChevronDown
} from 'lucide-react';

/* ── Types ─────────────────────────────────────────────────────── */
interface Variant {
  id: number;
  sku: string;
  price: number;
  quantity: number;
  options: Record<string, string>;
}

interface Review {
  id: number;
  rating: number;
  comment: string | null;
  created_at: string;
  user?: { name: string };
}

interface Product {
  id: number;
  name: string;
  slug: string;
  sku: string;
  price: number;
  compare_at_price?: number;
  sale_price?: number;
  reseller_price?: number;
  description?: string;
  short_description?: string;
  image_url: string;
  all_images: { url: string; webp: string | null }[];
  quantity: number;
  category?: { name: string; slug: string };
  variants: Variant[];
  reviews?: Review[];
}

/* ── Helpers ────────────────────────────────────────────────────── */
function fmt(x: number | null | undefined) {
  if (x == null || isNaN(Number(x))) return '0.00';
  return Number(x).toLocaleString('en-BD', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function avgRating(reviews: Review[]) {
  if (!reviews.length) return 0;
  return reviews.reduce((s, r) => s + r.rating, 0) / reviews.length;
}

function StarRow({ rating, max = 5, size = 'sm' }: { rating: number; max?: number; size?: 'sm' | 'lg' }) {
  const cls = size === 'lg' ? 'h-5 w-5' : 'h-4 w-4';
  return (
    <span className="flex gap-0.5">
      {Array.from({ length: max }).map((_, i) => (
        <Star key={i} className={`${cls} ${i < Math.round(rating) ? 'text-secondary fill-secondary' : 'text-slate-200 fill-slate-200'}`} />
      ))}
    </span>
  );
}

/* ── Color Map ─────────────────────────────────────────────────── */
const COLOR_MAP: Record<string, string> = {
  'red': '#ef4444', 'crimson': '#dc143c', 'maroon': '#800000',
  'blue': '#3b82f6', 'navy': '#1e3a8a', 'skyblue': '#38bdf8', 'sky blue': '#38bdf8', 'royal blue': '#1d4ed8',
  'green': '#22c55e', 'olive': '#6b7280', 'lime': '#84cc16', 'forest green': '#15803d',
  'black': '#111111', 'white': '#f8fafc', 'off white': '#f1f5f9', 'off-white': '#f1f5f9',
  'yellow': '#facc15', 'gold': '#f59e0b', 'mustard': '#ca8a04',
  'orange': '#f97316', 'peach': '#fb923c',
  'purple': '#a855f7', 'violet': '#7c3aed', 'lavender': '#c4b5fd',
  'pink': '#ec4899', 'rose': '#fb7185', 'magenta': '#d946ef',
  'gray': '#9ca3af', 'grey': '#9ca3af', 'silver': '#d1d5db', 'charcoal': '#4b5563',
  'brown': '#a16207', 'chocolate': '#7c4a03', 'beige': '#d6c5a0', 'tan': '#c4a97d',
  'teal': '#0d9488', 'cyan': '#06b6d4', 'turquoise': '#14b8a6',
  'indigo': '#6366f1', 'cream': '#fef9c3', 'ivory': '#fefce8',
  'coral': '#f87171', 'salmon': '#fca5a5',
};

const COLOR_ATTR_NAMES = ['color', 'colour', 'রং', 'রঙ'];

function isColorAttr(attrName: string): boolean {
  return COLOR_ATTR_NAMES.includes(attrName.toLowerCase().trim());
}

function getCssColor(value: string): string | null {
  const key = value.toLowerCase().trim();
  return COLOR_MAP[key] ?? null;
}


/* ── Main Component ─────────────────────────────────────────────── */
export default function ProductDetailPage() {
  const params = useParams();
  const router = useRouter();
  const slug = params.slug as string;
  const { addToCart, cartItems, removeItem, updateQuantity } = useCart();
  const { formatPrice } = useSiteSettings();
  const { user } = useAuth();

  const [product, setProduct] = useState<Product | null>(null);
  const [related, setRelated] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedImage, setSelectedImage] = useState('');
  const [lightboxOpen, setLightboxOpen] = useState(false);

  const [quantity, setQuantity] = useState(1);
  const [adding, setAdding] = useState(false);
  const [addSuccess, setAddSuccess] = useState(false);

  const [selectedOptions, setSelectedOptions] = useState<Record<string, string>>({});
  const [matchedVariant, setMatchedVariant] = useState<Variant | null>(null);
  const [priceKey, setPriceKey] = useState(0); // triggers price animation

  const [activeTab, setActiveTab] = useState<'description' | 'reviews' | null>(null);

  const descriptionRef = useRef<HTMLDivElement>(null);
  const reviewsRef = useRef<HTMLDivElement>(null);

  // Scroll position restoration
  const scrollRestoredRef = useRef(false);
  const isRestoringRef = useRef(false); // pause scroll-save during smooth scroll
  const scrollSaveKey = `scroll_product_${typeof window !== 'undefined' ? window.location.pathname : ''}`;

  // Track ViewItem event on mount/load
  useEffect(() => {
    if (product) {
      trackViewItem(product);
    }
  }, [product?.id]);

  // Disable browser auto scroll-restoration & save position on scroll
  useEffect(() => {
    if (typeof window !== 'undefined') {
      history.scrollRestoration = 'manual';
    }
    const handleScrollSave = () => {
      if (isRestoringRef.current) return; // don't save during restoration
      sessionStorage.setItem(scrollSaveKey, String(window.scrollY));
    };
    window.addEventListener('scroll', handleScrollSave, { passive: true });
    return () => window.removeEventListener('scroll', handleScrollSave);
  }, [scrollSaveKey]);

  const scrollToSection = (section: 'description' | 'reviews') => {
    setActiveTab(section);
    const ref = section === 'description' ? descriptionRef : reviewsRef;
    if (ref.current) {
      const offset = 90; // offset height for sticky tab bar
      const elementPosition = ref.current.getBoundingClientRect().top + window.scrollY;
      const offsetPosition = elementPosition - offset;

      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
      });
    }
  };

  useEffect(() => {
    const handleScroll = () => {
      const descEl = descriptionRef.current;
      const revEl = reviewsRef.current;
      if (!descEl || !revEl) return;

      const scrollPosition = window.scrollY;
      const offset = 120; // scroll offset buffer

      const descTop = descEl.getBoundingClientRect().top + scrollPosition;
      const revTop = revEl.getBoundingClientRect().top + scrollPosition;

      if (scrollPosition + offset >= revTop) {
        setActiveTab('reviews');
      } else if (scrollPosition + offset >= descTop) {
        setActiveTab('description');
      } else {
        setActiveTab(null);
      }
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [product]);

  // Related products scroll
  const relatedScrollRef = useRef<HTMLDivElement>(null);
  const [isHoveringRelated, setIsHoveringRelated] = useState(false);

  const scrollRelatedLeft = () => {
    if (relatedScrollRef.current) {
      relatedScrollRef.current.scrollBy({ left: -240, behavior: 'smooth' });
    }
  };

  const scrollRelatedRight = () => {
    if (relatedScrollRef.current) {
      const { scrollLeft, scrollWidth, clientWidth } = relatedScrollRef.current;
      if (scrollLeft + clientWidth >= scrollWidth - 10) {
        relatedScrollRef.current.scrollTo({ left: 0, behavior: 'smooth' });
      } else {
        relatedScrollRef.current.scrollBy({ left: 240, behavior: 'smooth' });
      }
    }
  };

  useEffect(() => {
    if (isHoveringRelated || related.length <= 4) return;
    const interval = setInterval(() => {
      scrollRelatedRight();
    }, 3500);
    return () => clearInterval(interval);
  }, [related, isHoveringRelated]);


  // Review form
  const [writeRating, setWriteRating] = useState<number>(0);
  const [writeComment, setWriteComment] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [submitSuccess, setSubmitSuccess] = useState(false);

  const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

  const isFirstSlugRender = useRef(true);
  const pendingScrollRestoreRef = useRef(false);

  /* fetch */
  useEffect(() => {
    if (!slug) return;
    const cacheKey = `product_detail_cache_${slug}`;
    
    // Check if we need to restore scroll position (only on initial render of this slug)
    if (isFirstSlugRender.current) {
      isFirstSlugRender.current = false;
      const saved = sessionStorage.getItem(scrollSaveKey);
      if (saved && parseInt(saved, 10) > 0) {
        pendingScrollRestoreRef.current = true;
        isRestoringRef.current = true; // block scroll-saving during loading
      }
    } else {
      sessionStorage.removeItem(scrollSaveKey);
      scrollRestoredRef.current = true;
      pendingScrollRestoreRef.current = false;
      window.scrollTo(0, 0);
    }

    // Load from cache first for instant render
    let hasCache = false;
    if (typeof window !== 'undefined') {
      try {
        const cached = sessionStorage.getItem(cacheKey);
        if (cached) {
          const parsed = JSON.parse(cached);
          if (parsed.product) {
            setProduct(parsed.product);
            setRelated(parsed.related || []);
            const main = parsed.product.image_url.startsWith('http') ? parsed.product.image_url : `${backendUrl}${parsed.product.image_url}`;
            setSelectedImage(main);
            if (parsed.product.variants?.length) {
              const first = parsed.product.variants.find((v: any) => v.quantity > 0) || parsed.product.variants[0];
              const opts: Record<string, string> = {};
              Object.entries(first?.options || {}).forEach(([k, v]) => { opts[k] = v as string; });
              setSelectedOptions(opts);
            }
            setLoading(false);
            hasCache = true;
          }
        }
      } catch (e) {
        console.error('Failed to parse product cache', e);
      }
    }

    if (!hasCache) {
      setLoading(true);
    }

    api.get(`/api/products/${slug}`)
      .then(res => {
        const p: Product = res.data.product;
        const rel = res.data.related || [];
        setProduct(p);
        setRelated(rel);
        const main = p.image_url.startsWith('http') ? p.image_url : `${backendUrl}${p.image_url}`;
        setSelectedImage(main);
        
        // Only set default options if they haven't been selected yet
        if (p.variants?.length) {
          const first = p.variants.find(v => v.quantity > 0) || p.variants[0];
          const opts: Record<string, string> = {};
          Object.entries(first?.options || {}).forEach(([k, v]) => { opts[k] = v; });
          setSelectedOptions(prev => Object.keys(prev).length === 0 ? opts : prev);
        }

        // Cache the result
        if (typeof window !== 'undefined') {
          try {
            sessionStorage.setItem(cacheKey, JSON.stringify({ product: p, related: rel }));
          } catch (e) {
            console.error('Failed to write product cache', e);
          }
        }
      })
      .catch(() => {
        if (!hasCache) {
          setProduct(null);
        }
      })
      .finally(() => setLoading(false));
  }, [slug]);

  /* Restore scroll AFTER product is fully rendered (loading = false) */
  useEffect(() => {
    if (loading) return;
    if (!pendingScrollRestoreRef.current) return;
    pendingScrollRestoreRef.current = false;
    const saved = sessionStorage.getItem(scrollSaveKey);
    if (!saved) {
      isRestoringRef.current = false;
      return;
    }
    const pos = parseInt(saved, 10);
    if (isNaN(pos) || pos <= 0) {
      isRestoringRef.current = false;
      return;
    }
    setTimeout(() => {
      isRestoringRef.current = true;
      window.scrollTo({ top: pos, behavior: 'smooth' });
      scrollRestoredRef.current = true;
      // Re-enable saving after smooth scroll animation finishes (~600ms)
      // and lock in the correct target position
      setTimeout(() => {
        isRestoringRef.current = false;
        sessionStorage.setItem(scrollSaveKey, String(pos));
      }, 700);
    }, 120);
  }, [loading, scrollSaveKey]);

  /* match variant + trigger price animation */
  useEffect(() => {
    if (!product?.variants?.length) { setMatchedVariant(null); return; }
    const m = product.variants.find(v =>
      Object.entries(selectedOptions).every(([k, val]) => v.options[k] === val)
    );
    setMatchedVariant(m || null);
    setPriceKey(k => k + 1); // animate price on variant change
  }, [selectedOptions, product]);

  /* review submit */
  const handleReviewSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!product) return;
    if (!writeRating || writeRating < 1 || writeRating > 5) {
      setSubmitError('Please select a rating.');
      return;
    }
    setSubmitting(true); setSubmitError(''); setSubmitSuccess(false);
    try {
      const res = await api.post('/api/reviews', { product_id: product.id, rating: writeRating, comment: writeComment });
      if (res.data.success) {
        setSubmitSuccess(true); setWriteComment(''); setWriteRating(0);
        const r2 = await api.get(`/api/products/${slug}`);
        setProduct(r2.data.product);
      }
    } catch (err: any) {
      setSubmitError(err.response?.data?.message || 'Failed to submit review.');
    } finally { setSubmitting(false); }
  };
  const isVariant = product ? product.variants?.length > 0 : false;
  const targetVariantId = isVariant && matchedVariant ? matchedVariant.id : null;
  const existingCartItem = product
    ? cartItems.find(item => item.product_id === product.id && item.variant_id === targetVariantId)
    : undefined;
  const isInCart = !!existingCartItem;

  useEffect(() => {
    if (existingCartItem) {
      setQuantity(existingCartItem.quantity);
    } else {
      setQuantity(1);
    }
  }, [existingCartItem]);

  /* loading / not found */
  if (loading) return (
    <>
      <Header />
      <main className="bg-[#f5f5f5] min-h-screen pb-0 lg:pb-8 animate-pulse animate-fade-in">
        {/* Breadcrumb Skeleton */}
        <nav className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8 pt-4 pb-4 flex items-center gap-2">
          <div className="h-4 bg-slate-200 rounded w-12"></div>
          <div className="h-3 bg-slate-200 rounded w-3"></div>
          <div className="h-4 bg-slate-200 rounded w-16"></div>
          <div className="h-3 bg-slate-200 rounded w-3"></div>
          <div className="h-4 bg-slate-350 rounded w-28"></div>
        </nav>

        <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8 space-y-6">
          {/* Product Hero Card Skeleton */}
          <div className="bg-white rounded-2xl border border-slate-200/60 overflow-hidden shadow-xs">
            <div className="grid grid-cols-1 lg:grid-cols-2">
              
              {/* LEFT: Image Gallery Skeleton */}
              <div className="px-2 py-3 lg:p-8 border-b lg:border-b-0 lg:border-r border-slate-100 flex flex-col-reverse md:flex-row gap-4">
                {/* Thumbnails */}
                <div className="flex md:flex-col gap-2 md:w-20">
                  {[...Array(4)].map((_, i) => (
                    <div key={i} className="h-16 w-16 md:w-20 md:h-20 bg-slate-200 rounded-lg"></div>
                  ))}
                </div>
                {/* Main Image */}
                <div className="flex-1 aspect-square bg-slate-200 rounded-xl"></div>
              </div>

              {/* RIGHT: Product Details Skeleton */}
              <div className="p-4 sm:p-6 lg:p-8 flex flex-col justify-between space-y-6">
                <div className="space-y-4">
                  {/* Category */}
                  <div className="h-4 bg-slate-200 rounded w-24"></div>
                  {/* Title */}
                  <div className="h-8 bg-slate-200 rounded w-3/4"></div>
                  {/* Rating */}
                  <div className="flex items-center gap-2">
                    <div className="flex gap-1">
                      {[...Array(5)].map((_, i) => (
                        <div key={i} className="h-4 w-4 bg-slate-200 rounded-full"></div>
                      ))}
                    </div>
                    <div className="h-4 bg-slate-200 rounded w-20"></div>
                  </div>
                  {/* Price */}
                  <div className="flex items-baseline gap-3">
                    <div className="h-8 bg-slate-300 rounded w-24"></div>
                    <div className="h-6 bg-slate-250 rounded w-16"></div>
                  </div>
                  {/* Divider */}
                  <div className="border-t border-slate-100"></div>
                  {/* Short description */}
                  <div className="space-y-2">
                    <div className="h-3.5 bg-slate-200 rounded w-full"></div>
                    <div className="h-3.5 bg-slate-200 rounded w-5/6"></div>
                    <div className="h-3.5 bg-slate-200 rounded w-4/5"></div>
                  </div>
                </div>

                <div className="space-y-4 pt-4">
                  {/* Quantity selector / Add to Cart / Buy Now buttons */}
                  <div className="flex flex-col sm:flex-row gap-3">
                    <div className="h-12 bg-slate-200 rounded-xl w-full sm:w-32"></div>
                    <div className="h-12 bg-slate-300 rounded-xl flex-1"></div>
                    <div className="h-12 bg-slate-300 rounded-xl flex-1"></div>
                  </div>
                  {/* Meta */}
                  <div className="space-y-2 pt-2 border-t border-slate-100">
                    <div className="h-4 bg-slate-200 rounded w-32"></div>
                    <div className="h-4 bg-slate-200 rounded w-28"></div>
                  </div>
                </div>
              </div>

            </div>
          </div>

          {/* Description & Reviews Tabs Skeleton */}
          <div className="bg-white rounded-2xl border border-slate-200/60 p-6 space-y-4">
            <div className="flex gap-4 border-b border-slate-100 pb-3">
              <div className="h-8 bg-slate-300 rounded w-28"></div>
              <div className="h-8 bg-slate-200 rounded w-24"></div>
            </div>
            <div className="space-y-2">
              <div className="h-4 bg-slate-200 rounded w-full"></div>
              <div className="h-4 bg-slate-200 rounded w-full"></div>
              <div className="h-4 bg-slate-200 rounded w-3/4"></div>
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );

  if (!product) return (
    <><Header />
      <div className="mx-auto max-w-7xl px-4 py-20 text-center space-y-4">
        <Package className="h-16 w-16 text-slate-300 mx-auto" />
        <h2 className="text-xl font-black text-slate-800">Product not found</h2>
        <button onClick={() => router.push('/shop')}
          className="inline-flex items-center gap-2 px-5 py-2.5 bg-secondary text-white rounded-xl text-sm font-bold shadow-md hover:bg-secondary-dark transition-colors">
          <ArrowLeft className="h-4 w-4" /> Back to Shop
        </button>
      </div>
    <Footer /></>
  );

  /* derived values */
  // Admin panel: "Price" = current selling price, "Compare at price" = original/crossed-out price
  const currentPrice = isVariant
    ? (matchedVariant?.price && Number(matchedVariant.price) > 0 ? Number(matchedVariant.price) : Number(product.price))
    : Number(product.price);

  let originalPrice: number | null = null;
  if (isVariant && matchedVariant) {
    const comparePrice = product.compare_at_price ? Number(product.compare_at_price) : null;
    const mPrice = (matchedVariant.price && Number(matchedVariant.price) > 0) ? Number(matchedVariant.price) : Number(product.price);
    if (comparePrice && comparePrice > mPrice) {
      originalPrice = comparePrice;
    }
  } else if (!isVariant) {
    if (product.compare_at_price && Number(product.compare_at_price) > currentPrice) {
      originalPrice = Number(product.compare_at_price);
    }
  }

  const currentStock = isVariant ? (matchedVariant?.quantity ?? 0) : product.quantity;
  const currentSku = isVariant ? (matchedVariant?.sku ?? product.sku) : product.sku;
  const discount = originalPrice && originalPrice > currentPrice
    ? Math.round((1 - currentPrice / originalPrice) * 100) : 0;

  const optionGroups: Record<string, string[]> = {};
  product.variants.forEach(v => {
    Object.entries(v.options || {}).forEach(([k, val]) => {
      if (!optionGroups[k]) optionGroups[k] = [];
      if (!optionGroups[k].includes(val)) optionGroups[k].push(val);
    });
  });

  const allSelected = Object.keys(selectedOptions).length === Object.keys(optionGroups).length;
  const isOutOfStock = isVariant ? (!matchedVariant || matchedVariant.quantity <= 0) : product.quantity <= 0;
  const canAddToCart = !adding && allSelected && !isOutOfStock;



  const reviews = product.reviews || [];
  const avg = avgRating(reviews);
  const recCount = reviews.filter(r => r.rating >= 4).length;
  const pctRec = reviews.length ? (recCount / reviews.length) * 100 : 0;
  const ratingCounts = [5, 4, 3, 2, 1].map(s => ({
    star: s,
    count: reviews.filter(r => r.rating === s).length,
    pct: reviews.length ? Math.round((reviews.filter(r => r.rating === s).length / reviews.length) * 100) : 0,
  }));

  const handleQuantityChange = async (newVal: number) => {
    setQuantity(newVal);
    if (isInCart && existingCartItem) {
      try {
        await updateQuantity(existingCartItem.id, newVal);
      } catch (err: any) {
        console.error('Failed to update quantity', err);
      }
    }
  };

  const handleAddToCart = async () => {
    if (!product) return;
    if (isVariant && (!allSelected || !matchedVariant)) { alert('Please select all options'); return; }
    setAdding(true);
    try {
      if (isInCart && existingCartItem) {
        await removeItem(existingCartItem.id);
      } else {
        await addToCart(product.id, targetVariantId, quantity, false, product);
        setAddSuccess(true);
        setTimeout(() => setAddSuccess(false), 2500);
      }
    } catch (err: any) {
      alert(err.message || 'Action failed');
    } finally { setAdding(false); }
  };

  const handleBuyNow = async () => {
    if (isVariant && (!allSelected || !matchedVariant)) { alert('Please select all options'); return; }
    if (isInCart) {
      router.push('/checkout');
      return;
    }
    setAdding(true);
    try {
      await addToCart(product.id, isVariant && matchedVariant ? matchedVariant.id : null, quantity, false, product);
      router.push('/checkout');
    } catch (err: any) {
      alert(err.message || 'Failed to add to cart');
    } finally { setAdding(false); }
  };

  const imgUrl = (url: string) => url.startsWith('http') ? url : `${backendUrl}${url}`;
  const allImages = product.all_images?.length ? product.all_images : [{ url: product.image_url, webp: null }];

  const handlePrevImage = () => {
    const idx = allImages.findIndex(img => imgUrl(img.url) === selectedImage);
    if (idx > 0) {
      setSelectedImage(imgUrl(allImages[idx - 1].url));
    } else {
      setSelectedImage(imgUrl(allImages[allImages.length - 1].url));
    }
  };

  const handleNextImage = () => {
    const idx = allImages.findIndex(img => imgUrl(img.url) === selectedImage);
    if (idx < allImages.length - 1) {
      setSelectedImage(imgUrl(allImages[idx + 1].url));
    } else {
      setSelectedImage(imgUrl(allImages[0].url));
    }
  };

  return (
    <>
      <Header />
      <main className="bg-[#f5f5f5] min-h-screen pb-0 lg:pb-8 animate-fade-in">

        {/* ── Breadcrumb ── */}
        <nav className="breadcrumb-nav mx-auto max-w-7xl px-2 sm:px-6 lg:px-8 pt-0 pb-0 lg:py-[12px] flex items-center gap-1.5 text-[13px] lg:text-[14px] text-[#666666] font-open-sans font-medium flex-wrap">
          <Link href="/" className="hover:text-secondary transition-colors">Home</Link>
          <ChevronRight className="h-3 w-3 text-slate-400" />
          <span className="text-[#666666] font-semibold">Products</span>
        </nav>

        <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8 pt-0 pb-6 space-y-6">

          {/* ── Product Hero Card ── */}
          <div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-0">

              {/* LEFT: Image Gallery */}
              <div className="px-2 py-3 lg:p-8 border-b lg:border-b-0 lg:border-r border-slate-100">
                <div className="flex flex-col-reverse md:flex-row gap-2 md:gap-4">
                  {/* Thumbnails (vertical on desktop, horizontal on mobile) */}
                  {allImages.length > 1 && (
                    <div className="flex md:flex-col gap-2 md:gap-3 overflow-x-auto md:overflow-y-auto pb-1 md:pb-0 shrink-0 md:w-20 max-h-[500px]">
                      {allImages.map((img, idx) => {
                        const url = imgUrl(img.url);
                        const active = selectedImage === url;
                        return (
                          <button
                            key={idx}
                            type="button"
                            onClick={() => setSelectedImage(url)}
                            className={`relative flex-shrink-0 h-16 w-16 md:w-20 md:h-20 rounded-lg overflow-hidden border-2 transition-all ${
                              active ? 'border-secondary shadow-md' : 'border-slate-200 hover:border-slate-400'
                            }`}
                          >
                            <Image src={url} alt="" fill sizes="(max-width: 768px) 64px, 80px" className="object-cover" />
                            {active && (
                              <div className="absolute inset-0 bg-secondary/15 flex items-center justify-center">
                                <div className="bg-secondary text-white rounded-full p-0.5 shadow-sm">
                                  <Check className="h-3 w-3 stroke-[3]" />
                                </div>
                              </div>
                            )}
                          </button>
                        );
                      })}
                    </div>
                  )}

                  {/* Main image */}
                  <div className="relative flex-1 aspect-square overflow-hidden rounded-xl bg-slate-50 border border-slate-100 cursor-zoom-in group">
                    <Image
                      src={selectedImage}
                      alt={product.name}
                      fill
                      sizes="(max-width: 1024px) 100vw, 50vw"
                      className="object-contain object-center transition-transform duration-300 group-hover:scale-105"
                      onClick={() => setLightboxOpen(true)}
                      priority={true}
                    />
                    {discount > 0 && (
                      <span className="absolute top-3 left-3 bg-green-500 text-white text-[11px] font-black px-2 py-1 rounded-md shadow z-10">
                        -{discount}%
                      </span>
                    )}
                    {isOutOfStock && (
                      <div className="absolute inset-0 bg-white/70 flex items-center justify-center z-10">
                        <span className="bg-red-500 text-white font-black px-4 py-2 rounded-lg text-sm">Out of Stock</span>
                      </div>
                    )}
                    <div className="absolute top-3 right-3 bg-white/80 backdrop-blur-sm rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity z-10">
                      <ZoomIn className="h-4 w-4 text-slate-600" />
                    </div>

                    {/* Navigation Arrows */}
                    {allImages.length > 1 && (
                      <>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            handlePrevImage();
                          }}
                          className="absolute left-3 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white text-slate-450 hover:text-slate-600 rounded-full p-1.5 shadow-md transition-all z-10"
                        >
                          <ChevronLeft className="h-5 w-5" />
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleNextImage();
                          }}
                          className="absolute right-3 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white text-blue-500 rounded-full p-1.5 shadow-md transition-all z-10"
                        >
                          <ChevronRight className="h-5 w-5" />
                        </button>
                      </>
                    )}
                  </div>
                </div>
              </div>

              {/* RIGHT: Product Info */}
              <div className="px-2 py-4 lg:p-8 flex flex-col gap-4 lg:gap-5 justify-between">
                <div className="space-y-4">
                  {/* Title */}
                  <div>
                    <h1 className="text-[18px] lg:text-[24px] font-normal text-slate-800 leading-snug font-open-sans">{product.name}</h1>
                    {reviews.length > 0 && (
                      <div className="flex items-center gap-3 mt-2">
                        <button onClick={() => scrollToSection('reviews')} className="flex items-center gap-1.5 group">
                          <StarRow rating={avg} />
                          <span className="text-xs text-slate-500 font-semibold group-hover:text-secondary transition-colors">({reviews.length})</span>
                        </button>
                      </div>
                    )}
                  </div>

                  {/* Price Block with Divider */}
                  <div className="mb-4 border-b border-slate-100">
                    <div className="flex items-center gap-3 flex-wrap">
                      <span
                        key={priceKey}
                        className="text-[18px] lg:text-[26px] font-normal text-secondary font-open-sans variant-price-animate"
                      >
                        {formatPrice(currentPrice)}
                      </span>
                      {originalPrice && originalPrice > currentPrice && (
                        <span className="text-lg font-normal text-slate-400 line-through font-open-sans">{formatPrice(originalPrice)}</span>
                      )}
                      {discount > 0 && (
                        <span className="text-[11px] sm:text-xs font-bold text-white bg-[#24b35c] px-2 py-0.5 rounded-md ml-1 whitespace-nowrap">
                          Save {discount}%
                        </span>
                      )}
                    </div>
                    {user?.role === 'reseller' && product.reseller_price !== undefined && (
                      <div className="mt-3 inline-flex flex-col gap-1 bg-emerald-50 text-emerald-800 p-2.5 rounded-xl border border-emerald-100 font-open-sans text-xs font-medium min-w-[200px] text-left">
                        <div>Reseller Cost: <span className="font-medium text-xs">{formatPrice(product.reseller_price)}</span></div>
                        <div className="text-emerald-600">Reseller Profit: <span className="font-medium text-xs">{formatPrice(currentPrice - Number(product.reseller_price))}</span></div>
                      </div>
                    )}
                  </div>

                  {/* ── Variant Selectors ── */}
                  {isVariant && (
                    <div className="space-y-4">
                      {Object.entries(optionGroups).map(([key, values]) => {
                        const isColor = isColorAttr(key);
                        return (
                          <div key={key} className="space-y-3">
                            {/* Attribute label */}
                            <div className="flex items-baseline gap-2">
                              <span className="text-[14px] md:text-[15px] font-semibold md:font-bold text-slate-900 font-open-sans">
                                {isColor ? 'রং বাছাই করুন:' : 'বাছাই করুন:'}
                              </span>
                            </div>

                            {/* Swatches or Pills */}
                            <div className="flex flex-wrap gap-1.5 sm:gap-2">
                              {values.map(val => {
                                const isSelected = selectedOptions[key] === val;
                                const isDisabled = !product.variants.some(
                                  v => v.options[key] === val && v.quantity > 0
                                );
                                const cssColor = isColor ? getCssColor(val) : null;

                                if (isColor && cssColor) {
                                  /* ── Color Swatch ── */
                                  const isLight = ['white', 'off white', 'off-white', 'cream', 'ivory', 'silver', 'beige'].includes(val.toLowerCase().trim());
                                  return (
                                    <div key={val} className="relative group/swatch">
                                      <button
                                        type="button"
                                        disabled={isDisabled}
                                        title={val}
                                        onClick={() => setSelectedOptions(prev => ({ ...prev, [key]: val }))}
                                        className={`relative h-8 w-8 rounded-full transition-all duration-200 flex items-center justify-center ${
                                          isSelected
                                            ? 'ring-2 ring-secondary ring-offset-2 scale-110'
                                            : isDisabled
                                              ? 'opacity-35 cursor-not-allowed'
                                              : 'hover:ring-2 hover:ring-slate-400 hover:ring-offset-1 hover:scale-105'
                                        } ${isLight ? 'border border-slate-300' : ''}`}
                                        style={{ backgroundColor: cssColor }}
                                      >
                                        {isSelected && (
                                          <Check
                                            className={`h-3.5 w-3.5 stroke-[3] ${
                                              isLight ? 'text-slate-700' : 'text-white'
                                            }`}
                                          />
                                        )}
                                        {isDisabled && (
                                          <div className="absolute inset-0 rounded-full overflow-hidden">
                                            <div className="absolute top-1/2 left-0 right-0 h-[1.5px] bg-red-400 rotate-45 origin-center" />
                                          </div>
                                        )}
                                      </button>
                                      {/* Color name tooltip */}
                                      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-0.5 bg-slate-800 text-white text-[10px] font-semibold rounded whitespace-nowrap opacity-0 group-hover/swatch:opacity-100 transition-opacity pointer-events-none z-20">
                                        {val}{isDisabled ? ' (Out of Stock)' : ''}
                                      </div>
                                    </div>
                                  );
                                }

                                /* ── Pill Button ── */
                                const matchingVar = product.variants.find(
                                  v => v.options[key] === val &&
                                       Object.entries(selectedOptions).every(([k, sVal]) => k === key || v.options[k] === sVal)
                                );
                                
                                let optDiscount = 0;
                                if (matchingVar) {
                                  let comparePrice = product.compare_at_price ? Number(product.compare_at_price) : null;
                                  let sellPrice = product.sale_price ? Number(product.sale_price) : Number(product.price);
                                  
                                  if (!comparePrice && product.price > sellPrice) {
                                    comparePrice = Number(product.price);
                                  }
                                  
                                  if (!comparePrice) {
                                    comparePrice = sellPrice * 1.25;
                                  }

                                  const mPrice = (matchingVar.price && Number(matchingVar.price) > 0) ? Number(matchingVar.price) : sellPrice;
                                  const ratio = mPrice / sellPrice;
                                  const varCompare = comparePrice * ratio;
                                  
                                  if (varCompare > mPrice) {
                                    let pct = Math.round((1 - mPrice / varCompare) * 100);
                                    if (ratio > 1) {
                                      pct += Math.round((ratio - 1) * 6);
                                    } else if (ratio < 1) {
                                      pct -= Math.round((1 - ratio) * 4);
                                    }
                                    optDiscount = Math.max(5, pct);
                                  }
                                }

                                return (
                                  <div key={val} className="relative group/pill">
                                    <button
                                      type="button"
                                      disabled={isDisabled}
                                      onClick={() => setSelectedOptions(prev => ({ ...prev, [key]: val }))}
                                      className={`relative px-2 py-1.5 sm:px-4 sm:py-2 rounded-lg text-[11px] sm:text-[14px] font-medium border-2 transition-all duration-200 flex items-center justify-between shadow-xs ${
                                        isSelected
                                          ? 'bg-[#f4f7eb] border-[#8bbd40] text-slate-900 shadow-sm'
                                          : isDisabled
                                            ? 'bg-slate-50 border-slate-100 text-slate-300 cursor-not-allowed'
                                            : 'bg-white border-slate-200/80 text-slate-700 hover:border-[#8bbd40] hover:shadow-xs'
                                      }`}
                                    >
                                      <span>
                                        {isDisabled ? <s>{val}</s> : val}
                                      </span>
                                      {!isDisabled && optDiscount > 0 && (
                                        <span className="ml-1 sm:ml-2.5 px-1 sm:px-1.5 py-0.5 text-[8px] sm:text-[9px] font-bold text-[#d12c2c] bg-slate-100 rounded-md whitespace-nowrap">
                                          {optDiscount}% OFF
                                        </span>
                                      )}
                                    </button>
                                    {/* Out of stock tooltip for pills */}
                                    {isDisabled && (
                                      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-0.5 bg-slate-800 text-white text-[10px] font-semibold rounded whitespace-nowrap opacity-0 group-hover/pill:opacity-100 transition-opacity pointer-events-none z-20">
                                        Out of Stock
                                      </div>
                                    )}
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        );
                      })}

                      {/* ── Selected variant summary removed ── */}
                    </div>
                  )}

                  {/* Quantity & Actions Block */}
                  <div className="space-y-4">
                    {/* Quantity Selector Row */}
                    {!isOutOfStock && (
                      <div className="flex items-center gap-4">
                        <span className="text-sm font-semibold text-slate-700 w-16 font-open-sans">Quantity:</span>
                        <div className="flex items-center border border-slate-200 rounded-lg overflow-hidden bg-white w-[140px] h-[40px] sm:w-[160px] sm:h-12 select-none">
                          <button
                            type="button"
                            onClick={() => handleQuantityChange(Math.max(1, quantity - 1))}
                            className="w-[35px] sm:w-[40px] h-full flex items-center justify-center bg-slate-50 hover:bg-slate-100 text-slate-500 hover:text-slate-700 cursor-pointer border-r border-slate-200 transition-colors"
                          >
                            <Minus className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
                          </button>
                          <span className="flex-1 text-center text-[15px] sm:text-base font-semibold text-slate-800 font-open-sans">{quantity}</span>
                          <button
                            type="button"
                            onClick={() => handleQuantityChange(Math.min(currentStock, quantity + 1))}
                            className="w-[35px] sm:w-[40px] h-full flex items-center justify-center bg-slate-50 hover:bg-slate-100 text-slate-500 hover:text-slate-700 cursor-pointer border-l border-slate-200 transition-colors"
                          >
                            <Plus className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
                          </button>
                        </div>
                      </div>
                    )}

                    {/* Actions Grid */}
                    <div className="space-y-4">
                      {isOutOfStock ? (
                        /* STOCK OUT Button */
                        <button
                          type="button"
                          className="w-full h-12 flex items-center justify-center rounded-lg text-[12px] md:text-[14px] font-semibold font-open-sans tracking-wider border-2 border-red-500 text-red-500 bg-white transition-all duration-300 hover:bg-red-600 hover:text-white cursor-pointer"
                        >
                          STOCK OUT
                        </button>
                      ) : (
                        /* ADD TO CART & BUY NOW Buttons */
                        <div className="grid grid-cols-2 gap-4">
                          {/* ADD TO CART */}
                          <button
                            type="button"
                            onClick={handleAddToCart}
                            disabled={!canAddToCart}
                            className={`h-12 flex items-center justify-center gap-1 sm:gap-2 rounded-lg text-[12px] md:text-[14px] font-semibold font-open-sans whitespace-nowrap px-1 sm:px-3 transition-all cursor-pointer ${
                              addSuccess
                                ? 'bg-green-500 text-white border-green-500 shadow-none'
                                : !canAddToCart
                                  ? 'bg-slate-100 text-slate-400 cursor-not-allowed border-slate-200 shadow-none'
                                  : 'bg-secondary hover:bg-secondary-dark text-white hover:shadow-md'
                            }`}
                          >
                            {adding ? <Loader2 className="h-4 w-4 animate-spin" />
                              : addSuccess ? <><Check className="h-4 w-4" />ADDED!</>
                              : isInCart ? <><ShoppingBag className="h-4.5 w-4.5 sm:h-5 sm:w-5" />REMOVE FROM CART</>
                              : <><ShoppingBag className="h-4.5 w-4.5 sm:h-5 sm:w-5" />ADD TO CART</>}
                          </button>

                          {/* BUY NOW */}
                          <button
                            type="button"
                            onClick={handleBuyNow}
                            disabled={!canAddToCart}
                            className={`h-12 flex items-center justify-center gap-1 sm:gap-2 rounded-lg text-[12px] md:text-[14px] font-semibold font-open-sans whitespace-nowrap px-1 sm:px-3 transition-all cursor-pointer ${
                              !canAddToCart
                                ? 'bg-slate-100 text-slate-400 cursor-not-allowed'
                                : 'bg-[#051C1A] hover:bg-[#020d0c] text-white hover:shadow-md'
                            }`}
                          >
                            BUY NOW
                          </button>
                        </div>
                      )}

                      {/* WhatsApp & Call For Order (Shown for all states) */}
                      <div className="grid grid-cols-2 gap-4">
                        {/* Order on WhatsApp */}
                        <a
                          href={`https://wa.me/8801XXXXXXXXX?text=I want to order: ${encodeURIComponent(product.name)}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="h-12 flex items-center justify-center gap-1 sm:gap-2 rounded-lg text-[12px] md:text-[14px] font-semibold font-open-sans whitespace-nowrap px-1 sm:px-3 bg-[#13A85B] hover:bg-[#0f8b4a] text-white hover:shadow-md transition-all"
                        >
                          <svg className="h-4 w-4 sm:h-5 sm:w-5 fill-current text-white" viewBox="0 0 24 24">
                            <path d="M12.004 2C6.48 2 2 6.48 2 12.004c0 1.763.46 3.483 1.333 5L2 22l5.127-1.343a9.92 9.92 0 004.877 1.347c5.523 0 10.003-4.478 10.003-10.002C22.007 6.48 17.527 2 12.004 2zm5.727 14.397c-.247.697-1.203 1.258-1.66 1.303-.457.045-.91.229-2.914-.564-2.48-.977-4.08-3.51-4.202-3.674-.123-.165-1.006-1.341-1.006-2.557 0-1.217.636-1.815.864-2.062.228-.247.5-.31.666-.31.165 0 .33.003.473.01.149.007.35-.054.548.423.202.488.69 1.688.75 1.81.062.122.102.264.02.427-.082.164-.123.264-.247.41-.122.145-.26.326-.37.44-.122.123-.25.258-.108.502.143.244.636 1.05 1.36 1.696.932.83 1.715 1.085 1.959 1.206.244.123.385.102.527-.063.143-.164.61-.71.773-.952.163-.243.327-.202.549-.122.223.082 1.41.666 1.655.788.245.123.408.183.47.288.06.105.06 1.026-.187 1.723z" />
                          </svg>
                          Order On WhatsApp
                        </a>

                        {/* Call for Order */}
                        <a
                          href="tel:+8801XXXXXXXXX"
                          className="h-12 flex items-center justify-center gap-1 sm:gap-2 rounded-lg text-[12px] md:text-[14px] font-semibold font-open-sans whitespace-nowrap px-1 sm:px-3 bg-[#1B3C8C] hover:bg-[#153073] text-white hover:shadow-md transition-all"
                        >
                          <svg className="h-4 w-4 sm:h-5 sm:w-5 fill-current text-white" viewBox="0 0 24 24">
                            <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57a1.02 1.02 0 00-1.02.24l-2.2 2.2a15.04 15.04 0 01-6.59-6.59l2.2-2.2a1 1 0 00.25-1.02A11.36 11.36 0 018.5 4c0-.56-.44-1-1-1H4c-.56 0-1 .44-1 1 0 9.39 7.61 17 17 17 .56 0 1-.44 1-1v-3.5c0-.56-.44-1-1-1z" />
                          </svg>
                          Call For Order
                        </a>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Trust badges */}
                <div className="grid grid-cols-3 gap-2 border-t border-slate-100 pt-4">
                  {[
                    { icon: <Truck className="h-4 w-4" />, label: 'Fast Delivery' },
                    { icon: <ShieldCheck className="h-4 w-4" />, label: '100% Original' },
                    { icon: <RotateCcw className="h-4 w-4" />, label: 'Easy Return' },
                  ].map(b => (
                    <div key={b.label} className="flex flex-col items-center gap-1 p-2 rounded-xl bg-slate-50 text-center">
                      <span className="text-secondary">{b.icon}</span>
                      <span className="text-[10px] font-bold text-slate-500">{b.label}</span>
                    </div>
                  ))}
                </div>
              </div>

            </div>
          </div>

          {/* ── Description + Reviews Tabs ── */}
          <div className="space-y-6">
            {/* Tab bar (Pills layout - hidden on mobile) */}
            <div className="sticky top-2 z-20 bg-white/95 backdrop-blur-md rounded-2xl shadow-md border border-slate-100 p-4 hidden lg:flex gap-3 flex-wrap">
              <button
                type="button"
                onClick={() => scrollToSection('description')}
                className={`px-6 py-2.5 rounded-lg text-sm transition-all font-open-sans cursor-pointer ${
                  activeTab === 'description'
                    ? 'bg-primary text-white font-bold'
                    : 'bg-[#f5f5f5] text-slate-700 font-semibold hover:bg-slate-200'
                }`}
              >
                Description
              </button>
              <button
                type="button"
                onClick={() => scrollToSection('reviews')}
                className={`px-6 py-2.5 rounded-lg text-sm transition-all font-open-sans cursor-pointer ${
                  activeTab === 'reviews'
                    ? 'bg-primary text-white font-bold'
                    : 'bg-[#f5f5f5] text-slate-700 font-semibold hover:bg-slate-200'
                }`}
              >
                Customer Reviews ({reviews.length})
              </button>
            </div>

            {/* Description Section Card */}
            <div ref={descriptionRef} className="bg-white rounded-2xl shadow-sm border border-slate-100 p-4 lg:p-10">
              <div className="relative pb-2 mb-4">
                <h2 className="text-[14px] lg:text-[16px] font-bold text-slate-800 font-open-sans">Product Details</h2>
                <div className="absolute bottom-0 left-0 w-12 h-0.5 bg-secondary" />
              </div>
              {product.description ? (
                <div
                  className="prose prose-sm max-w-none text-slate-655 leading-relaxed font-open-sans"
                  dangerouslySetInnerHTML={{ __html: product.description }}
                />
              ) : (
                <p className="text-slate-400 text-sm text-center py-6 font-open-sans">No description available for this product.</p>
              )}
            </div>

            {/* Reviews Section Card */}
            <div ref={reviewsRef} className="bg-white rounded-2xl shadow-sm border border-slate-100 p-4 lg:p-10 space-y-8">

                {/* Summary & Form Grid */}
                <div className={`grid grid-cols-1 lg:grid-cols-12 gap-8 items-start ${reviews.length > 0 ? 'pb-8 border-b border-slate-100' : ''}`}>
                  
                  {/* Left Column: Rating Summary */}
                  <div className="lg:col-span-5 space-y-5">
                    {/* Big number and average rating */}
                    <div className="flex items-center gap-4">
                      <span className="text-5xl font-black text-slate-800 tracking-tight leading-none">
                        {reviews.length ? avg.toFixed(1) : '0.0'}
                      </span>
                      <div className="flex flex-col text-left">
                        <span className="text-xs font-semibold text-slate-500">Average Rating</span>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <StarRow rating={avg} />
                          <span className="text-[11px] text-slate-400 font-medium">({reviews.length} Reviews)</span>
                        </div>
                      </div>
                    </div>

                    {/* Recommended percentage */}
                    <div className="text-left">
                      <div className="flex items-baseline gap-2">
                        <span className="text-2xl font-black text-slate-800 leading-none">{pctRec.toFixed(2)}%</span>
                        <span className="text-xs font-semibold text-slate-550">Recommended</span>
                        <span className="text-[10px] text-slate-400 font-medium">({recCount} of {reviews.length})</span>
                      </div>
                    </div>

                    {/* Bar breakdown */}
                    <div className="space-y-2.5">
                      {ratingCounts.map(({ star, count, pct }) => (
                        <div key={star} className="flex items-center gap-3">
                          <div className="w-[75px] shrink-0">
                            <StarRow rating={star} />
                          </div>
                          <div className="flex-1 bg-slate-100 rounded-full h-2 overflow-hidden">
                            <div
                              className="h-full bg-secondary rounded-full transition-all"
                              style={{ width: `${pct}%` }}
                            />
                          </div>
                          <span className="text-[11px] font-bold text-slate-500 w-8 text-right shrink-0">{pct}%</span>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Right Column: Submit Your Review Form */}
                  <div className="lg:col-span-7 space-y-4">
                    <div className="relative pb-2">
                      <h3 className="text-[14px] lg:text-[26px] font-bold text-slate-800 font-open-sans">Submit Your Review</h3>
                      <div className="absolute bottom-0 left-0 w-12 h-0.5 bg-secondary" />
                    </div>
                    
                    <p className="text-[14px] text-slate-450 font-open-sans">
                      Your email address will not be published. Required fields are marked *
                    </p>

                    {user ? (
                      <form onSubmit={handleReviewSubmit} className="space-y-4">
                        <div>
                          <label className="block text-[14px] font-bold text-slate-700 mb-2 font-open-sans">
                            Write your opinion about the product
                          </label>
                          <textarea
                            required
                            rows={5}
                            value={writeComment}
                            onChange={e => setWriteComment(e.target.value)}
                            placeholder="Write Your Review Here..."
                            className="w-full text-sm p-4 bg-white border border-slate-200 rounded-md focus:border-secondary focus:ring-1 focus:ring-secondary/20 focus:outline-none placeholder:text-slate-400 resize-none font-open-sans"
                          />
                        </div>

                        <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
                          <div className="flex-1">
                            <label className="block text-xs font-bold text-slate-700 mb-2 font-open-sans">Your Rating:</label>
                            <select
                              required
                              value={writeRating || ''}
                              onChange={e => setWriteRating(Number(e.target.value))}
                              className="w-full text-sm p-3 bg-white border border-slate-200 rounded-md focus:border-secondary focus:ring-1 focus:ring-secondary/20 focus:outline-none text-slate-700"
                            >
                              <option value="">Select One</option>
                              <option value="5">Perfect</option>
                              <option value="4">Good</option>
                              <option value="3">Average</option>
                              <option value="2">Not that bad</option>
                              <option value="1">Very poor</option>
                            </select>
                          </div>
                          <button
                            type="submit"
                            disabled={submitting}
                            className="bg-[#333333] hover:bg-black text-white text-xs font-bold uppercase tracking-widest py-3.5 px-8 transition-colors flex items-center justify-center gap-2 shrink-0 cursor-pointer h-[46px]"
                          >
                            {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
                            SUBMIT REVIEW
                          </button>
                        </div>
                        {submitError && <div className="p-3 bg-red-50 border border-red-100 rounded-lg text-red-650 text-xs font-semibold font-open-sans">{submitError}</div>}
                        {submitSuccess && <div className="p-3 bg-green-50 border border-green-100 rounded-lg text-green-650 text-xs font-semibold font-open-sans">Review submitted successfully!</div>}
                      </form>
                    ) : (
                      <div className="space-y-4">
                        <div className="opacity-50 pointer-events-none space-y-4">
                          <div>
                            <label className="block text-[14px] font-bold text-slate-700 mb-2 font-open-sans">
                              Write your opinion about the product
                            </label>
                            <textarea
                              disabled
                              rows={5}
                              placeholder="Write Your Review Here..."
                              className="w-full text-sm p-4 bg-white border border-slate-200 rounded-md placeholder:text-slate-400 resize-none font-open-sans"
                            />
                          </div>

                          <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
                            <div className="flex-1">
                              <label className="block text-xs font-bold text-slate-700 mb-2 font-open-sans">Your Rating:</label>
                              <select disabled className="w-full text-sm p-3 bg-white border border-slate-200 rounded-md text-slate-400">
                                <option>Select One</option>
                              </select>
                            </div>
                            <button disabled className="bg-slate-300 text-white text-xs font-bold uppercase tracking-widest py-3.5 px-8 h-[46px]">
                              SUBMIT REVIEW
                            </button>
                          </div>
                        </div>
                        <div className="flex items-center justify-between p-4 bg-slate-50 border border-slate-200 rounded-xl mt-4">
                          <p className="text-sm text-slate-600 font-medium font-open-sans">Login to submit a review</p>
                          <button
                            onClick={() => router.push(`/login?redirect=/products/${product.slug}`)}
                            className="px-5 py-2.5 bg-secondary text-white rounded-lg text-xs font-bold hover:bg-secondary-dark transition-colors cursor-pointer font-open-sans shadow-sm"
                          >
                            Login Now
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Review list */}
                {reviews.length > 0 && (
                  <div className="space-y-6 divide-y divide-slate-100">
                    {reviews.map((rev, idx) => (
                      <div key={rev.id || idx} className="pt-6 first:pt-0 space-y-2">
                        <div className="flex items-start justify-between gap-4">
                          <div className="flex items-center gap-3">
                            <div className="w-9 h-9 rounded-full bg-gradient-to-br from-orange-400 to-rose-500 flex items-center justify-center text-white font-black text-sm flex-shrink-0">
                              {(rev.user?.name || 'A')[0].toUpperCase()}
                            </div>
                            <div>
                              <p className="text-sm font-bold text-slate-800">{rev.user?.name || 'Verified Buyer'}</p>
                              <span className="text-[11px] font-semibold text-green-600 bg-green-50 px-1.5 py-0.5 rounded flex items-center gap-1 w-fit">
                                <Check className="h-2.5 w-2.5" />Verified Purchase
                              </span>
                            </div>
                          </div>
                          <span className="text-[11px] text-slate-400 font-medium shrink-0">
                            {new Date(rev.created_at).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })}
                          </span>
                        </div>
                        <StarRow rating={rev.rating} />
                        {rev.comment && <p className="text-sm text-slate-600 leading-relaxed">{rev.comment}</p>}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

          {/* ── Related Products ── */}
          {related.length > 0 && (
            <div className="space-y-4">
              <div className="flex items-center justify-between border-b border-slate-200/60 pb-2 mb-4 relative">
                <h2 className="text-lg font-black text-slate-800 font-open-sans">Related Products</h2>
                <div className="absolute bottom-0 left-0 w-12 h-0.5 bg-secondary" />
                <div className="flex items-center gap-4">
                  {/* Desktop navigation arrows */}
                  <div className="hidden md:flex items-center gap-1.5">
                    <button
                      type="button"
                      onClick={scrollRelatedLeft}
                      className="p-1.5 rounded-full border border-slate-200 bg-white hover:bg-slate-50 transition-colors text-slate-600 cursor-pointer shadow-sm hover:border-slate-350"
                    >
                      <ChevronLeft className="h-4 w-4" />
                    </button>
                    <button
                      type="button"
                      onClick={scrollRelatedRight}
                      className="p-1.5 rounded-full border border-slate-200 bg-white hover:bg-slate-50 transition-colors text-slate-600 cursor-pointer shadow-sm hover:border-slate-350"
                    >
                      <ChevronRight className="h-4 w-4" />
                    </button>
                  </div>
                  <Link href={`/shop${product.category ? `?category=${product.category.slug}` : ''}`}
                    className="text-xs font-bold text-secondary hover:text-secondary-dark transition-colors flex items-center gap-1 font-open-sans">
                    More Products <ChevronRight className="h-3.5 w-3.5" />
                  </Link>
                </div>
              </div>
              <div 
                className="flex overflow-x-auto gap-4 pb-3 no-scrollbar"
                ref={relatedScrollRef}
                onMouseEnter={() => setIsHoveringRelated(true)}
                onMouseLeave={() => setIsHoveringRelated(false)}
              >
                {related.map(prod => (
                  <div key={prod.id} className="flex-shrink-0 w-[165px] sm:w-[210px]">
                    <ProductCard product={prod} />
                  </div>
                ))}
              </div>
            </div>
          )}

        </div>


      </main>

      {/* ── Image Lightbox ── */}
      {lightboxOpen && (
        <div className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4" onClick={() => setLightboxOpen(false)}>
          <button className="absolute top-4 right-4 text-white bg-white/20 rounded-full p-2 hover:bg-white/30 transition-colors">
            <X className="h-6 w-6" />
          </button>
          <img src={selectedImage} alt={product.name} className="max-h-[90vh] max-w-[90vw] object-contain rounded-lg" onClick={e => e.stopPropagation()} />
        </div>
      )}

      <Footer />
    </>
  );
}