// 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;

// ───────────────────────── Persistence helpers (demo) ─────────────────────────
const LS_CART = 'ep_cart';
const LS_WISH = 'ep_wishlist';
const LS_USER = 'ep_user';
const LS_LANG = 'ep_lang';
function loadLS(key, fallback) {
  try { const s = typeof localStorage !== 'undefined' && localStorage.getItem(key); return s ? JSON.parse(s) : fallback; }
  catch { return fallback; }
}
function saveLS(key, val) { try { localStorage.setItem(key, JSON.stringify(val)); } catch {} }

// ───────────────────────── Hash router ─────────────────────────
// URL hash routing resolves client-side; no Cloudflare _routes.json needed.
// Shape: #/product/p17 · #/catalog/cleanse?tag=best · #/article/a1 · #/about · etc.
const ROUTES_WITH_ID = new Set(['product', 'article', 'role']);
function serializeRoute(r) {
  if (!r || r.name === 'home') return '';
  let path = '/' + r.name;
  if (ROUTES_WITH_ID.has(r.name) && r.id) path += '/' + encodeURIComponent(r.id);
  else if (r.name === 'catalog' && r.cat) path += '/' + encodeURIComponent(r.cat);
  const qs = [];
  if (r.name === 'catalog' && r.tag) qs.push('tag=' + encodeURIComponent(r.tag));
  if (qs.length) path += '?' + qs.join('&');
  return path;
}
function parseRoute(hash) {
  const raw = (hash || '').replace(/^#/, '');
  if (!raw || raw === '/' || raw === '') return { name: 'home' };
  const [pathPart, queryPart] = raw.split('?');
  const segs = pathPart.replace(/^\//, '').split('/').filter(Boolean).map(decodeURIComponent);
  if (segs.length === 0) return { name: 'home' };
  const name = segs[0];
  const route = { name };
  if (ROUTES_WITH_ID.has(name) && segs[1]) route.id = segs[1];
  else if (name === 'catalog' && segs[1]) route.cat = segs[1];
  if (queryPart) { const tag = new URLSearchParams(queryPart).get('tag'); if (tag) route.tag = tag; }
  return route;
}

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

function StoreProvider({ children, settings }) {
  const [route, setRoute] = useState(() => parseRoute(typeof window !== 'undefined' ? window.location.hash : ''));
  const [cart, setCart] = useState(() => { const r = loadLS(LS_CART, []); return Array.isArray(r) ? r.filter(i => i && i.id && i.qty > 0) : []; });
  const [cartOpen, setCartOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [lang, setLang] = useState(() => loadLS(LS_LANG, 'uk'));
  const [toast, setToast] = useState(null);
  const [pulse, setPulse] = useState(0);
  const [wishlist, setWishlist] = useState(() => { const r = loadLS(LS_WISH, []); return Array.isArray(r) ? r : []; });    // [productId, ...]
  const [searchOpen, setSearchOpen] = useState(false);
  const [user, setUser] = useState(() => loadLS(LS_USER, null));          // { email, name, points, tier } | null
  const [authOpen, setAuthOpen] = useState(false);  // login/register modal
  const [checkoutPrefill, setCheckoutPrefill] = useState(null); // {name,phone,email,comment} from 1-click

  // Persist to localStorage (demo — survives reload + new tab).
  useEffect(() => { saveLS(LS_CART, cart); }, [cart]);
  useEffect(() => { saveLS(LS_WISH, wishlist); }, [wishlist]);
  useEffect(() => { saveLS(LS_USER, user); }, [user]);
  useEffect(() => { saveLS(LS_LANG, lang); }, [lang]);

  // Sync route ↔ window.location.hash (back/forward + reload preservation).
  useEffect(() => {
    const onHash = () => {
      const next = parseRoute(window.location.hash);
      setRoute(cur => serializeRoute(cur) === serializeRoute(next) ? cur : next);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  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 next = '#' + serializeRoute(r);
    if (typeof window !== 'undefined' && window.location.hash !== next) {
      if (next === '#') history.replaceState(null, '', window.location.pathname + window.location.search);
      else window.location.hash = serializeRoute(r);
    }
  };
  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,
    checkoutPrefill, setCheckoutPrefill,
  };
  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 === 'consult' ? 'active' : ''} onClick={() => goto({ name: 'consult' })}>{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 (auto-rotating banner set) ─────────────────────────
function Hero({ mobile }) {
  const { goto, t, tr, fmt, lang } = useStore();
  const P = window.ECOPROF_PRODUCTS;
  const find = (re, fb) => P.find(x => re.test(x.name)) || P.find(x => x.id === fb) || P[0];

  const heroP = find(/Green Barrier Serum/, 'p11');
  const spot  = find(/Radiance Vit C/, 'p18');
  const promoP = P.find(x => x.promo && x.promo.type === '2+1') || find(/Carboxy/, 'p25');

  // ── Slide A — editorial: copy + portrait + product chip ──
  const slideEditorial = (
    <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>
          </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">
          <img src="portraits/hero.jpg" alt="Bio Barrier"
            style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
          <div onClick={() => goto({ name: 'product', id: heroP.id })} role="link" tabIndex={0}
            onKeyDown={(e) => { if (e.key === 'Enter') goto({ name: 'product', id: heroP.id }); }}
            style={{ position:'absolute', left: 20, bottom: 20, zIndex: 3, cursor: 'pointer', 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>
            <span style={{ marginLeft: 4, color:'var(--ep-ink-3)', display:'inline-flex' }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
            </span>
          </div>
        </div>
      </div>
    </div>
  );

  // ── Slide B — product spotlight: copy + product on a tinted disc ──
  const slideSpotlight = (
    <div className="ep-container">
      <div className="ep-hero-grid">
        <div>
          <div className="ep-eyebrow">{spot.award ? window.ECOPROF_AWARDS[spot.award]?.label : (lang==='uk'?'Бестселер':'Bestseller')}</div>
          <h1 className="ep-hero-title" style={{ fontSize: mobile?'clamp(38px,11vw,56px)':'clamp(54px,5vw,84px)' }}>
            {spot.name.split(' ').slice(0,-1).join(' ')}<br/><em>{spot.name.split(' ').slice(-1)}</em>
          </h1>
          <p className="ep-hero-lede">{tr(spot.sub)}.</p>
          <div className="ep-hero-ctas" style={{ alignItems:'center' }}>
            <button className="ep-btn accent" onClick={() => goto({ name: 'product', id: spot.id })}>
              {lang==='uk'?'Детальніше':'See details'} <I.arrow/>
            </button>
            <span style={{ fontFamily:'var(--ep-font-display)', fontSize: 26, fontWeight: 600, color:'var(--ep-ink)' }}>{fmt(spot.price)}</span>
          </div>
        </div>
        <div className="ep-hero-art" style={{ background:'transparent', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <div style={{ position:'absolute', top:'50%', left:'50%', transform:'translate(-50%,-50%)', width:'min(86%, 460px)', aspectRatio:'1', borderRadius:'50%', background:`radial-gradient(circle at 38% 32%, #ffffff, ${spot.color||'#E6EBE4'} 78%)` }}/>
          <img src={spot.image} alt={spot.name} onClick={() => goto({ name:'product', id: spot.id })}
            style={{ position:'relative', zIndex:2, height:'76%', objectFit:'contain', cursor:'pointer', filter:'drop-shadow(0 24px 40px rgba(42,36,30,0.18))' }}/>
        </div>
      </div>
    </div>
  );

  // ── Slide C — promo / gift: centered statement + product trio ──
  const promoTrio = [promoP, spot, heroP];
  const slidePromo = (
    <div className="ep-container">
      <div style={{ textAlign:'center', maxWidth: 760, margin:'0 auto', display:'flex', flexDirection:'column', alignItems:'center', gap: mobile?16:20 }}>
        <div className="ep-eyebrow" style={{ color:'var(--ep-accent)' }}>{lang==='uk'?'Акція тижня · 2+1':'Deal of the week · 2+1'}</div>
        <h1 className="ep-hero-title" style={{ fontSize: mobile?'clamp(34px,10vw,50px)':'clamp(48px,4.6vw,76px)', margin:0 }}>
          {lang==='uk'?<>Збери ритуал —<br/><em>третій у подарунок</em></>:<>Build a ritual —<br/><em>third one free</em></>}
        </h1>
        <p className="ep-hero-lede" style={{ maxWidth: 520 }}>
          {lang==='uk'?'Обери три засоби з улюблених ліній — найдешевший даруємо.':'Pick any three from our favourite lines — the cheapest is on us.'}
        </p>
        <div style={{ display:'flex', gap: mobile?12:18, justifyContent:'center', margin:'4px 0 6px' }}>
          {promoTrio.map((p, i) => (
            <div key={i} onClick={() => goto({ name:'product', id: p.id })}
              style={{ width: mobile?78:104, height: mobile?78:104, borderRadius: '50%', background:`radial-gradient(circle at 38% 32%, #fff, ${p.color||'#E6EBE4'} 82%)`, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', boxShadow:'0 8px 22px rgba(42,36,30,0.08)' }}>
              <img src={p.image} alt={p.name} style={{ width:'70%', height:'70%', objectFit:'contain' }}/>
            </div>
          ))}
        </div>
        <button className="ep-btn accent" onClick={() => goto({ name: 'catalog', tag: 'promo' })}>
          {lang==='uk'?'До акційних товарів':'Shop the deal'} <I.arrow/>
        </button>
      </div>
    </div>
  );

  const slides = [slideEditorial, slideSpotlight, slidePromo];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % slides.length), 6500);
    return () => clearInterval(id);
  }, [slides.length]);

  return (
    <section className="ep-hero">
      <div className="ep-hero-rotator" style={{ minHeight: mobile ? undefined : 560 }}>
        {slides.map((S, i) => (
          <div key={i} className={`ep-hero-slide ${i === idx ? 'on' : ''}`}
            style={mobile ? { display: i === idx ? 'block' : 'none' } : {}} aria-hidden={i !== idx}>
            {S}
          </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)',
          rowGap: mobile ? 36 : 52,
          columnGap: mobile ? 14 : 12,
          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>
            );
          })}
        </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 promoBadge = window.promoBadge(p.promo, lang);
  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">
        {promoBadge && <span className="ep-promo-pill">{promoBadge}</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>
          <span className="ep-product-price">{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, lang } = 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: 'promo', label: lang==='uk' ? 'Акції' : 'Promos' },
  ];
  const list = useMemo(() => {
    const all = window.ECOPROF_PRODUCTS;
    if (filter === 'all')  return all.filter(p => p.badges.includes('best') || p.badges.includes('new') || p.promo).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 === 'promo') return all.filter(p => p.promo).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:'Пройти ще раз',
    resTitle:'Залиш заявку на консультацію',
    formSub:'Дерматолог вивчить твої відповіді та зв’яжеться, щоб підібрати догляд саме під твою шкіру.',
    yourAnswers:'Твої відповіді',
    fName:'Ім’я', fPhone:'Телефон', fComment:'Коментар (необов’язково)',
    fCommentPh:'Що ще варто знати про твою шкіру?',
    send:'Надіслати заявку',
    sentTitle:'Заявку прийнято',
    sentSub:'Дякуємо! Дерматолог зв’яжеться з тобою впродовж 2 годин у робочий час.',
  } : {
    step:(n,total)=>`Step ${n} of ${total}`, time:'~60 sec',
    next:'Next', back:'Back', skip:'Skip', restart:'Start over',
    resTitle:'Request your consultation',
    formSub:'Our dermatologist reviews your answers and gets in touch to build a routine for your skin.',
    yourAnswers:'Your answers',
    fName:'Name', fPhone:'Phone', fComment:'Comment (optional)',
    fCommentPh:'Anything else we should know about your skin?',
    send:'Send request',
    sentTitle:'Request received',
    sentSub:'Thank you! Our dermatologist will contact you within 2 working hours.',
  };

  const [step, setStep] = useState(0);   // 0..Q.length = result
  const [answers, setAnswers] = useState({});
  const [form, setForm] = useState({ name:'', phone:'', email:'', comment:'', slot: (lang==='uk'?'Зранку (9:00–12:00)':'Morning (9:00–12:00)') });
  const [sent, setSent] = useState(false);
  const [bookForm, setBookForm] = useState({ name:'', phone:'', email:'', slot: (lang==='uk'?'Зранку (9:00–12:00)':'Morning (9:00–12:00)') });
  const [bookSent, setBookSent] = useState(false);
  const total = Q.length;
  const atResult = step >= total;

  // Summary of chosen answers — passed along as context to the dermatologist.
  const answerSummary = Q.map(q => {
    const opt = q.opts.find(([oid]) => oid === answers[q.id]);
    return opt ? opt[1] : null;
  }).filter(Boolean);

  const reset = () => { setStep(0); setAnswers({}); setForm({ name:'', phone:'', email:'', comment:'' }); setSent(false); };

  // 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 }); setTimeout(() => setStep(s => s + 1), 260); }}
                  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 — auto-advances on select; only a Back control */}
          <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, display:'inline-flex', alignItems:'center', gap: 6 }}>
                ← {UI.back}
              </button>
            ) : <span/>}
            <span className="ep-mono" style={{ fontSize: 10.5, color:'var(--ep-ink-3)', letterSpacing:'0.06em' }}>
              {lang==='uk' ? 'Обери варіант' : 'Pick an option'}
            </span>
          </div>
        </>
      )}

      {atResult && !sent && (
        <>
          <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.formSub}</div>

          {/* Consultation request form */}
          <form
            onSubmit={(e) => { e.preventDefault(); setSent(true); }}
            style={{ display:'flex', flexDirection:'column', gap: 12, marginTop: 6, paddingTop: 18, borderTop:'1px solid var(--ep-line-2)' }}>
            <div style={{ display:'flex', gap: 12 }}>
              <input required value={form.name} onChange={(e)=>setForm({...form, name:e.target.value})} placeholder={UI.fName}
                style={{ flex:1, minWidth:0, height: 52, padding:'0 16px', border:'1px solid var(--ep-line-2)', borderRadius: 12, background:'#fff', font:'15px var(--ep-font)', color:'var(--ep-ink)', outline:'none', boxSizing:'border-box' }}/>
              <input required type="tel" value={form.phone} onChange={(e)=>setForm({...form, phone:e.target.value})} placeholder={UI.fPhone}
                style={{ flex:1, minWidth:0, height: 52, padding:'0 16px', border:'1px solid var(--ep-line-2)', borderRadius: 12, background:'#fff', font:'15px var(--ep-font)', color:'var(--ep-ink)', outline:'none', boxSizing:'border-box' }}/>
            </div>
            <input required type="email" value={form.email} onChange={(e)=>setForm({...form, email:e.target.value})} placeholder="Email"
              style={{ height: 52, padding:'0 16px', border:'1px solid var(--ep-line-2)', borderRadius: 12, background:'#fff', font:'15px var(--ep-font)', color:'var(--ep-ink)', outline:'none', boxSizing:'border-box' }}/>
            <div>
              <div className="ep-mono" style={{ fontSize: 10, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--ep-ink-3)', marginBottom: 8 }}>{lang==='uk'?'Зручний час':'Preferred time'}</div>
              <div style={{ display:'flex', flexWrap:'wrap', gap: 9 }}>
                {(lang==='uk'
                  ? ['Зранку (9:00–12:00)','Вдень (12:00–16:00)','Ввечері (16:00–20:00)']
                  : ['Morning (9:00–12:00)','Afternoon (12:00–16:00)','Evening (16:00–20:00)']
                ).map((s) => {
                  const on = form.slot === s;
                  return (
                    <button type="button" key={s} onClick={()=>setForm({...form, slot:s})}
                      style={{ height: 46, padding:'0 16px', borderRadius: 12, cursor:'pointer', textAlign:'center', flex:'1 1 auto',
                        border: on?'1.5px solid var(--ep-accent)':'1px solid var(--ep-line-2)',
                        background: on?'var(--ep-accent-soft)':'#fff', color:'var(--ep-ink)',
                        font:'13.5px var(--ep-font)', fontWeight: on?600:400, whiteSpace:'nowrap', transition:'border-color .15s var(--ep-ease), background .15s var(--ep-ease)' }}>
                      {s}
                    </button>
                  );
                })}
              </div>
            </div>
            <textarea rows={2} value={form.comment} onChange={(e)=>setForm({...form, comment:e.target.value})} placeholder={UI.fCommentPh}
              style={{ padding:'13px 16px', border:'1px solid var(--ep-line-2)', borderRadius: 12, background:'#fff', font:'15px var(--ep-font)', color:'var(--ep-ink)', resize:'vertical', outline:'none', boxSizing:'border-box' }}/>
            <button type="submit"
              style={{ background:'var(--ep-accent)', color:'var(--ep-accent-ink)', border:0, height: 56, padding:'0 24px', borderRadius: 999, fontSize: 15, fontWeight: 500, cursor:'pointer', display:'inline-flex', alignItems:'center', gap: 8, justifyContent:'center', marginTop: 2 }}>
              {UI.send} <span style={{ fontSize: 15, lineHeight: 1 }}>→</span>
            </button>
          </form>
        </>
      )}

      {atResult && sent && (
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', flex: 1, gap: 12, padding:'20px 0' }}>
          <div style={{ width: 56, height: 56, borderRadius:'50%', background:'var(--ep-accent-soft)', color:'var(--ep-accent)', display:'inline-flex', alignItems:'center', justifyContent:'center' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 7"/></svg>
          </div>
          <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.015em', color:'var(--ep-ink)' }}>{UI.sentTitle}</div>
          <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin: 0, lineHeight: 1.55, maxWidth: 340 }}>{UI.sentSub}</p>
          <button onClick={reset} style={{ background:'transparent', border:'1px solid var(--ep-line)', color:'var(--ep-ink)', padding:'10px 18px', borderRadius: 999, fontSize: 12.5, fontWeight: 500, cursor:'pointer', marginTop: 4 }}>↻ {UI.restart}</button>
        </div>
      )}
    </div>
  );

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

  // Paid-consultation booking form (used on the home block + Consult page).
  const bookingPanel = (
    <div style={{ display:'flex', flexDirection:'column', gap: 12, minHeight: 380, justifyContent: bookSent ? 'center' : 'flex-start' }}>
      {!bookSent ? (
        <>
          <div className="ep-eyebrow" style={{ color:'var(--ep-accent)' }}>{lang==='uk'?'Запис · 800 ₴':'Booking · ₴800'}</div>
          <h3 style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.015em', margin:'2px 0 2px' }}>
            {lang==='uk'?'Обери зручний час':'Pick a time that suits you'}
          </h3>
          <p style={{ fontSize: 13, color:'var(--ep-ink-2)', margin:'0 0 6px', lineHeight: 1.5 }}>
            {lang==='uk'?'Залиш контакти — підтвердимо слот у Zoom і надішлемо нагадування.':'Leave your details — we’ll confirm a Zoom slot and send a reminder.'}
          </p>
          <div style={{ display:'flex', gap: 9 }}>
            <input value={bookForm.name} onChange={(e)=>setBookForm({...bookForm, name:e.target.value})} placeholder={lang==='uk'?'Ім’я':'Name'}
              style={{ flex:1, minWidth:0, height: 44, padding:'0 12px', border:'1px solid var(--ep-line-2)', borderRadius: 10, background:'#fff', font:'14px var(--ep-font)', color:'var(--ep-ink)', outline:'none' }}/>
            <input type="tel" value={bookForm.phone} onChange={(e)=>setBookForm({...bookForm, phone:e.target.value})} placeholder={lang==='uk'?'Телефон':'Phone'}
              style={{ flex:1, minWidth:0, height: 44, padding:'0 12px', border:'1px solid var(--ep-line-2)', borderRadius: 10, background:'#fff', font:'14px var(--ep-font)', color:'var(--ep-ink)', outline:'none' }}/>
          </div>
          <input type="email" value={bookForm.email} onChange={(e)=>setBookForm({...bookForm, email:e.target.value})} placeholder="Email"
            style={{ height: 44, padding:'0 12px', border:'1px solid var(--ep-line-2)', borderRadius: 10, background:'#fff', font:'14px var(--ep-font)', color:'var(--ep-ink)', outline:'none' }}/>
          <select value={bookForm.slot} onChange={(e)=>setBookForm({...bookForm, slot:e.target.value})}
            style={{ height: 44, padding:'0 12px', border:'1px solid var(--ep-line-2)', borderRadius: 10, background:'#fff', font:'14px var(--ep-font)', color:'var(--ep-ink)', outline:'none' }}>
            {(lang==='uk'
              ? ['Зранку (9:00–12:00)','Вдень (12:00–16:00)','Ввечері (16:00–20:00)','Вихідні']
              : ['Morning (9:00–12:00)','Afternoon (12:00–16:00)','Evening (16:00–20:00)','Weekends']
            ).map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
          <button
            disabled={!bookForm.phone.trim() || !bookForm.email.trim()}
            onClick={() => setBookSent(true)}
            style={{ background:'var(--ep-accent)', color:'var(--ep-accent-ink)', border:0, padding:'14px 22px', borderRadius: 999, fontSize: 14, fontWeight: 500, cursor:'pointer', display:'inline-flex', alignItems:'center', gap: 8, justifyContent:'center', marginTop: 2 }}>
            {lang==='uk'?'Записатися · 800 ₴':'Book · ₴800'} <I.arrow/>
          </button>
          <p style={{ fontSize: 11, color:'var(--ep-ink-3)', margin: 0, textAlign:'center' }}>
            {lang==='uk'?'Оплата після підтвердження слота менеджером.':'Payment after a manager confirms the slot.'}
          </p>
        </>
      ) : (
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center', gap: 12 }}>
          <div style={{ width: 56, height: 56, borderRadius:'50%', background:'var(--ep-accent-soft)', color:'var(--ep-accent)', display:'inline-flex', alignItems:'center', justifyContent:'center' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 7"/></svg>
          </div>
          <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.015em', color:'var(--ep-ink)' }}>{lang==='uk'?'Заявку прийнято':'Request received'}</div>
          <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin: 0, lineHeight: 1.55, maxWidth: 320 }}>{lang==='uk'?'Менеджер зв’яжеться, щоб підтвердити час консультації з Тетяною Григорівною.':'A manager will contact you to confirm the time with Tetiana.'}</p>
          <button onClick={() => { setBookSent(false); setBookForm({ name:'', phone:'', email:'', slot: (lang==='uk'?'Зранку (9:00–12:00)':'Morning (9:00–12:00)') }); }}
            style={{ background:'transparent', border:'1px solid var(--ep-line)', color:'var(--ep-ink)', padding:'10px 18px', borderRadius: 999, fontSize: 12.5, fontWeight: 500, cursor:'pointer' }}>{lang==='uk'?'Готово':'Done'}</button>
        </div>
      )}
    </div>
  );

  // 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={{ position:'relative', minHeight: mobile?380:undefined, background:'var(--ep-surface-3)', overflow:'hidden' }}>
            <img src="images/tetyana-hryhorivna.png" alt={lang==='uk'?'Тетяна Григорівна':'Tetiana Hryhorivna'} style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', objectPosition:'center top', display:'block' }}/>
            <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg, rgba(20,16,12,0) 38%, rgba(20,16,12,0.82) 100%)', pointerEvents:'none' }}/>
            <div style={{ position:'absolute', left:0, right:0, bottom:0, padding: mobile?'24px':'40px 44px', zIndex:2, color:'#fff' }}>
              <div className="ep-eyebrow" style={{ color:'rgba(255,255,255,0.8)' }}>{lang === 'uk' ? 'Онлайн-консультація' : 'Online consult'}</div>
              <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?26:34, fontWeight:500, letterSpacing:'-0.025em', lineHeight:1.05, color:'#fff', margin:'12px 0 12px' }}>
                {lang === 'uk' ? 'Потрібна персональна порада?' : 'Need a personal opinion?'}
              </h2>
              <p style={{ color:'rgba(255,255,255,0.88)', fontSize: mobile?14:15, margin:'0 0 16px', maxWidth:420, lineHeight:1.55 }}>
                {lang === 'uk'
                  ? 'Дерматолог Тетяна Григорівна розбере твою шкіру у Zoom або Viber і складе план догляду.'
                  : 'Dermatologist Tetiana Hryhorivna reviews your skin on Zoom or Viber and builds a care plan.'}
              </p>
              <div style={{ display:'inline-flex', alignItems:'center', gap:10, padding:'8px 14px', borderRadius:999, background:'rgba(255,255,255,0.14)', border:'1px solid rgba(255,255,255,0.25)', backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)' }}>
                <span style={{ fontFamily:'var(--ep-font-display)', fontSize:18, fontWeight:600, color:'#fff', whiteSpace:'nowrap' }}>{fmt(800)}</span>
                <span style={{ width:1, height:13, background:'rgba(255,255,255,0.3)' }}/>
                <span style={{ fontSize:12.5, color:'rgba(255,255,255,0.85)', whiteSpace:'nowrap' }}>30 {lang==='uk'?'хв':'min'} · Zoom · Viber</span>
              </div>
            </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',
          }}>
            <img src="portraits/story.jpg" alt=""
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
          </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: '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,
});
