'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ReelsSettings, ReelItemSetting } from '@/lib/settings';
import { Product } from '@/types/woocommerce';
import { useCart } from '@/context/CartContext';
import { useSize } from '@/context/SizeContext';

interface ReelsSectionProps {
  settings?: ReelsSettings;
  allProducts?: Product[];
}

export function parseVideoSource(url?: string): {
  type: 'youtube' | 'vimeo' | 'tiktok' | 'direct' | 'none';
  embedUrl?: string;
  directUrl?: string;
} {
  if (!url || !url.trim()) return { type: 'none' };
  const u = url.trim();

  // YouTube Shorts, Watch, Embed
  const ytMatch = u.match(/(?:youtube\.com\/(?:watch\?v=|shorts\/|embed\/)|youtu\.be\/)([\w-]{11})/i);
  if (ytMatch) {
    const id = ytMatch[1];
    const origin = typeof window !== 'undefined' && window.location?.origin ? window.location.origin : 'https://panel.hayat.com';
    return {
      type: 'youtube',
      embedUrl: `https://www.youtube.com/embed/${id}?autoplay=1&mute=1&controls=0&loop=1&playlist=${id}&playsinline=1&rel=0&enablejsapi=1&origin=${encodeURIComponent(origin)}`,
    };
  }

  // TikTok - supports:
  // 1. https://www.tiktok.com/@user/video/7123456789012345678
  // 2. https://www.tiktok.com/v/7123456789012345678
  // 3. https://www.tiktok.com/player/v1/7123456789012345678
  // 4. https://www.tiktok.com/embed/v2/7123456789012345678 or /embed/7123456789012345678
  // 5. Mobile / web links containing 15-22 digit numeric video ID
  if (/tiktok\.com/i.test(u)) {
    const idMatch = u.match(/(?:video\/|v\/|player\/v1\/|embed\/v2\/|embed\/)?(\d{15,22})/i)
      || u.match(/(\d{15,22})/);
    if (idMatch && idMatch[1]) {
      const id = idMatch[1];
      return {
        type: 'tiktok',
        embedUrl: `https://www.tiktok.com/player/v1/${id}?autoplay=1&controls=1&music_info=0&description=0&volume_control=1`,
      };
    }
    if (u.includes('/player/v1/') || u.includes('/embed/')) {
      return {
        type: 'tiktok',
        embedUrl: u,
      };
    }
  }

  // Vimeo
  const vimeoMatch = u.match(/vimeo\.com\/(?:video\/)?(\d+)/i);
  if (vimeoMatch) {
    const id = vimeoMatch[1];
    return {
      type: 'vimeo',
      embedUrl: `https://player.vimeo.com/video/${id}?autoplay=1&muted=1&loop=1&background=1&autopause=0`,
    };
  }

  return { type: 'direct', directUrl: u };
}

const DEFAULT_REELS_ITEMS: ReelItemSetting[] = [
  {
    id: 'r1',
    title: 'খাঁটি মধু — সরাসরি চাক থেকে',
    video_url: '/reels/video001.mp4',
    poster: '/images/hero/honey.png',
    product_name: 'খাঁটি মধু',
    product_link: '/category/honey',
    enabled: true,
    order: 1,
  },
  {
    id: 'r2',
    title: 'ভেষজ গুঁড়া — পরিষ্কার ও মিহি',
    video_url: '/reels/video002.mp4',
    poster: '/images/hero/herbs.png',
    product_name: 'ফাইনেস্ট ভেষজ',
    product_link: '/category/finest-herbs',
    enabled: true,
    order: 2,
  },
  {
    id: 'r3',
    title: 'কম্বো প্যাক — পুরো পরিবারের জন্য',
    video_url: '/reels/video003.mp4',
    poster: '/images/hero/combo.png',
    product_name: 'কম্বো প্যাক',
    product_link: '/category/combo-packs',
    enabled: true,
    order: 3,
  },
  {
    id: 'r4',
    title: 'বাদাম ও বীজ — প্রতিদিনের পুষ্টি',
    video_url: '/reels/video004.mp4',
    poster: '/images/categories/nuts-seeds.png',
    product_name: 'বাদাম ও বীজ',
    product_link: '/category/nuts-seeds',
    enabled: true,
    order: 4,
  },
];

export default function ReelsSection({ settings, allProducts = [] }: ReelsSectionProps) {
  const router = useRouter();
  const { itemCount, openCart, quickAdd, addToCart } = useCart();
  const { selectedSize } = useSize();

  // Settings
  const isEnabled = settings?.enabled !== false;
  const title = settings?.title || 'Watch & buy';
  const subtitle = settings?.subtitle || 'Real pairs, filmed on real feet. Tap one to watch.';
  const btnText = settings?.btn_text || 'Shop all';
  const btnLink = settings?.btn_link || '/shop';

  // Raw reel items (filter active ones, fallback to default seed items)
  const rawItems = settings?.items && settings.items.length > 0
    ? settings.items.filter(item => {
        const en: any = item.enabled;
        return en !== false && en !== 0 && en !== '0' && en !== 'false';
      })
    : DEFAULT_REELS_ITEMS;

  const baseReels = rawItems.length > 0 ? rawItems : DEFAULT_REELS_ITEMS;

  // Modal Viewer State
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [isMuted, setIsMuted] = useState<boolean>(true);
  const [isPaused, setIsPaused] = useState<boolean>(false);
  const [slides, setSlides] = useState<ReelItemSetting[]>([]);
  const [activeSlideIndex, setActiveSlideIndex] = useState<number>(0);
  const [addedReelId, setAddedReelId] = useState<string | null>(null);

  // ---- Performance gates: page content first, reels load on approach ----
  const [isPageReady, setIsPageReady] = useState(false);
  const [isRailNear, setIsRailNear] = useState(false); // within 800px -> preload
  const [isRailFar, setIsRailFar] = useState(true);    // beyond 2000px -> unload
  const [isTabVisible, setIsTabVisible] = useState(
    typeof document === 'undefined' ? true : document.visibilityState === 'visible'
  );
  // Video sources mount only after page-ready AND rail-near AND not far.
  const canLoadVideo = isPageReady && isRailNear && !isRailFar;

  useEffect(() => {
    let done = false;
    const markReady = () => {
      if (done) return;
      done = true;
      // small idle buffer after window load so main content settles first
      window.setTimeout(() => setIsPageReady(true), 300);
    };
    if (document.readyState === 'complete') markReady();
    else window.addEventListener('load', markReady, { once: true });
    return () => window.removeEventListener('load', markReady);
  }, []);

  useEffect(() => {
    const el = marqueeContainerRef.current;
    if (!el || typeof IntersectionObserver === 'undefined') {
      setIsRailNear(true);
      setIsRailFar(false);
      return;
    }
    const nearObs = new IntersectionObserver(
      (es) => { const e = es[0]; if (e) setIsRailNear(e.isIntersecting); },
      { rootMargin: '800px 0px', threshold: 0 }
    );
    const farObs = new IntersectionObserver(
      (es) => { const e = es[0]; if (e) setIsRailFar(!e.isIntersecting); },
      { rootMargin: '2000px 0px', threshold: 0 }
    );
    nearObs.observe(el);
    farObs.observe(el);
    return () => { nearObs.disconnect(); farObs.disconnect(); };
  }, []);

  useEffect(() => {
    const onVis = () => setIsTabVisible(document.visibilityState === 'visible');
    document.addEventListener('visibilitychange', onVis);
    return () => document.removeEventListener('visibilitychange', onVis);
  }, []);

  // References
  const marqueeContainerRef = useRef<HTMLDivElement | null>(null);
  const railRef = useRef<HTMLDivElement | null>(null);
  const rvScrollRef = useRef<HTMLDivElement | null>(null);
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);

  // Find linked product for a reel (matching ID, slug, or permalink)
  const findProduct = useCallback(
    (reel: ReelItemSetting): Product | undefined => {
      const pidStr = String(reel.product_id || '').trim();
      const slugFromLink = reel.product_link ? reel.product_link.replace(/^\/product\//, '').replace(/\/$/, '').trim() : '';
      return allProducts.find(
        (p) => (pidStr && (String(p.id) === pidStr || p.slug === pidStr)) || (slugFromLink && p.slug === slugFromLink)
      );
    },
    [allProducts]
  );

  // ---------------------------------------------------------------------------
  // Continuous Marquee Ticker: Auto-scroll animation & user interaction pauses
  // ---------------------------------------------------------------------------
  useEffect(() => {
    const el = marqueeContainerRef.current;
    const rail = railRef.current;
    if (!el || !rail || baseReels.length === 0) return;

    let animId: number;
    let pos = el.scrollLeft || 0;
    let paused = false;
    let resumeTimeout: NodeJS.Timeout;
    const speed = 0.26;

    const tick = () => {
      // Don't scroll the marquee when the rail is far away, the tab is hidden,
      // or the fullscreen modal is open — saves CPU/battery.
      const idleOk = !isRailFar && isTabVisible && !isOpen;
      if (!paused && idleOk && rail.scrollWidth > el.clientWidth) {
        const period = rail.scrollWidth / 2;
        pos += speed;
        if (period > 0 && pos >= period) {
          pos -= period;
        }
        el.scrollLeft = pos;
      }
      animId = requestAnimationFrame(tick);
    };

    animId = requestAnimationFrame(tick);

    const onPause = () => {
      paused = true;
      clearTimeout(resumeTimeout);
    };

    const onResume = (delay = 1200) => {
      clearTimeout(resumeTimeout);
      resumeTimeout = setTimeout(() => {
        pos = el.scrollLeft;
        paused = false;
      }, delay);
    };

    const onWheel = () => {
      onPause();
      onResume(1600);
    };

    el.addEventListener('pointerenter', onPause);
    el.addEventListener('pointerleave', () => onResume(400));
    el.addEventListener('touchstart', onPause, { passive: true });
    el.addEventListener('touchend', () => onResume(1200), { passive: true });
    el.addEventListener('wheel', onWheel, { passive: true });

    return () => {
      cancelAnimationFrame(animId);
      clearTimeout(resumeTimeout);
    };
  }, [baseReels, isRailFar, isTabVisible, isOpen]);

  // ---------------------------------------------------------------------------
  // Rail Preview Videos: Simultaneous Autoplay (Muted & Loop, Continuous on Slide)
  // ---------------------------------------------------------------------------
  // ---------------------------------------------------------------------------
  // Rail Preview Videos: play ONLY the cards actually on screen.
  // Sources mount only when page-ready + rail-near (see canLoadVideo above);
  // each card's video plays while visible, pauses when scrolled away,
  // when the tab hides, or when the fullscreen modal opens.
  // ---------------------------------------------------------------------------
  useEffect(() => {
    const rail = railRef.current;
    if (!rail || typeof IntersectionObserver === 'undefined') return;

    const cards = Array.from(rail.querySelectorAll<HTMLElement>('a.reel'));
    if (cards.length === 0) return;

    const syncCard = (card: HTMLElement, visible: boolean) => {
      const v = card.querySelector<HTMLVideoElement>('video.rmedia');
      if (!v) return;
      const shouldPlay = visible && canLoadVideo && isTabVisible && !isOpen;
      v.muted = true;
      v.defaultMuted = true;
      v.playsInline = true;
      v.loop = true;
      if (shouldPlay) {
        if (v.paused) {
          const p = v.play();
          if (p && p.catch) p.catch(() => {});
        }
      } else if (!v.paused) {
        v.pause();
      }
    };

    const visObs = new IntersectionObserver(
      (entries) => {
        entries.forEach((en) => syncCard(en.target as HTMLElement, en.isIntersecting));
      },
      { root: null, threshold: 0.25 }
    );
    cards.forEach((c) => visObs.observe(c));

    // Re-sync on tab/modal/load-state changes
    cards.forEach((c) => {
      const r = c.getBoundingClientRect();
      const visible = r.bottom > 0 && r.top < window.innerHeight && r.right > 0 && r.left < window.innerWidth;
      syncCard(c, visible);
    });

    return () => visObs.disconnect();
  }, [baseReels, canLoadVideo, isTabVisible, isOpen]);

  // ---------------------------------------------------------------------------
  // Full-Screen Video Modal: Touch-responsive vertical reel playback
  // ---------------------------------------------------------------------------
  const openReels = useCallback((startIndex: number) => {
    // Duplicate 3 cycles for infinite vertical scroll snapping
    const tripleList = [...baseReels, ...baseReels, ...baseReels];
    setSlides(tripleList);
    setIsOpen(true);
    setIsMuted(true);
    setIsPaused(false);
    setActiveSlideIndex(startIndex);

    document.body.classList.add('rv-lock');

    requestAnimationFrame(() => {
      const sc = rvScrollRef.current;
      if (sc) {
        sc.scrollTop = startIndex * sc.clientHeight;
      }
    });
  }, [baseReels]);

  const closeReels = useCallback(() => {
    setIsOpen(false);
    setIsPaused(false);
    setIsMuted(true);
    document.body.classList.remove('rv-lock');

    // Pause all slide videos
    videoRefs.current.forEach((v) => {
      if (v) {
        try {
          v.pause();
          v.currentTime = 0;
        } catch (_) {}
      }
    });
  }, []);

  // Sync active reel video on scroll
  const handleScroll = useCallback(() => {
    const sc = rvScrollRef.current;
    if (!sc) return;

    const slideHeight = Math.max(1, sc.clientHeight);
    const curIndex = Math.round(sc.scrollTop / slideHeight);

    if (curIndex !== activeSlideIndex) {
      setActiveSlideIndex(curIndex);
      setIsPaused(false);
      setIsMuted(false);
    }

    // Play active video, pause others
    videoRefs.current.forEach((v, idx) => {
      if (!v) return;
      if (idx === curIndex) {
        v.muted = isMuted;
        if (!isPaused) {
          const pr = v.play();
          if (pr && pr.catch) pr.catch(() => {});
        }
      } else {
        try {
          v.pause();
        } catch (_) {}
      }
    });

    // Infinite vertical scroll: if within 3 slides of end, append 1 more cycle
    if (curIndex >= slides.length - 3) {
      setSlides((prev) => [...prev, ...baseReels]);
    }
  }, [activeSlideIndex, isMuted, isPaused, slides.length, baseReels]);

  // Play/Pause center tap
  const togglePlayPause = () => {
    const nextPaused = !isPaused;
    setIsPaused(nextPaused);

    const activeVideo = videoRefs.current[activeSlideIndex];
    if (activeVideo) {
      if (nextPaused) {
        activeVideo.pause();
      } else {
        const pr = activeVideo.play();
        if (pr && pr.catch) pr.catch(() => {});
      }
    }
  };

  // Toggle Mute
  const toggleMute = () => {
    const nextMuted = !isMuted;
    setIsMuted(nextMuted);

    const activeVideo = videoRefs.current[activeSlideIndex];
    if (activeVideo) {
      activeVideo.muted = nextMuted;
    }
  };

  // Handle "Add to cart" in Reel Modal
  const handleAddToCart = (reel: ReelItemSetting, e: React.MouseEvent) => {
    e.stopPropagation();
    const prod = findProduct(reel);
    if (prod) {
      quickAdd(prod, false, selectedSize);
    } else {
      const realPId = Number(String(reel.product_id || '').replace(/\D/g, '')) || Number(String(reel.id || '').replace(/\D/g, '')) || 9999;
      addToCart({
        id: realPId,
        name: reel.product_name || reel.title || 'Featured Reel Product',
        slug: reel.product_link?.replace(/^\/product\//, '') || 'featured-reel',
        brand: 'Hayat Supplements',
        price: Number(reel.product_price) || 1650,
        regularPrice: Number(reel.product_regular_price) || 2850,
        image: reel.poster || '/images/hero2.webp',
        categories: ['sneakers'],
        concerns: [],
        stockStatus: 'IN_STOCK',
      } as any, 1);
    }

    setAddedReelId(reel.id || 'current');
    setTimeout(() => {
      setAddedReelId(null);
    }, 1400);
  };

  // Handle "Buy now" in Reel Modal
  const handleBuyNow = (reel: ReelItemSetting, e: React.MouseEvent) => {
    e.stopPropagation();
    const prod = findProduct(reel);
    if (prod) {
      quickAdd(prod, true, selectedSize);
    } else {
      const realPId = Number(String(reel.product_id || '').replace(/\D/g, '')) || Number(String(reel.id || '').replace(/\D/g, '')) || 9999;
      addToCart({
        id: realPId,
        name: reel.product_name || reel.title || 'Featured Reel Product',
        slug: reel.product_link?.replace(/^\/product\//, '') || 'featured-reel',
        brand: 'Hayat Supplements',
        price: Number(reel.product_price) || 1650,
        regularPrice: Number(reel.product_regular_price) || 2850,
        image: reel.poster || '/images/hero2.webp',
        categories: ['sneakers'],
        concerns: [],
        stockStatus: 'IN_STOCK',
      } as any, 1);
    }
    closeReels();
    router.push('/checkout');
  };

  // Handle Escape key
  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        closeReels();
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [isOpen, closeReels]);

  if (!isEnabled) {
    return null;
  }

  // Double items for infinite marquee loop
  const marqueeItems = [...baseReels, ...baseReels];

  return (
    <>
      {/* Reels Section: Header & Video Marquee */}
      <section className="sec reelsec" aria-label="রিলস">
        <div className="wrap">
          <div className="sec-h">
            <div>
              <span className="eyebrow">Hayat Reels</span>
              <h2>{title}</h2>
              {subtitle && <p>{subtitle}</p>}
            </div>
            <Link className="link" href={btnLink}>
              {btnText}
            </Link>
          </div>
        </div>

      <style dangerouslySetInnerHTML={{ __html: `
        .reels-section-wrap {
          padding-top: clamp(32px, 3.8vw, 48px) !important;
          margin-top: 4px !important;
          padding-bottom: 16px !important;
        }
        .reels-header-bar {
          display: flex !important;
          align-items: baseline !important;
          justify-content: space-between !important;
          gap: 20px !important;
          margin-bottom: 22px !important;
          width: 100% !important;
        }
        .reels-title-row {
          display: flex !important;
          align-items: baseline !important;
          gap: 16px !important;
          flex-wrap: wrap !important;
          flex: 1 1 auto !important;
          min-width: 0 !important;
        }
        .reels-title {
          font-family: var(--d, "Space Grotesk", sans-serif) !important;
          font-size: clamp(26px, 3.2vw, 36px) !important;
          font-weight: 700 !important;
          letter-spacing: -0.025em !important;
          color: var(--graphite, #191B1E) !important;
          margin: 0 !important;
          line-height: 1.15 !important;
          white-space: nowrap !important;
        }
        .reels-subtitle {
          color: var(--soft, #6E757E) !important;
          font-size: 15px !important;
          font-weight: 400 !important;
          margin: 0 !important;
          line-height: 1.35 !important;
        }
        .reels-desktop-sub {
          display: block !important;
        }
        .reels-mobile-sub {
          display: none !important;
        }
        .reels-cta-link {
          margin-left: auto !important;
          font-size: 14px !important;
          font-weight: 600 !important;
          color: var(--graphite, #191B1E) !important;
          text-decoration: underline !important;
          text-decoration-thickness: 2px !important;
          text-underline-offset: 4px !important;
          white-space: nowrap !important;
          flex-shrink: 0 !important;
          display: inline-block !important;
          transition: opacity 0.2s !important;
        }
        .reels-cta-link:hover {
          opacity: 0.75 !important;
        }

        @media (max-width: 680px) {
          .reels-section-wrap {
            padding-top: clamp(22px, 4.5vw, 30px) !important;
            margin-top: 0 !important;
            padding-bottom: 12px !important;
          }
          .reels-header-bar {
            display: flex !important;
            flex-direction: row !important;
            align-items: baseline !important;
            justify-content: space-between !important;
            gap: 12px !important;
            margin-bottom: 4px !important;
            width: 100% !important;
          }
          .reels-title-row {
            display: flex !important;
            align-items: baseline !important;
            flex: 1 1 auto !important;
            min-width: 0 !important;
            gap: 0 !important;
          }
          .reels-title {
            font-size: 25px !important;
            line-height: 1.2 !important;
            letter-spacing: -0.02em !important;
            white-space: normal !important;
            word-break: normal !important;
            overflow-wrap: break-word !important;
            width: 100% !important;
          }
          .reels-desktop-sub {
            display: none !important;
          }
          .reels-mobile-sub {
            display: block !important;
            font-size: 13px !important;
            color: var(--soft, #6E757E) !important;
            margin: 4px 0 14px 0 !important;
            line-height: 1.35 !important;
            width: 100% !important;
          }
          .reels-cta-link {
            font-size: 13.5px !important;
            align-self: baseline !important;
            margin-left: 0 !important;
            flex-shrink: 0 !important;
          }
        }
      `}} />

      {/* Interactive Continuous Video Marquee */}
      <div
        className="rscroll"
        ref={marqueeContainerRef}
        data-speed=".35"
        aria-label="Product reels"
        tabIndex={0}
      >
        <div className="rrow" ref={railRef}>
          {marqueeItems.map((reel, idx) => {
            const prod = findProduct(reel);
            const originalIndex = idx % baseReels.length;
            const cardTitle = reel.product_name || prod?.name || reel.title;
            const priceVal = (prod?.price !== undefined && prod?.price !== null) ? prod.price : reel.product_price;
            const priceText = priceVal
              ? `৳${Number(priceVal).toLocaleString('en-US')}`
              : 'Coming soon';
            const posterSrc = reel.poster || prod?.image || '/images/hero2.webp';
            const vSource = parseVideoSource(reel.video_url);

            return (
              <a
                key={`reel-${idx}-${reel.id || originalIndex}`}
                className="reel"
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  openReels(originalIndex);
                }}
                aria-label={`Watch: ${cardTitle}`}
              >
                {vSource.type === 'direct' && vSource.directUrl ? (
                  <video
                    className="rmedia"
                    src={canLoadVideo ? vSource.directUrl : undefined}
                    muted
                    loop
                    playsInline
                    preload={canLoadVideo ? 'metadata' : 'none'}
                    poster={posterSrc}
                  />
                ) : (
                  <img
                    className="rmedia"
                    src={posterSrc}
                    alt={cardTitle || ''}
                    loading="lazy"
                  />
                )}

                {/* Top Right Play Icon Badge */}
                <span className="rplay">
                  <svg viewBox="0 0 24 24">
                    <path d="M8 5v14l11-7z" />
                  </svg>
                </span>

                {/* Bottom Gradient Caption */}
                <span className="rcap">
                  <b>{cardTitle}</b>
                  <small>{priceText}</small>
                </span>
              </a>
            );
          })}
        </div>
      </div>

      </section>

      <div className="railgap" />

      {/* Full-Screen Reels Video Player Modal */}
      <div
        className={`rv ${isOpen ? 'open' : ''} ${isPaused ? 'paused' : ''}`}
        id="rv"
        aria-hidden={!isOpen}
        role="dialog"
        aria-modal="true"
        aria-label="Product Reels"
      >
        {/* Vertical Scroll Snap Container */}
        <div className="rvscroll" id="rvscroll" ref={rvScrollRef} onScroll={handleScroll}>
          {slides.map((slide, sIdx) => {
            const prod = findProduct(slide);
            const slideTitle = slide.product_name || prod?.name || slide.title || 'Featured Style';
            const price = (prod?.price !== undefined && prod?.price !== null) ? prod.price : (slide.product_price || '');
            const regPrice = (prod?.regularPrice !== undefined && prod?.regularPrice !== null) ? prod.regularPrice : (slide.product_regular_price || '');
            const posterImg = slide.poster || prod?.image || '/images/hero2.webp';
            const prodThumb = prod?.image || posterImg;
            const isSoldOut = prod?.stockStatus === 'OUT_OF_STOCK';

            return (
              <section key={`rv-slide-${sIdx}`} className="rvslide" data-i={sIdx}>
                <div className="rvstage">
                  {/* Background Video / Embed / Image */}
                  {(() => {
                    const vSource = parseVideoSource(slide.video_url);
                    if (vSource.type === 'youtube' || vSource.type === 'vimeo' || vSource.type === 'tiktok') {
                      return (
                        <iframe
                          className="rmedia rvm"
                          src={vSource.embedUrl}
                          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen"
                          referrerPolicy="no-referrer-when-downgrade"
                          allowFullScreen
                          style={{
                            border: 0,
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                          }}
                        />
                      );
                    }
                    if (vSource.type === 'direct' && vSource.directUrl) {
                      return (
                        <video
                          ref={(el) => {
                            videoRefs.current[sIdx] = el;
                          }}
                          className="rmedia rvm"
                          src={vSource.directUrl}
                          muted={isMuted}
                          loop
                          playsInline
                          preload="auto"
                          poster={posterImg}
                        />
                      );
                    }
                    return (
                      <img
                        className="rmedia rvm"
                        src={posterImg}
                        alt={slideTitle}
                        loading="lazy"
                      />
                    );
                  })()}

                  {/* Invisible Tap Surface to Toggle Play/Pause (only for native direct video) */}
                  {parseVideoSource(slide.video_url).type === 'direct' && (
                    <button
                      className="rvtap"
                      aria-label="Play or pause"
                      onClick={togglePlayPause}
                    />
                  )}

                  {/* Floating Glassmorphic Product Card */}
                  <div className="rvcard">
                    <div className="rvhead">
                      <img src={prodThumb} alt={slideTitle} />
                      <div style={{ minWidth: 0 }}>
                        <h4>{slideTitle}</h4>
                        <span className="rvprice">
                          {price ? (
                            <>
                              <b>৳{Number(price).toLocaleString('en-US')}</b>
                              {regPrice && Number(regPrice) > Number(price) && (
                                <del>৳{Number(regPrice).toLocaleString('en-US')}</del>
                              )}
                            </>
                          ) : (
                            <b
                              style={{
                                fontSize: '13.5px',
                                fontFamily: 'var(--b)',
                                fontWeight: 500,
                                color: 'var(--soft, #6E757E)',
                              }}
                            >
                              Not in stock yet
                            </b>
                          )}
                        </span>
                      </div>
                    </div>

                    <div className="rvbtns">
                      {isSoldOut ? (
                        <>
                          <span
                            className="cbtn add"
                            style={{ pointerEvents: 'none', opacity: 0.6 }}
                          >
                            Sold out
                          </span>
                          <Link
                            className="cbtn buy"
                            href="/contact"
                            onClick={closeReels}
                          >
                            Notify me
                          </Link>
                        </>
                      ) : price ? (
                        <>
                          <button
                            type="button"
                            className="cbtn add"
                            onClick={(e) => handleAddToCart(slide, e)}
                          >
                            {addedReelId === slide.id ? 'Added ✓' : 'Add to cart'}
                          </button>
                          <button
                            type="button"
                            className="cbtn buy"
                            onClick={(e) => handleBuyNow(slide, e)}
                          >
                            Buy now
                          </button>
                        </>
                      ) : (
                        <>
                          <Link
                            className="cbtn add"
                            href="/shop?c=sneakers"
                            onClick={closeReels}
                          >
                            Browse sneakers
                          </Link>
                          <Link
                            className="cbtn buy"
                            href="/contact"
                            onClick={closeReels}
                          >
                            Notify me
                          </Link>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              </section>
            );
          })}
        </div>

        {/* Top Control Bar */}
        <div className="rvtop">
          {/* Mute / Unmute Button */}
          <button
            className="rvbtn"
            id="rvmute"
            aria-label={isMuted ? 'Unmute' : 'Mute'}
            onClick={toggleMute}
          >
            {isMuted ? (
              <svg viewBox="0 0 24 24">
                <path d="M5 9v6h4l5 4V5L9 9z" />
                <path d="M17 9l4 6M21 9l-4 6" />
              </svg>
            ) : (
              <svg viewBox="0 0 24 24">
                <path d="M5 9v6h4l5 4V5L9 9z" />
                <path d="M17 8a5 5 0 0 1 0 8" />
              </svg>
            )}
          </button>

          {/* Right Action Buttons */}
          <span className="rvright">
            {/* Bag Button with Live Cart Item Count */}
            <button
              className="rvbtn"
              id="rvcart"
              aria-label="Open bag"
              onClick={() => {
                closeReels();
                openCart();
              }}
            >
              <svg viewBox="0 0 24 24">
                <path d="M5 8h14l-1 12H6z" />
                <path d="M9 8V6a3 3 0 0 1 6 0v2" />
              </svg>
              {itemCount > 0 && <b className="rvcount">{itemCount}</b>}
            </button>

            {/* Close Button */}
            <button
              className="rvbtn"
              id="rvclose"
              aria-label="Close reels"
              onClick={closeReels}
            >
              <svg viewBox="0 0 24 24">
                <path d="M6 6l12 12M18 6L6 18" />
              </svg>
            </button>
          </span>
        </div>

        {/* Big Animated Center Play Icon (Shown when paused) */}
        <button
          className="rvbig"
          id="rvplay"
          aria-label={isPaused ? 'Play' : 'Pause'}
          onClick={togglePlayPause}
        >
          <svg viewBox="0 0 24 24">
            <path d="M8 5v14l11-7z" />
          </svg>
        </button>

        {/* Bottom Swipe Up Hint */}
        <div className="rvhint">
          <span>Swipe up for the next reel</span>
        </div>
      </div>
    </>
  );
}
