// store-app.jsx — Ecoprof store: Header, Home, Cart context. i18n-aware.
// Lang state lives in StoreProvider; t(key, lang) + tr(field, lang) + fmtMoney(n, lang).

const { useState, useEffect, useRef, useMemo, useContext, createContext } = React;

// ───────────────────────── Store state (shared) ─────────────────────────
const StoreCtx = createContext(null);

function StoreProvider({ children, settings }) {
  const [route, setRoute] = useState({ name: 'home' });
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [lang, setLang] = useState('uk');
  const [toast, setToast] = useState(null);
  const [pulse, setPulse] = useState(0);
  const [wishlist, setWishlist] = useState([]);    // [productId, ...]
  const [searchOpen, setSearchOpen] = useState(false);
  const [user, setUser] = useState(null);          // { email, name, points, tier } | null
  const [authOpen, setAuthOpen] = useState(false);  // login/register modal

  const toggleWishlist = (id) => setWishlist(w => w.includes(id) ? w.filter(x => x !== id) : [...w, id]);
  const isWished = (id) => wishlist.includes(id);
  const login = (data) => { setUser({
    email: data.email || 'user@ecoprof.ua',
    name: data.name || 'Olena',
    points: 2400,           // demo balance
    tier: 'silver',         // bronze | silver | gold
    tierDiscount: 5,        // % personal discount based on tier
  }); setAuthOpen(false); };
  const logout = () => setUser(null);
  const spendPoints = (n) => setUser(u => u ? { ...u, points: Math.max(0, u.points - n) } : u);

  const goto = (r) => { setRoute(r); setMenuOpen(false); window.scrollTo?.({ top: 0, behavior: 'instant' }); };
  const addToCart = (id, qty = 1) => {
    setCart((c) => {
      const ex = c.find(i => i.id === id);
      return ex ? c.map(i => i.id === id ? { ...i, qty: i.qty + qty } : i)
                : [...c, { id, qty }];
    });
    setToast({ id, ts: Date.now() });
    setPulse(p => p + 1);
  };
  const setQty = (id, qty) => {
    setCart((c) => qty <= 0 ? c.filter(i => i.id !== id) : c.map(i => i.id === id ? { ...i, qty } : i));
  };
  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const subtotal = cart.reduce((s, i) => {
    const p = window.ECOPROF_PRODUCTS.find(p => p.id === i.id);
    return s + (p ? p.price * i.qty : 0);
  }, 0);

  // localized helpers bound to current lang
  const _t = (k) => window.t(k, lang);
  const _tr = (f) => window.tr(f, lang);
  const _fm = (n) => window.fmtMoney(n, lang);

  const value = {
    route, goto, cart, addToCart, setQty,
    cartOpen, setCartOpen, cartCount, subtotal,
    menuOpen, setMenuOpen, settings,
    lang, setLang, t: _t, tr: _tr, fmt: _fm,
    toast, setToast, pulse,
    wishlist, toggleWishlist, isWished,
    searchOpen, setSearchOpen,
    user, login, logout, spendPoints,
    authOpen, setAuthOpen,
  };
  return <StoreCtx.Provider value={value}>{children}</StoreCtx.Provider>;
}

const useStore = () => useContext(StoreCtx);

// ── Apply tweak settings as CSS vars ─────────────────────
function useApplySettings(rootRef, settings) {
  useEffect(() => {
    if (!rootRef.current || !settings) return;
    const r = rootRef.current;
    r.style.setProperty('--ep-accent', settings.accent || '#c47862');
    r.style.setProperty('--ep-accent-soft', hexA(settings.accent || '#c47862', 0.1));
    r.style.setProperty('--ep-circle', (settings.circleSize || 132) + 'px');
    const cs = settings.cardStyle || 'clean';
    if (cs === 'clean') {
      r.style.setProperty('--ep-card-bg', 'var(--ep-surface)');
      r.style.setProperty('--ep-card-border', '1px solid var(--ep-line-2)');
      r.style.setProperty('--ep-card-radius', '14px');
    } else if (cs === 'tinted') {
      r.style.setProperty('--ep-card-bg', 'transparent');
      r.style.setProperty('--ep-card-border', '0');
      r.style.setProperty('--ep-card-radius', '14px');
    } else if (cs === 'soft') {
      r.style.setProperty('--ep-card-bg', '#fdfaf4');
      r.style.setProperty('--ep-card-border', '0');
      r.style.setProperty('--ep-card-radius', '22px');
    }
  }, [settings, rootRef]);
}

function hexA(hex, a) {
  const h = hex.replace('#','');
  const n = h.length === 3 ? h.split('').map(c=>c+c).join('') : h;
  const r = parseInt(n.slice(0,2),16), g = parseInt(n.slice(2,4),16), b = parseInt(n.slice(4,6),16);
  return `rgba(${r},${g},${b},${a})`;
}

// ───────────────────────── Icons (inline) ─────────────────────────
const I = {
  search: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg>,
  bag:    () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 8h14l-1.2 11.2A2 2 0 0 1 15.8 21H8.2a2 2 0 0 1-2-1.8L5 8z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>,
  heart:  () => <svg width="20" height="20" viewBox="0 0 24 24" fill="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>,
  user:   () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6"/></svg>,
  menu:   () => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>,
  x:      () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>,
  arrow:  () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  star:   () => <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7 7 .8-5.3 4.9 1.6 7.3L12 18l-6.3 4 1.6-7.3L2 9.8 9 9z"/></svg>,
  play:   () => <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M6 4l14 8-14 8z"/></svg>,
  check:  () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>,
};

// ───────────────────────── Lang toggle ─────────────────────────
function LangToggle({ compact = false }) {
  const { lang, setLang } = useStore();
  return (
    <div style={{
      display:'inline-flex', alignItems:'center', height: compact ? 28 : 32, padding: 2,
      border:'1px solid var(--ep-line-2)', borderRadius: 999, gap: 0,
      fontFamily:'var(--ep-font-mono)', fontSize: 10.5, letterSpacing:'0.06em',
      background:'rgba(255,255,255,0.4)',
    }}>
      {['uk','en'].map(l => (
        <button key={l}
          onClick={() => setLang(l)}
          style={{
            border:'none', cursor:'pointer', padding: compact ? '0 9px' : '0 11px', height: '100%',
            borderRadius: 999, background: lang === l ? 'var(--ep-ink)' : 'transparent',
            color: lang === l ? '#fff' : 'var(--ep-ink-2)',
            fontWeight: 600, fontFamily:'inherit', fontSize:'inherit', letterSpacing:'inherit',
            transition: 'background .15s var(--ep-ease), color .15s var(--ep-ease)',
          }}>
          {l.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

// ───────────────────────── Toast on add ─────────────────────────
function CartToast() {
  const { toast, lang, setCartOpen } = useStore();
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (!toast) return;
    setVisible(true);
    const tm = setTimeout(() => setVisible(false), 2400);
    return () => clearTimeout(tm);
  }, [toast]);
  if (!toast) return null;
  const p = window.ECOPROF_PRODUCTS.find(x => x.id === toast.id);
  if (!p) return null;
  return (
    <div className={`ep-toast ${visible ? 'visible' : ''}`}>
      <div className="ep-toast-thumb">
        <ProductMedia p={p}/>
      </div>
      <div className="ep-toast-meta">
        <div className="ep-toast-eyebrow">
          <span style={{ display:'inline-flex', verticalAlign:'middle', marginRight: 6, color:'var(--ep-accent)' }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
          </span>
          {lang === 'uk' ? 'Додано в кошик' : 'Added to bag'}
        </div>
        <div className="ep-toast-name">{p.name}</div>
      </div>
      <button onClick={() => setCartOpen(true)} className="ep-toast-cta">
        {lang === 'uk' ? 'Кошик' : 'Bag'} →
      </button>
    </div>
  );
}

// ───────────────────────── Header ─────────────────────────
function Header({ mobile }) {
  const { goto, cartCount, setCartOpen, route, setMenuOpen, t, lang, pulse, setSearchOpen, wishlist, user, setAuthOpen } = useStore();
  const [pulseCls, setPulseCls] = useState('');
  useEffect(() => {
    if (!pulse) return;
    setPulseCls('ep-cart-pulse');
    const tm = setTimeout(() => setPulseCls(''), 620);
    return () => clearTimeout(tm);
  }, [pulse]);
  return (
    <header className="ep-header">
      <div className="ep-container ep-header-inner">
        {mobile && (
          <button className="ep-icon-btn" onClick={() => setMenuOpen(true)} aria-label="menu"><I.menu/></button>
        )}
        <a className="ep-logo" onClick={() => goto({ name: 'home' })}>
          ecoprof<span className="dot"/>
        </a>
        {!mobile && (
          <nav className="ep-nav">
            <a className={route.name === 'catalog' && !route.cat ? 'active' : ''} onClick={() => goto({ name: 'catalog' })}>{t('nav.shop')}</a>
            <a className={route.name === 'lines' ? 'active' : ''} onClick={() => goto({ name: 'lines' })}>{t('nav.lines')}</a>
            <a className={route.name === 'quiz' ? 'active' : ''} onClick={() => goto({ name: 'quiz' })}>{t('nav.quiz')}</a>
            <a className={['journal','article'].includes(route.name) ? 'active' : ''} onClick={() => goto({ name: 'journal' })}>{t('nav.journal')}</a>
            <a className={route.name === 'gift' ? 'active' : ''} onClick={() => goto({ name: 'gift' })}>{lang === 'uk' ? 'Подарункові карти' : 'Gift cards'}</a>
            <a className={route.name === 'about' ? 'active' : ''} onClick={() => goto({ name: 'about' })}>{t('nav.about')}</a>
            <a className={route.name === 'contact' ? 'active' : ''} onClick={() => goto({ name: 'contact' })}>{lang === 'uk' ? 'Контакти' : 'Contact'}</a>
          </nav>
        )}
        <div className="ep-header-actions">
          {!mobile && <LangToggle/>}
          {!mobile && <button className="ep-icon-btn" onClick={() => setSearchOpen(true)}><I.search/></button>}
          {!mobile && <button className="ep-icon-btn" onClick={() => user ? goto({ name: 'account' }) : setAuthOpen(true)}><I.user/></button>}
          {!mobile && (
            <button className="ep-icon-btn" onClick={() => goto({ name: 'wishlist' })}>
              <I.heart/>
              {wishlist.length > 0 && <span className="ep-cart-count" style={{ background:'var(--ep-ink)' }}>{wishlist.length}</span>}
            </button>
          )}
          {mobile && <LangToggle compact/>}
          <button className="ep-icon-btn" onClick={() => setCartOpen(true)}>
            <span className={pulseCls} style={{ display:'inline-flex', alignItems:'center', justifyContent:'center' }}>
              <I.bag/>
            </span>
            {cartCount > 0 && <span className="ep-cart-count">{cartCount}</span>}
          </button>
        </div>
      </div>
    </header>
  );
}

// ───────────────────────── Promo strip ─────────────────────────
function PromoStrip() {
  const { t } = useStore();
  const items = [t('promo.shipping'), t('promo.new'), t('promo.returns'), t('promo.samples')];
  const doubled = [...items, ...items, ...items, ...items];
  return (
    <div className="ep-promo-strip">
      <div className="ep-promo-track">
        {doubled.map((tx, i) => <span key={i}>{tx}</span>)}
      </div>
    </div>
  );
}

// ───────────────────────── Hero ─────────────────────────
function Hero({ mobile }) {
  const { goto, t } = useStore();
  return (
    <section className="ep-hero">
      <div className="ep-container">
        <div className="ep-hero-grid">
          <div>
            <div className="ep-eyebrow">{t('hero.eyebrow')}</div>
            <h1 className="ep-hero-title">
              {t('hero.title.1')}<br/><em>{t('hero.title.2')}</em>
            </h1>
            <p className="ep-hero-lede">{t('hero.lede')}</p>
            <div className="ep-hero-ctas">
              <button className="ep-btn accent" onClick={() => goto({ name: 'catalog', tag: 'best' })}>
                {t('hero.cta.best')} <I.arrow/>
              </button>
              <button className="ep-btn ghost" onClick={() => goto({ name: 'quiz' })}>{t('hero.cta.quiz')}</button>
            </div>
            <div className="ep-hero-meta">
              <div className="ep-hero-meta-item"><div className="v">50</div><div className="k">{t('hero.meta.1k')}</div></div>
              <div className="ep-hero-meta-item"><div className="v">12+</div><div className="k">{t('hero.meta.2k')}</div></div>
              <div className="ep-hero-meta-item"><div className="v">4.86</div><div className="k">{t('hero.meta.3k')}</div></div>
            </div>
          </div>
          <div className="ep-hero-art">
            {(() => {
              const heroP = window.ECOPROF_PRODUCTS.find(x => x.id === 'p11') || window.ECOPROF_PRODUCTS[0];
              return (
                <>
                  <image-slot
                    id="hero-portrait"
                    shape="rounded"
                    radius="22"
                    src="portraits/hero.jpg"
                    placeholder="Крупний план обличчя · перетягни сюди фото моделі / Drop a face close-up here"
                    style={{ width: '100%', height: '100%', display: 'block' }}
                  ></image-slot>
                  {/* product chip overlay — bottom-left */}
                  <div style={{
                    position:'absolute', left: 20, bottom: 20, zIndex: 3,
                    display:'flex', alignItems:'center', gap: 10,
                    padding: '7px 16px 7px 7px', borderRadius: 999,
                    background: 'rgba(255,255,255,0.92)', backdropFilter:'blur(10px)',
                    border: '1px solid rgba(255,255,255,0.6)',
                    boxShadow: '0 8px 24px rgba(0,0,0,0.10)',
                  }}>
                    <div style={{ width: 36, height: 36, borderRadius:'50%', background:'#fff', overflow:'hidden', flex:'none', border:'1px solid var(--ep-line-2)' }}>
                      <img src={heroP.image} alt="" style={{ width:'100%', height:'100%', objectFit:'contain', padding: 3, boxSizing:'border-box' }}/>
                    </div>
                    <div>
                      <div style={{ fontSize: 9.5, fontFamily:'var(--ep-font-mono)', color:'var(--ep-ink-3)', letterSpacing:'0.1em', textTransform:'uppercase' }}>{t('hero.eyebrow').replace(/.*·\s*/, '')}</div>
                      <div style={{ fontSize: 13, fontWeight: 500, color:'var(--ep-ink)', lineHeight: 1.1 }}>{heroP.name}</div>
                    </div>
                  </div>
                </>
              );
            })()}
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Category circles ─────────────────────────
function CategoryCircles({ mobile }) {
  const { t, tr, lang, goto } = useStore();
  // Find representative product image per category (first product with matching cat)
  const repFor = (catId) => window.ECOPROF_PRODUCTS.find(p => p.cat === catId);
  const countFor = (catId) => window.ECOPROF_PRODUCTS.filter(p => p.cat === catId).length;
  const countLabel = (n) => lang === 'uk'
    ? `${n} ${n === 1 ? 'продукт' : (n >= 2 && n <= 4 ? 'продукти' : 'продуктів')}`
    : `${n} ${n === 1 ? 'product' : 'products'}`;
  return (
    <section className="ep-section" style={{ paddingTop: mobile ? 24 : 40 }}>
      <div className="ep-container">
        <div className="ep-section-head">
          <div>
            <div className="ep-eyebrow">{t('cats.eyebrow')}</div>
            <h2 className="ep-section-title">{t('cats.title')}</h2>
            <p className="ep-section-sub">{t('cats.sub')}</p>
          </div>
          {!mobile && <a className="ep-btn ghost sm" onClick={() => goto({ name: 'catalog' })}>{t('cats.all')} <I.arrow/></a>}
        </div>
        <div className="ep-cat-strip" style={{
          display: 'grid',
          gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(5, 1fr)',
          gap: mobile ? 20 : 36,
          justifyItems: 'center',
          flexWrap: 'initial',
          overflow: 'visible',
          padding: 0, margin: 0,
        }}>
          {window.ECOPROF_CATEGORIES.map((c) => {
            const rep = repFor(c.id);
            return (
              <div key={c.id} className="ep-cat-circle"
                onClick={() => goto({ name: 'catalog' })}
                style={{ '--ring-bg': c.color }}>
                <div className="ring">
                  {rep ? <img src={rep.image} alt={tr(c.name)} loading="lazy"/> : <CategoryIcon shape={c.shape} color={c.ink}/>}
                </div>
                <div className="label">{tr(c.name)}</div>
                <div className="count">{countLabel(countFor(c.id))}</div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Product Card ─────────────────────────
function ProductCard({ p, saleVariant = 'b' }) {
  const { goto, addToCart, setQty, cart, settings, t, tr, fmt, lang, isWished, toggleWishlist } = useStore();
  const cat = window.ECOPROF_CATEGORIES.find(c => c.id === p.cat);
  const onSale = !!p.oldPrice;
  const variant = settings?.saleStyle || saleVariant;
  const cartItem = cart.find(c => c.id === p.id);
  const inCart = !!cartItem;
  const wished = isWished(p.id);

  return (
    <article className={`ep-product ${inCart ? 'in-cart' : ''}`} onClick={() => goto({ name: 'product', id: p.id })}
      style={{ '--cat-color': cat?.color }}>
      <div className="ep-product-img-wrap">
        {onSale && variant === 'd' && <div className="ep-sale-d">SALE −{Math.round((1 - p.price/p.oldPrice)*100)}%</div>}
        {onSale && variant === 'b' && (
          <span className="ep-sale-pill">−{Math.round((1 - p.price/p.oldPrice)*100)}%</span>
        )}
        <button
          className={`ep-wish-btn ${wished ? 'on' : ''}`}
          onClick={(e) => { e.stopPropagation(); toggleWishlist(p.id); }}
          aria-label={wished ? 'remove from wishlist' : 'add to wishlist'}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill={wished ? '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>
        {inCart && (
          <span className="ep-incart-pill" title={lang==='uk'?'У кошику':'In bag'}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
            {lang==='uk' ? 'У кошику' : 'In bag'}
          </span>
        )}
        <div className="ep-product-img">
          <ProductMedia p={p}/>
        </div>
        {inCart ? (
          <div className="ep-product-stepper" onClick={(e) => e.stopPropagation()}>
            <button onClick={() => setQty(p.id, cartItem.qty - 1)} aria-label="-">
              <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M1 5.5h9"/></svg>
            </button>
            <span>{cartItem.qty}</span>
            <button onClick={() => setQty(p.id, cartItem.qty + 1)} aria-label="+">
              <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M5.5 1v9M1 5.5h9"/></svg>
            </button>
          </div>
        ) : (
          <button className="ep-product-add" onClick={(e) => { e.stopPropagation(); addToCart(p.id); }}>
            {t('card.add')}
          </button>
        )}
      </div>
      <div className="ep-badges">
        {p.badges.includes('new')  && <span className="ep-badge new">NEW</span>}
        {p.badges.includes('best') && <span className="ep-badge best">{lang === 'uk' ? 'Бестселер' : 'Bestseller'}</span>}
      </div>
      <div className="ep-product-cat">{tr(cat.name)} · {p.vol}</div>
      <div className="ep-product-name">{p.name}</div>
      <div className="ep-product-sub">{tr(p.sub)}</div>
      <div className="ep-product-bottom">
        <div>
          {onSale && variant === 'a' && <span className="ep-product-old">{fmt(p.oldPrice)}</span>}
          {onSale && variant === 'c' && <span className="ep-sale-c-dot" style={{ display:'inline-block', marginRight:6, verticalAlign:'middle' }}/>}
          <span className="ep-product-price" style={onSale ? { color: 'var(--ep-sale)' } : null}>{fmt(p.price)}</span>
        </div>
        <div className="ep-product-rating">
          <I.star/> {p.rating.toFixed(2)}
        </div>
      </div>
    </article>
  );
}

// ───────────────────────── Bestsellers ─────────────────────────
function Bestsellers({ mobile }) {
  const { t } = useStore();
  const [filter, setFilter] = useState('all');
  const tabs = [
    { id: 'all',   label: t('best.tab.all') },
    { id: 'best',  label: t('best.tab.best') },
    { id: 'new',   label: t('best.tab.new') },
    { id: 'sale',  label: t('best.tab.sale') },
  ];
  const list = useMemo(() => {
    const all = window.ECOPROF_PRODUCTS;
    if (filter === 'all')  return all.filter(p => p.badges.includes('best') || p.badges.includes('new') || p.oldPrice).slice(0, 8);
    if (filter === 'best') return all.filter(p => p.badges.includes('best')).slice(0, 8);
    if (filter === 'new')  return all.filter(p => p.badges.includes('new')).slice(0, 8);
    if (filter === 'sale') return all.filter(p => p.oldPrice).slice(0, 8);
    return [];
  }, [filter]);

  return (
    <section className="ep-section">
      <div className="ep-container">
        <div className="ep-section-head">
          <div>
            <div className="ep-eyebrow">{t('best.eyebrow')}</div>
            <h2 className="ep-section-title">{t('best.title')}</h2>
            <p className="ep-section-sub">{t('best.sub')}</p>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {tabs.map(tt => (
              <button key={tt.id} className={`ep-chip ${filter === tt.id ? 'active' : ''}`} onClick={() => setFilter(tt.id)}>{tt.label}</button>
            ))}
          </div>
        </div>
        <div className="ep-grid">
          {list.map(p => <ProductCard key={p.id} p={p}/>)}
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Sale-variants showcase ─────────────────────────
function SaleVariantsShowcase({ mobile }) {
  const { t } = useStore();
  const sale = window.ECOPROF_PRODUCTS.find(p => p.id === 'p15');
  const variants = [
    { id: 'a', label: t('sale.a.label'), sub: t('sale.a.sub') },
    { id: 'b', label: t('sale.b.label'), sub: t('sale.b.sub') },
    { id: 'c', label: t('sale.c.label'), sub: t('sale.c.sub') },
    { id: 'd', label: t('sale.d.label'), sub: t('sale.d.sub') },
  ];
  return (
    <section className="ep-section" style={{ background: 'var(--ep-surface-2)', padding: mobile ? '48px 0' : '72px 0' }}>
      <div className="ep-container">
        <div className="ep-section-head">
          <div>
            <div className="ep-eyebrow">{t('sale.eyebrow')}</div>
            <h2 className="ep-section-title">{t('sale.title')}</h2>
            <p className="ep-section-sub">{t('sale.sub')}</p>
          </div>
        </div>
        <div className="ep-grid">
          {variants.map(v => (
            <div key={v.id}>
              <div style={{ marginBottom: 12, display:'flex', alignItems:'baseline', justifyContent:'space-between' }}>
                <span className="ep-mono" style={{ color: 'var(--ep-ink)', fontWeight: 600 }}>{t('sale.variant')} {v.id.toUpperCase()}</span>
                <span className="ep-mono" style={{ fontSize: 10 }}>{v.id}</span>
              </div>
              <ProductCard p={sale} saleVariant={v.id}/>
              <div style={{ marginTop: 12, fontSize: 13, color: 'var(--ep-ink)' }}>{v.label}</div>
              <div style={{ fontSize: 12, color: 'var(--ep-ink-3)', marginTop: 2 }}>{v.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Awards strip ─────────────────────────
function AwardsStrip() {
  const items = [
    { medal: '#7E3A33', short: 'Vogue', label: "Editor's Choice 2025" },
    { medal: '#523F73', short: 'Allure', label: 'Best of Beauty 2026' },
    { medal: '#735320', short: 'Elle',   label: 'Beauty Shortlist 2025' },
    { medal: '#2F5A48', short: 'Cosmo',  label: 'Clean Beauty Award' },
    { medal: '#5A4634', short: 'GQ',     label: 'Grooming Pick 2026' },
  ];
  return (
    <section style={{ background: 'var(--ep-surface-3)' }}>
      <div className="ep-container">
        <div className="ep-awards">
          {items.map((a, i) => (
            <div key={i} className="ep-award">
              <div className="ep-award-medal" style={{ '--medal': a.medal }}><span>{a.short}</span></div>
              <div className="ep-award-label">{a.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Quiz (LIVE) ─────────────────────────
function QuizCallout({ mobile, embedded = false }) {
  const { t, tr, lang, goto, addToCart, fmt } = useStore();

  // Questions definition. opts:[{id,label}] — single-select; ids feed recommendation logic.
  const Q = lang === 'uk' ? [
    { id:'type', q:'Який твій тип шкіри?',                  opts:[ ['dry','Суха · стягується'],['normal','Нормальна'],['oily','Жирна · блищить'],['combo','Комбінована'] ]},
    { id:'concern', q:'Що турбує найбільше?',                opts:[ ['hydration','Зневоднення'],['age','Вік, тонус'],['acne','Акне, пори'],['pigment','Пігментація'],['sensitive','Чутливість'] ]},
    { id:'age', q:'Скільки тобі років?',                      opts:[ ['<25','до 25'],['25-34','25 – 34'],['35-44','35 – 44'],['45+','45 та старше'] ]},
    { id:'experience', q:'Який рівень догляду зараз?',        opts:[ ['none','Тільки починаю'],['basic','Базовий ритуал'],['adv','Просунутий'] ]},
    { id:'budget', q:'Який бюджет на місяць?',                opts:[ ['low','до 1000 ₴'],['mid','1000 – 2500 ₴'],['high','2500 ₴ +'] ]},
    { id:'texture', q:'Які текстури кремів подобаються?',     opts:[ ['light','Легкі гель-креми'],['rich','Поживні, щільні'],['any','Будь-які'] ]},
    { id:'spf', q:'Чи готова наносити SPF щодня?',            opts:[ ['yes','Так, обов’язково'],['sometimes','Іноді'],['no','Ні'] ]},
  ] : [
    { id:'type', q:"What's your skin type?",                  opts:[ ['dry','Dry · feels tight'],['normal','Normal'],['oily','Oily · shiny'],['combo','Combination'] ]},
    { id:'concern', q:"What's your main concern?",             opts:[ ['hydration','Dehydration'],['age','Ageing, firmness'],['acne','Acne, pores'],['pigment','Pigmentation'],['sensitive','Sensitivity'] ]},
    { id:'age', q:'Your age?',                                 opts:[ ['<25','Under 25'],['25-34','25 – 34'],['35-44','35 – 44'],['45+','45 and over'] ]},
    { id:'experience', q:'Routine experience?',                opts:[ ['none','Just starting'],['basic','Basic routine'],['adv','Advanced'] ]},
    { id:'budget', q:'Monthly budget?',                        opts:[ ['low','Under ₴1000'],['mid','₴1000 – 2500'],['high','₴2500+'] ]},
    { id:'texture', q:'Cream textures you like?',              opts:[ ['light','Light gel-creams'],['rich','Rich & nourishing'],['any','Either'] ]},
    { id:'spf', q:'SPF every day?',                            opts:[ ['yes','Yes, always'],['sometimes','Sometimes'],['no','No'] ]},
  ];

  const UI = lang === 'uk' ? {
    step:(n,total)=>`Крок ${n} з ${total}`, time:'~60 сек',
    next:'Далі', back:'Назад', skip:'Пропустити', restart:'Пройти ще раз', addAll:'Додати всі в кошик',
    resTitle:'Твій ритуал готовий', resSub:(n)=>`Підібрали ${n} формул під твої відповіді. Можеш додати все в кошик або переглянути кожне.`,
  } : {
    step:(n,total)=>`Step ${n} of ${total}`, time:'~60 sec',
    next:'Next', back:'Back', skip:'Skip', restart:'Start over', addAll:'Add all to bag',
    resTitle:'Your routine is ready', resSub:(n)=>`Picked ${n} formulas matched to your answers. Add the lot or open each.`,
  };

  const [step, setStep] = useState(0);   // 0..Q.length = result
  const [answers, setAnswers] = useState({});
  const total = Q.length;
  const atResult = step >= total;

  // recommendation logic
  const recommended = useMemo(() => {
    if (!atResult) return [];
    const A = answers;
    const P = window.ECOPROF_PRODUCTS;
    const picks = new Set();
    const pick = (predicate, limit = 1) => {
      const found = P.filter(predicate).slice(0, limit);
      found.forEach(p => picks.add(p.id));
    };
    // 1. Cleanser based on type
    if (A.type === 'oily' || A.concern === 'acne') pick(p => p.cat === 'cleanse' && /focus|charcoal/i.test(p.name));
    else if (A.type === 'dry' || A.type === 'normal') pick(p => p.cat === 'cleanse' && /angel|gentle/i.test(p.name));
    else pick(p => p.cat === 'cleanse');
    // 2. Toner
    pick(p => p.cat === 'tone');
    // 3. Serum by concern
    if (A.concern === 'age') pick(p => p.cat === 'age' && /retinol|peptide|lift/i.test(p.name));
    else if (A.concern === 'pigment') pick(p => /brightening|arbu|vit c/i.test(p.name));
    else if (A.concern === 'acne') pick(p => p.cat === 'acne' && /azsal|sos/i.test(p.name));
    else if (A.concern === 'sensitive') pick(p => /green barrier|centella|barrier/i.test(p.name) && p.cat === 'serum');
    else pick(p => p.cat === 'serum' && /angels|barrier/i.test(p.name));
    // 4. Cream
    if (A.texture === 'light') pick(p => p.cat === 'cream' && /cloud|gel|lift/i.test(p.name));
    else if (A.texture === 'rich') pick(p => p.cat === 'cream' && /comfort|night|rich|radiance/i.test(p.name));
    else pick(p => p.cat === 'cream' && /lift|radiance/i.test(p.name));
    // 5. SPF
    if (A.spf === 'yes' || A.spf === 'sometimes') pick(p => p.cat === 'spf');
    // budget cap
    let result = P.filter(p => picks.has(p.id));
    if (A.budget === 'low') result = result.filter(p => p.price <= 1200);
    return result.slice(0, 4);
  }, [atResult, answers]);

  const recTotal = recommended.reduce((s, p) => s + p.price, 0);

  const reset = () => { setStep(0); setAnswers({}); };

  // Bare interactive quiz panel — used both inline and embedded.
  const quizPanel = (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 14,
      minHeight: 460,
    }}>
      {!atResult && (
        <>
          {/* Progress */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap: 8 }}>
            <span className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-2)' }}>{UI.step(step+1, total)} <span style={{ color:'var(--ep-ink-3)', marginLeft: 4 }}>· {UI.time}</span></span>
            <div style={{ display:'flex', gap: 4 }}>
              {Q.map((_,i) => (
                <span key={i} style={{
                  width: 14, height: 3, borderRadius: 2,
                  background: i <= step ? 'var(--ep-accent)' : 'var(--ep-line-2)',
                  transition: 'background .2s var(--ep-ease)',
                }}/>
              ))}
            </div>
          </div>

          {/* Question */}
          <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 20, fontWeight: 500, letterSpacing:'-0.015em', lineHeight: 1.2, color:'var(--ep-ink)', marginTop: 4 }}>
            {Q[step].q}
          </div>

          {/* Options */}
          <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
            {Q[step].opts.map(([oid, oLabel]) => {
              const isSel = answers[Q[step].id] === oid;
              return (
                <div key={oid}
                  onClick={() => setAnswers({ ...answers, [Q[step].id]: oid })}
                  style={{
                    display:'flex', alignItems:'center', gap: 12,
                    padding: '13px 16px',
                    borderRadius: 12,
                    border: isSel ? '1.5px solid var(--ep-accent)' : '1px solid var(--ep-line-2)',
                    background: isSel ? 'var(--ep-accent-soft)' : 'transparent',
                    fontSize: 14, color: 'var(--ep-ink)',
                    transition: 'all .15s var(--ep-ease)', cursor: 'pointer',
                  }}>
                  <span style={{
                    width: 18, height: 18, borderRadius: '50%', flex:'none',
                    border: isSel ? '5px solid var(--ep-accent)' : '1.5px solid var(--ep-line)',
                    background: '#fff',
                  }}/>
                  <span style={{ flex:1 }}>{oLabel}</span>
                </div>
              );
            })}
          </div>

          {/* Footer */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop: 'auto', paddingTop: 16, borderTop: '1px solid var(--ep-line-2)' }}>
            {step > 0 ? (
              <button onClick={() => setStep(step-1)}
                style={{ background:'transparent', border:0, color:'var(--ep-ink-2)', fontSize: 12.5, cursor: 'pointer', padding: 0 }}>
                ← {UI.back}
              </button>
            ) : <span/>}
            <button disabled={!answers[Q[step].id]}
              onClick={() => setStep(step + 1)}
              style={{
                background: answers[Q[step].id] ? 'var(--ep-ink)' : 'var(--ep-line)',
                color:'#fff', border:0, padding:'10px 18px', borderRadius: 999, fontSize: 13, fontWeight: 500,
                cursor: answers[Q[step].id] ? 'pointer' : 'not-allowed',
                display:'inline-flex', alignItems:'center', gap: 6,
                transition: 'background .15s var(--ep-ease)',
              }}>
              {step === total - 1 ? UI.resTitle : UI.next} <span style={{ fontSize: 14, lineHeight: 1 }}>→</span>
            </button>
          </div>
        </>
      )}

      {atResult && (
        <>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <span className="ep-mono" style={{ fontSize: 10, color:'var(--ep-accent)' }}>✓ {UI.step(total, total)}</span>
            <button onClick={reset} style={{ background:'transparent', border:0, color:'var(--ep-ink-3)', fontSize: 11, cursor:'pointer', padding: 0 }}>↻ {UI.restart}</button>
          </div>
          <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.015em', lineHeight: 1.2, color:'var(--ep-ink)' }}>
            {UI.resTitle}
          </div>
          <div style={{ fontSize: 13, color:'var(--ep-ink-2)', lineHeight: 1.5 }}>{UI.resSub(recommended.length)}</div>

          {/* Compact product list */}
          <div style={{ display:'flex', flexDirection:'column', gap: 0, marginTop: 4 }}>
            {recommended.map(p => (
              <div key={p.id}
                onClick={() => goto({ name:'product', id: p.id })}
                style={{
                  display:'flex', alignItems:'center', gap: 12, padding: '10px 0',
                  borderTop:'1px solid var(--ep-line-2)', cursor:'pointer',
                }}>
                <div style={{ width: 44, height: 44, borderRadius: 6, background:'#fff', border:'1px solid var(--ep-line-2)', flex:'none', overflow:'hidden', display:'flex' }}>
                  <ProductMedia p={p}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color:'var(--ep-ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{p.name}</div>
                  <div style={{ fontSize: 11, color:'var(--ep-ink-3)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{tr(p.sub)}</div>
                </div>
                <div style={{ fontSize: 12.5, fontVariantNumeric:'tabular-nums', color:'var(--ep-ink-2)' }}>{fmt(p.price)}</div>
              </div>
            ))}
          </div>

          {/* Add all */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap: 12, marginTop: 'auto', paddingTop: 12, borderTop:'1px solid var(--ep-line-2)' }}>
            <div>
              <div style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{lang==='uk'?'Разом':'Total'}</div>
              <div style={{ fontSize: 18, fontFamily:'var(--ep-font-display)', fontWeight: 500 }}>{fmt(recTotal)}</div>
            </div>
            <button
              onClick={() => recommended.forEach(p => addToCart(p.id))}
              style={{
                background:'var(--ep-accent)', color:'var(--ep-accent-ink)', border:0,
                padding:'10px 16px', borderRadius: 999, fontSize: 12.5, fontWeight: 500, cursor:'pointer',
                display:'inline-flex', alignItems:'center', gap: 6,
              }}>{UI.addAll} <span style={{ fontSize: 14, lineHeight: 1 }}>→</span></button>
          </div>
        </>
      )}
    </div>
  );

  // Embedded: bare panel, parent provides framing
  if (embedded) return quizPanel;

  // Home: 2-column section with text on left, quiz on right inside ONE card
  return (
    <section className="ep-section" style={{ padding: mobile ? '32px 0' : '72px 0' }}>
      <div className="ep-container">
        <div style={{
          display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
          gap: 0, alignItems:'stretch',
          background: 'var(--ep-surface-2)',
          borderRadius: 'var(--ep-r-xl)', overflow:'hidden',
        }}>
          <div style={{ padding: mobile ? '32px 24px' : '56px 48px', display:'flex', flexDirection:'column', justifyContent:'center' }}>
            <div className="ep-eyebrow">{lang === 'uk' ? 'Онлайн-консультація' : 'Online consult'}</div>
            <h2 className="ep-section-title" style={{ marginTop: 12, marginBottom: 14 }}>
              {lang === 'uk' ? 'Потрібна персональна порада?' : 'Need a personal opinion?'}
            </h2>
            <p style={{ color: 'var(--ep-ink-2)', fontSize: 15, margin: '0 0 16px', maxWidth: 420, lineHeight: 1.55 }}>
              {lang === 'uk'
                ? 'Дерматолог Ольга Лісняк проводить 30-хвилинну зустріч у Zoom: аналіз шкіри, протокол на 6 тижнів, підбір продуктів. 800 ₴.'
                : 'Dermatologist Olga Lisnyak runs a 30-min Zoom session: skin analysis, 6-week protocol, product picks. ₴800.'}
            </p>
            <p style={{ color: 'var(--ep-ink-3)', fontSize: 13, margin: '0 0 24px', maxWidth: 420 }}>
              {lang === 'uk'
                ? 'Або пройди безкоштовний підбір праворуч — без реєстрації, за 60 секунд.'
                : 'Or take the free quiz on the right — no sign-up, 60 seconds.'}
            </p>
            <div>
              <button className="ep-btn accent" onClick={() => goto({ name: 'quiz' })}>
                {lang === 'uk' ? 'Записатися до дерматолога' : 'Book a dermatologist'} <I.arrow/>
              </button>
            </div>
          </div>
          <div style={{
            padding: mobile ? '24px' : '40px 48px',
            background: '#ffffff',
            borderLeft: mobile ? 'none' : '1px solid var(--ep-line-2)',
            borderTop: mobile ? '1px solid var(--ep-line-2)' : 'none',
          }}>
            {quizPanel}
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Editorial story ─────────────────────────
function StoryBlock({ mobile }) {
  const { t } = useStore();
  return (
    <section className="ep-section" style={{ paddingTop: mobile ? 48 : 80 }}>
      <div className="ep-container">
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 32, alignItems: 'stretch' }}>
          <div style={{
            aspectRatio: mobile ? '4/3' : '5/4',
            borderRadius: 'var(--ep-r-xl)', overflow: 'hidden',
            background: 'var(--ep-surface-3)',
            position: 'relative',
          }}>
            <image-slot
              id="story-portrait"
              shape="rounded"
              radius="22"
              src="portraits/story.jpg"
              placeholder="Фото обличчя · вечірній ритуал / Drop a portrait — evening routine"
              style={{ width: '100%', height: '100%', display: 'block' }}
            ></image-slot>
          </div>
          <div style={{ display:'flex', flexDirection:'column', justifyContent:'center', padding: mobile ? '0' : '0 16px' }}>
            <div className="ep-eyebrow">{t('story.eyebrow')}</div>
            <h2 className="ep-section-title" style={{ marginTop:8, marginBottom:16 }}>{t('story.title')}</h2>
            <p style={{ color:'var(--ep-ink-2)', fontSize:16, lineHeight:1.6, margin:'0 0 24px', maxWidth:520 }}>{t('story.body')}</p>
            <div>
              <button className="ep-btn ghost" onClick={() => goto({ name: 'article', id: 'a1' })}>{t('story.cta')} <I.arrow/></button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── Footer ─────────────────────────
function Footer({ mobile }) {
  const { t, goto } = useStore();
  return (
    <footer className="ep-footer">
      <div className="ep-container">
        <div className="ep-footer-grid">
          <div>
            <div className="ep-logo" style={{ marginBottom: 16 }}>ecoprof<span className="dot"/></div>
            <p style={{ color:'var(--ep-ink-2)', fontSize:14, maxWidth: 280, margin:0 }}>{t('foot.tagline')}</p>
          </div>
          <div>
            <h4>{t('foot.h.shop')}</h4>
            <ul>
              <li><a onClick={() => goto({ name: 'lines' })}>{t('foot.shop.lines')}</a></li>
              <li><a onClick={() => goto({ name: 'catalog' })}>{t('foot.shop.new')}</a></li>
              <li><a onClick={() => goto({ name: 'catalog' })}>{t('foot.shop.best')}</a></li>
              <li><a onClick={() => goto({ name: 'gift' })}>{t('foot.shop.gift')}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t('foot.h.help')}</h4>
            <ul>
              <li><a onClick={() => goto({ name: 'shipping' })}>{t('foot.help.ship')}</a></li>
              <li><a onClick={() => goto({ name: 'returns' })}>{t('foot.help.ret')}</a></li>
              <li><a onClick={() => goto({ name: 'quiz' })}>{t('foot.help.quiz')}</a></li>
              <li><a onClick={() => goto({ name: 'faq' })}>{t('foot.help.faq')}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t('foot.h.brand')}</h4>
            <ul>
              <li><a onClick={() => goto({ name: 'about' })}>{t('foot.b.about')}</a></li>
              <li><a onClick={() => goto({ name: 'journal' })}>{t('foot.b.journal')}</a></li>
              <li><a onClick={() => goto({ name: 'contact' })}>{t('foot.b.contact')}</a></li>
              <li><a onClick={() => goto({ name: 'careers' })}>{t('foot.b.career')}</a></li>
            </ul>
          </div>
        </div>
        <div className="ep-footer-bottom">
          <div>{t('foot.copy')}</div>
          <div style={{ display:'flex', gap:16 }}>
            <a onClick={() => goto({ name: 'privacy' })}>Privacy</a>
            <a onClick={() => goto({ name: 'terms' })}>Terms</a>
            <a onClick={() => goto({ name: 'cookies' })}>Cookies</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  StoreProvider, useStore, useApplySettings, hexA, I,
  Header, PromoStrip, Hero, CategoryCircles, ProductCard,
  Bestsellers, SaleVariantsShowcase, AwardsStrip, QuizCallout,
  StoryBlock, Footer, LangToggle, CartToast,
});
