/* global React */

// ========== CATEGORIES ==========
const ALL_PRODUCTS = (window.PRODUCTS_DATA || []);
const _byCat = (g) => ALL_PRODUCTS.filter(p => p.catGroup === g);
const _firstImg = (g, fallback) => (_byCat(g)[0]?.local_img) || fallback;

// Transparent hero art per category (overrides catalog thumbs for cleaner tiles).
const CATS = [
  { name: 'Screens',     count: _byCat('Screens').length,     img: 'assets/privacy-iphone-transparent.png', accent: 'var(--ink)', dark: true, transparent: true },
  { name: 'Power',       count: _byCat('Power').length,       img: 'assets/powerbank-transparent.png',      accent: 'var(--gold)', transparent: true },
  { name: 'Watch',       count: _byCat('Watch').length,       img: _firstImg('Watch','assets/watch-case.jpg'), accent: '#fff' },
  { name: 'Stylus',      count: _byCat('Stylus').length,      img: _firstImg('Stylus','assets/pencil.jpg'),    accent: 'var(--cream-2)' },
  { name: 'Camera',      count: _byCat('Camera').length,      img: 'assets/ar-screen-transparent.png',       accent: '#fff', transparent: true },
  { name: 'Accessories', count: _byCat('Accessories').length, img: 'assets/charger-transparent.png',         accent: 'var(--cream-2)', transparent: true },
];

function Categories() {
  return (
    <section className="section" id="screens">
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
          <h2 className="display" style={{ fontSize: 'clamp(40px, 6.5vw, 88px)', margin: 0, lineHeight: 1.05, paddingTop: '0.1em' }}>
            Everything your<br/>phone needs.
          </h2>
          <a href="/category/all" className="mono" style={{ textDecoration: 'underline' }}>View all {ALL_PRODUCTS.length} products →</a>
        </div>
        <div className="cats-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 16 }}>
          {CATS.map((c, i) => (
            <a key={c.name} href={`/category/${c.name.toLowerCase()}`} className="card" style={{
              textDecoration: 'none', color: c.dark ? 'var(--cream)' : 'var(--ink)',
              aspectRatio: i === 0 ? '2/2.4' : (i === CATS.length - 1 ? '2/1.05' : '1/1.05'),
              gridColumn: i === 0 ? 'span 2' : (i === CATS.length - 1 ? 'span 2' : 'span 1'),
              gridRow: i === 0 ? 'span 2' : 'span 1',
              padding: i === 0 ? 24 : 'clamp(14px, 1.4vw, 22px)',
              minWidth: 0,
              overflow: 'hidden',
              display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
              background: c.accent,
              border: c.accent === '#fff' ? '1px solid var(--line)' : 'none'
            }}>
              <div>
                <div className="mono" style={{ opacity: 0.6 }}>0{i+1} / CATEGORY</div>
                <h3 className="display" style={{
                  fontSize: i === 0 ? 'clamp(48px, 6vw, 88px)' : 'clamp(20px, 2.2vw, 34px)',
                  margin: '8px 0 0',
                  lineHeight: 1.05,
                  wordBreak: 'break-word',
                  hyphens: 'auto'
                }}>{c.name}</h3>
                <div style={{ fontSize: 'clamp(11px, 1vw, 13px)', opacity: 0.7, marginTop: 4 }}>{c.count} items</div>
              </div>
              <div style={{
                display: 'flex', justifyContent: 'center', alignItems: 'center',
                flex: 1, minHeight: 0, width: '100%',
                marginTop: 'clamp(8px, 1vw, 16px)'
              }}>
                <div style={{
                  // Size the disc by available HEIGHT first (height:100% +
                  // aspectRatio makes it a square that fits the bottom of the
                  // tile), capped at 92% of the tile WIDTH so on wide/short
                  // tiles (Accessories span-2) it doesn't bleed sideways.
                  height: '100%',
                  aspectRatio: '1/1',
                  maxWidth: '92%',
                  maxHeight: '100%',
                  borderRadius: '50%',
                  background: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  overflow: 'hidden', // clips image bounding-box to the round shape
                  boxShadow: '0 12px 30px rgba(0,0,0,0.18)'
                }}>
                  <img src={c.img} alt={c.name} style={{
                    // Force every image to occupy the SAME visible bounding
                    // box (90% of disc, both axes) so categories look uniform
                    // even though source photos have different built-in
                    // whitespace and aspect ratios. object-fit: contain keeps
                    // the original aspect ratio inside the box.
                    width:  '90%',
                    height: '90%',
                    objectFit: 'contain',
                    objectPosition: 'center',
                    mixBlendMode: c.transparent ? 'normal' : 'multiply'
                  }}/>
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ========== BESTSELLERS ==========
// Curated picks from real Lito catalog (one per category, mixed)
const _pick = (g, n=3) => _byCat(g).slice(0, n);
const _bg = ['#fff','var(--cream-2)'];
const _curated = [
  ..._pick('Screens',2),
  ..._pick('Power',2),
  ..._pick('Watch',1),
  ..._pick('Stylus',1),
  ..._pick('Camera',1),
  ..._pick('Accessories',1),
].slice(0,8);
const PRODUCTS = _curated.map((p, i) => ({
  id: p.id, slug: p.slug, cat: p.catGroup, name: p.name, price: p.price, orig: p.orig,
  img: p.local_img,
  // Second image for hover swap. Falls back to the primary so every card still
  // animates on hover (different scale start/end → looks like a real swap).
  // Upload a true second photo per product in super-admin to get a different
  // image revealed on hover, like DailyObjects.
  img2: (p.images && p.images.find(im => im.url && im.url !== p.local_img)?.url) || p.local_img,
  color: _bg[i % 2]
}));

function Bestsellers() {
  return (
    <section className="section" id="bestsellers">
      <div className="container">
        <div style={{ marginBottom: 48 }}>
          <span className="mono" style={{ color: 'var(--muted)' }}>◆ WHAT EVERYONE'S BUYING</span>
          <h2 className="display" style={{ fontSize: 'clamp(48px, 6vw, 80px)', margin: '12px 0 0' }}>Top of the drop.</h2>
        </div>
        <div className="bestsellers-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
          {PRODUCTS.map(p => (
            <div key={p.id} className="card pcard-hover" style={{ padding: 0, display: 'flex', flexDirection: 'column' }}>
              <a href={`/products/${p.slug}`} style={{ textDecoration: 'none', color: 'var(--ink)' }}>
                <div className="pcard-img" style={{ background: p.color, height: 260, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}>
                  <img src={p.img}  alt={p.name} className="pcard-img-a" style={{ maxWidth: '75%', maxHeight: '75%', objectFit: 'contain', mixBlendMode: 'multiply' }}/>
                  <img src={p.img2} alt="" aria-hidden="true" className="pcard-img-b" style={{ maxWidth: '75%', maxHeight: '75%', objectFit: 'contain', mixBlendMode: 'multiply' }}/>
                  {p.orig && (
                    <div className="chip" style={{ position: 'absolute', top: 14, left: 14, background: 'var(--ink)', zIndex: 2 }}>
                      −{Math.round((1 - p.price/p.orig) * 100)}%
                    </div>
                  )}
                </div>
                <div style={{ padding: '18px 18px 12px' }}>
                  <div className="mono" style={{ color: 'var(--muted)', marginBottom: 6 }}>{p.cat.toUpperCase()}</div>
                  <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 8, lineHeight: 1.3 }}>{p.name}</div>
                  <div>
                    <span className="display" style={{ fontSize: 20 }}>₹{p.price.toLocaleString('en-IN')}</span>
                    {p.orig && <span style={{ color: 'var(--muted)', textDecoration: 'line-through', marginLeft: 8, fontSize: 13 }}>₹{p.orig.toLocaleString('en-IN')}</span>}
                  </div>
                </div>
              </a>
              {/* Explicit "Add to cart" button — replaces the easy-to-miss "+" circle */}
              <button
                onClick={(e) => { e.preventDefault(); e.stopPropagation(); window.litoAdd && window.litoAdd(p.id); }}
                style={{
                  margin: '0 18px 18px', padding: '13px 16px',
                  background: 'var(--ink)', color: 'var(--cream)',
                  border: 0, fontFamily: 'inherit', fontWeight: 600,
                  fontSize: 12, letterSpacing: '.08em', textTransform: 'uppercase',
                  cursor: 'pointer', borderRadius: 2,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  transition: 'background .15s ease',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--violet)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'var(--ink)'}
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/>
                  <line x1="3" y1="6" x2="21" y2="6"/>
                  <path d="M16 10a4 4 0 0 1-8 0"/>
                </svg>
                Add to cart
              </button>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ========== TESTIMONIALS ==========
const REVIEWS = [
  { name: 'Aarav S.', phone: 'Samsung S24 Ultra', rating: 5, text: 'Dropped my phone on tiles. Glass took a chip, screen is mint. Doing its job.' },
  { name: 'Anaya K.', phone: 'iPhone 15 Pro', rating: 5, text: 'Edges are flush. Feels like the phone. Fingerprints don\'t stick. Premium for the price.' },
  { name: 'Vihaan M.', phone: 'Apple Watch Ultra', rating: 5, text: 'You can\'t even tell it\'s there. Touch is 1:1. Gym + office daily, zero scratches.' },
  { name: 'Rohan V.', phone: 'iPhone 15 Pro Max', rating: 5, text: 'The privacy one is a cheat code on the metro. Nobody\'s reading over your shoulder.' },
];

function Reviews() {
  return (
    <section className="section" style={{ background: 'var(--ink)', color: 'var(--cream)' }}>
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 56, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <span className="mono" style={{ color: 'var(--gold)' }}>◆ 12,400 REVIEWS · 4.8 / 5</span>
            <h2 className="display" style={{ fontSize: 'clamp(56px, 7vw, 112px)', margin: '16px 0 0' }}>
              Real phones.<br/>
              <span className="italic-accent">Real saves.</span>
            </h2>
          </div>
          <a href="#" style={{ color: 'var(--cream)', textDecoration: 'underline' }} className="mono">Read all →</a>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
          {REVIEWS.map((r, i) => (
            <div key={i} style={{ padding: 28, border: '1px solid rgba(245,241,234,0.15)', borderRadius: 22, background: 'rgba(255,255,255,0.02)' }}>
              <div style={{ color: 'var(--gold)', fontSize: 18, marginBottom: 16 }}>{'★'.repeat(r.rating)}</div>
              <p style={{ fontSize: 16, lineHeight: 1.5, marginBottom: 24, textWrap: 'pretty' }}>"{r.text}"</p>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', fontSize: 13 }}>
                <div>
                  <div style={{ fontWeight: 600 }}>{r.name}</div>
                  <div className="mono" style={{ color: 'rgba(245,241,234,0.5)', marginTop: 4 }}>{r.phone}</div>
                </div>
                <span className="pill" style={{ background: 'transparent', borderColor: 'rgba(245,241,234,0.2)', color: 'var(--cream)' }}>Verified</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ========== TRUST STRIP ==========
function Trust() {
  const items = [
    { big: '4–9', sub: 'DAY DELIVERY', note: 'Pan India' },
    { big: '3', sub: 'DAY RETURNS', note: 'No questions' },
    { big: '12.4K', sub: 'REVIEWS', note: '4.8★ avg' },
    { big: 'COD', sub: 'AVAILABLE', note: 'All orders' },
  ];
  return (
    <section style={{ padding: '60px 48px', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
      <div className="container" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
        {items.map((it, i) => (
          <div key={i} style={{ borderRight: i < 3 ? '1px solid var(--line)' : 'none', paddingLeft: i > 0 ? 24 : 0 }}>
            <div className="display" style={{ fontSize: 64, lineHeight: 1 }}>{it.big}</div>
            <div className="mono" style={{ marginTop: 8 }}>{it.sub}</div>
            <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 4 }}>{it.note}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ========== CTA ==========
function CTA() {
  return (
    <section style={{ padding: '120px 48px' }}>
      <div className="container" style={{
        background: 'var(--ink)',
        color: 'var(--cream)',
        padding: '100px 60px',
        position: 'relative',
        overflow: 'hidden',
        borderRadius: 4
      }}>
        <div style={{ position: 'relative', zIndex: 2, maxWidth: 720 }}>
          <span className="mono" style={{ color: 'var(--gold)' }}>◆ THE BUNDLE · APR 2026</span>
          <h2 className="display" style={{ fontSize: 'clamp(64px, 9vw, 140px)', margin: '20px 0 28px', color: 'var(--cream)' }}>
            Outfit the<br/><span className="italic-accent">whole device.</span>
          </h2>
          <p style={{ fontSize: 20, maxWidth: 520, lineHeight: 1.5, color: 'rgba(244,242,237,0.7)' }}>
            Pair a case, a screen, and a cable. 15% off the bundle. Free shipping. One kit, fully protected.
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 40 }}>
            <a href="/category/all" className="btn lg" style={{ background: 'var(--gold)', color: 'var(--ink)', borderColor: 'var(--gold)', textDecoration: 'none' }}>Build your bundle →</a>
            <a href="/category/all" className="btn ghost lg" style={{ color: 'var(--cream)', borderColor: 'var(--cream)', textDecoration: 'none' }}>Shop all</a>
          </div>
        </div>
        <img src="assets/lion-mark.png" style={{
          position: 'absolute', right: -80, bottom: -80,
          width: 520, height: 520, opacity: 0.1,
          filter: 'brightness(3)', zIndex: 1
        }}/>
      </div>
    </section>
  );
}

function Footer() {
  const cols = [
    { title: 'Shop', items: [
      ['Screen Protectors', '#screens'],
      ['Cables & Chargers', '#bestsellers'],
      ['Powerbanks', '#bestsellers'],
      ['Watch Accessories', '#bestsellers'],
      ['iPad Stylus', '#bestsellers'],
      ['Camera Lens', '#bestsellers'],
    ]},
    { title: 'Support', items: [
      ['Shipping Policy', '/shipping-policy'],
      ['Returns Policy', '/returns-policy'],
      ['Privacy Policy', '/privacy-policy'],
      ['Terms & Conditions', '/terms'],
      ['WhatsApp 98798 73001', 'https://wa.me/919879873001'],
    ]},
    { title: 'Company', items: [
      ['About Lito', '#'],
      ['Made in India', '#'],
      ['Reviews', '#'],
      ['Email info@lito.in', 'mailto:info@lito.in'],
    ]},
  ];
  return (
    <footer style={{ background: 'var(--ink)', color: 'var(--cream)', padding: '80px 48px 40px' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr', gap: 60, marginBottom: 80 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <img src="assets/lion-mark.png" style={{ width: 56, height: 56, objectFit: 'contain', filter: 'brightness(2)' }}/>
              <div className="display" style={{ fontSize: 48, letterSpacing: '0.1em', fontWeight: 700 }}>LITO</div>
            </div>
            <p style={{ color: 'rgba(244,242,237,0.6)', maxWidth: 320, marginTop: 16, lineHeight: 1.5 }}>
              Premium protection, engineered in India. Guard against everything — drops, scratches, prying eyes.
            </p>
            <div style={{ marginTop: 24, display: 'flex', gap: 10 }}>
              <a href="https://www.instagram.com/litoindia_" target="_blank" rel="noopener" aria-label="Lito on Instagram"
                 style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid rgba(244,242,237,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--cream)', textDecoration: 'none', transition: 'background .15s ease, border-color .15s ease' }}
                 onMouseEnter={e => { e.currentTarget.style.background = 'var(--cream)'; e.currentTarget.style.color = 'var(--ink)'; e.currentTarget.style.borderColor = 'var(--cream)'; }}
                 onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--cream)'; e.currentTarget.style.borderColor = 'rgba(244,242,237,0.25)'; }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="3" width="18" height="18" rx="5"/>
                  <circle cx="12" cy="12" r="4"/>
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/>
                </svg>
              </a>
            </div>
          </div>
          {cols.map(c => (
            <div key={c.title}>
              <div className="mono" style={{ color: 'var(--gold)', marginBottom: 18 }}>◆ {c.title.toUpperCase()}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
                {c.items.map(([label, href]) => <li key={label}><a href={href} style={{ color: 'rgba(245,241,234,0.8)', textDecoration: 'none', fontSize: 14 }}>{label}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', borderTop: '1px solid rgba(245,241,234,0.15)', paddingTop: 24 }} className="mono">
          <span style={{ color: 'rgba(245,241,234,0.5)' }}>© 2026 AEON TECHNOLOGIES · AHMEDABAD, IN</span>
          <span style={{ color: 'rgba(245,241,234,0.5)' }}>WHATSAPP 98798 73001 · INFO@LITO.IN</span>
        </div>
      </div>
    </footer>
  );
}

// ========== VIDEO SHOP ("Tap to shop what you see") ==========
// Manual carousel (no auto-rotate). Videos always auto-play muted/looped.
// 5 visible per page on desktop, 2 on mobile. Arrows BELOW the strip.
// Each tile has a transparent product mini-card overlaid bottom-left, and a
// full-width black "Add To Cart" + dropdown caret strip beneath.
const { useState: useStateV, useEffect: useEffectV, useRef: useRefV } = React;
function VideoShop() {
  const [items, setItems] = useStateV([]);
  const [ready, setReady] = useStateV(false);
  const [page, setPage]   = useStateV(0);
  const railRef = useRefV(null);

  useEffectV(() => {
    fetch('/api/home-videos')
      .then(r => r.ok ? r.json() : [])
      .then(d => setItems(Array.isArray(d) ? d : []))
      .catch(() => setItems([]))
      .finally(() => setReady(true));
  }, []);

  if (!ready || !items.length) return null;

  // Page sizing: 5 desktop, 2 mobile (CSS controls per-tile flex-basis;
  // here we just compute the page count for the dot indicator)
  const isMobile = typeof window !== 'undefined' && window.matchMedia('(max-width: 720px)').matches;
  const perPage  = isMobile ? 2 : 5;
  const pages    = Math.max(1, Math.ceil(items.length / perPage));

  const scrollToPage = (p) => {
    const next = Math.max(0, Math.min(pages - 1, p));
    setPage(next);
    const rail = railRef.current;
    if (!rail) return;
    rail.scrollTo({ left: rail.clientWidth * next, behavior: 'smooth' });
  };

  // Keep dot state in sync if user pans by dragging on touch
  const onScroll = () => {
    const rail = railRef.current;
    if (!rail) return;
    const p = Math.round(rail.scrollLeft / Math.max(1, rail.clientWidth));
    if (p !== page) setPage(p);
  };

  return (
    <section className="section videoshop-section" style={{ padding: '60px 24px 0', background: 'var(--cream)' }}>
      <div className="container" style={{ maxWidth: 1380, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <span className="mono" style={{ color: 'var(--muted)' }}>◆ STRAIGHT FROM THE COUNTER</span>
          <h2 className="display" style={{ fontSize: 'clamp(34px, 4.6vw, 64px)', margin: '10px 0 0', lineHeight: 1.05 }}>
            Tap to shop <span className="italic-accent">what you see.</span>
          </h2>
        </div>

        {/* Horizontal scroll-snap rail. CSS gives each tile a viewport-fraction
            width so exactly perPage tiles fit the rail. When there are FEWER
            items than fit a page (e.g. only 1 video), we center the rail so it
            doesn't sit lonely on the left edge. */}
        <div className="videoshop-rail" ref={railRef} onScroll={onScroll}
             style={{
               display: 'flex',
               gap: 14,
               overflowX: 'auto',
               scrollSnapType: 'x mandatory',
               scrollBehavior: 'smooth',
               WebkitOverflowScrolling: 'touch',
               paddingBottom: 4,
               // Only center when content fits — otherwise center clips overflow on the left edge
               justifyContent: items.length <= perPage ? 'center' : 'flex-start',
             }}>
          {items.map(p => <VideoTile key={p.id} p={p} />)}
        </div>

        {/* Controls — only shown when more than one page exists */}
        {pages > 1 && (
        <div className="videoshop-controls" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, marginTop: 22, marginBottom: 8 }}>
          <button aria-label="Previous" onClick={() => scrollToPage(page - 1)} disabled={page === 0}
                  className="vs-arrow" style={{ width: 44, height: 44, borderRadius: '50%', border: '1.5px solid var(--ink)', background: 'transparent', color: 'var(--ink)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: page === 0 ? 0.35 : 1, transition: 'opacity .15s' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
          </button>
          <div style={{ display: 'flex', gap: 8 }}>
            {Array.from({ length: pages }).map((_, i) => (
              <button key={i} aria-label={`Go to page ${i+1}`} onClick={() => scrollToPage(i)}
                      style={{ width: i === page ? 28 : 8, height: 8, borderRadius: 4, border: 0, padding: 0, background: i === page ? 'var(--ink)' : 'var(--line)', cursor: 'pointer', transition: 'width .25s ease, background .15s' }}/>
            ))}
          </div>
          <button aria-label="Next" onClick={() => scrollToPage(page + 1)} disabled={page === pages - 1}
                  className="vs-arrow" style={{ width: 44, height: 44, borderRadius: '50%', border: '1.5px solid var(--ink)', background: 'var(--ink)', color: 'var(--cream)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: page === pages - 1 ? 0.35 : 1, transition: 'opacity .15s' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
          </button>
        </div>
        )}
      </div>
    </section>
  );
}

function VideoTile({ p }) {
  const fmt = (n) => '₹' + Number(n || 0).toLocaleString('en-IN');
  const img = p.local_img && (p.local_img.startsWith('/') || p.local_img.startsWith('http')) ? p.local_img : (p.local_img ? '/' + p.local_img : '');
  const videoRef = useRefV(null);
  const [needsTap, setNeedsTap] = useStateV(false);

  // Triple-redundant autoplay: imperative attributes + play() on every
  // possible event + a visible "tap to play" overlay if the browser still
  // refuses. The overlay is the final guarantee — works on Brave, low-power
  // mode, every browser policy.
  useEffectV(() => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = true;
    v.defaultMuted = true;
    v.playsInline = true;
    v.setAttribute('muted', '');
    v.setAttribute('playsinline', '');
    v.setAttribute('webkit-playsinline', '');
    const tryPlay = () => {
      const promise = v.play();
      if (promise && typeof promise.then === 'function') {
        promise.then(() => setNeedsTap(false)).catch(() => setNeedsTap(true));
      }
    };
    tryPlay();
    v.addEventListener('loadedmetadata', tryPlay);
    v.addEventListener('canplay', tryPlay);
    v.addEventListener('playing', () => setNeedsTap(false));
    const io = new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (e.isIntersecting) tryPlay();
        else { try { v.pause(); } catch {} }
      }
    }, { threshold: 0.15 });
    io.observe(v);
    const wakeAll = () => tryPlay();
    document.addEventListener('touchstart', wakeAll, { once: true, passive: true });
    document.addEventListener('click',      wakeAll, { once: true });
    document.addEventListener('scroll',     wakeAll, { once: true, passive: true });
    return () => {
      io.disconnect();
      v.removeEventListener('loadedmetadata', tryPlay);
      v.removeEventListener('canplay', tryPlay);
      document.removeEventListener('touchstart', wakeAll);
      document.removeEventListener('click', wakeAll);
      document.removeEventListener('scroll', wakeAll);
    };
  }, []);

  const onTilePress = (e) => {
    if (!needsTap) return;
    e.preventDefault();
    e.stopPropagation();
    const v = videoRef.current;
    if (!v) return;
    v.muted = true; v.playsInline = true;
    const p = v.play();
    if (p && typeof p.then === 'function') p.then(() => setNeedsTap(false)).catch(() => {});
  };

  return (
    // No inline `flex` — width is locked by CSS `.videoshop-tile` so the
    // 5-col desktop / 2-col mobile rule is never overridden by inline styles.
    <article className="videoshop-tile" style={{ scrollSnapAlign: 'start', display: 'flex', flexDirection: 'column' }}>
      <a href={`/products/${p.slug}`} onClick={onTilePress}
         style={{ position: 'relative', display: 'block', aspectRatio: '9/16', background: '#000', overflow: 'hidden', borderRadius: 8, textDecoration: 'none' }}>
        <video ref={videoRef}
               src={p.video_url}
               poster={img || undefined}
               muted loop playsInline autoPlay
               preload="metadata"
               onError={(e) => console.error('[VideoShop] failed to load:', p.video_url, 'code:', e.target.error?.code)}
               onLoadedData={() => console.log('[VideoShop] ready:', p.video_url)}
               style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        {/* Tappable play overlay — only visible if browser blocks autoplay.
            Tapping the tile (handled by onClick on the parent <a>) starts
            playback and hides this. */}
        {needsTap && (
          <div style={{
            position: 'absolute', inset: 0,
            background: 'rgba(0,0,0,0.35)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', zIndex: 2
          }}>
            <div style={{
              width: 64, height: 64, borderRadius: '50%',
              background: 'rgba(255,255,255,0.92)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 8px 24px rgba(0,0,0,0.35)'
            }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="#0F1A2E"><path d="M8 5v14l11-7z"/></svg>
            </div>
          </div>
        )}
        {/* Gradient + overlaid product mini-card (DailyObjects style) */}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0) 60%, rgba(0,0,0,0.55) 100%)', pointerEvents: 'none' }}/>
        <div className="vs-mini" style={{
          position: 'absolute', left: 10, right: 10, bottom: 10,
          background: 'rgba(255,255,255,0.96)', backdropFilter: 'blur(4px)',
          borderRadius: 6, padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 8
        }}>
          <span style={{ width: 38, height: 38, flexShrink: 0, background: '#fff', border: '1px solid var(--line)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
            {img && <img src={img} alt="" style={{ maxWidth: '85%', maxHeight: '85%', objectFit: 'contain', mixBlendMode: 'multiply' }}/>}
          </span>
          <span style={{ flex: 1, minWidth: 0, color: 'var(--ink)' }}>
            <span style={{ display: 'block', fontWeight: 600, fontSize: 12, lineHeight: 1.25, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</span>
            <span className="mono" style={{ display: 'block', fontSize: 10, marginTop: 1, letterSpacing: '.04em' }}>
              <span style={{ color: 'var(--ink)', fontWeight: 700 }}>{fmt(p.price)}</span>
              {p.orig && Number(p.orig) > Number(p.price) && (
                <span style={{ color: 'var(--muted)', textDecoration: 'line-through', marginLeft: 6, fontWeight: 400 }}>
                  {fmt(p.orig)}
                </span>
              )}
            </span>
          </span>
        </div>
      </a>
      {/* Add to Cart strip + dropdown caret (caret links to product page) */}
      <div style={{ display: 'flex', marginTop: 8, borderRadius: 6, overflow: 'hidden' }}>
        <button onClick={() => { window.litoAdd && window.litoAdd(p.id); }}
                style={{ flex: 1, background: 'var(--ink)', color: 'var(--cream)', border: 0, padding: '14px 16px', cursor: 'pointer', fontFamily: 'Space Grotesk', fontWeight: 600, fontSize: 13, letterSpacing: '.06em', textTransform: 'uppercase' }}>
          Add to cart
        </button>
        <a href={`/products/${p.slug}`} aria-label="Open product"
           style={{ width: 52, background: 'var(--ink)', color: 'var(--cream)', borderLeft: '1px solid rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
        </a>
      </div>
    </article>
  );
}

// ========== INSTAGRAM FEED ==========
// Talks to /api/instagram (server caches Meta Graph response 10 min). Renders
// a 4-up grid on desktop / 2-up on mobile. Each tile clicks through to the
// post on instagram.com. The whole section is hidden if no posts come back
// (so a missing/expired token never leaves a broken-looking band on the page).
const { useState: useStateI, useEffect: useEffectI } = React;
function InstagramGrid() {
  const [items, setItems] = useStateI([]);
  const [ready, setReady] = useStateI(false);
  useEffectI(() => {
    fetch('/api/instagram')
      .then(r => r.ok ? r.json() : { items: [] })
      .then(d => setItems(Array.isArray(d.items) ? d.items.slice(0, 8) : []))
      .catch(() => setItems([]))
      .finally(() => setReady(true));
  }, []);

  if (!ready) return null;          // first paint: render nothing (no flash)
  if (!items.length) return null;   // no posts → hide the section entirely

  return (
    <section className="section ig-section" style={{ padding: '80px 48px', borderTop: '1px solid var(--line)' }}>
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 40, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <span className="mono" style={{ color: 'var(--muted)' }}>◆ ON THE GRID · @LITO</span>
            <h2 className="display" style={{ fontSize: 'clamp(40px, 5vw, 72px)', margin: '12px 0 0', lineHeight: 1.05 }}>
              Follow the <span className="italic-accent">drops.</span>
            </h2>
          </div>
          <a href="https://instagram.com/lito" target="_blank" rel="noopener" className="mono" style={{ textDecoration: 'underline', color: 'var(--ink)' }}>
            @lito on instagram →
          </a>
        </div>
        <div className="ig-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {items.slice(0, 8).map(p => (
            <a key={p.id} href={p.permalink} target="_blank" rel="noopener" className="ig-tile" style={{
              position: 'relative', aspectRatio: '1/1', overflow: 'hidden', borderRadius: 4,
              background: '#000', display: 'block', textDecoration: 'none', color: 'var(--cream)'
            }}>
              <img
                src={p.thumb || p.url}
                alt={p.caption || 'Instagram post'}
                loading="lazy"
                className="ig-img"
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', transition: 'transform .6s cubic-bezier(.2,.7,.2,1), opacity .3s ease' }}
              />
              {/* Hover overlay with caption + IG glyph */}
              <div className="ig-overlay" style={{
                position: 'absolute', inset: 0,
                background: 'linear-gradient(180deg, rgba(0,0,0,0) 40%, rgba(0,0,0,0.78) 100%)',
                opacity: 0, transition: 'opacity .25s ease',
                display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 14
              }}>
                <div style={{ alignSelf: 'flex-end', width: 28, height: 28, border: '1.5px solid #fff', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="#fff"/></svg>
                </div>
                <div style={{ fontSize: 12, lineHeight: 1.35, display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                  {p.caption || ''}
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Categories, Bestsellers, Reviews, Trust, CTA, InstagramGrid, VideoShop, Footer, PRODUCTS, CATS });
