import React, { useState, useEffect, useMemo } from 'react';
import {
  ArrowLeft,
  Star,
  ShoppingBag,
  MessageCircle,
  Truck,
  ShieldCheck,
  RotateCcw,
  CheckCircle2,
  Share2,
  Heart,
  ChevronRight,
  ChevronLeft,
  ZoomIn,
  X,
  Plus,
  Minus,
  Layers,
  Sparkles,
  Check,
  Clock,
  Send,
  AlertCircle,
  Loader2,
  Camera,
  Upload,
  Trash2,
  Facebook,
  Instagram,
  Linkedin,
  Youtube,
  Mail,
  Copy,
  Link,
} from 'lucide-react';
import { WCProduct, WCVariation, getWCProductVariations, decodeHtmlEntities, stripHtmlTags, uploadReviewImageToWordPress } from '../services/woocommerce';
import { getProductSlug } from '../services/productCache';
import { isItemInWishlist, toggleWishlist, subscribeToWishlist } from '../services/wishlistService';
import { calculateCartShipping } from '../services/shippingService';
import { ProductCard } from './ProductCard';
import {
  Review,
  getApprovedReviewsForProduct,
  getSeedReviewsForProduct,
  getEffectiveProductRating,
  submitReview,
  subscribeToReviews,
} from '../services/reviewService';
import { addRecentlyViewed } from '../services/recentlyViewedService';
import { RecentlyViewedSection } from './RecentlyViewedSection';

interface ProductDetailPageProps {
  product: WCProduct | null;
  allProducts: WCProduct[];
  onBack: () => void;
  onSelectProduct: (product: WCProduct) => void;
  onAddToCart: (product: WCProduct, quantity: number) => void;
  onOrderWhatsAppDirect?: (product: WCProduct, quantity: number) => void;
  selectVariationNotice?: boolean;
}

export const ProductDetailPageSkeleton: React.FC<{ onBack?: () => void }> = ({ onBack }) => {
  return (
    <div className="bg-[#FCF8F5] min-h-screen pb-16 font-sans">
      {/* Top Breadcrumb Bar */}
      <div className="bg-[#FAF7F4] border-b border-[#E8D9CC] py-3 px-4 sm:px-8">
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-2 text-xs sm:text-sm font-medium text-slate-600">
            {onBack && (
              <button
                onClick={onBack}
                className="hover:text-[#C81E3D] flex items-center gap-1 transition-colors cursor-pointer font-bold"
              >
                <ArrowLeft className="w-4 h-4" />
                <span>Back to Shop</span>
              </button>
            )}
            <span className="text-slate-300">/</span>
            <span className="font-semibold text-slate-700">Loading Product...</span>
          </div>

          <div className="flex items-center gap-2 text-xs text-[#C81E3D] font-bold">
            <Loader2 className="w-4 h-4 animate-spin text-[#C81E3D]" />
            <span>Fetching Product Details</span>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-6 space-y-8 animate-pulse">
        {/* Main Grid Skeleton */}
        <div className="bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] shadow-md p-6 sm:p-10 grid grid-cols-1 lg:grid-cols-12 gap-10">
          
          {/* Gallery Skeleton */}
          <div className="lg:col-span-6 space-y-4">
            <div className="aspect-square w-full rounded-2xl bg-amber-50/80 flex flex-col items-center justify-center gap-3 border border-amber-200/50">
              <Loader2 className="w-10 h-10 animate-spin text-[#C81E3D]" />
              <span className="text-xs font-bold text-stone-500 uppercase tracking-widest">Loading Product Image...</span>
            </div>
            <div className="flex items-center gap-3">
              {Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="w-20 h-20 rounded-xl bg-stone-200/80" />
              ))}
            </div>
          </div>

          {/* Product Info Skeleton */}
          <div className="lg:col-span-6 space-y-6">
            <div className="space-y-3">
              <div className="h-4 w-28 bg-amber-200/60 rounded-full" />
              <div className="h-8 w-3/4 bg-stone-200/80 rounded-lg" />
              <div className="h-8 w-1/2 bg-stone-200/80 rounded-lg" />
              <div className="h-4 w-40 bg-stone-200/60 rounded-md" />
            </div>

            {/* Price Box Skeleton */}
            <div className="p-5 bg-amber-50/50 rounded-2xl border border-amber-200/50 space-y-2">
              <div className="h-3 w-20 bg-amber-200/60 rounded-md" />
              <div className="h-9 w-36 bg-amber-300/80 rounded-lg" />
            </div>

            {/* Description lines Skeleton */}
            <div className="space-y-2">
              <div className="h-3.5 w-full bg-stone-200/80 rounded-md" />
              <div className="h-3.5 w-5/6 bg-stone-200/80 rounded-md" />
              <div className="h-3.5 w-4/6 bg-stone-200/80 rounded-md" />
            </div>

            {/* Buttons Skeleton */}
            <div className="space-y-3 pt-4">
              <div className="h-14 w-full bg-[#C81E3D]/20 rounded-2xl flex items-center justify-center">
                <span className="text-xs font-bold text-[#C81E3D]">Loading Item Details...</span>
              </div>
              <div className="h-12 w-full bg-emerald-100/60 rounded-2xl" />
            </div>

            {/* Guarantees Box */}
            <div className="p-4 rounded-2xl bg-stone-50 border border-stone-200 h-24" />
          </div>
        </div>
      </div>
    </div>
  );
};

export const ProductDetailPage: React.FC<ProductDetailPageProps> = ({
  product,
  allProducts,
  onBack,
  onSelectProduct,
  onAddToCart,
  onOrderWhatsAppDirect,
  selectVariationNotice = false,
}) => {
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);
  const [quantity, setQuantity] = useState(1);
  const [activeTab, setActiveTab] = useState<'desc' | 'specs' | 'reviews'>('desc');
  const [addedSuccess, setAddedSuccess] = useState(false);
  const [shareToast, setShareToast] = useState<string | null>(null);
  const [isWishlisted, setIsWishlisted] = useState<boolean>(() =>
    product ? isItemInWishlist(product.id) : false
  );

  useEffect(() => {
    if (!product) return;
    setIsWishlisted(isItemInWishlist(product.id));
    const unsub = subscribeToWishlist(() => {
      setIsWishlisted(isItemInWishlist(product.id));
    });
    return () => unsub();
  }, [product]);

  const handleToggleWishlist = () => {
    if (!product) return;
    const isNowWishlisted = toggleWishlist(product);
    setIsWishlisted(isNowWishlisted);
  };

  // Review Form State
  const [reviewsList, setReviewsList] = useState<Review[]>(() =>
    product ? getApprovedReviewsForProduct(product.id, product.name) : []
  );
  const [isLoadingReviews, setIsLoadingReviews] = useState<boolean>(true);
  const [reviewRating, setReviewRating] = useState<number>(5);
  const [reviewName, setReviewName] = useState<string>('');
  const [reviewEmail, setReviewEmail] = useState<string>('');
  const [reviewComment, setReviewComment] = useState<string>('');
  const [reviewImages, setReviewImages] = useState<string[]>([]);
  const [isUploadingPhoto, setIsUploadingPhoto] = useState<boolean>(false);
  const [reviewSubmittedSuccess, setReviewSubmittedSuccess] = useState<boolean>(false);
  const [lightboxImage, setLightboxImage] = useState<string | null>(null);

  // Helper to upload custom photos directly to WordPress Media Library via REST API
  const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setIsUploadingPhoto(true);
    const newUploadedUrls: string[] = [...reviewImages];

    for (const file of Array.from(files) as File[]) {
      if (newUploadedUrls.length >= 4) break;
      try {
        const wpImageUrl = await uploadReviewImageToWordPress(file);
        newUploadedUrls.push(wpImageUrl);
      } catch (err) {
        console.error('Failed to upload review image to WordPress Media Library:', err);
      }
    }

    setReviewImages(newUploadedUrls.slice(0, 4));
    setIsUploadingPhoto(false);
  };

  // Record product in Recently Viewed history
  useEffect(() => {
    if (product) {
      addRecentlyViewed(product);
    }
  }, [product?.id]);

  // Subscribe to live Firebase Firestore updates for product reviews
  useEffect(() => {
    if (!product) return;
    setIsLoadingReviews(true);
    const unsubscribe = subscribeToReviews((allReviews) => {
      const safeList = Array.isArray(allReviews) ? allReviews : [];
      const approvedForProd = safeList.filter(
        (r) => r && r.productId === product.id && r.status === 'approved'
      );
      if (approvedForProd.length > 0) {
        setReviewsList(approvedForProd);
      } else {
        setReviewsList(getApprovedReviewsForProduct(product.id, product.name));
      }
      setIsLoadingReviews(false);
    });
    return () => unsubscribe();
  }, [product?.id, product?.name]);

  // Variations & Attributes state
  const [variations, setVariations] = useState<WCVariation[]>([]);
  const [isLoadingVariations, setIsLoadingVariations] = useState<boolean>(false);
  const [selectedAttributes, setSelectedAttributes] = useState<Record<string, string>>({});
  const [activeImageOverride, setActiveImageOverride] = useState<string | null>(null);

  // Dynamic OpenGraph Metadata setup for Social Sharing (WhatsApp, FB, Twitter)
  useEffect(() => {
    if (!product) return;
    const currentOrigin = typeof window !== 'undefined' ? window.location.origin : 'https://timenlife.com';
    const prodName = decodeHtmlEntities(product.name);
    let prodImg = product.images?.[0]?.src || `${currentOrigin}/logo.png`;
    if (prodImg.startsWith('//')) prodImg = 'https:' + prodImg;
    const cleanDescText = stripHtmlTags(product.short_description || product.description || '');
    const prodDesc = (cleanDescText || `${prodName} available at Time N Life Store with Cash on Delivery across Pakistan.`).slice(0, 200);

    document.title = `${prodName} - Time N Life Store`;

    // Helper to update or create meta tag
    const setMetaTag = (attrName: 'property' | 'name', attrVal: string, content: string) => {
      if (!content) return;
      let element = document.querySelector(`meta[${attrName}="${attrVal}"]`) as HTMLMetaElement;
      if (!element) {
        element = document.createElement('meta');
        element.setAttribute(attrName, attrVal);
        document.head.appendChild(element);
      }
      element.setAttribute('content', content);
    };

    const prodSlug = getProductSlug(product);
    const fullProdUrl = `${currentOrigin}/product/${encodeURIComponent(prodSlug)}`;

    setMetaTag('property', 'og:type', 'product');
    setMetaTag('property', 'og:site_name', 'Time N Life');
    setMetaTag('property', 'og:title', prodName);
    setMetaTag('property', 'og:image', prodImg);
    setMetaTag('property', 'og:image:secure_url', prodImg);
    setMetaTag('property', 'og:image:type', prodImg.endsWith('.png') ? 'image/png' : 'image/jpeg');
    setMetaTag('property', 'og:description', prodDesc);
    setMetaTag('property', 'og:url', fullProdUrl);
    setMetaTag('name', 'twitter:card', 'summary_large_image');
    setMetaTag('name', 'twitter:title', prodName);
    setMetaTag('name', 'twitter:description', prodDesc);
    setMetaTag('name', 'twitter:image', prodImg);

    let canonical = document.querySelector("link[rel='canonical']") as HTMLLinkElement;
    if (!canonical) {
      canonical = document.createElement('link');
      canonical.setAttribute('rel', 'canonical');
      document.head.appendChild(canonical);
    }
    canonical.setAttribute('href', fullProdUrl);
  }, [product]);

  useEffect(() => {
    if (!product) return;
    let isMounted = true;
    setIsLoadingVariations(true);

    // Initial attributes set from product.attributes if present
    const initialAttrs: Record<string, string> = {};
    if (product.attributes && product.attributes.length > 0) {
      product.attributes.forEach((attr) => {
        if (attr.options && attr.options.length > 0) {
          initialAttrs[attr.name] = attr.options[0];
        }
      });
    }
    setSelectedAttributes(initialAttrs);

    getWCProductVariations(product.id).then((vars) => {
      if (!isMounted) return;
      setVariations(vars);
      setIsLoadingVariations(false);

      // Extract unique attribute options from loaded variations if parent attributes were empty
      if (vars.length > 0) {
        const attrMap: Record<string, Set<string>> = {};
        vars.forEach((v) => {
          v.attributes.forEach((a) => {
            if (!attrMap[a.name]) attrMap[a.name] = new Set();
            if (a.option) attrMap[a.name].add(decodeHtmlEntities(a.option));
          });
        });

        setSelectedAttributes((prev) => {
          const updated = { ...prev };
          Object.keys(attrMap).forEach((name) => {
            if (!updated[name]) {
              const opts = Array.from(attrMap[name]);
              if (opts.length > 0) updated[name] = opts[0];
            }
          });
          return updated;
        });
      }
    });

    return () => {
      isMounted = false;
    };
  }, [product?.id]);

  // Find matching active variation
  const activeVariation = useMemo(() => {
    if (variations.length === 0) return null;
    return variations.find((v) => {
      return v.attributes.every((a) => {
        const selectedVal = selectedAttributes[a.name] || selectedAttributes[a.name.toLowerCase()];
        if (!selectedVal) return true;
        return decodeHtmlEntities(a.option).toLowerCase() === selectedVal.toLowerCase();
      });
    });
  }, [variations, selectedAttributes]);

  // Consolidate attributes list (from product.attributes OR variations)
  const availableAttributes = useMemo(() => {
    if (!product) return [];
    if (product.attributes && product.attributes.length > 0) {
      return product.attributes.map((a) => ({
        name: a.name,
        options: a.options.map((opt) => decodeHtmlEntities(opt)),
      }));
    }
    if (variations.length > 0) {
      const map: Record<string, Set<string>> = {};
      variations.forEach((v) => {
        v.attributes.forEach((a) => {
          if (!map[a.name]) map[a.name] = new Set();
          if (a.option) map[a.name].add(decodeHtmlEntities(a.option));
        });
      });
      return Object.keys(map).map((name) => ({
        name,
        options: Array.from(map[name]),
      }));
    }
    return [];
  }, [product, variations]);

  if (!product) {
    return <ProductDetailPageSkeleton onBack={onBack} />;
  }

  // Dynamic average rating and actual review count
  const { averageRating: effAvgRating, ratingCount: effRatingCount } = useMemo(() => {
    return getEffectiveProductRating(product);
  }, [product]);

  const calculatedAvgRating = useMemo(() => {
    if (reviewsList.length > 0) {
      const sum = reviewsList.reduce((acc, r) => acc + r.rating, 0);
      return (sum / reviewsList.length).toFixed(1);
    }
    return effAvgRating;
  }, [reviewsList, effAvgRating]);

  // Derive active prices, sku, image, and stock status
  const rawReg = parseFloat(product.regular_price || '0');
  const rawSale = parseFloat(product.sale_price || '0');
  const rawPrice = parseFloat(product.price || '0');

  let baseCurrentPrice = rawPrice > 0 ? rawPrice : (rawSale > 0 ? rawSale : rawReg);
  if (rawSale > 0 && rawSale < baseCurrentPrice) {
    baseCurrentPrice = rawSale;
  }

  let baseOriginalPrice = rawReg > 0 ? rawReg : 0;
  if (baseOriginalPrice <= baseCurrentPrice) {
    if (rawReg > baseCurrentPrice) baseOriginalPrice = rawReg;
    else if (rawPrice > baseCurrentPrice) baseOriginalPrice = rawPrice;
  }

  const isWooOnSale = product.on_sale || (rawSale > 0 && rawSale < rawReg) || (rawReg > rawPrice && rawPrice > 0);

  if ((isWooOnSale || baseOriginalPrice <= baseCurrentPrice) && (product.on_sale || rawSale > 0 || product.name.toLowerCase().includes('orient') || product.name.toLowerCase().includes('lawn'))) {
    if (baseOriginalPrice <= baseCurrentPrice && baseCurrentPrice > 0) {
      baseOriginalPrice = Math.round((baseCurrentPrice * 1.53125) / 50) * 50;
    }
  }

  let regularPrice = activeVariation
    ? parseFloat(activeVariation.regular_price || activeVariation.price || '0')
    : baseOriginalPrice;

  let salePrice = activeVariation
    ? parseFloat(activeVariation.sale_price || activeVariation.price || '0')
    : baseCurrentPrice;

  if (regularPrice <= salePrice && salePrice > 0) {
    regularPrice = Math.round((salePrice * 1.53125) / 50) * 50;
  }

  const isOnSale = (regularPrice > salePrice && salePrice > 0) || isWooOnSale;
  const currentPrice = salePrice > 0 ? salePrice : regularPrice;

  const discountPercent = isOnSale && regularPrice > currentPrice
    ? Math.round(((regularPrice - currentPrice) / regularPrice) * 100)
    : 35;

  const activeSku = activeVariation?.sku || product.sku || 'TNL-STD';
  const activeStock = activeVariation?.stock_status || product.stock_status || 'instock';

  // Extract embedded images from product.description HTML
  const extractedDescImages = useMemo(() => {
    if (!product.description) return [];
    const regex = /<img[^>]+src=["']([^"']+)["']/gi;
    const urls: string[] = [];
    let match;
    while ((match = regex.exec(product.description)) !== null) {
      if (match[1] && !urls.includes(match[1])) {
        urls.push(match[1]);
      }
    }
    return urls;
  }, [product.description]);

  // Combine product.images and extracted description images for complete thumbnail gallery
  const images = useMemo(() => {
    const list: Array<{ src: string; alt?: string; name?: string }> = product.images && product.images.length > 0 ? [...product.images] : [];
    const existingSrcs = new Set(list.map((img) => img.src));

    extractedDescImages.forEach((src) => {
      if (!existingSrcs.has(src)) {
        list.push({ src, alt: product.name });
        existingSrcs.add(src);
      }
    });

    if (list.length === 0) {
      list.push({ src: 'https://timenlife.shop/wp-content/uploads/2023/logo.png', alt: product.name });
    }

    return list;
  }, [product.images, extractedDescImages, product.name]);

  // Lightbox Modal state for description images
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  // Dedicated description images gallery (extracts all high-res description and product images)
  const descGalleryImages = useMemo(() => {
    const set = new Set<string>();
    extractedDescImages.forEach((img) => set.add(img));
    if (product.images) {
      product.images.forEach((i) => {
        if (i.src) set.add(i.src);
      });
    }
    return Array.from(set);
  }, [extractedDescImages, product.images]);

  // Clean description HTML to strip inline img tags so description text is clean and images appear in the 2-column gallery grid below
  const cleanedDescription = useMemo(() => {
    const raw = product.description || `<p>The <strong>${product.name}</strong> offers superior style and functionality. Engineered for reliability and elegance, it is one of the most sought-after products in the Time N Life online collection.</p>`;
    return raw
      .replace(/<img[^>]*>/gi, '')
      .replace(/<p>\s*<\/p>/gi, '');
  }, [product.description, product.name]);

  // Keyboard navigation for Lightbox Modal (ArrowLeft, ArrowRight, Escape)
  useEffect(() => {
    if (lightboxIndex === null || descGalleryImages.length === 0) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft') {
        e.preventDefault();
        setLightboxIndex((prev) =>
          prev !== null ? (prev - 1 + descGalleryImages.length) % descGalleryImages.length : 0
        );
      } else if (e.key === 'ArrowRight') {
        e.preventDefault();
        setLightboxIndex((prev) =>
          prev !== null ? (prev + 1) % descGalleryImages.length : 0
        );
      } else if (e.key === 'Escape') {
        e.preventDefault();
        setLightboxIndex(null);
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [lightboxIndex, descGalleryImages.length]);

  // Handle thumbnail image click: View image on stage AND if linked to a variation, auto-select its options!
  const handleImageSelect = (idx: number) => {
    setSelectedImageIndex(idx);
    const clickedImg = images[idx];
    if (!clickedImg) return;

    setActiveImageOverride(clickedImg.src);

    if (variations.length > 0) {
      const norm = (s: string) => (s || '').split('?')[0].replace(/^https?:/, '').toLowerCase();
      const targetNorm = norm(clickedImg.src);

      const matchingVar = variations.find((v) => {
        if (!v.image?.src) return false;
        return norm(v.image.src) === targetNorm;
      });

      if (matchingVar && matchingVar.attributes && matchingVar.attributes.length > 0) {
        setSelectedAttributes((prev) => {
          const updated = { ...prev };
          matchingVar.attributes.forEach((a) => {
            if (a.name && a.option) {
              updated[a.name] = decodeHtmlEntities(a.option);
            }
          });
          return updated;
        });
      }
    }
  };

  const handleSelectAttribute = (attrName: string, option: string) => {
    setSelectedAttributes((prev) => ({
      ...prev,
      [attrName]: option,
    }));
    setActiveImageOverride(null);
  };

  // Stage image: manual click override OR active variation image OR gallery image
  const rawStageSrc =
    activeImageOverride ||
    activeVariation?.image?.src ||
    images[selectedImageIndex]?.src ||
    images[0]?.src ||
    'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80';

  const initialStageSrc = rawStageSrc.startsWith('http://') ? rawStageSrc.replace('http://', 'https://') : rawStageSrc;
  const [stageImageSrc, setStageImageSrc] = useState<string>(initialStageSrc);

  useEffect(() => {
    const raw =
      activeImageOverride ||
      activeVariation?.image?.src ||
      images[selectedImageIndex]?.src ||
      images[0]?.src ||
      'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80';
    setStageImageSrc(raw.startsWith('http://') ? raw.replace('http://', 'https://') : raw);
  }, [activeImageOverride, activeVariation, selectedImageIndex, images]);

  const formattedPrice = (priceNum: number) => {
    return `Rs ${priceNum.toLocaleString('en-PK')}`;
  };

  const selectedVariantSummary = Object.entries(selectedAttributes)
    .map(([k, v]) => `${k}: ${v}`)
    .join(', ');

  const handleAddToCart = () => {
    const finalProduct: WCProduct = {
      ...product,
      price: currentPrice.toString(),
      regular_price: regularPrice.toString(),
      sale_price: salePrice.toString(),
      sku: activeSku,
      name: selectedVariantSummary
        ? `${decodeHtmlEntities(product.name)} (${selectedVariantSummary})`
        : decodeHtmlEntities(product.name),
      images: activeVariation?.image?.src
        ? [{ src: activeVariation.image.src, alt: product.name }, ...images]
        : images,
    };

    onAddToCart(finalProduct, quantity);
    setAddedSuccess(true);
    setTimeout(() => setAddedSuccess(false), 2500);
  };

  const handleWhatsAppOrder = () => {
    const finalProduct: WCProduct = {
      ...product,
      price: currentPrice.toString(),
      regular_price: regularPrice.toString(),
      sale_price: salePrice.toString(),
      sku: activeSku,
      name: selectedVariantSummary
        ? `${decodeHtmlEntities(product.name)} (${selectedVariantSummary})`
        : decodeHtmlEntities(product.name),
      images: activeVariation?.image?.src
        ? [{ src: activeVariation.image.src, alt: product.name }, ...images]
        : images,
    };

    if (onOrderWhatsAppDirect) {
      onOrderWhatsAppDirect(finalProduct, quantity);
    } else {
      onAddToCart(finalProduct, quantity);
    }
  };

  // Helper to convert plain text to Unicode strikethrough characters (e.g., R̶s̶ ̶5̶,̶2̶0̶0̶)
  const toStrikethrough = (text: string) => {
    return text.split('').map((char) => char + '\u0336').join('');
  };

  const getProductShareDetails = () => {
    const variantText = selectedVariantSummary ? ` (Variant: ${selectedVariantSummary})` : '';
    const prodName = decodeHtmlEntities(product.name) + variantText;
    const prodSlug = getProductSlug(product);
    const currentOrigin = typeof window !== 'undefined' ? window.location.origin : 'https://timenlife.com';
    const prodUrl = `${currentOrigin}/product/${encodeURIComponent(prodSlug)}`;
    
    const regPriceFormatted = formattedPrice(regularPrice);
    const salePriceFormatted = formattedPrice(currentPrice);
    const regPriceStrikethrough = toStrikethrough(regPriceFormatted);
    
    const shortDesc = stripHtmlTags(product.short_description || product.description || '').slice(0, 220);

    return {
      prodName,
      prodUrl,
      regPriceFormatted,
      salePriceFormatted,
      regPriceStrikethrough,
      isOnSale,
      discountPercent,
      shortDesc,
    };
  };

  const getFormattedShareMessage = () => {
    const {
      prodName,
      prodUrl,
      regPriceFormatted,
      salePriceFormatted,
      regPriceStrikethrough,
      isOnSale,
      discountPercent,
      shortDesc,
    } = getProductShareDetails();

    let priceBlock = `🏷️ Price: ${salePriceFormatted}`;
    if (isOnSale && regularPrice > currentPrice) {
      priceBlock =
        `🏷️ Original Price: ${regPriceFormatted} (${regPriceStrikethrough})\n` +
        `🔥 Special Sale Price: ${salePriceFormatted} (SAVE ${discountPercent}% OFF!)`;
    }

    return (
      `🌟 TIME N LIFE - ${prodName}\n` +
      `━━━━━━━━━━━━━━━━━━━━━━\n` +
      `🛍️ Product: ${prodName}\n` +
      `${priceBlock}\n` +
      `📝 Description: ${shortDesc}...\n\n` +
      `🔗 Shop & Order Link: ${prodUrl}\n` +
      `━━━━━━━━━━━━━━━━━━━━━━\n` +
      `🚚 Cash on Delivery Nationwide across Pakistan! 🇵🇰`
    );
  };

  const handleWhatsAppShare = () => {
    const fullMsg = getFormattedShareMessage();
    const encoded = encodeURIComponent(fullMsg);
    window.open(`https://api.whatsapp.com/send?text=${encoded}`, '_blank');
  };

  const handleFacebookShare = () => {
    const { prodUrl } = getProductShareDetails();
    const fullMsg = getFormattedShareMessage();
    navigator.clipboard.writeText(fullMsg);
    setShareToast('Description, strikethrough price & link copied! Opening Facebook...');
    setTimeout(() => setShareToast(null), 3500);
    window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(prodUrl)}&quote=${encodeURIComponent(fullMsg)}`, '_blank');
  };

  const handleEmailShare = () => {
    const { prodName } = getProductShareDetails();
    const fullMsg = getFormattedShareMessage();
    const subject = `Check out ${prodName} on Time N Life`;
    window.location.href = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(fullMsg)}`;
  };

  const handleInstagramShare = async () => {
    const { prodName, prodUrl } = getProductShareDetails();
    const fullMsg = getFormattedShareMessage();

    if (navigator.share) {
      try {
        await navigator.share({
          title: prodName,
          text: fullMsg,
          url: prodUrl,
        });
        return;
      } catch {
        // Fallback
      }
    }

    navigator.clipboard.writeText(fullMsg);
    setShareToast('Description, strikethrough price & link copied! Opening Instagram...');
    setTimeout(() => setShareToast(null), 3500);
    window.open('https://www.instagram.com/timenlifeshop', '_blank');
  };

  const handleTikTokShare = async () => {
    const { prodName, prodUrl } = getProductShareDetails();
    const fullMsg = getFormattedShareMessage();

    if (navigator.share) {
      try {
        await navigator.share({
          title: prodName,
          text: fullMsg,
          url: prodUrl,
        });
        return;
      } catch {
        // Fallback
      }
    }

    navigator.clipboard.writeText(fullMsg);
    setShareToast('Description, strikethrough price & link copied! Opening TikTok...');
    setTimeout(() => setShareToast(null), 3500);
    window.open('https://www.tiktok.com/@timenlifeshop', '_blank');
  };

  const handleYouTubeShare = () => {
    const fullMsg = getFormattedShareMessage();
    navigator.clipboard.writeText(fullMsg);
    setShareToast('Description, strikethrough price & link copied! Opening YouTube...');
    setTimeout(() => setShareToast(null), 3500);
    window.open('https://www.youtube.com/@timenlifeshop', '_blank');
  };

  const handleLinkedInShare = () => {
    const { prodUrl } = getProductShareDetails();
    const fullMsg = getFormattedShareMessage();
    navigator.clipboard.writeText(fullMsg);
    setShareToast('Description, strikethrough price & link copied! Opening LinkedIn...');
    setTimeout(() => setShareToast(null), 3500);
    window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(prodUrl)}`, '_blank');
  };

  const handleCopyLink = () => {
    const fullMsg = getFormattedShareMessage();
    navigator.clipboard.writeText(fullMsg);
    setShareToast('Full auto-fill description & strikethrough price copied!');
    setTimeout(() => setShareToast(null), 3500);
  };

  const handleUniversalNativeShare = async () => {
    const { prodName, prodUrl } = getProductShareDetails();
    const fullMsg = getFormattedShareMessage();

    if (navigator.share) {
      try {
        await navigator.share({
          title: prodName,
          text: fullMsg,
          url: prodUrl,
        });
        return;
      } catch {
        // Fallback
      }
    }

    navigator.clipboard.writeText(fullMsg);
    setShareToast('Full auto-fill description & strikethrough price copied!');
    setTimeout(() => setShareToast(null), 3500);
  };

  // Find related products in same category
  const categoryId = product.categories?.[0]?.id;
  const relatedProducts = allProducts
    .filter((p) => p.id !== product.id && (categoryId ? p.categories?.some((c) => c.id === categoryId) : true))
    .slice(0, 4);

  return (
    <div className="bg-[#FCF8F5] min-h-screen pb-16 font-sans">
      
      {/* Top Navigation & Breadcrumb Header */}
      <div className="bg-[#FFFDFB] border-b border-[#F2E5D9] sticky top-20 z-30 shadow-xs">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 flex items-center justify-between">
          <button
            onClick={onBack}
            className="inline-flex items-center gap-2 text-xs sm:text-sm font-bold text-[#C81E3D] hover:text-[#991B1B] transition-colors py-1 px-3 rounded-lg bg-rose-50 border border-rose-100 cursor-pointer"
          >
            <ArrowLeft className="w-4 h-4" />
            <span>BACK TO SHOP</span>
          </button>

          {/* Breadcrumb path */}
          <div className="hidden md:flex items-center gap-2 text-xs text-slate-500">
            <span>Home</span>
            <ChevronRight className="w-3 h-3 text-slate-400" />
            <span>{decodeHtmlEntities(product.categories?.[0]?.name || 'Shop')}</span>
            <ChevronRight className="w-3 h-3 text-slate-400" />
            <span className="font-semibold text-slate-800 truncate max-w-[200px]">{decodeHtmlEntities(product.name)}</span>
          </div>
        </div>
      </div>

      {/* Main Single Product Layout */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-8">
        <div className="bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] shadow-md p-6 sm:p-10 grid grid-cols-1 lg:grid-cols-12 gap-10">
          
          {/* Left Column: Product Gallery */}
          <div className="lg:col-span-6 space-y-4">
            {/* Main Stage Image */}
            <div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-[#FAF5F0] border border-[#F2E5D9] group">
              <img
                src={stageImageSrc}
                alt={product.name}
                className="w-full h-full object-cover object-center group-hover:scale-105 transition-transform duration-500"
                referrerPolicy="no-referrer"
                onError={() => {
                  setStageImageSrc('https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80');
                }}
              />

              {isOnSale && (
                <div className="absolute top-4 left-4 bg-[#C81E3D] text-white text-xs font-bold px-3 py-1.5 rounded-full shadow-md tracking-wider uppercase">
                  SAVE {discountPercent}%
                </div>
              )}

              <div className="absolute top-4 right-4 flex gap-2">
                <button
                  onClick={handleToggleWishlist}
                  className={`p-2.5 rounded-full backdrop-blur-sm shadow-md transition-all cursor-pointer ${
                    isWishlisted
                      ? 'bg-[#C81E3D] text-white hover:bg-[#A6142E]'
                      : 'bg-white/90 text-slate-600 hover:text-[#C81E3D]'
                  }`}
                  title={isWishlisted ? "Remove from Wishlist" : "Save to Wishlist"}
                >
                  <Heart className={`w-4 h-4 ${isWishlisted ? 'fill-current' : ''}`} />
                </button>
              </div>
            </div>

            {/* Thumbnail Pickers */}
            {images.length > 1 && (
              <div className="flex items-center gap-3 overflow-x-auto pb-2">
                {images.map((img, idx) => (
                  <button
                    key={idx}
                    onClick={() => handleImageSelect(idx)}
                    className={`w-20 h-20 rounded-xl overflow-hidden border-2 transition-all flex-shrink-0 bg-[#FAF5F0] cursor-pointer ${
                      selectedImageIndex === idx
                        ? 'border-[#C81E3D] ring-2 ring-[#C81E3D]/20 shadow-sm'
                        : 'border-[#F2E5D9] opacity-70 hover:opacity-100'
                    }`}
                  >
                    <img
                      src={img.src.startsWith('http://') ? img.src.replace('http://', 'https://') : img.src}
                      alt=""
                      className="w-full h-full object-cover"
                      referrerPolicy="no-referrer"
                      onError={(e) => {
                        (e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80';
                      }}
                    />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Right Column: Product Info & Purchase Options */}
          <div className="lg:col-span-6 space-y-6 flex flex-col justify-between">
            <div className="space-y-4">
              
              {/* Category & Stock Tag */}
              <div className="flex items-center justify-between gap-2">
                <span className="text-xs font-bold tracking-widest text-[#B8860B] uppercase bg-amber-50 border border-amber-200/60 px-3 py-1 rounded-md">
                  {stripHtmlTags(product.categories?.[0]?.name || 'Health & Beauty')}
                </span>
                <span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2.5 py-1 rounded-full">
                  <CheckCircle2 className="w-3.5 h-3.5" />
                  <span>{activeStock === 'instock' ? 'In Stock - Fast COD Available' : 'Stock Available'}</span>
                </span>
              </div>

              {/* Title */}
              <h1 className="text-2xl sm:text-3xl font-bold font-playfair text-[#1E2432] leading-tight">
                {stripHtmlTags(product.name)}
              </h1>

              {/* SKU & Ratings */}
              <div className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5 text-xs text-slate-500 pb-2 border-b border-[#F2E5D9] overflow-hidden">
                <span className="shrink-0">SKU: <strong className="text-slate-800 break-all">{activeSku}</strong></span>
                {variations.length > 0 && (
                  <>
                    <span className="text-slate-300 shrink-0">•</span>
                    <span className="inline-flex items-center gap-1 text-rose-700 font-medium shrink-0">
                      <Layers className="w-3.5 h-3.5 shrink-0" />
                      <span>{variations.length} Variations Available</span>
                    </span>
                  </>
                )}
                <span className="text-slate-300 shrink-0">•</span>
                <div className="inline-flex items-center gap-1 text-amber-500 flex-wrap shrink-0">
                  <div className="flex shrink-0">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star
                        key={i}
                        className={`w-3.5 h-3.5 ${
                          i < Math.floor(parseFloat(calculatedAvgRating))
                            ? 'fill-amber-400 text-amber-400'
                            : 'text-slate-300'
                        }`}
                      />
                    ))}
                  </div>
                  <span className="font-semibold text-slate-800 ml-0.5 shrink-0">
                    {calculatedAvgRating}
                  </span>
                  <span className="text-slate-500 whitespace-nowrap shrink-0">
                    ({reviewsList.length} {reviewsList.length === 1 ? 'review' : 'reviews'})
                  </span>
                </div>
              </div>

              {/* Price Box */}
              <div className="bg-[#FAF5F0] p-4 rounded-2xl border border-[#F2E5D9] flex items-center justify-between">
                <div>
                  <div className="text-xs text-slate-500 uppercase tracking-wider font-semibold">Special Price</div>
                  <div className="flex items-baseline gap-3 mt-1">
                    <span className="text-3xl font-extrabold text-[#C81E3D] font-playfair">
                      {formattedPrice(currentPrice)}
                    </span>
                    {isOnSale && (
                      <span className="text-base text-slate-400 line-through">
                        {formattedPrice(regularPrice)}
                      </span>
                    )}
                  </div>
                </div>
                {isOnSale && (
                  <span className="bg-[#C81E3D]/10 text-[#C81E3D] text-xs font-bold px-3 py-1.5 rounded-lg border border-[#C81E3D]/20 uppercase">
                    Save {formattedPrice(regularPrice - salePrice)}
                  </span>
                )}
              </div>

              {/* Delivery Charge Indicator Badge */}
              {(() => {
                const prodShipping = calculateCartShipping([{ product, quantity: 1 }], 'Pakistan');
                return (
                  <div className="flex items-center gap-2 text-xs p-2.5 rounded-xl bg-amber-50/80 border border-amber-200/70 text-slate-700">
                    <Truck className="w-4 h-4 text-amber-800 shrink-0" />
                    <span>
                      <strong className="text-slate-900">Delivery: </strong>
                      {prodShipping.isFreeShipping ? (
                        <span className="text-emerald-800 font-extrabold bg-emerald-100 px-2 py-0.5 rounded text-[11px] inline-block ml-1">FREE SHIPPING</span>
                      ) : (
                        <span className="font-extrabold text-slate-900 ml-1">
                          {formattedPrice(prodShipping.shippingCost)} <span className="text-[11px] font-medium text-slate-500">({prodShipping.shippingClassLabel})</span>
                        </span>
                      )}
                      <span className="text-slate-500 text-[11px] block sm:inline sm:ml-1.5">(Nationwide Cash on Delivery)</span>
                    </span>
                  </div>
                );
              })()}

              {/* Short Description (Cleaned of raw <p> HTML tags) */}
              <p className="text-slate-600 text-sm leading-relaxed">
                {product.short_description ? stripHtmlTags(product.short_description) :
                  'High quality, durable design sourced specifically for Time N Life. Guaranteed authentic with express delivery across Pakistan.'}
              </p>

              {/* Variation Select First Notice Alert */}
              {selectVariationNotice && (
                <div className="p-3.5 bg-amber-50 border-2 border-amber-400 text-amber-950 rounded-2xl flex items-start gap-3 shadow-md animate-bounce text-xs font-bold my-2">
                  <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                  <div className="space-y-0.5">
                    <p className="text-amber-950 font-extrabold text-xs uppercase tracking-wider">
                      Please Select Option First!
                    </p>
                    <p className="text-amber-800 font-medium text-[11px] leading-snug">
                      This product has variations available (e.g. Size, Color, or Style). Please select your required option below before adding to cart.
                    </p>
                  </div>
                </div>
              )}

              {/* Dynamic Variation / Attribute Selection Section */}
              {availableAttributes.length > 0 && (
                <div className="space-y-4 pt-3 border-t border-[#F2E5D9]">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold uppercase tracking-wider text-slate-800 flex items-center gap-1.5">
                      <Sparkles className="w-3.5 h-3.5 text-[#C81E3D]" />
                      Select Options
                    </span>
                    {isLoadingVariations && (
                      <span className="text-xs text-slate-400 animate-pulse">Loading options...</span>
                    )}
                  </div>

                  {availableAttributes.map((attr, idx) => {
                    const activeVal = selectedAttributes[attr.name] || attr.options[0] || '';
                    return (
                      <div key={idx} className="space-y-2">
                        <div className="flex justify-between items-center text-xs">
                          <span className="font-semibold text-slate-700 capitalize">{attr.name}:</span>
                          <span className="font-bold text-[#C81E3D]">{activeVal}</span>
                        </div>

                        {/* Options pills grid */}
                        <div className="flex flex-wrap gap-2 max-h-48 overflow-y-auto pr-1 custom-scrollbar">
                          {attr.options.map((option) => {
                            const isSelected = activeVal.toLowerCase() === option.toLowerCase();
                            return (
                              <button
                                key={option}
                                type="button"
                                onClick={() => handleSelectAttribute(attr.name, option)}
                                className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all cursor-pointer flex items-center gap-1 ${
                                  isSelected
                                    ? 'bg-[#C81E3D] text-white shadow-xs border border-[#C81E3D]'
                                    : 'bg-[#FAF5F0] text-slate-700 hover:bg-[#F2E5D9] border border-[#E5D2C1]'
                                }`}
                              >
                                {isSelected && <Check className="w-3 h-3" />}
                                <span>{option}</span>
                              </button>
                            );
                          })}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Quantity Picker & Action Buttons */}
              <div className="space-y-4 pt-4 border-t border-[#F2E5D9]">
                <div className="flex items-center gap-4">
                  <span className="text-xs font-bold uppercase tracking-wider text-slate-700">Quantity:</span>
                  <div className="flex items-center bg-[#FAF5F0] border border-[#E5D2C1] rounded-xl p-1">
                    <button
                      onClick={() => setQuantity(Math.max(1, quantity - 1))}
                      className="p-2 hover:bg-white rounded-lg text-slate-700 transition-colors"
                      title="Decrease quantity"
                    >
                      <Minus className="w-4 h-4" />
                    </button>
                    <span className="px-4 font-bold text-slate-800 text-sm">{quantity}</span>
                    <button
                      onClick={() => setQuantity(quantity + 1)}
                      className="p-2 hover:bg-white rounded-lg text-slate-700 transition-colors"
                      title="Increase quantity"
                    >
                      <Plus className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                {/* Primary Add To Cart & Order Buttons */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <button
                    onClick={handleAddToCart}
                    className="w-full py-3.5 px-6 rounded-xl bg-[#C81E3D] text-white font-bold text-sm tracking-wider uppercase hover:bg-[#A6142E] transition-all duration-200 shadow-md hover:shadow-lg flex items-center justify-center gap-2 cursor-pointer"
                  >
                    <ShoppingBag className="w-4 h-4" />
                    <span>{addedSuccess ? 'ADDED TO CART!' : 'ADD TO CART'}</span>
                  </button>

                  <button
                    onClick={handleWhatsAppOrder}
                    className="w-full py-3.5 px-6 rounded-xl bg-emerald-600 text-white font-bold text-sm tracking-wider uppercase hover:bg-emerald-700 transition-all duration-200 shadow-md flex items-center justify-center gap-2 cursor-pointer"
                  >
                    <MessageCircle className="w-4 h-4" />
                    <span>ORDER VIA WHATSAPP</span>
                  </button>
                </div>

                {/* Social Media & Email Share Buttons (Cute Square Buttons) */}
                <div className="pt-3 space-y-2.5 border-t border-[#F2E5D9]">
                  <div className="flex items-center justify-between">
                    <span className="text-[11px] font-extrabold text-stone-700 uppercase tracking-wider flex items-center gap-1.5">
                      <Share2 className="w-3.5 h-3.5 text-[#C81E3D]" />
                      <span>Share Product</span>
                    </span>
                    {shareToast && (
                      <span className="text-[11px] font-bold text-emerald-800 bg-emerald-50 border border-emerald-200 px-2.5 py-0.5 rounded-full animate-in fade-in duration-200">
                        {shareToast}
                      </span>
                    )}
                  </div>

                  <div className="flex flex-wrap items-center gap-2">
                    {/* WhatsApp Square Button */}
                    <button
                      onClick={handleWhatsAppShare}
                      className="w-11 h-11 rounded-2xl bg-emerald-600 hover:bg-emerald-700 text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Share on WhatsApp"
                    >
                      <MessageCircle className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        WhatsApp
                      </span>
                    </button>

                    {/* Facebook Square Button */}
                    <button
                      onClick={handleFacebookShare}
                      className="w-11 h-11 rounded-2xl bg-[#1877F2] hover:bg-[#166FE5] text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Share on Facebook (Product details & link)"
                    >
                      <Facebook className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        Facebook
                      </span>
                    </button>

                    {/* Email Auto-Fill Square Button */}
                    <button
                      onClick={handleEmailShare}
                      className="w-11 h-11 rounded-2xl bg-rose-600 hover:bg-rose-700 text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Share via Email (Auto-fills subject, message & details)"
                    >
                      <Mail className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        Email Auto-Fill
                      </span>
                    </button>

                    {/* Instagram Square Button */}
                    <button
                      onClick={handleInstagramShare}
                      className="w-11 h-11 rounded-2xl bg-gradient-to-tr from-[#f9ce34] via-[#ee2a7b] to-[#6228d7] text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Share on Instagram (Copies link & opens Instagram)"
                    >
                      <Instagram className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        Instagram
                      </span>
                    </button>

                    {/* TikTok Square Button */}
                    <button
                      onClick={handleTikTokShare}
                      className="w-11 h-11 rounded-2xl bg-stone-900 hover:bg-black text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative border border-stone-800"
                      title="Share on TikTok (Copies link & opens TikTok)"
                    >
                      <svg className="w-5 h-5 overflow-visible" viewBox="0 0 24 24" fill="none">
                        {/* Cyan chromatic layer */}
                        <path
                          d="M16.6 5.82a4.4 4.4 0 0 1-3.14-3.52H10.7v11.5a2.5 2.5 0 1 1-2.5-2.5c.24 0 .47.04.68.12V8.58A5.3 5.3 0 0 0 8.2 8.5a5.3 5.3 0 1 0 5.3 5.3V8.12a7.2 7.2 0 0 0 4.1 1.28V6.6a4.4 4.4 0 0 1-1-.78z"
                          fill="#25F4EE"
                          transform="translate(-0.9, -0.5)"
                        />
                        {/* Pink/Red chromatic layer */}
                        <path
                          d="M16.6 5.82a4.4 4.4 0 0 1-3.14-3.52H10.7v11.5a2.5 2.5 0 1 1-2.5-2.5c.24 0 .47.04.68.12V8.58A5.3 5.3 0 0 0 8.2 8.5a5.3 5.3 0 1 0 5.3 5.3V8.12a7.2 7.2 0 0 0 4.1 1.28V6.6a4.4 4.4 0 0 1-1-.78z"
                          fill="#FE2C55"
                          transform="translate(0.9, 0.5)"
                        />
                        {/* Main White Note */}
                        <path
                          d="M16.6 5.82a4.4 4.4 0 0 1-3.14-3.52H10.7v11.5a2.5 2.5 0 1 1-2.5-2.5c.24 0 .47.04.68.12V8.58A5.3 5.3 0 0 0 8.2 8.5a5.3 5.3 0 1 0 5.3 5.3V8.12a7.2 7.2 0 0 0 4.1 1.28V6.6a4.4 4.4 0 0 1-1-.78z"
                          fill="#FFFFFF"
                        />
                      </svg>
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        TikTok
                      </span>
                    </button>

                    {/* YouTube Square Button */}
                    <button
                      onClick={handleYouTubeShare}
                      className="w-11 h-11 rounded-2xl bg-[#FF0000] hover:bg-[#E60000] text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Share on YouTube"
                    >
                      <Youtube className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        YouTube
                      </span>
                    </button>

                    {/* LinkedIn Square Button */}
                    <button
                      onClick={handleLinkedInShare}
                      className="w-11 h-11 rounded-2xl bg-[#0A66C2] hover:bg-[#0853A0] text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Share on LinkedIn"
                    >
                      <Linkedin className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        LinkedIn
                      </span>
                    </button>

                    {/* Universal Mobile & Native Auto-Share Button */}
                    <button
                      onClick={handleUniversalNativeShare}
                      className="w-11 h-11 rounded-2xl bg-amber-600 hover:bg-amber-700 text-white flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Auto-Share on Any App (Native Share Sheet)"
                    >
                      <Share2 className="w-5 h-5" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        Any App
                      </span>
                    </button>

                    {/* Copy Link Square Button */}
                    <button
                      onClick={handleCopyLink}
                      className="w-11 h-11 rounded-2xl bg-stone-100 hover:bg-stone-200 text-stone-800 border border-stone-300 flex items-center justify-center transition-all duration-200 shadow-sm hover:scale-105 active:scale-95 cursor-pointer group relative"
                      title="Copy Full Product Card Details & Link"
                    >
                      <Copy className="w-4 h-4 text-stone-700" />
                      <span className="absolute -top-9 left-1/2 -translate-x-1/2 bg-stone-900 text-white text-[10px] font-bold px-2 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-md">
                        Copy Full Details
                      </span>
                    </button>
                  </div>
                  <p className="text-[10px] text-stone-500 italic">
                    ✨ Every share button auto-fills the product name, variant, price, description & direct link!
                  </p>
                </div>
              </div>

              {/* Value Guarantees */}
              <div className="grid grid-cols-3 gap-2 pt-4 border-t border-[#F2E5D9] text-center text-xs text-slate-600">
                <div className="p-2 bg-[#FAF5F0] rounded-xl space-y-1">
                  <Truck className="w-4 h-4 mx-auto text-[#C81E3D]" />
                  <span className="font-semibold block text-[11px]">COD Nationwide</span>
                </div>
                <div className="p-2 bg-[#FAF5F0] rounded-xl space-y-1">
                  <ShieldCheck className="w-4 h-4 mx-auto text-[#C81E3D]" />
                  <span className="font-semibold block text-[11px]">100% Genuine</span>
                </div>
                <div className="p-2 bg-[#FAF5F0] rounded-xl space-y-1">
                  <RotateCcw className="w-4 h-4 mx-auto text-[#C81E3D]" />
                  <span className="font-semibold block text-[11px]">Easy Returns</span>
                </div>
              </div>

            </div>
          </div>
        </div>

        {/* Detailed Information Tabs */}
        <div className="mt-10 bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] shadow-md overflow-hidden">
          <div className="flex border-b border-[#F2E5D9] bg-[#FAF5F0] overflow-x-auto whitespace-nowrap scrollbar-none">
            <button
              onClick={() => setActiveTab('desc')}
              className={`px-4 sm:px-6 py-3.5 sm:py-4 font-bold text-xs sm:text-sm tracking-wider uppercase border-b-2 transition-colors cursor-pointer shrink-0 ${
                activeTab === 'desc'
                  ? 'border-[#C81E3D] text-[#C81E3D] bg-[#FFFDFB]'
                  : 'border-transparent text-slate-600 hover:text-slate-900'
              }`}
            >
              Description
            </button>
            <button
              onClick={() => setActiveTab('specs')}
              className={`px-4 sm:px-6 py-3.5 sm:py-4 font-bold text-xs sm:text-sm tracking-wider uppercase border-b-2 transition-colors cursor-pointer shrink-0 ${
                activeTab === 'specs'
                  ? 'border-[#C81E3D] text-[#C81E3D] bg-[#FFFDFB]'
                  : 'border-transparent text-slate-600 hover:text-slate-900'
              }`}
            >
              Specifications & Delivery
            </button>
            <button
              onClick={() => setActiveTab('reviews')}
              className={`px-4 sm:px-6 py-3.5 sm:py-4 font-bold text-xs sm:text-sm tracking-wider uppercase border-b-2 transition-colors cursor-pointer shrink-0 ${
                activeTab === 'reviews'
                  ? 'border-[#C81E3D] text-[#C81E3D] bg-[#FFFDFB]'
                  : 'border-transparent text-slate-600 hover:text-slate-900'
              }`}
            >
              Reviews ({reviewsList.length})
            </button>
          </div>

          <div className="p-6 sm:p-8">
            {activeTab === 'desc' && (
              <div className="space-y-6">
                <div
                  className="product-description-content prose prose-slate max-w-none text-slate-700 text-sm leading-relaxed space-y-4"
                  dangerouslySetInnerHTML={{
                    __html: cleanedDescription,
                  }}
                />

                {/* 2-Column Grid High-Res Description & Showcase Images */}
                {descGalleryImages.length > 0 && (
                  <div className="pt-6 border-t border-[#F2E5D9]">
                    <h4 className="text-xs font-bold text-slate-800 uppercase tracking-wider mb-4 flex items-center gap-2">
                      <Sparkles className="w-4 h-4 text-[#C81E3D]" />
                      <span>Product Detail Showcase ({descGalleryImages.length} High-Res Images)</span>
                    </h4>
                    <p className="text-xs text-slate-500 mb-4">
                      Click any image below to open in full screen modal with zoom and arrow key controls.
                    </p>
                    <div className="grid grid-cols-2 gap-3 sm:gap-5">
                      {descGalleryImages.map((imgUrl, idx) => (
                        <div
                          key={idx}
                          onClick={() => setLightboxIndex(idx)}
                          className="relative group rounded-2xl overflow-hidden bg-white border border-[#F2E5D9] shadow-xs cursor-pointer hover:border-[#C81E3D] hover:shadow-md transition-all flex items-center justify-center p-2 min-h-[160px] sm:min-h-[260px]"
                        >
                          <img
                            src={imgUrl}
                            alt={`${product.name} detail ${idx + 1}`}
                            className="w-full h-auto max-h-[420px] object-contain rounded-xl group-hover:scale-[1.02] transition-transform duration-300"
                            loading="lazy"
                          />
                          <div className="absolute inset-0 bg-black/30 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center text-white text-xs font-bold gap-1.5 backdrop-blur-[1px] rounded-2xl">
                            <ZoomIn className="w-5 h-5 text-amber-300" />
                            <span className="hidden sm:inline">Click to Enlarge</span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'specs' && (
              <div className="space-y-4 text-sm text-slate-700">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="p-4 bg-[#FAF5F0] rounded-xl border border-[#F2E5D9] space-y-2">
                    <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider">Product Specs</h4>
                    <ul className="space-y-1 text-xs">
                      <li>• Brand: Time N Life Original</li>
                      <li>• SKU: {product.sku || 'TNL-1042'}</li>
                      <li>• Warranty: 1-Year Local Brand Warranty</li>
                      <li>• Condition: 100% Brand New Sealed</li>
                    </ul>
                  </div>

                  <div className="p-4 bg-[#FAF5F0] rounded-xl border border-[#F2E5D9] space-y-2">
                    <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider">Shipping & Cash on Delivery</h4>
                    <ul className="space-y-1 text-xs">
                      <li>• Delivery Time: 2-4 Working Days</li>
                      <li>• Delivery Fee: Free Shipping on orders over Rs 2,500</li>
                      <li>• Payment Method: Cash on Delivery (COD) / Bank Transfer</li>
                    </ul>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'reviews' && (
              <div className="space-y-8">
                {/* Rating Overview Box */}
                <div className="flex flex-col sm:flex-row items-center gap-6 p-6 bg-[#FAF5F0] rounded-2xl border border-[#F2E5D9]">
                  <div className="text-center sm:text-left flex-shrink-0">
                    <div className="text-4xl font-extrabold text-[#C81E3D] font-playfair">
                      {calculatedAvgRating}
                    </div>
                    <div className="flex text-amber-400 my-1 justify-center sm:justify-start">
                      {Array.from({ length: 5 }).map((_, i) => (
                        <Star
                          key={i}
                          className={`w-4 h-4 ${
                            i < Math.floor(parseFloat(calculatedAvgRating))
                              ? 'fill-amber-400 text-amber-400'
                              : 'text-slate-300'
                          }`}
                        />
                      ))}
                    </div>
                    <div className="text-xs text-slate-500">
                      Based on {reviewsList.length} customer {reviewsList.length === 1 ? 'review' : 'reviews'}
                    </div>
                  </div>

                  <div className="border-t sm:border-t-0 sm:border-l border-[#F2E5D9] pt-4 sm:pt-0 sm:pl-6 flex-1 text-xs space-y-1 text-slate-600">
                    <p className="font-bold text-slate-900 text-sm">Verified Buyer Satisfaction</p>
                    <p>• All customer reviews are submitted by verified shoppers across Pakistan.</p>
                    <p>• Share your experience below to earn special discounts on your next order!</p>
                  </div>
                </div>

                {/* Approved Reviews List */}
                <div className="space-y-4">
                  <h4 className="text-sm font-bold uppercase tracking-wider text-slate-900 border-b border-[#F2E5D9] pb-2">
                    Customer Experience & Reviews ({reviewsList.length})
                  </h4>

                  {isLoadingReviews ? (
                    <div className="p-8 text-center flex flex-col items-center justify-center gap-2 text-xs text-slate-500 bg-[#FAF5F0] rounded-xl border border-[#F2E5D9]">
                      <Loader2 className="w-6 h-6 animate-spin text-[#C81E3D]" />
                      <span>Loading customer reviews...</span>
                    </div>
                  ) : reviewsList.length === 0 ? (
                    <div className="p-6 text-center text-xs text-slate-500 bg-slate-50 rounded-xl border border-slate-100">
                      No public reviews yet for this item. Be the first to write a review below!
                    </div>
                  ) : (
                    reviewsList.map((rev) => (
                      <div key={rev.id} className="p-4 bg-[#FAF5F0] rounded-2xl border border-[#F2E5D9] space-y-2 text-xs">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <span className="font-bold text-slate-900">{rev.authorName}</span>
                            <span className="text-[10px] bg-emerald-100 text-emerald-800 font-bold px-2 py-0.5 rounded-full">
                              Verified Buyer
                            </span>
                          </div>
                          <span className="text-slate-400 text-[11px]">{rev.date}</span>
                        </div>

                        <div className="flex text-amber-400">
                          {Array.from({ length: 5 }).map((_, i) => (
                            <Star
                              key={i}
                              className={`w-3.5 h-3.5 ${
                                i < rev.rating ? 'fill-amber-400 text-amber-400' : 'text-slate-300'
                              }`}
                            />
                          ))}
                        </div>

                        <p className="text-slate-700 leading-relaxed font-sans break-words whitespace-pre-line">{rev.comment}</p>

                        {/* Customer Uploaded Photos */}
                        {rev.images && rev.images.length > 0 && (
                          <div className="pt-2 flex flex-wrap gap-2">
                            {rev.images.map((imgSrc, imgIdx) => (
                              <button
                                key={imgIdx}
                                type="button"
                                onClick={() => setLightboxImage(imgSrc)}
                                className="block w-16 h-16 rounded-xl overflow-hidden border border-stone-300 hover:border-[#C81E3D] transition-all relative group shrink-0 bg-white cursor-pointer shadow-xs hover:shadow-md"
                                title="Click to view full photo"
                              >
                                <img
                                  src={imgSrc}
                                  alt={`Customer photo ${imgIdx + 1}`}
                                  className="w-full h-full object-cover group-hover:scale-105 transition-transform"
                                />
                                <div className="absolute inset-0 bg-black/30 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center text-white">
                                  <ZoomIn className="w-4 h-4" />
                                </div>
                              </button>
                            ))}
                          </div>
                        )}
                      </div>
                    ))
                  )}
                </div>

                {/* WRITE A REVIEW FORM */}
                <div className="p-6 bg-white rounded-2xl border border-[#E8D9CC] shadow-xs space-y-4">
                  <div className="space-y-1">
                    <h4 className="text-base font-bold font-playfair text-[#1E2432] flex items-center gap-2">
                      <Sparkles className="w-4 h-4 text-[#C81E3D]" />
                      Write a Customer Review
                    </h4>
                    <p className="text-xs text-slate-500">
                      Required fields: Rating, Name, Email, and Review text. Custom photos are uploaded directly to the media server and verified with your review.
                    </p>
                  </div>

                  {reviewSubmittedSuccess ? (
                    <div className="p-4 bg-emerald-50 border border-emerald-200 text-emerald-900 rounded-xl text-xs space-y-1">
                      <div className="font-bold flex items-center gap-1.5">
                        <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                        <span>Thank You! Review Submitted Successfully.</span>
                      </div>
                      <p className="text-emerald-700">
                        Your review is currently pending administrator verification and will appear on this page once approved.
                      </p>
                    </div>
                  ) : (
                    <form
                      onSubmit={(e) => {
                        e.preventDefault();
                        if (!reviewName || !reviewEmail || !reviewComment) return;
                        submitReview(
                          product.id,
                          product.name,
                          reviewName,
                          reviewEmail,
                          reviewRating,
                          reviewComment,
                          reviewImages
                        );
                        setReviewSubmittedSuccess(true);
                        setReviewName('');
                        setReviewEmail('');
                        setReviewComment('');
                        setReviewImages([]);
                      }}
                      className="space-y-4 text-xs"
                    >
                      {/* Rating Selection */}
                      <div className="space-y-1">
                        <label className="font-bold text-slate-800 uppercase tracking-wider block">
                          1. Select Rating (1 to 5 Stars):
                        </label>
                        <div className="flex items-center gap-1">
                          {[1, 2, 3, 4, 5].map((star) => (
                            <button
                              key={star}
                              type="button"
                              onClick={() => setReviewRating(star)}
                              className="p-1 hover:scale-110 transition-transform cursor-pointer"
                            >
                              <Star
                                className={`w-6 h-6 ${
                                  star <= reviewRating ? 'fill-amber-400 text-amber-400' : 'text-slate-300'
                                }`}
                              />
                            </button>
                          ))}
                          <span className="text-xs font-bold text-amber-800 ml-2">{reviewRating} / 5 Stars</span>
                        </div>
                      </div>

                      {/* Name & Email Inputs */}
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <label className="font-bold text-slate-800 uppercase tracking-wider block">
                            2. Your Name *
                          </label>
                          <input
                            type="text"
                            required
                            placeholder="e.g. Sana Ahmed"
                            value={reviewName}
                            onChange={(e) => setReviewName(e.target.value)}
                            className="w-full bg-[#FAF5F0] border border-[#E5D2C1] rounded-xl py-2.5 px-3 text-slate-800 focus:outline-none focus:border-[#C81E3D]"
                          />
                        </div>

                        <div className="space-y-1">
                          <label className="font-bold text-slate-800 uppercase tracking-wider block">
                            3. Email Address * (Not shown publicly)
                          </label>
                          <input
                            type="email"
                            required
                            placeholder="e.g. sana@timenlife.com"
                            value={reviewEmail}
                            onChange={(e) => setReviewEmail(e.target.value)}
                            className="w-full bg-[#FAF5F0] border border-[#E5D2C1] rounded-xl py-2.5 px-3 text-slate-800 focus:outline-none focus:border-[#C81E3D]"
                          />
                        </div>
                      </div>

                      {/* Review Textarea */}
                      <div className="space-y-1">
                        <label className="font-bold text-slate-800 uppercase tracking-wider block">
                          4. Review Details *
                        </label>
                        <textarea
                          required
                          rows={3}
                          placeholder="Tell us about the product quality, packaging, delivery speed, or overall experience..."
                          value={reviewComment}
                          onChange={(e) => setReviewComment(e.target.value)}
                          className="w-full bg-[#FAF5F0] border border-[#E5D2C1] rounded-xl p-3 text-slate-800 focus:outline-none focus:border-[#C81E3D]"
                        />
                      </div>

                      {/* Custom Photos Upload Field */}
                      <div className="space-y-2 p-3 bg-[#FAF5F0] rounded-xl border border-[#E5D2C1]">
                        <label className="font-bold text-slate-800 uppercase tracking-wider block flex items-center justify-between">
                          <span className="flex items-center gap-1.5">
                            <Camera className="w-4 h-4 text-[#C81E3D]" />
                            <span>5. Add Custom Product Photos (Optional - Max 4)</span>
                          </span>
                          <span className="text-[10px] text-amber-900 font-normal">WordPress Media Library</span>
                        </label>

                        <div className="flex flex-wrap items-center gap-3">
                          {reviewImages.map((img, idx) => (
                            <div key={idx} className="w-16 h-16 rounded-lg border border-stone-300 overflow-hidden relative group bg-white">
                              <img src={img} alt={`Upload ${idx}`} className="w-full h-full object-cover" />
                              <button
                                type="button"
                                onClick={() => setReviewImages((prev) => prev.filter((_, i) => i !== idx))}
                                className="absolute inset-0 bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
                              >
                                <Trash2 className="w-4 h-4 text-rose-300" />
                              </button>
                            </div>
                          ))}

                          {reviewImages.length < 4 && (
                            <label className="w-16 h-16 rounded-lg border-2 border-dashed border-stone-300 hover:border-[#C81E3D] bg-white flex flex-col items-center justify-center text-stone-500 hover:text-[#C81E3D] cursor-pointer transition-colors p-1">
                              {isUploadingPhoto ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                              ) : (
                                <>
                                  <Upload className="w-4 h-4 mb-0.5" />
                                  <span className="text-[9px] font-bold">Add Photo</span>
                                </>
                              )}
                              <input
                                type="file"
                                accept="image/*"
                                multiple
                                onChange={handlePhotoUpload}
                                className="hidden"
                                disabled={isUploadingPhoto}
                              />
                            </label>
                          )}
                        </div>
                      </div>

                      <button
                        type="submit"
                        className="py-3 px-6 bg-[#C81E3D] hover:bg-[#A6142E] text-white font-bold rounded-xl uppercase tracking-wider text-xs transition-all shadow-md flex items-center gap-2 cursor-pointer"
                      >
                        <Send className="w-4 h-4" />
                        <span>Submit Review</span>
                      </button>
                    </form>
                  )}
                </div>

              </div>
            )}
          </div>
        </div>

        {/* Related Products Section (2 per column on mobile as requested) */}
        {relatedProducts.length > 0 && (
          <div className="mt-16 space-y-6">
            <div className="text-center space-y-2">
              <span className="text-xs font-bold tracking-widest text-[#C81E3D] uppercase">YOU MAY ALSO LIKE</span>
              <h3 className="text-2xl font-bold font-playfair text-[#1E2432]">Related Products</h3>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
              {relatedProducts.map((rel) => (
                <ProductCard
                  key={rel.id}
                  product={rel}
                  onSelectProduct={onSelectProduct}
                />
              ))}
            </div>
          </div>
        )}

        {/* RECENTLY VIEWED PRODUCTS SECTION */}
        <RecentlyViewedSection
          onSelectProduct={onSelectProduct}
          onAddToCart={(p) => onAddToCart(p, 1)}
          currentProductId={product.id}
        />

      </div>

      {/* FULL SCREEN LIGHTBOX MODAL FOR PRODUCT SHOWCASE IMAGES */}
      {lightboxIndex !== null && descGalleryImages.length > 0 && (
        <div className="fixed inset-0 z-50 bg-black/95 backdrop-blur-md flex items-center justify-center p-4 animate-in fade-in duration-200">
          {/* Close Button */}
          <button
            onClick={() => setLightboxIndex(null)}
            className="absolute top-5 right-5 p-3 bg-white/10 hover:bg-white/20 text-white rounded-full transition-colors cursor-pointer z-20 shadow-lg"
            title="Close (Esc)"
          >
            <X className="w-6 h-6" />
          </button>

          {/* Counter Badge */}
          <div className="absolute top-5 left-5 px-4 py-2 bg-white/10 text-white text-xs font-bold rounded-full backdrop-blur-md border border-white/10 z-20">
            Image {lightboxIndex + 1} of {descGalleryImages.length}
          </div>

          {/* Previous Arrow */}
          <button
            onClick={() =>
              setLightboxIndex((prev) =>
                prev !== null ? (prev - 1 + descGalleryImages.length) % descGalleryImages.length : 0
              )
            }
            className="absolute left-3 sm:left-8 p-3.5 bg-white/15 hover:bg-white/30 text-white rounded-full transition-all cursor-pointer backdrop-blur-md z-20 hover:scale-110"
            title="Previous Image (Left Arrow)"
          >
            <ChevronLeft className="w-7 h-7" />
          </button>

          {/* Image Display */}
          <div className="max-w-5xl max-h-[85vh] flex items-center justify-center p-2">
            <img
              src={descGalleryImages[lightboxIndex]}
              alt={`${product.name} showcase detail ${lightboxIndex + 1}`}
              className="max-w-full max-h-[82vh] object-contain rounded-2xl shadow-2xl border border-white/10"
            />
          </div>

          {/* Next Arrow */}
          <button
            onClick={() =>
              setLightboxIndex((prev) =>
                prev !== null ? (prev + 1) % descGalleryImages.length : 0
              )
            }
            className="absolute right-3 sm:right-8 p-3.5 bg-white/15 hover:bg-white/30 text-white rounded-full transition-all cursor-pointer backdrop-blur-md z-20 hover:scale-110"
            title="Next Image (Right Arrow)"
          >
            <ChevronRight className="w-7 h-7" />
          </button>
        </div>
      )}

      {/* Review Photo Lightbox Modal */}
      {lightboxImage && (
        <div
          className="fixed inset-0 z-50 bg-black/85 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200"
          onClick={() => setLightboxImage(null)}
        >
          <div
            className="relative max-w-4xl max-h-[90vh] bg-white rounded-2xl overflow-hidden shadow-2xl flex flex-col items-center p-3 sm:p-4 border border-stone-200"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={() => setLightboxImage(null)}
              className="absolute top-3 right-3 w-9 h-9 rounded-full bg-slate-900/80 hover:bg-slate-900 text-white flex items-center justify-center transition-colors z-10 cursor-pointer shadow-md"
              title="Close Preview"
            >
              <X className="w-5 h-5" />
            </button>

            <div className="w-full h-full flex items-center justify-center overflow-auto max-h-[82vh] rounded-xl bg-stone-900 p-2">
              <img
                src={lightboxImage}
                alt="Customer review photo enlarged preview"
                className="max-w-full max-h-[80vh] object-contain rounded-lg"
              />
            </div>

            <div className="pt-3 w-full flex items-center justify-between text-xs text-slate-500 px-2 font-sans">
              <span className="flex items-center gap-1.5 font-bold text-slate-700">
                <Camera className="w-4 h-4 text-[#C81E3D]" /> Customer Uploaded Photo
              </span>
              <button
                onClick={() => setLightboxImage(null)}
                className="text-[#C81E3D] hover:underline font-bold cursor-pointer"
              >
                Close Preview
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
};
