// store-pdp.jsx — Product detail, Cart drawer, Mobile menu (i18n-aware)

const { useState: useS2, useEffect: useE2, useMemo: useM2 } = React;

// ───────────────────────── Product page ─────────────────────────
function ProductPage({ id, mobile }) {
  const p = window.ECOPROF_PRODUCTS.find(x => x.id === id);
  const cat = window.ECOPROF_CATEGORIES.find(c => c.id === p?.cat);
  const { addToCart, goto, settings, t, tr, fmt, lang, isWished, toggleWishlist } = useStore();
  const [qty, setQty] = useS2(1);
  const [tab, setTab] = useS2('description');
  const [activeImg, setActiveImg] = useS2(0);
  const [bundle, setBundle] = useS2({});

  const fbtIds = (window.ECOPROF_BUNDLES[id] || [id, 'p11', 'p17', 'p25']).filter(x => x !== id);
  const fbtList = [p, ...fbtIds.map(fid => window.ECOPROF_PRODUCTS.find(x => x.id === fid)).filter(Boolean)];

  useE2(() => {
    const init = {};
    fbtList.forEach(x => { init[x.id] = true; });
    setBundle(init);
  }, [id]);

  if (!p) return null;

  const bundleSelected = fbtList.filter(x => bundle[x.id]);
  const bundleTotal = bundleSelected.reduce((s, x) => s + x.price, 0);
  const bundleOld   = bundleSelected.reduce((s, x) => s + (x.oldPrice || x.price), 0);
  const bundleSave  = bundleOld - bundleTotal;
  const comboPrice = Math.round(bundleTotal * 0.95);
  const comboSave  = bundleTotal - comboPrice + (bundleSave > 0 ? bundleSave : 0);

  const sameLine = window.ECOPROF_PRODUCTS.filter(x => x.cat === p.cat && x.id !== p.id);
  let related = sameLine.slice(0, 4);
  // If category has < 4 products, supplement with bestsellers from other lines
  if (related.length < 4) {
    const extras = window.ECOPROF_PRODUCTS
      .filter(x => x.id !== p.id && x.cat !== p.cat && x.badges.includes('best'))
      .filter(x => !related.some(r => r.id === x.id))
      .slice(0, 4 - related.length);
    related = [...related, ...extras];
  }
  const relatedTitleKey = sameLine.length > 0 ? 'related.same' : 'related.also';

  const variant = settings?.saleStyle || 'b';
  const onSale = !!p.oldPrice;

  return (
    <div>
      <div className="ep-container" style={{ paddingTop: 16, paddingBottom: 8 }}>
        <div className="ep-mono" style={{ fontSize: 11 }}>
          <a onClick={() => goto({ name: 'home' })} style={{ cursor:'pointer' }}>{t('nav.shop')}</a>
          <span style={{ margin: '0 8px' }}>/</span>
          <a>{tr(cat.name)}</a>
          <span style={{ margin: '0 8px' }}>/</span>
          <span style={{ color: 'var(--ep-ink)' }}>{p.name}</span>
        </div>
      </div>

      <div className="ep-container">
        <div className="ep-pdp-grid">
          {/* Gallery */}
          <div className="ep-pdp-gallery">
            <div className="ep-pdp-main">
              {onSale && variant === 'd' && <div className="ep-sale-d" style={{ top: 24 }}>SALE −{Math.round((1 - p.price/p.oldPrice)*100)}%</div>}
              {p.badges.includes('new') && (
                <span className="ep-badge new" style={{ position:'absolute', top:24, left:24 }}>NEW</span>
              )}
              {p.award && (
                <div style={{ position:'absolute', top:24, right:24 }}>
                  <span className="ep-award-pill" style={{ '--award-tint': window.ECOPROF_AWARDS[p.award]?.tint }}>
                    {window.ECOPROF_AWARDS[p.award]?.label}
                  </span>
                </div>
              )}
              <ProductMedia p={p}/>
            </div>
            <div className="ep-pdp-thumbs">
              {[0,1,2].map(i => (
                <div key={i} className={`ep-pdp-thumb ${activeImg === i ? 'active' : ''}`} onClick={() => setActiveImg(i)}>
                  <ProductMedia p={p}/>
                </div>
              ))}
              {p.youtube && (
                <div className={`ep-pdp-thumb video ${activeImg === 3 ? 'active' : ''}`} onClick={() => setActiveImg(3)}/>
              )}
            </div>
          </div>

          {/* Info */}
          <div className="ep-pdp-info">
            <div className="ep-eyebrow" style={{ color: cat.ink }}>{tr(cat.name)} · {p.vol}</div>
            <h1 className="ep-pdp-title">{p.name}</h1>
            <p className="ep-pdp-sub">{tr(p.sub)}</p>

            <div style={{ display:'flex', alignItems:'center', gap: 12 }}>
              <span style={{ color:'#d9a04a', display:'inline-flex', gap: 1 }}>
                {Array.from({length:5}).map((_,i) => <I.star key={i}/>)}
              </span>
              <span style={{ fontSize: 13, color: 'var(--ep-ink-2)' }}>{p.rating.toFixed(2)} · {p.reviews} {t('pdp.reviews')}</span>
            </div>

            {p.award && (
              <div className="ep-pdp-awards" style={{ marginTop: 20 }}>
                {[p.award, 'editor-choice-2025'].slice(0, 2).map((a, i) => {
                  const aw = window.ECOPROF_AWARDS[a];
                  if (!aw) return null;
                  return (
                    <div key={i} className="ep-pdp-award">
                      <div className="medal" style={{ '--medal': cat.ink }}>{aw.label.split(' ')[0].slice(0,3)}</div>
                      <div className="meta">
                        <div className="a">{aw.label}</div>
                        <div className="b">{tr(aw.sub)}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}

            <div className="ep-pdp-price-row">
              {onSale && variant === 'c' && <span className="ep-sale-c-dot" style={{ marginRight: 4 }}/>}
              <span className="ep-pdp-price" style={onSale ? { color: 'var(--ep-sale)' } : null}>{fmt(p.price)}</span>
              {onSale && <span className="ep-pdp-old">{fmt(p.oldPrice)}</span>}
              {onSale && variant === 'b' && <span className="ep-sale-b">−{Math.round((1 - p.price/p.oldPrice)*100)}%</span>}
            </div>

            {p.youtube && (
              <div className="ep-youtube-card" onClick={(e) => e.stopPropagation()}>
                <div className="ep-youtube-thumb"/>
                <div className="ep-youtube-meta">
                  <div className="yt-eyebrow">{t('pdp.yt.eyebrow')}</div>
                  <div className="yt-title">{t('pdp.yt.title')} «{p.name}»</div>
                  <div className="yt-dur">{t('pdp.yt.dur')}</div>
                </div>
              </div>
            )}

            {/* Before / After — для anti-age, brightening, retinol, lifting тощо */}
            {p.beforeAfter && (
              <div style={{ marginTop: 28 }}>
                <div className="ep-eyebrow" style={{ marginBottom: 12 }}>
                  {lang==='uk' ? 'До і після · ' : 'Before & after · '}
                  <span style={{ color:'var(--ep-accent)' }}>{p.beforeAfter.days} {lang==='uk' ? 'днів' : 'days'}</span>
                </div>
                <div style={{ position:'relative', borderRadius: 18, overflow:'hidden', aspectRatio: '16/10', background:'#fdfaf4', border:'1px solid var(--ep-line-2)' }}>
                  {/* Before half */}
                  <div style={{ position:'absolute', inset: 0, clipPath: 'polygon(0 0, 55% 0, 45% 100%, 0 100%)' }}>
                    <image-slot
                      id={`ba-before-${p.id}`}
                      shape="rect"
                      placeholder={lang==='uk' ? 'Фото «до» — перетягни сюди' : 'Drop "before" photo'}
                      style={{ width: '100%', height: '100%', display: 'block' }}
                    ></image-slot>
                  </div>
                  {/* After half */}
                  <div style={{ position:'absolute', inset: 0, clipPath: 'polygon(55% 0, 100% 0, 100% 100%, 45% 100%)' }}>
                    <image-slot
                      id={`ba-after-${p.id}`}
                      shape="rect"
                      placeholder={lang==='uk' ? 'Фото «після»' : 'Drop "after" photo'}
                      style={{ width: '100%', height: '100%', display: 'block' }}
                    ></image-slot>
                  </div>
                  {/* Diagonal divider */}
                  <div style={{
                    position:'absolute', top: 0, bottom: 0,
                    left: '50%', width: 2, transform: 'translateX(-50%) rotate(8deg)',
                    background: 'rgba(255,255,255,0.9)', boxShadow: '0 0 8px rgba(0,0,0,0.15)',
                    pointerEvents: 'none', zIndex: 5,
                  }}/>
                  {/* Labels */}
                  <div style={{
                    position:'absolute', top: 14, left: 14, zIndex: 6,
                    padding:'4px 10px', borderRadius: 999, background:'rgba(255,255,255,0.92)', backdropFilter:'blur(4px)',
                    fontFamily:'var(--ep-font-mono)', fontSize: 10, fontWeight: 600, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--ep-ink)',
                  }}>{lang==='uk' ? 'До' : 'Before'}</div>
                  <div style={{
                    position:'absolute', top: 14, right: 14, zIndex: 6,
                    padding:'4px 10px', borderRadius: 999, background:'var(--ep-accent)', color:'var(--ep-accent-ink)',
                    fontFamily:'var(--ep-font-mono)', fontSize: 10, fontWeight: 600, letterSpacing:'0.12em', textTransform:'uppercase',
                  }}>{lang==='uk' ? 'Після' : 'After'}</div>
                </div>
                <p style={{ fontSize: 12.5, color:'var(--ep-ink-3)', marginTop: 10, fontStyle:'italic' }}>
                  {lang==='uk' ? 'Реальна клієнтка, без ретушу. Результати індивідуальні.' : 'Real customer, no retouching. Results vary.'}
                </p>
              </div>
            )}

            <ul className="ep-pdp-bullets">
              <li>{t('pdp.bullets.1')}</li>
              <li>{t('pdp.bullets.2')}</li>
              <li>{t('pdp.bullets.3')}</li>
              <li>{t('pdp.bullets.4')}</li>
            </ul>

            <div className="ep-pdp-actions">
              <div className="ep-qty">
                <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
                <span>{qty}</span>
                <button onClick={() => setQty(qty + 1)}>+</button>
              </div>
              <button className="ep-btn accent" onClick={() => addToCart(p.id, qty)}>
                {t('pdp.btn.add')} · {fmt(p.price * qty)}
              </button>
              <button
                onClick={() => toggleWishlist(p.id)}
                className="ep-icon-btn"
                style={{
                  border:'1px solid var(--ep-line)', width:48, height:48,
                  color: isWished(p.id) ? 'var(--ep-accent)' : 'var(--ep-ink)',
                  background: isWished(p.id) ? 'var(--ep-accent-soft)' : 'transparent',
                }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill={isWished(p.id) ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 1 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
                </svg>
              </button>
            </div>

            <div style={{ display:'flex', gap: 24, flexWrap:'wrap', marginTop: 24, fontSize: 12, color:'var(--ep-ink-3)' }}>
              <span>{t('pdp.trust.ret')}</span>
              <span>{t('pdp.trust.smp')}</span>
              <span>{t('pdp.trust.shp')}</span>
            </div>
          </div>
        </div>

        {/* Frequently Bought Together */}
        <div className="ep-fbt">
          <div className="ep-fbt-head">
            <div>
              <div className="ep-eyebrow">{t('fbt.eyebrow')}</div>
              <h3 className="ep-section-title" style={{ fontSize: mobile ? 22 : 26, marginTop: 6 }}>{t('fbt.title')}</h3>
            </div>
            <div className="ep-mono" style={{ fontSize: 11 }}>{t('fbt.discount')}</div>
          </div>
          <div className="ep-fbt-row">
            {fbtList.map((x, i) => (
              <React.Fragment key={x.id}>
                <div className={`ep-fbt-item ${bundle[x.id] ? 'checked' : ''}`}
                     onClick={() => setBundle({ ...bundle, [x.id]: !bundle[x.id] })}>
                  <div className="thumb">
                    <div className="check"/>
                    <ProductMedia p={x}/>
                  </div>
                  <div className="nm">{x.name}</div>
                  <div className="pr">{fmt(x.price)}</div>
                </div>
                {i < fbtList.length - 1 && <span className="ep-fbt-plus">+</span>}
              </React.Fragment>
            ))}
          </div>
          <div className="ep-fbt-total">
            <div style={{ display:'flex', alignItems:'baseline', gap: 12, flexWrap:'wrap' }}>
              <span style={{ color:'var(--ep-ink-3)', fontSize: 13 }}>{t('fbt.total')}</span>
              <span style={{ fontSize: 22, fontWeight: 500, fontFamily: 'var(--ep-font-display)' }}>{fmt(comboPrice)}</span>
              <span style={{ color:'var(--ep-ink-3)', textDecoration:'line-through', fontSize: 13 }}>{fmt(bundleTotal)}</span>
              {comboSave > 0 && <span className="saved">{t('fbt.saved')} {fmt(comboSave)}</span>}
            </div>
            <button className="ep-btn" onClick={() => bundleSelected.forEach(x => addToCart(x.id))}>
              {t('fbt.add')} · {bundleSelected.length} {t('fbt.pcs')}
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="ep-tabs">
          {['description','ingredients','howto','reviews'].map(tt => (
            <button key={tt} className={`ep-tab ${tab === tt ? 'active' : ''}`} onClick={() => setTab(tt)}>
              {{ description: t('tab.desc'), ingredients: t('tab.ing'), howto: t('tab.how'), reviews: `${t('tab.rev')} · ${p.reviews}` }[tt]}
            </button>
          ))}
        </div>
        <div style={{ maxWidth: 760, fontSize: 15, color: 'var(--ep-ink-2)', lineHeight: 1.7 }}>
          {tab === 'description' && (
            <div>
              <p>{tr(p.sub)}. {t('desc.p1')}</p>
              <p>{t('desc.p2')}</p>
            </div>
          )}
          {tab === 'ingredients' && (
            <div className="ep-mono" style={{ textTransform:'none', letterSpacing: 0, fontSize: 12.5, color:'var(--ep-ink-2)', lineHeight: 1.7 }}>
              Aqua, Niacinamide, Glycerin, Panthenol, Cica Extract, Allantoin, Sodium Hyaluronate, Pentylene Glycol, Phenoxyethanol, Hydroxyacetophenone, Citric Acid, Sodium Citrate.
            </div>
          )}
          {tab === 'howto' && (
            <div>
              <p>{t('how.am')}</p>
              <p>{t('how.pm')}</p>
            </div>
          )}
          {tab === 'reviews' && (
            <div>
              {[
                { n: lang === 'uk' ? 'Олена К.'  : 'Olena K.',  d:t('rev.date.1'), r:5, t:t('rev.1.t') },
                { n: lang === 'uk' ? 'Марія В.'  : 'Maria V.',  d:t('rev.date.2'), r:5, t:t('rev.2.t') },
                { n: lang === 'uk' ? 'Аліна С.'  : 'Alina S.',  d:t('rev.date.3'), r:4, t:t('rev.3.t') },
              ].map((r, i) => (
                <div key={i} className="ep-review">
                  <div className="hd">
                    <div className="av">{r.n[0]}</div>
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 13, color:'var(--ep-ink)' }}>{r.n}</div>
                      <div style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{r.d}</div>
                    </div>
                    <span className="stars" style={{ marginLeft:'auto' }}>{'★'.repeat(r.r)}{'☆'.repeat(5-r.r)}</span>
                  </div>
                  <div className="body">{r.t}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Related */}
        {related.length > 0 && (
        <section className="ep-section" style={{ paddingBottom: mobile ? 32 : 64 }}>
          <div className="ep-section-head">
            <div>
              <div className="ep-eyebrow">{sameLine.length > 0 ? `${tr(cat.name)} · ${t('pdp.relSub')}` : (lang === 'uk' ? 'Також рекомендуємо' : 'Also recommended')}</div>
              <h2 className="ep-section-title" style={{ fontSize: mobile ? 26 : 32 }}>{sameLine.length > 0 ? t('pdp.related') : (lang === 'uk' ? 'Може зацікавити' : 'You might also like')}</h2>
            </div>
          </div>
          <div className="ep-grid">
            {related.map(rp => <ProductCard key={rp.id} p={rp}/>)}
          </div>
        </section>
        )}
      </div>
    </div>
  );
}

// ───────────────────────── Cart drawer ─────────────────────────
function CartDrawer({ mobile }) {
  const { cart, cartOpen, setCartOpen, setQty, addToCart, subtotal, goto, t, tr, fmt, lang } = useStore();
  const ship = subtotal >= 1500 || subtotal === 0 ? 0 : 120;
  const total = subtotal + ship;
  return (
    <>
      <div className={`ep-drawer-backdrop ${cartOpen ? 'open' : ''}`} onClick={() => setCartOpen(false)}/>
      <aside className={`ep-drawer ${cartOpen ? 'open' : ''}`}>
        <div className="ep-drawer-head">
          <div>
            <div className="ep-eyebrow">{t('cart.eyebrow')}</div>
            <div style={{ fontSize: 18, fontWeight: 500, marginTop: 2 }}>
              {cart.length} {window.itemsLabel(cart.length, lang)}
            </div>
          </div>
          <button className="ep-icon-btn" onClick={() => setCartOpen(false)}><I.x/></button>
        </div>

        {subtotal > 0 && (
          <div style={{ padding: '12px 24px 0' }}>
            <div style={{ fontSize: 12, color:'var(--ep-ink-2)', marginBottom: 8 }}>
              {ship === 0 ? t('cart.ship.ok') : `${t('cart.ship.left')} ${fmt(1500 - subtotal)}`}
            </div>
            <div style={{ height: 4, background: 'var(--ep-line-2)', borderRadius: 999, overflow:'hidden' }}>
              <div style={{ width: Math.min(100, subtotal/15) + '%', height: '100%', background: 'var(--ep-accent)', transition: 'width .4s var(--ep-ease)' }}/>
            </div>
          </div>
        )}

        <div className="ep-drawer-body">
          {cart.length === 0 && (
            <div className="ep-cart-empty">
              <div className="ic"><I.bag/></div>
              <div style={{ fontSize: 16, color: 'var(--ep-ink)', fontWeight: 500 }}>{t('cart.empty.t')}</div>
              <div style={{ fontSize: 13, maxWidth: 280 }}>{t('cart.empty.s')}</div>
              <button className="ep-btn ghost sm" style={{ marginTop: 12 }} onClick={() => { setCartOpen(false); goto({ name:'home' }); }}>{t('cart.empty.cta')}</button>
            </div>
          )}
          {cart.map(it => {
            const p = window.ECOPROF_PRODUCTS.find(x => x.id === it.id);
            if (!p) return null;
            return (
              <div key={it.id} className="ep-cart-item">
                <div className="thumb">
                  <ProductMedia p={p}/>
                </div>
                <div className="meta">
                  <div className="nm">{p.name}</div>
                  <div className="sb">{tr(p.sub)} · {p.vol}</div>
                  <div className="row">
                    <div className="qty-sm">
                      <button onClick={() => setQty(it.id, it.qty - 1)}>−</button>
                      <span>{it.qty}</span>
                      <button onClick={() => setQty(it.id, it.qty + 1)}>+</button>
                    </div>
                    <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
                      <div className="pr">{fmt(p.price * it.qty)}</div>
                      <button className="x" onClick={() => setQty(it.id, 0)}><I.x/></button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
          {cart.length > 0 && (
            <div style={{ padding: '24px 0 8px' }}>
              <div className="ep-mono" style={{ fontSize: 10, marginBottom: 14, color:'var(--ep-ink-2)' }}>{t('cart.add.more')}</div>
              <div style={{ display:'flex', flexDirection:'column', gap: 0 }}>
                {window.ECOPROF_PRODUCTS
                  .filter(x => x.badges.includes('best') && !cart.some(c => c.id === x.id))
                  .slice(0, 3)
                  .map(up => (
                    <div key={up.id} style={{
                      display:'flex', alignItems:'center', gap: 12, padding: '10px 0',
                      borderTop: '1px solid var(--ep-line-2)',
                    }}>
                      <div style={{ width: 54, height: 54, borderRadius: 8, background: '#fff', border: '1px solid var(--ep-line-2)', flex:'none', overflow:'hidden', display:'flex' }}>
                        <ProductMedia p={up}/>
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, color:'var(--ep-ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{up.name}</div>
                        <div style={{ fontSize: 11, color:'var(--ep-ink-3)', marginTop: 1 }}>{up.vol}</div>
                      </div>
                      <div style={{ fontSize: 13, fontVariantNumeric:'tabular-nums', color:'var(--ep-ink-2)' }}>{fmt(up.price)}</div>
                      <button
                        onClick={() => addToCart(up.id)}
                        aria-label="add"
                        className="ep-upsell-add">
                        <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M5.5 1v9M1 5.5h9"/></svg>
                      </button>
                    </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {cart.length > 0 && (
          <div className="ep-drawer-foot">
            <div className="ep-cart-totals">
              <div className="row"><span>{t('cart.sub')}</span><span>{fmt(subtotal)}</span></div>
              <div className="row"><span>{t('cart.ship')}</span><span>{ship === 0 ? t('cart.ship.free') : fmt(ship)}</span></div>
              <div className="row total"><span>{t('cart.tot')}</span><span>{fmt(total)}</span></div>
            </div>
            <button className="ep-btn accent lg full" onClick={() => { setCartOpen(false); goto({ name: 'checkout' }); }}>{t('cart.checkout')} <I.arrow/></button>
            <div style={{ textAlign:'center', fontSize: 11, color:'var(--ep-ink-3)', marginTop: 12 }}>
              {t('cart.pay')}
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

// ───────────────────────── Mobile nav ─────────────────────────
function MobileMenu() {
  const { menuOpen, setMenuOpen, goto, t } = useStore();
  return (
    <div className={`ep-mob-menu ${menuOpen ? 'open' : ''}`}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 24 }}>
        <div className="ep-logo">ecoprof<span className="dot"/></div>
        <button className="ep-icon-btn" onClick={() => setMenuOpen(false)}><I.x/></button>
      </div>
      <a onClick={() => goto({ name:'catalog' })}>{t('nav.shop')}</a>
      <a onClick={() => goto({ name:'lines' })}>{t('nav.lines')}</a>
      <a>{t('nav.quiz')}</a>
      <a>{t('nav.journal')}</a>
      <a>{t('nav.about')}</a>
      <div style={{ marginTop:'auto', borderTop:'1px solid var(--ep-line-2)', paddingTop: 16 }}>
        <div style={{ marginBottom: 12 }}><LangToggle/></div>
        <div className="ep-mono">{t('mob.bottom')}</div>
      </div>
    </div>
  );
}

// ───────────────────────── Store (root) ─────────────────────────
function Store({ mobile = false, settings }) {
  const rootRef = React.useRef(null);
  useApplySettings(rootRef, settings);
  return (
    <StoreProvider settings={settings}>
      <div ref={rootRef} className={`ep-root ${mobile ? 'is-mobile' : ''}`}>
        <StoreInner mobile={mobile}/>
      </div>
    </StoreProvider>
  );
}

function StoreInner({ mobile }) {
  const { route } = useStore();
  const innerRef = React.useRef(null);

  // On route change, scroll the closest scrollable ancestor to the top.
  // The Store renders inside an .ep-board iframe-like container that scrolls
  // (not the window), so window.scrollTo would do nothing here.
  React.useEffect(() => {
    let el = innerRef.current;
    while (el) {
      if (el.scrollHeight > el.clientHeight + 1) {
        try { el.scrollTo({ top: 0, behavior: 'instant' }); } catch { el.scrollTop = 0; }
        return;
      }
      el = el.parentElement;
    }
    try { window.scrollTo({ top: 0, behavior: 'instant' }); } catch {}
  }, [route]);

  return (
    <div ref={innerRef}>
      <PromoStrip/>
      <Header mobile={mobile}/>
      <main>
        {route.name === 'home' && (
          <>
            <Hero mobile={mobile}/>
            <CategoryCircles mobile={mobile}/>
            <AwardsStrip/>
            <Bestsellers mobile={mobile}/>
            <QuizCallout mobile={mobile}/>
            <StoryBlock mobile={mobile}/>
          </>
        )}
        {route.name === 'product' && <ProductPage id={route.id} mobile={mobile}/>}
        {route.name === 'catalog' && <CatalogPage preset={route.cat} tag={route.tag} mobile={mobile}/>}
        {route.name === 'lines' && <LinesPage mobile={mobile}/>}
        {route.name === 'about' && <AboutPage mobile={mobile}/>}
        {route.name === 'journal' && <JournalPage mobile={mobile}/>}
        {route.name === 'article' && <ArticlePage id={route.id} mobile={mobile}/>}
        {route.name === 'contact' && <ContactPage mobile={mobile}/>}
        {route.name === 'shipping' && <ShippingPage mobile={mobile}/>}
        {route.name === 'returns' && <ReturnsPage mobile={mobile}/>}
        {route.name === 'faq' && <FAQPage mobile={mobile}/>}
        {route.name === 'gift' && <GiftCardsPage mobile={mobile}/>}
        {route.name === 'careers' && <CareersPage mobile={mobile}/>}
        {route.name === 'role' && <RolePage id={route.id} mobile={mobile}/>}
        {route.name === 'wishlist' && <WishlistPage mobile={mobile}/>}
        {route.name === 'auth' && <AuthPage mobile={mobile}/>}
        {route.name === 'account' && <AccountPage mobile={mobile}/>}
        {route.name === 'privacy' && <PrivacyPage mobile={mobile}/>}
        {route.name === 'terms' && <TermsPage mobile={mobile}/>}
        {route.name === 'cookies' && <CookiesPage mobile={mobile}/>}
        {route.name === 'checkout' && <CheckoutPage mobile={mobile}/>}
        {route.name === 'quiz' && <QuizPage mobile={mobile}/>}
      </main>
      <Footer mobile={mobile}/>
      <CartDrawer mobile={mobile}/>
      <CartToast/>
      <SearchOverlay/>
      <CookieBanner/>
      <AuthModal/>
      {mobile && <MobileMenu/>}
    </div>
  );
}

Object.assign(window, { ProductPage, CartDrawer, MobileMenu, Store, StoreInner });
