// Homepage, Shop, Product Detail

function useInView(threshold = 0.12) {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVisible(true); obs.disconnect(); }
    }, { threshold });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, visible];
}

function ProductCard({ p, vp, goto, addToCart, wishlist, toggleWish }) {
  const [hover, setHover] = React.useState(false);
  const [imgHover, setImgHover] = React.useState(false);
  const [heartPop, setHeartPop] = React.useState(false);
  const isMobile = vp === 'mobile';
  const handleWish = (e) => { e.stopPropagation(); toggleWish(p.id); setHeartPop(true); setTimeout(() => setHeartPop(false), 420); };
  const isWished = wishlist.includes(p.id);
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} className="card-hover" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div onMouseEnter={() => setImgHover(true)} onMouseLeave={() => setImgHover(false)} style={{ position: 'relative', aspectRatio: '4/5', borderRadius: 8, overflow: 'hidden', background: 'var(--surface)', cursor: 'pointer' }} onClick={() => goto('Product', p.id)}>
        {p.img
          ? <img src={window.imgSrc(p.img)} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', transform: imgHover ? 'scale(1.05)' : 'scale(1)', transition: 'transform 0.4s cubic-bezier(0.22,1,0.36,1)' }}/>
          : <div className="ph product" style={{ width: '100%', height: '100%', border: 'none', transform: imgHover ? 'scale(1.05)' : 'scale(1)', transition: 'transform 0.4s cubic-bezier(0.22,1,0.36,1)' }}>{p.name}<br/>{p.weight}</div>
        }
        {p.badge && <div style={{ position: 'absolute', top: 12, left: 12 }}><span className={`badge ${p.badge === 'Premium' ? 'gold' : p.badge === 'New' ? 'solid' : 'accent'}`}>{p.badge}</span></div>}
        <button onClick={handleWish} className={`wish-btn${heartPop ? ' popping' : ''}`} style={{ position: 'absolute', top: 12, right: 12, width: 32, height: 32, borderRadius: 999, background: 'var(--bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: isWished ? 'var(--accent)' : 'var(--ink)' }}>
          <window.Icon name={isWished ? 'heartFill' : 'heart'} size={14}/>
        </button>
        {(hover || isMobile) && (
          <button onClick={(e) => { e.stopPropagation(); addToCart(p); }}
            style={{ position: 'absolute', bottom: 12, left: 12, right: 12, padding: '11px 12px', background: 'var(--ink)', color: 'var(--bg)', borderRadius: 999, fontSize: 12, fontWeight: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, animation: 'quickAddIn 0.22s cubic-bezier(0.22,1,0.36,1)' }}>
            <window.Icon name="plus" size={12}/> Quick add — ₹{p.price}
          </button>
        )}
      </div>
      <div style={{ padding: '8px 10px 10px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
          <button onClick={() => goto('Product', p.id)} style={{ textAlign: 'left', fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.3 }}>{p.name}</button>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', flexShrink: 0 }}>
            <span style={{ fontSize: 15, fontWeight: 500 }}>₹{p.price}</span>
            {p.mrp > p.price && <span className="mono" style={{ color: 'var(--muted)', textDecoration: 'line-through', fontSize: 9 }}>₹{p.mrp}</span>}
          </div>
        </div>
        <div style={{ color: 'var(--muted)', fontSize: 13, marginBottom: 10, lineHeight: 1.4 }}>{p.tagline}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <window.StarRow rating={p.rating} size={10}/>
          <span className="mono" style={{ color: 'var(--muted)' }}>{p.rating} · {p.reviews.toLocaleString()}</span>
        </div>
      </div>
    </div>
  );
};

function useCounter(target, active, duration = 1400) {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    if (!active) return;
    const num = parseInt(target);
    const start = performance.now();
    const tick = (now) => {
      const p = Math.min((now - start) / duration, 1);
      const ease = 1 - Math.pow(1 - p, 3);
      setCount(Math.round(ease * num));
      if (p < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [active]);
  return count;
}

// ============ HOMEPAGE ============
function HomePage({ vp, goto, addToCart, wishlist, toggleWish, openQuiz, onIngredientSelect }) {
  const isMobile = vp === 'mobile';
  const isTablet = vp === 'tablet';

  const heroProduct = window.PRODUCTS[0];

  const [concernRef, concernVisible] = useInView();
  const [bestsellerRef, bestsellerVisible] = useInView();
  const [ingredientRef, ingredientVisible] = useInView();
  const [reviewRef, reviewVisible] = useInView();
  const [journalRef, journalVisible] = useInView();
  const [ctaRef, ctaVisible] = useInView();
  const [statsRef, statsVisible] = useInView();

  const c0 = useCounter('40', statsVisible);
  const c1 = useCounter('53', statsVisible);
  const c2 = useCounter('6', statsVisible);
  const c3 = useCounter('100', statsVisible);
  const counters = [`${c0}+`, `${c1}`, `${c2}`, `${c3}%`];
  const stats = [['40+', 'herbs per formula'], ['53', 'herbs in Shahi Kalp'], ['6', 'products available'], ['100%', 'cold-processed']];
  const setSelectedIngredient = (h) => onIngredientSelect && onIngredientSelect(h);

  return (
    <div>
      {/* HERO */}
      <section className="container" style={{ padding: isMobile ? '32px 20px 48px' : isTablet ? '40px 32px 64px' : '64px 48px 96px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr', gap: isMobile ? 32 : 48, alignItems: 'center' }}>
          <div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 24 }}>
              <span className="badge gold">Heritage batch · winter '26</span>
            </div>
            <h1 className="h-display" style={{ fontSize: isMobile ? 40 : isTablet ? 52 : 'clamp(52px, 6vw, 88px)', marginBottom: 24 }}>
              <span style={{ display: 'block', overflow: 'hidden' }}>
                <span style={{ display: 'block', animation: 'fadeInUp 0.6s cubic-bezier(0.22,1,0.36,1) 0.1s both' }}>Rooted in Nature,</span>
              </span>
              <span style={{ display: 'block', overflow: 'hidden' }}>
                <span style={{ display: 'block', animation: 'fadeInUp 0.6s cubic-bezier(0.22,1,0.36,1) 0.22s both' }}>Refined for <em style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 400, color: 'var(--primary)' }}>You</em>.</span>
              </span>
            </h1>
            <p style={{ fontSize: isMobile ? 16 : 19, lineHeight: 1.5, color: 'var(--ink-2)', maxWidth: 520, marginBottom: 32, textWrap: 'pretty' }}>
              40+ traditional Ayurvedic herbs, cold-processed to preserve every compound. NK Herbal — Mumbai's trusted name in classical wellness formulations.
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-primary" onClick={() => goto('Product', heroProduct.id)}>Shop {heroProduct.name} — ₹{heroProduct.price.toLocaleString('en-IN')} <window.Icon name="arrR" size={14}/></button>
              <button className="btn btn-ghost" onClick={openQuiz}><window.Icon name="spark" size={14}/> Find my paste in 60s</button>
            </div>
            <div ref={statsRef} style={{ display: 'flex', gap: isMobile ? 16 : 32, marginTop: 48, flexWrap: 'wrap' }}>
              {stats.map(([n, l], i) => {
                const n2 = counters[i];
                return (
                  <div key={l}>
                    <div style={{ fontSize: isMobile ? 28 : 36, fontWeight: 500, letterSpacing: '-0.03em' }}>{n2}</div>
                    <div className="mono" style={{ color: 'var(--muted)', marginTop: 4 }}>{l}</div>
                  </div>
                );
              })}
            </div>
          </div>

          <div style={{ position: 'relative' }}>
            <img src={window.imgSrc('muejaza-hero.png')} alt={heroProduct.name} className="image-reveal" style={{ width: '100%', aspectRatio: '4/5', objectFit: 'cover', borderRadius: 12, display: 'block' }}/>
            <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16, background: 'color-mix(in oklab, var(--bg) 92%, transparent)', backdropFilter: 'blur(8px)', borderRadius: 8, padding: '12px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', border: '1px solid var(--line-soft)' }}>
              <div>
                <div className="mono" style={{ color: 'var(--muted)' }}>Batch NK-101 · Muejaza For Men</div>
                <div style={{ fontSize: 14, fontWeight: 500, marginTop: 4 }}>Cold-processed · 40+ herbs · 300 g</div>
              </div>
              <HoverArrowBtn onClick={() => goto('Ingredients')}/>
            </div>
          </div>
        </div>
      </section>

      {/* SOCIAL PROOF TICKER */}
      <div style={{ background: 'var(--surface)', borderTop: '1px solid var(--line-soft)', borderBottom: '1px solid var(--line-soft)', overflow: 'hidden', padding: '10px 0' }}>
        <style>{`.proof-track { display:flex; width:max-content; animation: marquee 30s linear infinite; } .proof-track:hover { animation-play-state:paused; }`}</style>
        <div className="proof-track">
          {[0,1].map(k => (
            <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
              {[
                { name: 'Rajesh D.', city: 'Mumbai', text: 'Best product for men\'s health. Noticed energy difference in 2 weeks.' },
                { name: 'Priya S.', city: 'Delhi', text: 'Shahi Kalp has become my daily ritual. Sleep is so much better.' },
                { name: 'Jitendar P.', city: 'Bengaluru', text: 'Good quality and fast delivery. Will definitely reorder.' },
                { name: 'Amit K.', city: 'Pune', text: 'The Kashmiri Shilajit quality is unmatched. Authentic resin.' },
                { name: 'Sunita R.', city: 'Chennai', text: 'Finally an Ayurvedic brand that explains what\'s inside the jar.' },
              ].map((r, i) => (
                <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 20, padding: '0 32px', whiteSpace: 'nowrap' }}>
                  <span style={{ display: 'inline-flex', gap: 4, color: 'var(--gold)' }}>★★★★★</span>
                  <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>"{r.text}"</span>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>— {r.name}, {r.city}</span>
                  <span style={{ color: 'var(--line)', fontSize: 16 }}>·</span>
                </span>
              ))}
            </div>
          ))}
        </div>
      </div>

      {/* SHOP BY CONCERN */}
      <section ref={concernRef} className="container" style={{ padding: isMobile ? '32px 20px' : '48px 48px', opacity: concernVisible ? 1 : 0, transform: concernVisible ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.5s cubic-bezier(0.22,1,0.36,1), transform 0.5s cubic-bezier(0.22,1,0.36,1)' }}>
        <div className="between" style={{ marginBottom: 32, flexWrap: 'wrap', gap: 12 }}>
          <h2 className="h-display" style={{ fontSize: isMobile ? 32 : 44 }}>What can we help with today?</h2>
          <button onClick={() => goto('Shop')} className="mono" style={{ color: 'var(--muted)', textDecoration: 'underline' }}>all concerns →</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : isTablet ? 'repeat(3, 1fr)' : 'repeat(6, 1fr)', gap: 12 }}>
          {window.CONCERNS.map(c => (
            <button key={c.id} onClick={() => goto('Shop')} className="concern-card" style={{ padding: '24px 16px', background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 12, display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 24, textAlign: 'left', minHeight: 140, transition: 'all 0.25s' }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink)'; e.currentTarget.style.background = 'var(--bg)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-soft)'; e.currentTarget.style.background = 'var(--surface)'; }}>
              <div className="concern-icon" style={{ width: 36, height: 36, borderRadius: 999, background: 'var(--bg)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--primary)' }}>
                <window.Icon name={c.icon} size={16}/>
              </div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em' }}>{c.label}</div>
                <div className="mono" style={{ color: 'var(--muted)', marginTop: 4 }}>{c.count} products</div>
              </div>
            </button>
          ))}
        </div>
      </section>

      {/* BEST SELLERS */}
      <section ref={bestsellerRef} className="container" style={{ padding: isMobile ? '32px 20px' : '64px 48px', opacity: bestsellerVisible ? 1 : 0, transform: bestsellerVisible ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.5s cubic-bezier(0.22,1,0.36,1), transform 0.5s cubic-bezier(0.22,1,0.36,1)' }}>
        <div className="between" style={{ marginBottom: 32, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="h-eyebrow">Best sellers</div>
            <h2 className="h-display" style={{ fontSize: isMobile ? 32 : 44, marginTop: 8 }}>The jars on every shelf.</h2>
          </div>
          <button onClick={() => goto('Shop')} className="btn btn-ghost">Shop all <window.Icon name="arrR" size={14}/></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: isMobile ? 16 : 28 }}>
          {window.PRODUCTS.slice(0, 4).map((p, i) => (
            <div key={p.id} style={{ opacity: bestsellerVisible ? 1 : 0, transform: bestsellerVisible ? 'translateY(0)' : 'translateY(20px)', transition: `opacity 0.5s cubic-bezier(0.22,1,0.36,1) ${i * 80}ms, transform 0.5s cubic-bezier(0.22,1,0.36,1) ${i * 80}ms` }}>
              <ProductCard p={p} vp={vp} goto={goto} addToCart={addToCart} wishlist={wishlist} toggleWish={toggleWish}/>
            </div>
          ))}
        </div>
      </section>

      {/* HERITAGE / STORY BLOCK */}
      <section style={{ background: 'var(--primary)', color: 'var(--primary-ink)', margin: isMobile ? '32px 0' : '64px 0' }}>
        <div className="container" style={{ padding: isMobile ? '64px 20px' : '120px 48px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1.2fr', gap: isMobile ? 32 : 64, alignItems: 'center' }}>
            <div>
              <div style={{ aspectRatio: '3/4', borderRadius: 12, overflow: 'hidden' }}>
                <img src={window.imgSrc('owner.png')} alt="NK Herbal founder" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
              </div>
            </div>
            <div>
              <div className="mono" style={{ opacity: 0.6, marginBottom: 16 }}>Est. 1962 · Kasaragod, Kerala</div>
              <h2 className="h-display" style={{ fontSize: isMobile ? 36 : 'clamp(48px, 5.5vw, 84px)', marginBottom: 24, textWrap: 'pretty' }}>
                Our grandfather refused to use a pressure cooker.
              </h2>
              <p style={{ fontSize: isMobile ? 16 : 19, lineHeight: 1.55, opacity: 0.9, marginBottom: 16, textWrap: 'pretty' }}>
                He believed slow heat changed the medicine — not the chemistry on paper, but what your body felt at the third teaspoon, the third month. We have not changed his mind.
              </p>
              <p style={{ fontSize: isMobile ? 16 : 19, lineHeight: 1.55, opacity: 0.9, marginBottom: 32, textWrap: 'pretty' }}>
                Every jar still takes 21 days, three vaidyas, one wood fire, and a frankly inconvenient amount of patience.
              </p>
              <button onClick={() => goto('About')} className="btn" style={{ background: 'var(--primary-ink)', color: 'var(--primary)' }}>The full story <window.Icon name="arrR" size={14}/></button>
            </div>
          </div>
        </div>
      </section>

      {/* BENTO GRID */}
      <section className="container" style={{ padding: isMobile ? '32px 20px' : '64px 48px' }}>
        <div className="h-eyebrow" style={{ marginBottom: 20 }}>Why NK Herbal</div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gridTemplateRows: 'auto', gap: 12 }}>
          {/* Large tile */}
          <div style={{ gridColumn: isMobile ? 'span 2' : 'span 2', gridRow: 'span 2', background: 'var(--ink)', color: 'var(--bg)', borderRadius: 16, padding: isMobile ? 24 : 36, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: isMobile ? 180 : 280 }}>
            <div className="mono" style={{ color: 'var(--gold)', fontSize: 10 }}>Cold-processed</div>
            <div>
              <div style={{ fontSize: isMobile ? 32 : 48, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1.05, marginBottom: 12 }}>40+<br/>herbs per<br/>formula</div>
              <div style={{ fontSize: 13, opacity: 0.7, lineHeight: 1.5 }}>Every formulation is cold-processed to preserve heat-sensitive compounds lost in conventional cooking.</div>
            </div>
          </div>
          {/* Cert tile */}
          <div style={{ background: 'var(--surface)', borderRadius: 16, padding: 20, border: '1px solid var(--line-soft)', display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.03em' }}>FSSAI</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>Approved & registered</div>
            <div style={{ marginTop: 'auto', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {['ISO 9001', 'Non-GMO', 'Cruelty Free'].map(c => <span key={c} className="badge" style={{ fontSize: 9 }}>{c}</span>)}
            </div>
          </div>
          {/* Shipping tile */}
          <div style={{ background: 'var(--primary)', color: 'var(--primary-ink)', borderRadius: 16, padding: 20, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
            <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>Free<br/>delivery</div>
            <div className="mono" style={{ fontSize: 10, opacity: 0.8 }}>Pan India · all orders</div>
          </div>
          {/* Save tile */}
          <div style={{ background: 'color-mix(in oklab, var(--gold) 12%, var(--bg))', border: '1px solid color-mix(in oklab, var(--gold) 30%, transparent)', borderRadius: 16, padding: 20 }}>
            <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--gold)', marginBottom: 6 }}>Save ₹499</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>Use code SAVE499 on first order</div>
          </div>
          {/* Review tile */}
          <div style={{ gridColumn: isMobile ? 'span 2' : 'span 1', background: 'var(--surface)', borderRadius: 16, padding: 20, border: '1px solid var(--line-soft)' }}>
            <div style={{ display: 'flex', gap: 2, color: 'var(--gold)', marginBottom: 10 }}>{'★★★★★'}</div>
            <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--ink-2)' }}>"Best product for men's health. Noticed energy difference in 2 weeks."</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginTop: 10 }}>Rajesh D. · Mumbai · verified</div>
          </div>
        </div>
      </section>

      {/* INGREDIENT SHELF */}
      <section ref={ingredientRef} className="container" style={{ padding: isMobile ? '32px 20px' : '64px 48px', opacity: ingredientVisible ? 1 : 0, transform: ingredientVisible ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.5s cubic-bezier(0.22,1,0.36,1), transform 0.5s cubic-bezier(0.22,1,0.36,1)' }}>
        <div className="between" style={{ marginBottom: 32, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="h-eyebrow">The herb shelf</div>
            <h2 className="h-display" style={{ fontSize: isMobile ? 32 : 44, marginTop: 8 }}>Sourcing is the recipe.</h2>
          </div>
          <button onClick={() => goto('Ingredients')} className="btn btn-ghost">Every ingredient <window.Icon name="arrR" size={14}/></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : isTablet ? 'repeat(3, 1fr)' : 'repeat(6, 1fr)', gap: isMobile ? 12 : 20 }}>
          {window.HERO_INGREDIENTS.map((h, i) => (
            <button key={h.name} onClick={() => setSelectedIngredient(h)} style={{ textAlign: 'left', padding: 0, opacity: ingredientVisible ? 1 : 0, transform: ingredientVisible ? 'translateY(0)' : 'translateY(16px)', transition: `opacity 0.45s cubic-bezier(0.22,1,0.36,1) ${i * 60}ms, transform 0.45s cubic-bezier(0.22,1,0.36,1) ${i * 60}ms` }}>
              {h.img
                ? <img src={window.imgSrc(h.img)} alt={h.name} style={{ width: '100%', aspectRatio: '1/1', objectFit: 'cover', borderRadius: 8, display: 'block', marginBottom: 12 }}/>
                : <div className="ph" style={{ aspectRatio: '1/1', marginBottom: 12, borderRadius: 8 }}>{h.name}</div>
              }
              <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.01em' }}>{h.name}</div>
              <div className="serif" style={{ color: 'var(--muted)', fontSize: 12, fontStyle: 'italic', marginTop: 2 }}>{h.latin}</div>
              <div className="mono" style={{ color: 'var(--accent)', marginTop: 8, fontSize: 10 }}>{h.role}</div>
            </button>
          ))}
        </div>
      </section>

      {/* REVIEWS */}
      <section ref={reviewRef} className="container" style={{ padding: isMobile ? '32px 20px' : '64px 48px', opacity: reviewVisible ? 1 : 0, transform: reviewVisible ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.5s cubic-bezier(0.22,1,0.36,1), transform 0.5s cubic-bezier(0.22,1,0.36,1)' }}>
        <div style={{ marginBottom: 32 }}>
          <div className="h-eyebrow">Verified customer reviews</div>
          <h2 className="h-display" style={{ fontSize: isMobile ? 32 : 44, marginTop: 8, display: 'flex', alignItems: 'baseline', gap: 16, flexWrap: 'wrap' }}>
            4.5 <window.StarRow rating={4.5} size={28}/> <span style={{ color: 'var(--muted)', fontSize: isMobile ? 18 : 22, fontWeight: 400, letterSpacing: 0 }}>out of five</span>
          </h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 16 : 24 }}>
          {window.REVIEWS.map((r, i) => (
            <div key={i} style={{ padding: 28, background: 'var(--surface)', borderRadius: 12, border: '1px solid var(--line-soft)' }}>
              <window.StarRow rating={r.rating} size={14}/>
              <h4 style={{ fontSize: 19, fontWeight: 500, letterSpacing: '-0.02em', margin: '16px 0', lineHeight: 1.25 }}>{r.title}</h4>
              <p style={{ color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 24, fontSize: 14, textWrap: 'pretty' }}>{r.body}</p>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 16, borderTop: '1px solid var(--line-soft)' }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{r.name}</div>
                  <div className="mono" style={{ color: 'var(--muted)', marginTop: 2 }}>{r.city}</div>
                </div>
                <span className="mono" style={{ color: 'var(--primary)', display: 'inline-flex', alignItems: 'center', gap: 4 }}><window.Icon name="check" size={11}/>verified</span>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* WHATSAPP CTA */}
      <section ref={ctaRef} className="container" style={{ padding: isMobile ? '32px 20px' : '64px 48px', opacity: ctaVisible ? 1 : 0, transform: ctaVisible ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.5s cubic-bezier(0.22,1,0.36,1), transform 0.5s cubic-bezier(0.22,1,0.36,1)' }}>
        <div style={{ background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 16, padding: isMobile ? 32 : 56, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 32, alignItems: 'center' }}>
          <div>
            <div className="mono" style={{ color: 'var(--accent)', marginBottom: 16 }}>Mon–Sat · 10 am – 7 pm IST</div>
            <h2 className="h-display" style={{ fontSize: isMobile ? 32 : 48, marginBottom: 16 }}>Have a question? Chat with us.</h2>
            <p style={{ fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 24, textWrap: 'pretty' }}>Not sure which formula is right for you? Our team is on WhatsApp — ask about ingredients, dosage, or anything else before you order.</p>
            <a href="https://wa.me/919867800415" target="_blank" rel="noopener noreferrer" className="btn btn-primary" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
              WhatsApp us
            </a>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {[
              { q: 'Which formula suits me?', a: 'Tell us your health goal and we\'ll point you to the right one.' },
              { q: 'What\'s in each jar?', a: 'Full ingredient lists, sourcing, and lab reports — no secrets.' },
              { q: 'Delivery & returns?', a: 'Free shipping across India · 7-day return policy.' },
            ].map(({ q, a }) => (
              <div key={q} style={{ padding: '14px 18px', background: 'var(--bg)', borderRadius: 10, border: '1px solid var(--line-soft)' }}>
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{q}</div>
                <div style={{ fontSize: 13, color: 'var(--muted)' }}>{a}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* JOURNAL TEASERS */}
      <section ref={journalRef} className="container" style={{ padding: isMobile ? '32px 20px' : '64px 48px', opacity: journalVisible ? 1 : 0, transform: journalVisible ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.5s cubic-bezier(0.22,1,0.36,1), transform 0.5s cubic-bezier(0.22,1,0.36,1)' }}>
        <div className="between" style={{ marginBottom: 32, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="h-eyebrow">The journal</div>
            <h2 className="h-display" style={{ fontSize: isMobile ? 32 : 44, marginTop: 8 }}>Slower reading.</h2>
          </div>
          <button onClick={() => goto('Journal')} className="btn btn-ghost">All notes <window.Icon name="arrR" size={14}/></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: isMobile ? 16 : 20 }}>
          {window.JOURNAL.map(j => (
            <button key={j.id} onClick={() => goto('Journal')} style={{ textAlign: 'left' }}>
              <div className="ph" style={{ aspectRatio: '4/3', borderRadius: 8, marginBottom: 16 }}>{j.cat}</div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 8 }}>
                <span className="badge">{j.cat}</span>
                <span className="mono" style={{ color: 'var(--muted)' }}>{j.read}</span>
              </div>
              <h4 style={{ fontSize: 18, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.25, marginBottom: 8, textWrap: 'pretty' }}>{j.title}</h4>
              <p style={{ color: 'var(--muted)', fontSize: 13, lineHeight: 1.5 }}>{j.excerpt}</p>
            </button>
          ))}
        </div>
      </section>

    </div>
  );
};

function HoverArrowBtn({ onClick }) {
  const [hov, setHov] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ width: 36, height: 36, borderRadius: 999, border: `1px solid ${hov ? 'var(--ink)' : 'var(--line)'}`, background: hov ? 'var(--ink)' : 'transparent', color: hov ? 'var(--bg)' : 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', position: 'relative', transition: 'all 0.25s cubic-bezier(0.22,1,0.36,1)' }}>
      <span style={{ display: 'inline-flex', transform: hov ? 'rotate(0deg)' : 'rotate(45deg)', transition: 'transform 0.25s cubic-bezier(0.22,1,0.36,1)' }}>
        <window.Icon name="arrUR" size={14}/>
      </span>
    </button>
  );
}

function CheckItem({ label }) {
  const [checked, setChecked] = React.useState(false);
  return (
    <button onClick={() => setChecked(c => !c)} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 14, textAlign: 'left', transition: 'opacity 0.2s' }}>
      <span style={{ width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${checked ? '#b8945e' : 'var(--line)'}`, background: checked ? '#b8945e' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'all 0.18s cubic-bezier(0.22,1,0.36,1)', color: '#fff' }}>
        {checked && <window.Icon name="check" size={10}/>}
      </span>
      <span style={{ color: checked ? 'var(--ink)' : 'var(--ink-2)' }}>{label}</span>
    </button>
  );
}

function SortDropdown({ value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const options = [
    { v: 'featured', l: 'Featured' },
    { v: 'rating', l: 'Top rated' },
    { v: 'price-low', l: 'Price: low → high' },
    { v: 'price-high', l: 'Price: high → low' },
  ];
  const selected = options.find(o => o.v === value);
  React.useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 16px', borderRadius: 999, border: '1px solid var(--line)', background: 'var(--bg)', fontSize: 13, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.01em', transition: 'border-color 0.2s' }}
        onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--ink)'}
        onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}>
        {selected.l}
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ opacity: 0.5, transform: open ? 'rotate(180deg)' : 'rotate(0)', transition: 'transform 0.2s' }}><path d="M6 9l6 6 6-6"/></svg>
      </button>
      {open && (
        <div style={{ position: 'absolute', top: 'calc(100% + 6px)', right: 0, background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden', zIndex: 50, minWidth: 180, boxShadow: '0 8px 32px rgba(42,32,26,0.12)', animation: 'fadeInUp 0.18s cubic-bezier(0.22,1,0.36,1)' }}>
          {options.map(o => (
            <button key={o.v} onClick={() => { onChange(o.v); setOpen(false); }}
              style={{ display: 'block', width: '100%', textAlign: 'left', padding: '11px 16px', fontSize: 13, fontWeight: o.v === value ? 500 : 400, color: o.v === value ? 'var(--primary)' : 'var(--ink)', background: o.v === value ? 'var(--surface)' : 'transparent', transition: 'background 0.15s' }}
              onMouseEnter={e => { if (o.v !== value) e.currentTarget.style.background = 'var(--surface)'; }}
              onMouseLeave={e => { if (o.v !== value) e.currentTarget.style.background = 'transparent'; }}>
              {o.l}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// ============ SHOP LISTING ============
function ShopPage({ vp, goto, addToCart, wishlist, toggleWish }) {
  const isMobile = vp === 'mobile';
  const isTablet = vp === 'tablet';
  const [filter, setFilter] = React.useState('all');
  const [sort, setSort] = React.useState('featured');
  const [openFilter, setOpenFilter] = React.useState(false);
  const [maxPrice, setMaxPrice] = React.useState(15000);
  const [gridKey, setGridKey] = React.useState(0);

  const applyFilter = (f) => { setFilter(f); setGridKey(k => k + 1); };
  // Only animate grid on release, not on every slider tick
  const handlePriceChange = (e) => setMaxPrice(Number(e.target.value));
  const handlePriceRelease = () => setGridKey(k => k + 1);

  let products = window.PRODUCTS.filter(p => (filter === 'all' || p.concerns.includes(filter)) && p.price <= maxPrice);
  if (sort === 'price-low') products = [...products].sort((a, b) => a.price - b.price);
  if (sort === 'price-high') products = [...products].sort((a, b) => b.price - a.price);
  if (sort === 'rating') products = [...products].sort((a, b) => b.rating - a.rating);

  return (
    <div className="container" style={{ padding: isMobile ? '32px 20px 64px' : '64px 48px 96px' }}>
      <div style={{ marginBottom: 40 }}>
        <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12 }}>Home / Shop / All pastes</div>
        <h1 className="h-display" style={{ fontSize: isMobile ? 44 : 'clamp(56px, 6.5vw, 96px)' }}>Every formula, in one place.</h1>
        <p style={{ fontSize: 17, color: 'var(--ink-2)', marginTop: 16, maxWidth: 600 }}>Six formulations. 40–53 herbs each. Cold-processed, preservative-free, FSSAI approved.</p>
      </div>

      <div style={{ display: 'flex', gap: 32, alignItems: 'flex-start' }}>
        {/* Sidebar filter */}
        {!isMobile && (
          <aside style={{ width: 240, flexShrink: 0, position: 'sticky', top: 100 }}>
            <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>Filter by concern</div>
            <div className="col gap-2">
              {[{id:'all',label:'All pastes'}, ...window.CONCERNS].map(c => (
                <button key={c.id} onClick={() => applyFilter(c.id)} style={{ textAlign: 'left', padding: '10px 0', fontSize: 15, color: filter === c.id ? 'var(--ink)' : 'var(--ink-2)', fontWeight: filter === c.id ? 500 : 400, display: 'flex', justifyContent: 'space-between', borderBottom: filter === c.id ? '1px solid var(--ink)' : '1px solid transparent', transition: 'all 0.2s' }}>
                  <span>{c.label}</span>
                  <span className="mono" style={{ color: 'var(--muted)' }}>{c.count || window.PRODUCTS.length}</span>
                </button>
              ))}
            </div>
            <div className="divider" style={{ margin: '24px 0' }}/>
            <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12 }}>Price</div>
            <div style={{ padding: '12px 0' }}>
              <input type="range" min="1499" max="15000" value={maxPrice} onChange={handlePriceChange} onMouseUp={handlePriceRelease} onTouchEnd={handlePriceRelease} style={{ width: '100%', accentColor: 'var(--ink)' }}/>
              <div className="between mono" style={{ color: 'var(--muted)', marginTop: 6 }}><span>₹1,499</span><span style={{ color: 'var(--ink)', fontWeight: 500 }}>₹{maxPrice.toLocaleString('en-IN')}</span></div>
            </div>
            <div className="divider" style={{ margin: '24px 0' }}/>
            <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12 }}>Suitable for</div>
            <div className="col gap-2">
              {['Diabetics', 'Kids 3+', 'Pregnancy-safe', 'Vegan'].map(t => (
                <CheckItem key={t} label={t}/>
              ))}
            </div>
          </aside>
        )}

        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="between" style={{ marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
            <div className="mono" style={{ color: 'var(--muted)' }}>{products.length} pastes</div>
            <div style={{ display: 'flex', gap: 10 }}>
              {isMobile && <button onClick={() => setOpenFilter(true)} className="btn btn-ghost btn-sm">Filters</button>}
              <SortDropdown value={sort} onChange={setSort}/>
            </div>
          </div>

          <div key={gridKey} style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)', gap: isMobile ? 16 : 28 }}>
            {products.length ? products.map((p, i) => (
              <div key={p.id} style={{ animation: `fadeInUp 0.45s cubic-bezier(0.22,1,0.36,1) ${i * 150}ms both` }}>
                <ProductCard p={p} vp={vp} goto={goto} addToCart={addToCart} wishlist={wishlist} toggleWish={toggleWish}/>
              </div>
            )) : (
              <div style={{ gridColumn: '1/-1', padding: '48px 0', textAlign: 'center', color: 'var(--muted)' }}>
                <div style={{ fontSize: 32, marginBottom: 12 }}>—</div>
                <div className="mono">No products in this range</div>
              </div>
            )}
          </div>

          {/* Bundle banner mid-grid */}
          <div style={{ marginTop: 48, padding: isMobile ? 24 : 40, background: 'var(--ink)', color: 'var(--bg)', borderRadius: 12, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.2fr 1fr', gap: 24, alignItems: 'center' }}>
            <div>
              <div className="mono" style={{ color: 'var(--gold)', marginBottom: 12 }}>Bundle & save · ₹3,001 off</div>
              <h3 className="h-display" style={{ fontSize: isMobile ? 28 : 40, marginBottom: 12 }}>The wellness duo.</h3>
              <p style={{ opacity: 0.8, marginBottom: 24, lineHeight: 1.5 }}>Muejaza + Shahi Kalp. Complete daily wellness for the whole family, cold-processed and FSSAI approved.</p>
              <button className="btn" style={{ background: 'var(--gold)', color: 'var(--ink)' }}>Get the combo — ₹8,999</button>
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
              {window.PRODUCTS.slice(0, 3).map(p => <div key={p.id} className="ph product" style={{ width: 90, height: 110, background: 'rgba(255,255,255,0.05)', color: 'rgba(255,255,255,0.4)' }}>{p.name.split(' ')[0]}</div>)}
            </div>
          </div>
        </div>
      </div>

      {/* Mobile filter sheet */}
      {openFilter && isMobile && (
        <div style={{ position: 'fixed', inset: 0, background: 'var(--bg)', zIndex: 200, padding: 20, overflowY: 'auto' }}>
          <div className="between" style={{ marginBottom: 24 }}>
            <div style={{ fontSize: 22, fontWeight: 500 }}>Filters</div>
            <button onClick={() => setOpenFilter(false)}><window.Icon name="close" size={20}/></button>
          </div>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12 }}>Concern</div>
          <div className="col gap-2" style={{ marginBottom: 24 }}>
            {[{id:'all',label:'All pastes'}, ...window.CONCERNS].map(c => (
              <button key={c.id} onClick={() => { setFilter(c.id); setOpenFilter(false); }} style={{ textAlign: 'left', padding: '14px 0', fontSize: 16, borderBottom: '1px solid var(--line-soft)', color: filter === c.id ? 'var(--ink)' : 'var(--ink-2)' }}>{c.label}</button>
            ))}
          </div>
          <button className="btn btn-primary" style={{ width: '100%' }} onClick={() => setOpenFilter(false)}>Apply</button>
        </div>
      )}
    </div>
  );
};

function MagnifierImage({ src, alt, onZoom }) {
  const [lens, setLens] = React.useState(null);
  const ref = React.useRef(null);
  const LENS = 150, ZOOM = 2.8;

  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    setLens({ x: e.clientX - r.left, y: e.clientY - r.top, w: r.width, h: r.height });
  };

  return (
    <div ref={ref} style={{ position: 'relative', aspectRatio: '4/5', borderRadius: 12, overflow: 'hidden', cursor: 'crosshair' }}
      onMouseMove={onMove} onMouseLeave={() => setLens(null)} onClick={() => onZoom && onZoom(src)}>
      <img src={src} alt={alt} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
      {lens && (
        <div style={{
          position: 'absolute',
          left: lens.x - LENS / 2, top: lens.y - LENS / 2,
          width: LENS, height: LENS, borderRadius: '50%',
          border: '2px solid rgba(255,255,255,0.7)',
          boxShadow: '0 4px 24px rgba(0,0,0,0.25)',
          pointerEvents: 'none',
          backgroundImage: `url(${src})`,
          backgroundSize: `${lens.w * ZOOM}px ${lens.h * ZOOM}px`,
          backgroundPositionX: `${-(lens.x * ZOOM) + LENS / 2}px`,
          backgroundPositionY: `${-(lens.y * ZOOM) + LENS / 2}px`,
          backgroundRepeat: 'no-repeat',
        }}/>
      )}
    </div>
  );
};

// ============ PRODUCT DETAIL ============
function ProductPage({ vp, goto, addToCart, wishlist, toggleWish, productId, onStickyATC, openQuiz, onZoom }) {
  const isMobile = vp === 'mobile';
  const isTablet = vp === 'tablet';
  const p = window.PRODUCTS.find(x => x.id === productId) || window.PRODUCTS[0];

  const [qty, setQty] = React.useState(1);
  const [variantIdx, setVariantIdx] = React.useState(0);
  const [tab, setTab] = React.useState('how');
  const [heartPop, setHeartPop] = React.useState(false);
  const handleWish = () => { toggleWish(p.id); setHeartPop(true); setTimeout(() => setHeartPop(false), 420); };
  const [activeImg, setActiveImg] = React.useState(0);
  const [showStickyATC, setShowStickyATC] = React.useState(false);
  const atcRef = React.useRef(null);
  const atcSeenRef = React.useRef(false);
  // Tab indicator — moved to component level to fix hooks-in-IIFE violation
  const TABS = [['how','How to take'], ['ingr','Ingredients'], ['science','The science'], ['faq','FAQ']];
  const tabRefs = React.useRef([]);
  const [indicatorStyle, setIndicatorStyle] = React.useState({ left: 0, width: 0 });
  React.useEffect(() => {
    const idx = TABS.findIndex(([id]) => id === tab);
    const el = tabRefs.current[idx];
    if (el) setIndicatorStyle({ left: el.offsetLeft, width: el.offsetWidth });
  }, [tab]);

  React.useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) atcSeenRef.current = true;
      if (atcSeenRef.current) setShowStickyATC(!e.isIntersecting);
    }, { threshold: 0 });
    if (atcRef.current) obs.observe(atcRef.current);
    return () => { obs.disconnect(); onStickyATC && onStickyATC(null); };
  }, []);

  React.useEffect(() => {
    if (onStickyATC) onStickyATC(showStickyATC ? { p, price, qty, addToCart, goto } : null);
  }, [showStickyATC, price, qty]);

  // Track recently viewed in localStorage
  React.useEffect(() => {
    const key = 'nkh_viewed';
    const existing = JSON.parse(localStorage.getItem(key) || '[]');
    const updated = [p.id, ...existing.filter(x => x !== p.id)].slice(0, 4);
    localStorage.setItem(key, JSON.stringify(updated));
  }, [p.id]);

  const isWished = wishlist.includes(p.id);
  const activeVariant = p.variants ? p.variants[variantIdx] : null;
  const price = activeVariant ? activeVariant.price : p.price;
  const mrp = activeVariant ? activeVariant.mrp : p.mrp;
  const weight = activeVariant ? activeVariant.label : p.weight;

  return (
    <div>
      <div className="container" style={{ padding: isMobile ? '24px 20px 48px' : '40px 48px 80px' }}>
        <div className="mono" style={{ color: 'var(--muted)', marginBottom: 24 }}>
          <button onClick={() => goto('Home')}>Home</button> / <button onClick={() => goto('Shop')}>Shop</button> / <span style={{ color: 'var(--ink)' }}>{p.name}</span>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : isTablet ? '1fr 1fr' : '1.1fr 1fr', gap: isMobile ? 32 : 64 }}>
          {/* Gallery */}
          <div style={{ display: 'flex', gap: 12, flexDirection: isMobile ? 'column' : 'row' }}>
            {!isMobile && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[0].map(i => (
                  <button key={i} onClick={() => setActiveImg(i)} style={{ width: 64, height: 80, borderRadius: 4, border: activeImg === i ? '1.5px solid var(--ink)' : '1px solid var(--line)', overflow: 'hidden', background: 'var(--surface)' }}>
                    {p.img
                      ? <img src={p.img} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                      : <div className="ph" style={{ width: '100%', height: '100%', fontSize: 9 }}>{i+1}</div>
                    }
                  </button>
                ))}
              </div>
            )}
            <div style={{ flex: 1, position: 'relative' }}>
              {p.img
                ? <MagnifierImage src={p.img} alt={p.name} onZoom={onZoom}/>
                : <div className="ph product" style={{ aspectRatio: '4/5', borderRadius: 12, fontSize: 14 }}>{p.name}<br/><span style={{ opacity: 0.7 }}>No image yet</span></div>
              }
              <div style={{ position: 'absolute', top: 16, right: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <button onClick={handleWish} className={`wish-btn${heartPop ? ' popping' : ''}`} style={{ width: 40, height: 40, borderRadius: 999, background: 'var(--bg)', border: '1px solid var(--line)', color: isWished ? 'var(--accent)' : 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon name={isWished ? 'heartFill' : 'heart'} size={16}/></button>
                <button onClick={() => openQuiz && openQuiz()} title="Find similar products" style={{ width: 40, height: 40, borderRadius: 999, background: 'var(--bg)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background 0.2s, transform 0.2s' }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--surface)'; e.currentTarget.style.transform = 'rotate(30deg)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg)'; e.currentTarget.style.transform = 'rotate(0deg)'; }}>
                  <window.Icon name="spark" size={16}/>
                </button>
              </div>
              {isMobile && p.img && (
                <div style={{ display: 'flex', gap: 8, marginTop: 12, overflowX: 'auto' }}>
                  <button className="ph" style={{ minWidth: 60, height: 75, borderRadius: 4, border: '1.5px solid var(--ink)', overflow: 'hidden', padding: 0 }}>
                    <img src={p.img} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Info */}
          <div>
            {p.badge && <span className={`badge ${p.badge === 'Premium' ? 'gold' : p.badge === 'New' ? 'solid' : 'accent'}`} style={{ marginBottom: 12 }}>{p.badge}</span>}
            <h1 className="h-display" style={{ fontSize: isMobile ? 36 : 56, marginTop: 12, marginBottom: 8 }}>{p.name}</h1>
            <p style={{ fontSize: 17, color: 'var(--ink-2)', marginBottom: 20 }}>{p.tagline}</p>

            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 24 }}>
              <window.StarRow rating={p.rating}/>
              <span className="mono" style={{ color: 'var(--muted)' }}>{p.rating} · {p.reviews.toLocaleString()} reviews</span>
            </div>

            <p style={{ fontSize: 16, lineHeight: 1.55, color: 'var(--ink-2)', marginBottom: 32, textWrap: 'pretty' }}>{p.description}</p>

            {p.variants ? (
              <div style={{ marginBottom: 24 }}>
                <div className="mono" style={{ color: 'var(--muted)', marginBottom: 8 }}>Size</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {p.variants.map((v, i) => (
                    <button key={v.label} onClick={() => setVariantIdx(i)} style={{ flex: 1, padding: 14, borderRadius: 8, border: variantIdx === i ? '1.5px solid var(--ink)' : '1px solid var(--line)', background: variantIdx === i ? 'var(--surface)' : 'transparent', textAlign: 'left' }}>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{v.label}</div>
                      <div className="mono" style={{ color: 'var(--muted)', marginTop: 4, fontSize: 11 }}>₹{v.price.toLocaleString('en-IN')}</div>
                    </button>
                  ))}
                </div>
              </div>
            ) : (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '10px 16px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 8, marginBottom: 24 }}>
                <window.Icon name="check" size={13}/>
                <span style={{ fontSize: 14, fontWeight: 500 }}>{p.weight}</span>
                <span className="mono" style={{ color: 'var(--muted)', fontSize: 10 }}>· one size</span>
              </div>
            )}

            <div className="between" style={{ marginBottom: 24 }}>
              <div>
                <div style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em' }}>₹{(price * qty).toLocaleString('en-IN')}</div>
                <div className="mono" style={{ color: 'var(--muted)', marginTop: 4 }}>MRP ₹{mrp.toLocaleString('en-IN')} · inclusive of all taxes</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--line)', borderRadius: 999 }}>
                <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ padding: 12 }}><window.Icon name="minus" size={14}/></button>
                <span style={{ padding: '0 12px', fontFamily: 'var(--font-mono)' }}>{qty}</span>
                <button onClick={() => setQty(qty + 1)} style={{ padding: 12 }}><window.Icon name="plus" size={14}/></button>
              </div>
            </div>

            <div ref={atcRef} style={{ display: 'flex', gap: 10, marginBottom: 32 }}>
              <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => { addToCart(p, qty); }}>Add to basket</button>
              <button className="btn btn-dark" onClick={() => { addToCart(p, qty); goto('Checkout'); }}>Buy now</button>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13, marginBottom: 20 }}>
              {[['Ships in 24h', 'Cold-chain dispatch'], ['Free shipping', 'Across India'], ['Lab-tested', 'Every batch'], ['Returns', '7-day, no questions']].map(([t, s]) => (
                <div key={t} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <window.Icon name="check" size={14}/>
                  <div>
                    <div style={{ fontWeight: 500 }}>{t}</div>
                    <div style={{ color: 'var(--muted)', fontSize: 12, marginTop: 2 }}>{s}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Batch transparency */}
            <div style={{ padding: '14px 16px', background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 3 }}>Current batch</div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>Batch #NK-{Math.abs(p.id.charCodeAt(0) * 7 % 900) + 100} · Made Jan 2026</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>FSSAI approved · ISO 9001-2015 · Lab-tested</div>
              </div>
              <button className="mono" style={{ fontSize: 10, color: 'var(--primary)', border: '1px solid var(--primary)', padding: '6px 10px', borderRadius: 999, whiteSpace: 'nowrap' }}>View report ↗</button>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ marginTop: 96 }}>
          <div className="tab-bar" style={{ display: 'flex', gap: 32, borderBottom: '1px solid var(--line)', marginBottom: 40, overflowX: 'auto' }}>
            {TABS.map(([id, l], i) => (
              <button key={id} ref={el => tabRefs.current[i] = el} onClick={() => setTab(id)} style={{ padding: '16px 0', fontSize: 15, fontWeight: tab === id ? 500 : 400, color: tab === id ? 'var(--ink)' : 'var(--muted)', whiteSpace: 'nowrap', transition: 'color 0.2s' }}>{l}</button>
            ))}
            <div className="tab-indicator" style={{ left: indicatorStyle.left, width: indicatorStyle.width }}/>
          </div>

          {tab === 'how' && (
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: 32 }}>
              {[
                { n: '01', t: 'Morning, on an empty stomach', d: 'One teaspoon (5g) by itself, or stirred into warm milk for kids and elders. Wait 20 minutes before food.' },
                { n: '02', t: 'Daily, through cool months', d: 'Take consistently from late September through March. In summer, halve the dose or switch to evening with cold milk.' },
                { n: '03', t: 'Pair with the morning ritual', d: 'Works best alongside warm water and twenty minutes of gentle movement. Avoid heavy fats or curd directly after.' },
              ].map(s => (
                <div key={s.n}>
                  <div className="mono" style={{ color: 'var(--accent)', marginBottom: 12 }}>{s.n}</div>
                  <h4 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 12 }}>{s.t}</h4>
                  <p style={{ color: 'var(--ink-2)', lineHeight: 1.55, fontSize: 15, textWrap: 'pretty' }}>{s.d}</p>
                </div>
              ))}
            </div>
          )}

          {tab === 'ingr' && (
            <div>
              <p style={{ fontSize: 16, color: 'var(--ink-2)', marginBottom: 24, maxWidth: 600, lineHeight: 1.5 }}>The full list — every herb, every quantity, every source. Nothing on the label that is not in the jar.</p>
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 12 }}>
                {window.HERO_INGREDIENTS.concat(window.HERO_INGREDIENTS).map((h, i) => (
                  <div key={i} style={{ padding: '16px 20px', background: 'var(--surface)', borderRadius: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{h.name}</div>
                      <div className="serif" style={{ fontStyle: 'italic', color: 'var(--muted)', fontSize: 12, marginTop: 2 }}>{h.latin}</div>
                    </div>
                    <div className="mono" style={{ color: 'var(--muted)' }}>{h.note.split(',')[0]}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === 'science' && (
            <div style={{ maxWidth: 720 }}>
              <p style={{ fontSize: isMobile ? 18 : 22, lineHeight: 1.5, color: 'var(--ink-2)', marginBottom: 24, textWrap: 'pretty' }}>The classical text Charaka Samhita describes chyawanprash as a <em className="serif">rasayana</em> — a formulation that improves the body's capacity to do its own work. We have not tried to improve on that idea.</p>
              <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink-2)', marginBottom: 24, textWrap: 'pretty' }}>What we have done is publish our lab work: heavy-metal panels for every batch, microbiology results, vitamin-C retention curves after the slow cook. Every batch number on the jar links to a one-page report.</p>
              <button className="btn btn-ghost">See batch {412} lab report <window.Icon name="arrUR" size={14}/></button>
            </div>
          )}

          {tab === 'faq' && (
            <div style={{ maxWidth: 720 }}>
              {[
                ['Is it safe for diabetics?', 'The classic recipe contains jaggery and honey. For diabetics, choose our Sugar-Free version (sweetened with whole dates) or consult our vaidya for a personalised plan.'],
                ['Can children take it?', 'Yes — but use the Kids formulation for ages 3+. The classic is calibrated for adolescents and adults.'],
                ['Why does the taste vary slightly between batches?', 'Because the herbs vary. Amla in November is different from amla in February. We let the difference through; we do not flatten it with flavoring.'],
                ['How long does an open jar keep?', 'Refrigerated, 6 months. At room temperature (below 25°C), 3 months. Always use a dry spoon.'],
              ].map(([q, a]) => (
                <details key={q} style={{ borderBottom: '1px solid var(--line-soft)', padding: '20px 0' }}>
                  <summary style={{ fontSize: 17, fontWeight: 500, cursor: 'pointer', listStyle: 'none', display: 'flex', justifyContent: 'space-between', gap: 16 }}>{q}<span className="faq-icon"><window.Icon name="plus" size={16}/></span></summary>
                  <p style={{ marginTop: 12, color: 'var(--ink-2)', lineHeight: 1.6, textWrap: 'pretty' }}>{a}</p>
                </details>
              ))}
            </div>
          )}
        </div>

        {/* You might also like */}
        <div style={{ marginTop: 80 }}>
          <h2 className="h-display" style={{ fontSize: isMobile ? 28 : 40, marginBottom: 32 }}>You might also like</h2>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: isMobile ? 16 : 28 }}>
            {window.PRODUCTS.filter(x => x.id !== p.id).slice(0, 4).map(pp => <ProductCard key={pp.id} p={pp} vp={vp} goto={goto} addToCart={addToCart} wishlist={wishlist} toggleWish={toggleWish}/>)}
          </div>
        </div>

        {/* Recently viewed */}
        {(() => {
          const viewed = JSON.parse(localStorage.getItem('nkh_viewed') || '[]').filter(id => id !== p.id);
          const viewedProducts = viewed.map(id => window.PRODUCTS.find(x => x.id === id)).filter(Boolean);
          if (!viewedProducts.length) return null;
          return (
            <div style={{ marginTop: 64 }}>
              <h2 className="h-display" style={{ fontSize: isMobile ? 24 : 32, marginBottom: 24 }}>Recently viewed</h2>
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: isMobile ? 16 : 28 }}>
                {viewedProducts.slice(0, 4).map(pp => <ProductCard key={pp.id} p={pp} vp={vp} goto={goto} addToCart={addToCart} wishlist={wishlist} toggleWish={toggleWish}/>)}
              </div>
            </div>
          );
        })()}
      </div>

    </div>
  );
}

window.ProductCard = ProductCard;
window.HomePage = HomePage;
window.ShopPage = ShopPage;
window.ProductPage = ProductPage;
