// store-pages.jsx — Static / editorial pages:
// About, Journal, Contact, Shipping, Returns, FAQ, Careers, Gift Cards, Quiz.
// Most are content-driven; bigger ones (Journal, Contact, Quiz) get richer layouts.

// ─── Shared PageHero (eyebrow + title + lede + breadcrumb) ────────────────
function PageHero({ eyebrow, title, lede, breadcrumb, mobile }) {
  const { goto, lang } = useStore();
  return (
    <div className="ep-container" style={{ paddingTop: 28, paddingBottom: mobile ? 24 : 48 }}>
      {breadcrumb && (
        <div className="ep-mono" style={{ fontSize: 11, marginBottom: 18 }}>
          <a onClick={() => goto({name:'home'})} style={{ cursor:'pointer' }}>Ecoprof</a>
          <span style={{ margin:'0 8px' }}>/</span>
          <span style={{ color:'var(--ep-ink)' }}>{breadcrumb}</span>
        </div>
      )}
      <div className="ep-eyebrow">{eyebrow}</div>
      <h1 className="ep-section-title" style={{ marginTop: 12, marginBottom: 16, fontSize: mobile ? 36 : 56 }}>{title}</h1>
      {lede && <p style={{ fontSize: mobile ? 15 : 17, color:'var(--ep-ink-2)', lineHeight: 1.55, maxWidth: 680, margin: 0 }}>{lede}</p>}
    </div>
  );
}

// ─── InfoPage — wraps simple content (sections of headings + body text) ────
function InfoPage({ hero, sections, faq, footerCTA, mobile }) {
  const { goto, lang } = useStore();
  return (
    <>
      <PageHero {...hero} mobile={mobile}/>
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : 'minmax(0, 220px) minmax(0, 1fr)',
          gap: mobile ? 32 : 80,
          alignItems: 'flex-start',
        }}>
          {/* Anchor nav (desktop) */}
          {!mobile && sections && sections.length > 1 && (
            <nav style={{ position:'sticky', top: 96, display:'flex', flexDirection:'column', gap: 10 }}>
              <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)', marginBottom: 4 }}>
                {lang === 'uk' ? 'На цій сторінці' : 'On this page'}
              </div>
              {sections.map((s, i) => (
                <a key={i} href={`#sec-${i}`} style={{ fontSize: 13, color: 'var(--ep-ink-2)', cursor:'pointer' }}>{s.title}</a>
              ))}
            </nav>
          )}
          <div style={{ maxWidth: 740 }}>
            {sections && sections.map((s, i) => (
              <section key={i} id={`sec-${i}`} style={{ marginBottom: 40 }}>
                {s.title && <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile ? 22 : 28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 14px' }}>{s.title}</h2>}
                {s.body && typeof s.body === 'string' && <p style={{ fontSize: 15, color:'var(--ep-ink-2)', lineHeight: 1.7, margin:'0 0 12px', whiteSpace:'pre-line' }}>{s.body}</p>}
                {s.body && Array.isArray(s.body) && s.body.map((para, j) => (
                  <p key={j} style={{ fontSize: 15, color:'var(--ep-ink-2)', lineHeight: 1.7, margin:'0 0 12px' }}>{para}</p>
                ))}
                {s.list && (
                  <ul style={{ padding: 0, margin: 0, listStyle:'none', display:'flex', flexDirection:'column', gap: 10 }}>
                    {s.list.map((item, j) => (
                      <li key={j} style={{ display:'flex', gap: 10, alignItems:'baseline', fontSize: 14.5, color:'var(--ep-ink-2)' }}>
                        <span style={{ flex:'none', width: 4, height: 4, borderRadius:'50%', background:'var(--ep-accent)', transform:'translateY(-3px)' }}/>
                        <span>{item}</span>
                      </li>
                    ))}
                  </ul>
                )}
                {s.callout && (
                  <div style={{ padding:'18px 22px', background:'var(--ep-surface-3)', borderRadius: 14, marginTop: 12, fontSize: 14, color:'var(--ep-ink)' }}>
                    {s.callout}
                  </div>
                )}
              </section>
            ))}

            {/* FAQ accordion */}
            {faq && faq.length > 0 && (
              <section style={{ marginTop: 40 }}>
                <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile ? 22 : 28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 18px' }}>
                  {lang === 'uk' ? 'Часті запитання' : 'FAQ'}
                </h2>
                <FAQList items={faq}/>
              </section>
            )}

            {footerCTA && (
              <div style={{ marginTop: 48, padding: '36px 32px', borderRadius: 22, background:'var(--ep-surface-2)' }}>
                <div className="ep-eyebrow" style={{ marginBottom: 8 }}>{footerCTA.eyebrow}</div>
                <h3 style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 8px' }}>{footerCTA.title}</h3>
                <p style={{ fontSize: 14, color:'var(--ep-ink-2)', margin:'0 0 18px', maxWidth: 480 }}>{footerCTA.body}</p>
                <button className="ep-btn" onClick={() => goto(footerCTA.route)}>{footerCTA.cta} →</button>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

function FAQList({ items }) {
  const [openIdx, setOpenIdx] = React.useState(0);
  return (
    <div style={{ borderTop:'1px solid var(--ep-line-2)' }}>
      {items.map((f, i) => {
        const open = openIdx === i;
        return (
          <div key={i} style={{ borderBottom:'1px solid var(--ep-line-2)' }}>
            <button onClick={() => setOpenIdx(open ? -1 : i)}
              style={{
                width:'100%', padding:'18px 0', background:'transparent', border:0,
                display:'flex', alignItems:'center', justifyContent:'space-between', gap: 16,
                cursor:'pointer', textAlign:'left', color:'var(--ep-ink)',
                fontSize: 15, fontWeight: 500, fontFamily:'inherit',
              }}>
              <span>{f.q}</span>
              <span style={{ flex:'none', fontSize: 18, lineHeight: 1, transform: open ? 'rotate(45deg)' : 'none', transition: 'transform .2s var(--ep-ease)' }}>+</span>
            </button>
            <div style={{ maxHeight: open ? 500 : 0, overflow: 'hidden', transition: 'max-height .3s var(--ep-ease)' }}>
              <div style={{ padding: '0 0 18px', fontSize: 14.5, color:'var(--ep-ink-2)', lineHeight: 1.7, maxWidth: 600 }}>
                {f.a}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─────────────────────────── ABOUT ────────────────────────────────────────
function AboutPage({ mobile }) {
  const { lang } = useStore();
  return (
    <InfoPage mobile={mobile}
      hero={{
        eyebrow: lang === 'uk' ? 'Про бренд' : 'About',
        title: lang === 'uk' ? 'Активна косметика з клінічних протоколів.' : 'Active skincare built to clinical protocols.',
        lede: lang === 'uk'
          ? 'Ecoprof — український бренд догляду, розроблений разом із дерматологами й технологами. Кожна формула проходить тестування в незалежних лабораторіях ЄС перед запуском.'
          : 'Ecoprof is a Ukrainian skincare brand co-developed with dermatologists and cosmetic chemists. Every formula is tested in independent EU labs before launch.',
        breadcrumb: lang === 'uk' ? 'Про бренд' : 'About',
      }}
      sections={lang === 'uk' ? [
        { title: 'Наш підхід',
          body: [
            'Ми робимо догляд, який працює в реальному житті, а не на маркетингових слайдах. Кожна лінійка — це система з 3-4 формул, які доповнюють одна одну.',
            'Концентрації активів вищі за середньоринкові, але м’якші за ті, що в кабінеті косметолога. Це дозволяє отримати клінічний результат удома — без подразнень і відновного періоду.',
          ]},
        { title: 'Цифри',
          list: [
            '6 років в розробці формул',
            '46 SKU у каталозі, 10 окремих лінійок',
            '12+ активних інгредієнтів європейського виробництва',
            '4.86 — середній рейтинг товарів за 12 000+ відгуків',
            '14 днів — гарантоване повернення',
          ]},
        { title: 'Команда',
          body: 'Ольга Лісняк — дерматолог, ведуча формулярка. Тарас Ковалевський — біохімік, контроль якості. Анна Ковальова — косметолог, освіта і клієнтська підтримка. Команда виробництва й логістики — в Києві.',
          callout: lang === 'uk' ? 'Зроблено в Києві, відвантажується по всьому світу.' : 'Crafted in Kyiv, shipped worldwide.',
        },
        { title: 'Сертифікати',
          body: 'GMP 22716 (Good Manufacturing Practice), не тестуємо на тваринах (PETA-сертифікат), всі формули веганські за винятком засобів з медом і шовком (вказано на упаковці).' },
      ] : [
        { title: 'Our approach',
          body: [
            'We make skincare that works in real life — not just on marketing decks. Every line is a 3-4 step system where products amplify each other.',
            'Active concentrations sit above market average, yet below clinical-cabinet levels. That delivers visible results at home, without irritation or recovery.',
          ]},
        { title: 'By the numbers',
          list: [
            '6 years formulating',
            '46 SKUs, 10 distinct lines',
            '12+ active ingredients from EU suppliers',
            '4.86 average rating across 12,000+ reviews',
            '14-day no-questions returns',
          ]},
        { title: 'Team',
          body: 'Olga Lisnyak — dermatologist, lead formulator. Taras Kovalevsky — biochemist, QC. Anna Kovaleva — esthetician, education and CX. Production and ops in Kyiv.',
          callout: 'Crafted in Kyiv, shipped worldwide.',
        },
        { title: 'Certifications',
          body: 'GMP 22716 (Good Manufacturing Practice), cruelty-free (PETA-certified), all formulas vegan except those with honey or silk (clearly marked).' },
      ]}
      footerCTA={{
        eyebrow: lang === 'uk' ? 'Підбір' : 'Quiz',
        title: lang === 'uk' ? 'Не знаєш з чого почати?' : 'Not sure where to start?',
        body: lang === 'uk' ? 'Пройди семишаговий підбір — отримай ритуал під свою шкіру.' : 'Take our 7-step quiz — get a personalised routine.',
        cta: lang === 'uk' ? 'Пройти підбір' : 'Start the quiz',
        route: { name: 'quiz' },
      }}
    />
  );
}

// ─────────────────────────── JOURNAL ──────────────────────────────────────
const JOURNAL_ARTICLES = [
  { id:'a1', cat:'guide', title:{uk:'Вечірній ритуал із 4 кроків', en:'4-step evening routine'},
    excerpt:{uk:'Очищення → активна сироватка → відновлення бар’єра → захист.', en:'Cleanse → active serum → barrier repair → protection.'},
    author:'Anna Kovaleva', mins:6, date:{uk:'12 травня 2026', en:'May 12, 2026'},
    cover: 'p17' },
  { id:'a2', cat:'science', title:{uk:'Що таке ретинальдегід і чим він кращий за ретинол', en:'Retinaldehyde vs retinol — what changes'},
    excerpt:{uk:'Третя похідна вітаміну А, що працює в 11 разів швидше. Розбираємо механізм.', en:'The third vitamin A derivative — 11× faster than retinol. We unpack the mechanism.'},
    author:'Olga Lisnyak', mins:9, date:{uk:'2 травня 2026', en:'May 2, 2026'},
    cover: 'p27' },
  { id:'a3', cat:'guide', title:{uk:'SPF щодня: 7 міфів і факти', en:'Daily SPF: 7 myths and facts'},
    excerpt:{uk:'Скільки потрібно крему, чи бронзує тебе сонце через вікно, що таке PA++++.', en:'How much to use, will you tan through windows, and what PA++++ actually means.'},
    author:'Olga Lisnyak', mins:5, date:{uk:'24 квітня 2026', en:'April 24, 2026'},
    cover: 'p26' },
  { id:'a4', cat:'concern', title:{uk:'Розацеа: як побудувати догляд', en:'Rosacea: building a routine'},
    excerpt:{uk:'Тригери, інгредієнти, які слід уникати, і протокол на 6 тижнів.', en:'Triggers, ingredients to avoid, and a 6-week protocol.'},
    author:'Olga Lisnyak', mins:8, date:{uk:'12 квітня 2026', en:'April 12, 2026'},
    cover: 'p11' },
  { id:'a5', cat:'science', title:{uk:'Гідрофільна олія VS міцелярна вода', en:'Cleansing oil vs micellar water'},
    excerpt:{uk:'Як працює подвійне очищення і коли воно справді потрібно.', en:'How double cleansing works — and when it actually matters.'},
    author:'Anna Kovaleva', mins:4, date:{uk:'1 квітня 2026', en:'April 1, 2026'},
    cover: 'p01' },
  { id:'a6', cat:'guide', title:{uk:'Кислоти 101: PHA, AHA, BHA', en:'Acids 101: PHA, AHA, BHA'},
    excerpt:{uk:'З чого почати, який тип шкіри що любить і чого не варто змішувати.', en:'Where to start, what suits your skin, and what not to mix.'},
    author:'Anna Kovaleva', mins:7, date:{uk:'22 березня 2026', en:'March 22, 2026'},
    cover: 'p09' },
];

function JournalPage({ mobile }) {
  const { tr, lang, goto } = useStore();
  const featured = JOURNAL_ARTICLES[0];
  const rest = JOURNAL_ARTICLES.slice(1);
  const cats = lang === 'uk'
    ? [{id:'all',n:'Усі'},{id:'guide',n:'Гайди'},{id:'science',n:'Наука'},{id:'concern',n:'Проблеми шкіри'}]
    : [{id:'all',n:'All'},{id:'guide',n:'Guides'},{id:'science',n:'Science'},{id:'concern',n:'Concerns'}];
  const [tab, setTab] = React.useState('all');
  const visible = rest.filter(a => tab === 'all' || a.cat === tab);

  const productImg = (id) => window.ECOPROF_PRODUCTS.find(p => p.id === id)?.image;

  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Журнал':'Journal'}
        title={lang==='uk'?'Догляд, який має сенс':'Skincare that makes sense'}
        lede={lang==='uk'?'Гайди, наука й щоденні протоколи від наших дерматологів і косметологів.':'Guides, science, and daily protocols from our dermatologists and estheticians.'}
        breadcrumb={lang==='uk'?'Журнал':'Journal'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        {/* Featured */}
        <div onClick={() => goto({ name: 'article', id: featured.id })}
          style={{
            display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1.05fr 0.95fr',
            gap: mobile ? 24 : 48, alignItems:'center',
            padding: mobile ? '24px 0' : '40px 0',
            borderTop: '1px solid var(--ep-line-2)',
            borderBottom: '1px solid var(--ep-line-2)',
            cursor: 'pointer', marginBottom: 48,
          }}>
          <div style={{
            aspectRatio: '6/5', borderRadius: 22, background:'#fdfaf4',
            display:'flex', alignItems:'center', justifyContent:'center', position:'relative',
          }}>
            <img src={productImg(featured.cover)} alt="" style={{ width:'60%', maxHeight:'80%', objectFit:'contain' }}/>
            <div className="ep-mono" style={{ position:'absolute', top: 16, left: 16, fontSize: 10, color:'var(--ep-ink-2)' }}>
              {lang==='uk'?'Випуск':'Issue'} · {featured.cat}
            </div>
          </div>
          <div>
            <div className="ep-eyebrow" style={{ color: 'var(--ep-accent)' }}>{lang==='uk'?'Виділяємо':'Featured'}</div>
            <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?28:40, fontWeight:500, letterSpacing:'-0.025em', lineHeight:1.05, margin:'14px 0 14px' }}>
              {tr(featured.title)}
            </h2>
            <p style={{ fontSize: 16, color:'var(--ep-ink-2)', lineHeight: 1.6, margin: '0 0 18px', maxWidth: 500 }}>{tr(featured.excerpt)}</p>
            <div style={{ display:'flex', gap: 14, alignItems:'center', fontSize: 12, color:'var(--ep-ink-3)' }}>
              <span>{featured.author}</span>
              <span>·</span>
              <span>{tr(featured.date)}</span>
              <span>·</span>
              <span>{featured.mins} {lang==='uk'?'хв':'min'}</span>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display:'flex', gap: 8, flexWrap:'wrap', marginBottom: 32 }}>
          {cats.map(c => (
            <button key={c.id} className={`ep-chip ${tab === c.id ? 'active' : ''}`} onClick={() => setTab(c.id)}>{c.n}</button>
          ))}
        </div>

        {/* Article grid */}
        <div className="ep-grid" style={{ gridTemplateColumns: mobile ? 'repeat(1, 1fr)' : 'repeat(3, 1fr)', gap: mobile ? 24 : 32 }}>
          {visible.map(a => (
            <article key={a.id} onClick={() => goto({ name: 'article', id: a.id })} style={{ cursor:'pointer' }}>
              <div style={{
                aspectRatio:'4/3', borderRadius: 14, background:'#fdfaf4',
                display:'flex', alignItems:'center', justifyContent:'center', marginBottom: 14,
                transition:'transform .35s var(--ep-ease)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-3px)'}
              onMouseLeave={(e) => e.currentTarget.style.transform = 'none'}
              >
                <img src={productImg(a.cover)} alt="" style={{ width:'55%', maxHeight:'80%', objectFit:'contain' }}/>
              </div>
              <div className="ep-mono" style={{ fontSize: 9.5, color:'var(--ep-ink-3)', marginBottom: 6 }}>{a.cat} · {a.mins} {lang==='uk'?'хв':'min'}</div>
              <h3 style={{ fontFamily:'var(--ep-font-display)', fontSize: 18, fontWeight:500, letterSpacing:'-0.015em', margin:'0 0 6px', lineHeight: 1.15 }}>{tr(a.title)}</h3>
              <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin:'0 0 8px', lineHeight: 1.5 }}>{tr(a.excerpt)}</p>
              <div style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{a.author} · {tr(a.date)}</div>
            </article>
          ))}
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── CONTACT ──────────────────────────────────────
function ContactPage({ mobile }) {
  const { lang } = useStore();
  const [sent, setSent] = React.useState(false);
  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Контакти':'Contact'}
        title={lang==='uk'?'Залишайся на зв’язку.':'Get in touch.'}
        lede={lang==='uk'?'Відповідаємо на пошту впродовж 24 годин по робочих днях. По телефону — миттєво.':'We reply within 24 hours on weekdays. Phone is instant.'}
        breadcrumb={lang==='uk'?'Контакти':'Contact'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1.1fr 1fr', gap: mobile ? 32 : 64, alignItems:'flex-start' }}>
          {/* Info */}
          <div style={{ display:'flex', flexDirection:'column', gap: 28 }}>
            <ContactBlock
              label={lang==='uk'?'Телефон':'Phone'}
              value="+380 (99) 397 36 84"
              sub={lang==='uk'?'Пн-Нд · 10:00 — 20:00':'Mon-Sun · 10:00 — 20:00'}
            />
            <ContactBlock
              label={lang==='uk'?'Електронна пошта':'Email'}
              value="hello@ecoprof.ua"
              sub={lang==='uk'?'Питання, партнерства, преса':'Questions, partnerships, press'}
            />
            <ContactBlock
              label={lang==='uk'?'Офіс і шоурум':'Office & showroom'}
              value={lang==='uk'?'м. Київ, вул. Золотоворітська 13':'13 Zolotovoritska St, Kyiv'}
              sub={lang==='uk'?'1 поверх · без вихідних':'1st floor · open every day'}
            />
            <ContactBlock
              label={lang==='uk'?'Соцмережі':'Social'}
              value={<>
                <a style={{ marginRight: 12, color:'var(--ep-ink)', borderBottom:'1px solid var(--ep-line)' }}>Instagram</a>
                <a style={{ marginRight: 12, color:'var(--ep-ink)', borderBottom:'1px solid var(--ep-line)' }}>Telegram</a>
                <a style={{ color:'var(--ep-ink)', borderBottom:'1px solid var(--ep-line)' }}>Facebook</a>
              </>}
              sub="@ecoprofcosmetics"
            />
          </div>

          {/* Form */}
          <div style={{ background:'#fdfaf4', borderRadius: 22, padding: mobile ? 24 : 32 }}>
            <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: 24, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 6px' }}>
              {lang==='uk'?'Напиши нам':'Write to us'}
            </h2>
            <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin:'0 0 22px' }}>
              {lang==='uk'?'Опиши свою задачу — підкажемо, що вибрати з каталогу або порадимо звернутися до косметолога.':'Tell us about your concern — we’ll either suggest products or refer you to our esthetician.'}
            </p>
            {sent ? (
              <div style={{ padding:'40px 20px', textAlign:'center', color:'var(--ep-ink)' }}>
                <div style={{ width: 48, height: 48, borderRadius:'50%', background:'var(--ep-accent)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 14px' }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
                </div>
                <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 20, fontWeight: 500, marginBottom: 6 }}>{lang==='uk'?'Прийнято':'Got it'}</div>
                <div style={{ fontSize: 13, color:'var(--ep-ink-2)' }}>{lang==='uk'?'Повернемось до тебе протягом 24 годин.':'We’ll get back within 24 hours.'}</div>
              </div>
            ) : (
              <form onSubmit={(e) => { e.preventDefault(); setSent(true); }}
                style={{ display:'flex', flexDirection:'column', gap: 14 }}>
                <FormField label={lang==='uk'?'Ім’я':'Name'} type="text"/>
                <FormField label="Email" type="email"/>
                <FormField label={lang==='uk'?'Повідомлення':'Message'} type="textarea"/>
                <button type="submit" className="ep-btn accent" style={{ marginTop: 4 }}>
                  {lang==='uk'?'Надіслати':'Send'} →
                </button>
              </form>
            )}
          </div>
        </div>

        {/* Map */}
        <div style={{ marginTop: mobile ? 40 : 64 }}>
          <div style={{
            display:'flex', alignItems:'flex-end', justifyContent:'space-between',
            gap: 16, flexWrap:'wrap', marginBottom: 16,
          }}>
            <div>
              <div className="ep-eyebrow">{lang==='uk'?'Як знайти':'How to find us'}</div>
              <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:28, fontWeight: 500, letterSpacing:'-0.02em', margin:'10px 0 4px' }}>
                {lang==='uk'?'Золотоворітська 13, Київ':'Zolotovoritska 13, Kyiv'}
              </h2>
              <div style={{ fontSize: 13.5, color:'var(--ep-ink-2)' }}>
                {lang==='uk'?'2 хв пішки від ст. м. «Золоті ворота»':'2 min walk from Zoloti Vorota metro station'}
              </div>
            </div>
            <button onClick={() => window.open('https://www.google.com/maps/dir/?api=1&destination=Zolotovoritska+13+Kyiv', '_blank', 'noopener')}
               className="ep-btn">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 2 }}>
                <path d="M21 10c0 6-9 13-9 13S3 16 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/>
              </svg>
              {lang==='uk'?'Прокласти маршрут':'Get directions'}
            </button>
          </div>
          <div style={{
            borderRadius: 22, overflow:'hidden', border:'1px solid var(--ep-line-2)',
            aspectRatio: mobile ? '4/3' : '21/9', background:'var(--ep-surface-3)',
          }}>
            <iframe
              src="https://www.google.com/maps?q=Zolotovoritska+13,+Kyiv&hl=uk&z=16&output=embed"
              title="Ecoprof showroom"
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              style={{ width:'100%', height:'100%', border: 0, display:'block', filter:'grayscale(0.15) saturate(0.85)' }}
            />
          </div>
        </div>
      </div>
    </>
  );
}
function ContactBlock({ label, value, sub }) {
  return (
    <div>
      <div className="ep-mono" style={{ fontSize: 10.5, color:'var(--ep-ink-3)', marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 18, fontFamily:'var(--ep-font-display)', fontWeight: 500, color:'var(--ep-ink)', letterSpacing:'-0.015em', marginBottom: 4 }}>{value}</div>
      {sub && <div style={{ fontSize: 12.5, color:'var(--ep-ink-2)' }}>{sub}</div>}
    </div>
  );
}
function FormField({ label, type }) {
  const isTextarea = type === 'textarea';
  return (
    <label style={{ display:'flex', flexDirection:'column', gap: 6 }}>
      <span className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-2)' }}>{label}</span>
      {isTextarea ? (
        <textarea rows={4} style={{
          padding:'10px 12px', border:'1px solid var(--ep-line-2)', borderRadius: 10,
          background:'#fff', font:'14px var(--ep-font)', color:'var(--ep-ink)', resize:'vertical', outline:'none',
        }}/>
      ) : (
        <input type={type} style={{
          height: 40, 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',
        }}/>
      )}
    </label>
  );
}

// ─────────────────────────── SHIPPING ─────────────────────────────────────
function ShippingPage({ mobile }) {
  const { lang } = useStore();
  return (
    <InfoPage mobile={mobile}
      hero={{
        eyebrow: lang==='uk'?'Допомога':'Help',
        title: lang==='uk'?'Доставка та оплата':'Shipping & payment',
        lede: lang==='uk'?'Безкоштовна доставка по Україні від 1500 ₴. Міжнародна доставка — від 3 робочих днів.':'Free domestic shipping over ₴1500. International ships in 3 days+.',
        breadcrumb: lang==='uk'?'Доставка':'Shipping',
      }}
      sections={lang==='uk' ? [
        { title: 'Україна',
          list: [
            'Нова Пошта · від 70 ₴ · 1-2 дні',
            'Укрпошта · від 50 ₴ · 2-4 дні',
            'Кур’єр по Києву · 120 ₴ · день у день при замовленні до 14:00',
            'Безкоштовна доставка від 1500 ₴',
          ]},
        { title: 'Міжнародна доставка',
          list: [
            'ЄС, UK · 220 ₴ + місцеві податки · 5-7 днів',
            'США, Канада · 280 ₴ + місцеві податки · 7-10 днів',
            'Інші країни — за окремим запитом, hello@ecoprof.ua',
          ]},
        { title: 'Оплата',
          body: 'Картка Visa/Mastercard, Apple Pay, Google Pay, Privat24, Monobank. Усі онлайн-платежі захищені 3D Secure. Для оптових замовлень — рахунок-фактура.',
        },
        { title: 'Подарункові карти',
          body: 'Номінали 500, 1000, 2000, 5000 ₴. Діють 12 місяців. Доставка email-кодом — миттєво.',
        },
      ] : [
        { title: 'Ukraine',
          list: [
            'Nova Poshta · from ₴70 · 1-2 days',
            'Ukrposhta · from ₴50 · 2-4 days',
            'Kyiv courier · ₴120 · same-day before 14:00',
            'Free over ₴1500',
          ]},
        { title: 'International',
          list: [
            'EU, UK · ₴220 + local taxes · 5-7 days',
            'US, Canada · ₴280 + local taxes · 7-10 days',
            'Anywhere else — write hello@ecoprof.ua',
          ]},
        { title: 'Payment',
          body: 'Visa/Mastercard, Apple Pay, Google Pay, Privat24, Monobank. All online payments protected with 3D Secure. Wholesale by invoice.',
        },
        { title: 'Gift cards',
          body: '₴500, 1000, 2000, 5000. Valid 12 months. Delivered as email code — instant.',
        },
      ]}
    />
  );
}

// ─────────────────────────── RETURNS ──────────────────────────────────────
function ReturnsPage({ mobile }) {
  const { lang } = useStore();
  return (
    <InfoPage mobile={mobile}
      hero={{
        eyebrow: lang==='uk'?'Допомога':'Help',
        title: lang==='uk'?'Повернення':'Returns',
        lede: lang==='uk'?'14 днів на повернення без пояснень. Якщо щось не підійшло — пиши нам, оформимо повернення.':'14-day no-questions returns. Email us if anything doesn’t suit.',
        breadcrumb: lang==='uk'?'Повернення':'Returns',
      }}
      sections={lang==='uk' ? [
        { title: 'Що можна повернути',
          list: [
            'Невідкритий товар у фабричній упаковці',
            'Відкритий, але вжитий не більше 25% флакону (зважуємо)',
            'Подарункові комплекти у незаймана упаковці',
          ]},
        { title: 'Що не можна повернути',
          list: [
            'Подарункові карти',
            'Товар з пошкодженою упаковкою (через перевезення — приймаємо)',
          ]},
        { title: 'Як оформити',
          body: 'Напиши на returns@ecoprof.ua з номером замовлення та фото товару. Видамо ТТН Нової Пошти за наш рахунок. Гроші повертаємо протягом 5 робочих днів після прийому посилки.',
        },
      ] : [
        { title: 'Eligible',
          list: [
            'Unopened product in factory packaging',
            'Opened, used less than 25% (we weigh)',
            'Gift sets in untouched packaging',
          ]},
        { title: 'Not eligible',
          list: [
            'Gift cards',
            'Damaged-in-shipping packaging is fine — we accept those',
          ]},
        { title: 'How to start',
          body: 'Email returns@ecoprof.ua with your order number and a photo. We send a prepaid Nova Poshta label. Refund within 5 business days of receipt.',
        },
      ]}
    />
  );
}

// ─────────────────────────── FAQ ───────────────────────────────────────────
function FAQPage({ mobile }) {
  const { lang } = useStore();
  const items = lang === 'uk' ? [
    { q:'Чи можна поєднувати ретинол із кислотами?',
      a:'У перші 4 тижні запровадження ретинальдегіду — ні. Дай шкірі звикнути. Після цього — кислоти у ранкову частину ритуалу, ретинол у вечірню.' },
    { q:'Як часто можна користуватися ензимною пудрою?',
      a:'Для жирної шкіри — 3 рази на тиждень, для сухої — 1-2 рази. Поєднується з усіма іншими активами.' },
    { q:'Чи підходить ваш SPF під макіяж?',
      a:'Так. Silk SPF 50+ має шовкову текстуру, лягає під тон як база. Не дає білого нальоту, не катиться.' },
    { q:'Чи перевіряєте формули на тваринах?',
      a:'Ніколи. У нас сертифікат PETA Beauty Without Bunnies. Усі тести — на in-vitro моделях шкіри або з людьми-волонтерами.' },
    { q:'Як зрозуміти, який тип шкіри в мене?',
      a:'Пройди наш безкоштовний підбір догляду — 7 запитань, отримаєш визначення типу + готовий ритуал.' },
    { q:'Чи можна купити сертифікат у подарунок?',
      a:'Так. Подарункові карти від 500 до 5000 ₴, діють 12 місяців. Доставка миттєво на email.' },
    { q:'Працюєте з косметологами оптом?',
      a:'Так — заповни форму партнерства на сторінці «Стати партнером», або напиши на b2b@ecoprof.ua.' },
  ] : [
    { q:'Can I mix retinol with acids?', a:'Not in the first 4 weeks of starting retinaldehyde. Let your skin adjust. After that, acids in the AM routine, retinol in the PM.' },
    { q:'How often can I use the enzyme powder?', a:'Oily skin — 3x a week. Dry — 1-2x. Pairs with any other active.' },
    { q:'Does your SPF work under makeup?', a:'Yes. Silk SPF 50+ has a silk texture, sits like a primer. No white cast, no pilling.' },
    { q:'Do you test on animals?', a:'Never. PETA Beauty Without Bunnies certified. We test on in-vitro skin models or human volunteers.' },
    { q:'How do I figure out my skin type?', a:'Take our free skin quiz — 7 questions, you get a type + a ready ritual.' },
    { q:'Do you do gift cards?', a:'Yes. ₴500 to ₴5000, valid 12 months. Instant email delivery.' },
    { q:'Do you work with estheticians wholesale?', a:'Yes — fill out the partnership form or email b2b@ecoprof.ua.' },
  ];
  // Group questions into 2 columns on desktop
  const half = Math.ceil(items.length / 2);
  const col1 = items.slice(0, half);
  const col2 = items.slice(half);
  return (
    <>
      <PageHero mobile={mobile}
        eyebrow="FAQ"
        title={lang==='uk'?'Часті запитання':'Frequently asked'}
        lede={lang==='uk'?'Якщо тут немає твого запитання — напиши нам, додамо.':'If your question isn’t here — email us, we’ll add it.'}
        breadcrumb="FAQ"
      />
      <div className="ep-container" style={{ paddingBottom: 64 }}>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 0 : 56 }}>
          <FAQList items={col1}/>
          {!mobile && <FAQList items={col2}/>}
          {mobile && <FAQList items={col2}/>}
        </div>
        <div style={{ marginTop: 56, padding:'28px 32px', background:'var(--ep-surface-2)', borderRadius: 22, maxWidth: 720 }}>
          <div className="ep-eyebrow" style={{ marginBottom: 6 }}>{lang==='uk'?'Не знайшов відповіді?':'Still have questions?'}</div>
          <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 20, fontWeight: 500, marginBottom: 6 }}>
            {lang==='uk'?'Напиши на hello@ecoprof.ua':'Email hello@ecoprof.ua'}
          </div>
          <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin: 0 }}>
            {lang==='uk'?'Відповідаємо протягом 24 годин по робочих днях.':'We reply within 24 hours on weekdays.'}
          </p>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── GIFT CARDS ────────────────────────────────────
function GiftCardsPage({ mobile }) {
  const { lang, fmt } = useStore();
  const denoms = [500, 1000, 2000, 5000];
  const [picked, setPicked] = React.useState(1000);
  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Магазин':'Shop'}
        title={lang==='uk'?'Подарункові карти':'Gift cards'}
        lede={lang==='uk'?'Найточніший подарунок: вибір лишається за отримувачем. Email-доставка миттєво, друкована — за 1 день.':'The safest gift — your recipient picks. Email instantly, printed in a day.'}
        breadcrumb={lang==='uk'?'Подарункові карти':'Gift cards'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 32 : 48, alignItems:'center' }}>
          {/* Card preview */}
          <div style={{
            aspectRatio: '1.6 / 1', borderRadius: 22, padding: 32,
            background:'linear-gradient(135deg, #c47862 0%, #2a241e 100%)',
            color:'#fff', display:'flex', flexDirection:'column', justifyContent:'space-between',
            position:'relative', overflow:'hidden',
          }}>
            <div style={{ position:'absolute', top:'-30%', right:'-15%', width:'80%', height:'160%', borderRadius:'50%', background:'rgba(255,255,255,0.06)' }}/>
            <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 32, fontWeight: 500, letterSpacing:'-0.03em' }}>
              ecoprof<span style={{ color:'#7c9b7d' }}>.</span>
            </div>
            <div>
              <div style={{ fontFamily:'var(--ep-font-mono)', fontSize: 11, letterSpacing:'0.1em', textTransform:'uppercase', opacity: 0.7, marginBottom: 4 }}>
                {lang==='uk'?'Подарункова карта':'Gift card'}
              </div>
              <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 56, fontWeight: 500, letterSpacing:'-0.03em' }}>
                {fmt(picked)}
              </div>
            </div>
          </div>

          {/* Form */}
          <div>
            <div className="ep-mono" style={{ fontSize: 10.5, color:'var(--ep-ink-2)', marginBottom: 10 }}>{lang==='uk'?'Номінал':'Amount'}</div>
            <div style={{ display:'flex', gap: 8, flexWrap:'wrap', marginBottom: 24 }}>
              {denoms.map(d => (
                <button key={d} onClick={() => setPicked(d)}
                  className={`ep-chip ${picked === d ? 'active' : ''}`} style={{ minWidth: 80 }}>{fmt(d)}</button>
              ))}
            </div>

            <FormField label={lang==='uk'?'Кому (ім’я)':'To (name)'} type="text"/>
            <div style={{ height: 14 }}/>
            <FormField label={lang==='uk'?'Email отримувача':'Recipient email'} type="email"/>
            <div style={{ height: 14 }}/>
            <FormField label={lang==='uk'?'Особисте повідомлення':'Personal note'} type="textarea"/>

            <button className="ep-btn accent" style={{ marginTop: 18 }}>
              {lang==='uk'?'Купити карту':'Buy card'} · {fmt(picked)} →
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── CAREERS ───────────────────────────────────────
const ROLES = [
  { id: 'consultant',
    uk:{title:'Косметолог-консультант', loc:'Київ · повна зайнятість', sub:'Робота з клієнтами у шоурумі та онлайн',
        about:'Шукаємо досвідченого косметолога, який буде працювати з клієнтами в шоурумі на Золотоворітській і вести онлайн-консультації.',
        resp:['Консультування клієнтів у шоурумі та через Zoom','Підбір догляду за каталогом Ecoprof','Ведення внутрішньої CRM','Допомога в навчальних івентах'],
        req:['Профільна освіта (косметологія)','Досвід від 3 років','Знання активних інгредієнтів і протоколів','Українська + базова англійська'],
        perks:['Зарплата 35-45k ₴','Безкоштовне навчання','100% продукції Ecoprof — твої']
    },
    en:{title:'Esthetician-consultant', loc:'Kyiv · full-time', sub:'Working with clients in showroom and online',
        about:'We’re looking for an experienced esthetician to work with clients at our Zolotovoritska showroom and run online consultations.',
        resp:['Consult clients in-store and via Zoom','Build routines from the Ecoprof catalogue','Maintain internal CRM','Help with educational events'],
        req:['Esthetics qualification','3+ years experience','Knowledge of active ingredients and protocols','Ukrainian + basic English'],
        perks:['Salary ₴35-45k','Free in-house training','100% of Ecoprof products on us']
    } },
  { id: 'chemist',
    uk:{title:'Технолог-формулярка', loc:'Київ · повна зайнятість', sub:'Розробка нових формул у R&D команді',
        about:'У R&D команду шукаємо технолога з біохімічною освітою для розробки нових формул сироваток і кремів.',
        resp:['Розробка прототипів і допуск у виробництво','Робота з постачальниками інгредієнтів ЄС','Тестування стабільності та активності','Документація відповідно до GMP 22716'],
        req:['Освіта: біохімія / косметична хімія','Досвід формуляції від 2 років','Знання COSING і регуляторики ЄС','Англійська upper-intermediate+'],
        perks:['Зарплата 45-65k ₴','Поїздки на конференції','Гнучкий графік']
    },
    en:{title:'Cosmetic chemist', loc:'Kyiv · full-time', sub:'Building new formulas in the R&D team',
        about:'We’re hiring a biochemist-trained formulator for our R&D team to develop new serum and cream formulas.',
        resp:['Prototype development and production hand-off','Working with EU ingredient suppliers','Stability and efficacy testing','GMP 22716 documentation'],
        req:['Biochemistry / cosmetic chemistry degree','2+ years formulating','COSING + EU regulatory knowledge','Upper-intermediate English+'],
        perks:['Salary ₴45-65k','Conference trips','Flexible schedule']
    } },
  { id: 'editor',
    uk:{title:'Контент-редактор', loc:'Дистанційно · part-time', sub:'Тексти для журналу та продуктів',
        about:'Шукаємо редактора, який добре пише про науку про шкіру українською. Не SEO-копірайтинг, а живі тексти для журналу.',
        resp:['Підготовка статей для журналу (4-6 на місяць)','Редагування описів продуктів','Інтерв’ю з нашими дерматологами','Координація з дизайн-командою'],
        req:['Журналістська або наукова освіта','Портфоліо публікацій','Розуміння теми бьюті/wellness — плюс','Англійська для роботи з джерелами'],
        perks:['25 годин на тиждень / 22-28k ₴','Повна дистанційна робота','Гнучкий графік']
    },
    en:{title:'Content editor', loc:'Remote · part-time', sub:'Writing for the journal and product pages',
        about:'We need an editor who writes about skin science well, in Ukrainian. Not SEO copy — alive journal pieces.',
        resp:['Writing 4-6 articles a month','Editing product descriptions','Interviewing our dermatologists','Coordinating with the design team'],
        req:['Journalism or science degree','Publication portfolio','Beauty / wellness familiarity is a plus','English for source work'],
        perks:['25 hrs/week · ₴22-28k','Fully remote','Flexible schedule']
    } },
  { id: 'logistics',
    uk:{title:'Менеджер логістики', loc:'Київ · повна зайнятість', sub:'Координація відвантажень і складу',
        about:'У логістичну команду шукаємо менеджера для роботи зі складом, кур’єрськими службами і міжнародними відвантаженнями.',
        resp:['Координація замовлень з Новою Поштою / Укрпоштою','Робота з міжнародними партнерами (EU/US)','Контроль складських залишків','Робота з рекламаціями'],
        req:['Досвід у логістиці від 2 років','1С / Excel — впевнено','Уважність до деталей','Українська + англійська'],
        perks:['Зарплата 28-35k ₴','Знижка на продукцію 70%','Робота поруч із метро']
    },
    en:{title:'Logistics manager', loc:'Kyiv · full-time', sub:'Coordinating shipments and inventory',
        about:'We’re looking for a logistics manager to work with our warehouse, courier services, and international shipments.',
        resp:['Coordinating with Nova Poshta / Ukrposhta','Working with EU/US partners','Inventory control','Handling complaints'],
        req:['2+ years in logistics','Confident with 1C / Excel','Detail-oriented','Ukrainian + English'],
        perks:['Salary ₴28-35k','70% discount on products','Office near metro']
    } },
];
function CareersPage({ mobile }) {
  const { lang, goto } = useStore();
  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Бренд':'Brand'}
        title={lang==='uk'?'Працюй з нами':'Join the team'}
        lede={lang==='uk'?'Команда з 14 людей у Києві. Ростемо, коли потрібно — а не коли модно.':'14 people in Kyiv. We hire when we need to — not when it’s trendy.'}
        breadcrumb={lang==='uk'?'Кар’єра':'Careers'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div className="ep-mono" style={{ fontSize: 10.5, color:'var(--ep-ink-2)', marginBottom: 14 }}>
          {lang==='uk'?'Відкриті позиції':'Open roles'} · {ROLES.length}
        </div>
        <div style={{ borderTop:'1px solid var(--ep-line-2)' }}>
          {ROLES.map((r, i) => {
            const d = r[lang === 'uk' ? 'uk' : 'en'];
            return (
              <div key={i}
                onClick={() => goto({ name: 'role', id: r.id })}
                style={{
                display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr auto',
                gap: mobile ? 6 : 24, alignItems:'center',
                padding: '22px 16px', borderBottom:'1px solid var(--ep-line-2)',
                borderRadius: 12,
                cursor:'pointer', transition:'background .15s var(--ep-ease)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ep-surface-3)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                <div>
                  <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 20, fontWeight: 500, letterSpacing:'-0.015em', color:'var(--ep-ink)' }}>{d.title}</div>
                  <div style={{ fontSize: 13, color:'var(--ep-ink-3)', marginTop: 2 }}>{d.loc}</div>
                </div>
                <div style={{ fontSize: 13.5, color:'var(--ep-ink-2)' }}>{d.sub}</div>
                <span style={{ fontSize: 13, color:'var(--ep-ink)', display:'inline-flex', alignItems:'center', gap: 6 }}>
                  {lang==='uk'?'Деталі':'Details'} <I.arrow/>
                </span>
              </div>
            );
          })}
        </div>
        <div style={{ marginTop: 40, padding: '28px 32px', background:'var(--ep-surface-2)', borderRadius: 22, maxWidth: 700 }}>
          <div className="ep-eyebrow" style={{ marginBottom: 6 }}>{lang==='uk'?'Немає підходящого?':'Nothing matches?'}</div>
          <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 18, fontWeight: 500, marginBottom: 6 }}>
            {lang==='uk'?'Пиши на jobs@ecoprof.ua':'Email jobs@ecoprof.ua'}
          </div>
          <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin: 0 }}>
            {lang==='uk'?'Розкажи коротко про себе й чому хочеш до нас. Розглядаємо й нестандартні ролі.':'Tell us briefly about yourself and why you want to join. We consider non-standard roles too.'}
          </p>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── ARTICLE (single post) ────────────────────────
// Extended article body keyed by article id. Each entry: paragraphs + youtube + products.
const ARTICLE_BODIES = {
  a1: {
    // why: original ID `fA2OZl5jh28` 404s. Big Buck Bunny (Blender Foundation, CC-licensed) as verified-stable placeholder.
    youtube: 'aqz-KE-bpKQ',
    intro: {
      uk: 'Будь-який догляд складається з 4 базових кроків: очистити, поживити, відновити, захистити. Кожен крок — окрема функція. Якщо пропустити один, наступний працює гірше.',
      en: 'Any routine is built on 4 base steps: cleanse, treat, repair, protect. Each step has its own job. Skip one — the next works worse.',
    },
    steps: {
      uk: [
        { n:'01', t:'Очищення', body:'Подвійне очищення вечірньою порою — олія + м’яка пінка. Олія знімає SPF і себум, пінка — залишки. Не виходь за межі 1 хв на цьому етапі.', product:'p01' },
        { n:'02', t:'Активна сироватка', body:'Один активний інгредієнт на сесію. Ретинальдегід, ніацинамід, вітамін С — на вибір. Якщо стартуєш ретинол, починай з 2 разів на тиждень.', product:'p27' },
        { n:'03', t:'Відновлення бар’єра', body:'Кераміди, пантенол, цераміди. Сироватка чи крем — залежить від того, як шкіра реагує. Це крок, який роблять найрідше — а він важливий саме після активів.', product:'p11' },
        { n:'04', t:'Захист (вночі)', body:'Так, вночі. Не SPF — а оклюзивний шар, який утримує всі активи всередині. Крем-щит на основі пептидів — на 8 годин.', product:'p17' },
      ],
      en: [
        { n:'01', t:'Cleanse', body:'Double-cleanse in the evening — oil first, then a gentle foam. The oil takes off SPF and sebum, the foam handles the rest. Keep this step under a minute.', product:'p01' },
        { n:'02', t:'Active serum', body:'One active per session. Retinaldehyde, niacinamide, vitamin C — pick one. If starting retinol, twice a week.', product:'p27' },
        { n:'03', t:'Barrier repair', body:'Ceramides, panthenol. Serum or cream — depends on how your skin reacts. The most skipped step — and the most important right after actives.', product:'p11' },
        { n:'04', t:'Protect (overnight)', body:'Yes, overnight. Not SPF — an occlusive layer to lock in all the actives. A peptide-based shield cream for 8 hours.', product:'p17' },
      ],
    },
    outro: {
      uk: 'Цей ритуал ми тестували на групі з 14 жінок 2 місяці. У 11 із 14 — підвищення зволоженості, у 8 — помітне покращення тону. Працює.',
      en: 'We tested this with 14 women over 2 months. 11 of 14 reported better hydration, 8 saw visible tone improvement. It works.',
    },
  },
  a2: {
    youtube: 'dQw4w9WgXcQ',
    intro: {
      uk: 'Ретинол перетворюється у шкірі на ретиноєву кислоту через 2 ферментативні реакції. Ретинальдегід — лише через одну. Ось чому він діє в 11 разів швидше.',
      en: 'Retinol converts to retinoic acid via 2 enzymatic steps. Retinaldehyde — just one. That’s why it’s 11× faster.',
    },
    steps: {
      uk: [
        { n:'01', t:'Який ефект отримаєш', body:'Розгладження дрібних зморшок, вирівнювання тону, контроль постакне. Перший результат — через 4 тижні.', product:'p27' },
        { n:'02', t:'Кому підходить', body:'Шкіра без активного запалення, кератинові розладу, незрозумілої чутливості. Якщо є питання — пройди підбір догляду.' },
      ],
      en: [
        { n:'01', t:'What to expect', body:'Smoother fine lines, more even tone, post-acne control. First results in 4 weeks.', product:'p27' },
        { n:'02', t:'Who it suits', body:'Skin without active inflammation, keratin disorders, or unexplained sensitivity. If unsure — take our skin quiz.' },
      ],
    },
    outro: { uk:'', en:'' },
  },
};

function ArticlePage({ id, mobile }) {
  const { tr, lang, goto, fmt } = useStore();
  const meta = JOURNAL_ARTICLES.find(a => a.id === id) || JOURNAL_ARTICLES[0];
  const body = ARTICLE_BODIES[id] || ARTICLE_BODIES.a1;
  const steps = body.steps[lang === 'uk' ? 'uk' : 'en'];
  const featuredProducts = steps.map(s => s.product).filter(Boolean).map(pid => window.ECOPROF_PRODUCTS.find(p => p.id === pid)).filter(Boolean);

  return (
    <div className="ep-container" style={{ paddingTop: 24, paddingBottom: 80 }}>
      {/* Breadcrumb */}
      <div className="ep-mono" style={{ fontSize: 11, marginBottom: 16 }}>
        <a onClick={() => goto({name:'home'})} style={{ cursor:'pointer' }}>Ecoprof</a>
        <span style={{ margin:'0 8px' }}>/</span>
        <a onClick={() => goto({name:'journal'})} style={{ cursor:'pointer' }}>{lang==='uk'?'Журнал':'Journal'}</a>
        <span style={{ margin:'0 8px' }}>/</span>
        <span style={{ color:'var(--ep-ink)' }}>{tr(meta.title)}</span>
      </div>

      {/* Title block */}
      <div style={{ maxWidth: 880, marginBottom: 32 }}>
        <div className="ep-eyebrow" style={{ color: 'var(--ep-accent)' }}>{meta.cat}</div>
        <h1 className="ep-section-title" style={{ marginTop: 14, fontSize: mobile ? 36 : 56, lineHeight: 1.02, marginBottom: 20 }}>{tr(meta.title)}</h1>
        <p style={{ fontSize: 17, color:'var(--ep-ink-2)', lineHeight: 1.55, margin:'0 0 18px', maxWidth: 700 }}>{tr(meta.excerpt)}</p>
        <div style={{ display:'flex', gap: 14, alignItems:'center', fontSize: 13, color:'var(--ep-ink-3)', flexWrap:'wrap' }}>
          <span style={{ color:'var(--ep-ink-2)', fontWeight: 500 }}>{meta.author}</span>
          <span>·</span>
          <span>{tr(meta.date)}</span>
          <span>·</span>
          <span>{meta.mins} {lang==='uk'?'хв читання':'min read'}</span>
        </div>
      </div>

      {/* YouTube embed */}
      <div style={{ marginBottom: 48, borderRadius: 22, overflow: 'hidden', position:'relative', aspectRatio: '16/9', maxWidth: 1080, background:'#1a1714' }}>
        <iframe
          src={`https://www.youtube.com/embed/${body.youtube}?rel=0`}
          title={tr(meta.title)}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
          style={{ position:'absolute', inset: 0, width: '100%', height: '100%', border: 0 }}
        />
      </div>

      {/* Body with sidebar */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: mobile ? '1fr' : 'minmax(0, 1fr) 280px',
        gap: mobile ? 32 : 64,
        alignItems: 'flex-start',
      }}>
        {/* Main article body */}
        <article style={{ maxWidth: 720 }}>
          <p style={{ fontFamily:'var(--ep-font-serif)', fontStyle:'italic', fontSize: mobile ? 20 : 22, lineHeight: 1.45, color:'var(--ep-ink)', margin:'0 0 40px' }}>
            {tr(body.intro)}
          </p>

          {steps.map((s, i) => {
            const p = s.product ? window.ECOPROF_PRODUCTS.find(x => x.id === s.product) : null;
            return (
              <section key={i} style={{ marginBottom: 40, paddingBottom: 32, borderBottom: i < steps.length - 1 ? '1px solid var(--ep-line-2)' : '0' }}>
                <div style={{ display:'flex', alignItems:'baseline', gap: 14, marginBottom: 12 }}>
                  <span className="ep-mono" style={{ fontSize: 11, color:'var(--ep-accent)', fontWeight: 600, letterSpacing: '0.1em' }}>{s.n}</span>
                  <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile ? 24 : 30, fontWeight: 500, letterSpacing:'-0.02em', margin: 0 }}>{s.t}</h2>
                </div>
                <p style={{ fontSize: 16, color:'var(--ep-ink-2)', lineHeight: 1.7, margin:'0 0 18px' }}>{s.body}</p>
                {p && (
                  <div onClick={() => goto({ name:'product', id: p.id })}
                    style={{
                      display:'flex', alignItems:'center', gap: 14,
                      padding: 14, borderRadius: 14,
                      background: 'var(--ep-surface-3)',
                      cursor: 'pointer', transition:'transform .2s var(--ep-ease)',
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-2px)'}
                    onMouseLeave={(e) => e.currentTarget.style.transform = 'none'}
                  >
                    <div style={{ width: 60, height: 60, borderRadius: 8, background:'#fff', border:'1px solid var(--ep-line-2)', flex:'none', overflow:'hidden', display:'flex' }}>
                      <ProductMedia p={p}/>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div className="ep-mono" style={{ fontSize: 9.5, color:'var(--ep-ink-2)', marginBottom: 2 }}>{lang==='uk'?'Згадуємо':'Featured'}</div>
                      <div style={{ fontSize: 14, fontWeight: 500, color:'var(--ep-ink)' }}>{p.name}</div>
                      <div style={{ fontSize: 12, color:'var(--ep-ink-3)' }}>{fmt(p.price)} · {p.vol}</div>
                    </div>
                    <I.arrow/>
                  </div>
                )}
              </section>
            );
          })}

          {body.outro[lang === 'uk' ? 'uk' : 'en'] && (
            <p style={{ fontSize: 17, color:'var(--ep-ink)', lineHeight: 1.6, margin:'0', padding:'24px 28px', background:'var(--ep-accent-soft)', borderRadius: 18 }}>
              {tr(body.outro)}
            </p>
          )}
        </article>

        {/* Sidebar: featured products */}
        {!mobile && featuredProducts.length > 0 && (
          <aside style={{ position:'sticky', top: 96 }}>
            <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)', marginBottom: 14 }}>
              {lang==='uk'?'Згадані продукти':'In this article'}
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap: 0 }}>
              {featuredProducts.map((p) => (
                <div key={p.id} onClick={() => goto({ name:'product', id: p.id })}
                  style={{
                    display:'flex', alignItems:'center', gap: 12, padding: '12px 0',
                    borderTop: '1px solid var(--ep-line-2)', cursor:'pointer',
                  }}>
                  <div style={{ width: 50, height: 50, borderRadius: 8, 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: 13, fontWeight: 500, color:'var(--ep-ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{p.name}</div>
                    <div style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{fmt(p.price)}</div>
                  </div>
                </div>
              ))}
            </div>
          </aside>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────── QUIZ standalone page ──────────────────────────
function RolePage({ id, mobile }) {
  const { lang, goto } = useStore();
  const role = ROLES.find(r => r.id === id) || ROLES[0];
  const d = role[lang === 'uk' ? 'uk' : 'en'];
  const [applied, setApplied] = React.useState(false);

  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Відкрита позиція':'Open role'}
        title={d.title}
        lede={d.about}
        breadcrumb={<><a onClick={() => goto({name:'careers'})} style={{cursor:'pointer'}}>{lang==='uk'?'Кар’єра':'Careers'}</a>
          <span style={{ margin:'0 8px' }}>/</span>
          <span style={{ color:'var(--ep-ink)' }}>{d.title}</span></>}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{ display:'flex', gap: 8, flexWrap:'wrap', marginBottom: 40 }}>
          <span className="ep-chip" style={{ background:'var(--ep-surface-3)' }}>{d.loc}</span>
          <span className="ep-chip" style={{ background:'var(--ep-surface-3)' }}>{d.sub}</span>
        </div>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1.4fr 1fr', gap: mobile ? 32 : 56, alignItems:'flex-start' }}>
          <div style={{ maxWidth: 680 }}>
            <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:26, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 14px' }}>
              {lang==='uk'?'Чим будеш займатися':'What you’ll do'}
            </h2>
            <ul style={{ padding: 0, margin: '0 0 32px', listStyle:'none', display:'flex', flexDirection:'column', gap: 10 }}>
              {d.resp.map((line, i) => (
                <li key={i} style={{ display:'flex', gap: 10, alignItems:'baseline', fontSize: 15, color:'var(--ep-ink-2)' }}>
                  <span style={{ flex:'none', width: 4, height: 4, borderRadius:'50%', background:'var(--ep-accent)', transform:'translateY(-3px)' }}/>
                  <span>{line}</span>
                </li>
              ))}
            </ul>

            <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:26, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 14px' }}>
              {lang==='uk'?'Що очікуємо':'What we expect'}
            </h2>
            <ul style={{ padding: 0, margin: '0 0 32px', listStyle:'none', display:'flex', flexDirection:'column', gap: 10 }}>
              {d.req.map((line, i) => (
                <li key={i} style={{ display:'flex', gap: 10, alignItems:'baseline', fontSize: 15, color:'var(--ep-ink-2)' }}>
                  <span style={{ flex:'none', width: 4, height: 4, borderRadius:'50%', background:'var(--ep-ink)', transform:'translateY(-3px)' }}/>
                  <span>{line}</span>
                </li>
              ))}
            </ul>

            <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:26, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 14px' }}>
              {lang==='uk'?'Що пропонуємо':'What we offer'}
            </h2>
            <ul style={{ padding: 0, margin: 0, listStyle:'none', display:'flex', flexDirection:'column', gap: 10 }}>
              {d.perks.map((line, i) => (
                <li key={i} style={{ display:'flex', gap: 10, alignItems:'baseline', fontSize: 15, color:'var(--ep-ink-2)' }}>
                  <span style={{ display:'inline-flex', flex:'none', color:'var(--ep-accent)', transform:'translateY(2px)' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
                  </span>
                  <span>{line}</span>
                </li>
              ))}
            </ul>
          </div>

          {/* Apply panel — sticky */}
          <aside style={{ position: mobile ? 'static' : 'sticky', top: 96 }}>
            <div style={{ background: 'var(--ep-surface-2)', borderRadius: 22, padding: mobile ? 24 : 28 }}>
              <div className="ep-eyebrow" style={{ marginBottom: 8 }}>{lang==='uk'?'Подати заявку':'Apply'}</div>
              <h3 style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 6px' }}>
                {lang==='uk'?'Цікавить позиція?':'Interested?'}
              </h3>
              <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin: '0 0 20px' }}>
                {lang==='uk'?'Залиш контакти й коротко розкажи про себе — повернемось упродовж 3 робочих днів.':'Leave your details and tell us briefly about yourself — we’ll get back within 3 business days.'}
              </p>
              {applied ? (
                <div style={{ padding: '20px 16px', background:'var(--ep-accent-soft)', borderRadius: 12, textAlign:'center' }}>
                  <div style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', width: 36, height: 36, borderRadius:'50%', background:'var(--ep-accent)', color:'#fff', marginBottom: 8 }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{lang==='uk'?'Заявку прийнято':'Application received'}</div>
                </div>
              ) : (
                <form onSubmit={(e) => { e.preventDefault(); setApplied(true); }}
                  style={{ display:'flex', flexDirection:'column', gap: 12 }}>
                  <FormField label={lang==='uk'?'Ім’я':'Name'} type="text"/>
                  <FormField label="Email" type="email"/>
                  <FormField label={lang==='uk'?'Телефон':'Phone'} type="tel"/>
                  <FormField label={lang==='uk'?'Коротко про себе':'About you'} type="textarea"/>
                  <button type="submit" className="ep-btn accent" style={{ marginTop: 4 }}>
                    {lang==='uk'?'Надіслати':'Send'} →
                  </button>
                </form>
              )}
            </div>
          </aside>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── QUIZ standalone page ──────────────────────────
function QuizPage({ mobile }) {
  const { lang, goto, fmt } = useStore();
  const [bookingOpen, setBookingOpen] = React.useState(false);
  const [booked, setBooked] = React.useState(false);

  const intro = lang === 'uk' ? {
    eyebrow: 'Підбір · 60 секунд',
    title: 'Скажи нам про свою шкіру.',
    lede: 'Ти не одна. Кожна жінка, з якою ми працюємо, починала з невпевненості. Прищі, чутливість, пігментація, втрата тонусу — усе це нормально, і все це вирішується. Скажи, що турбує — і отримаєш конкретний наступний крок.',
    breadcrumb: 'Підбір догляду',
  } : {
    eyebrow: 'Skin quiz · 60 sec',
    title: 'Tell us about your skin.',
    lede: 'You are not alone. Every woman we work with started with uncertainty. Breakouts, sensitivity, pigmentation, loss of firmness — all of this is normal, and all of it is solvable. Tell us what concerns you — get a concrete next step.',
    breadcrumb: 'Skin quiz',
  };

  const consult = lang === 'uk' ? {
    eyebrow: 'Онлайн-консультація',
    title: 'Поговори з дерматологом',
    sub: '30 хвилин у Zoom з Ольгою Лісняк',
    price: 800,
    duration: '30 хв',
    includes: [
      'Розгорнутий аналіз стану шкіри',
      'Письмовий протокол на 6 тижнів',
      'Особистий підбір з нашого каталогу',
      'Чек-лист помилок у догляді',
    ],
    next: 'Найближчий слот: завтра, 14:00',
    cta: 'Записатися · 800 ₴',
    booked: 'Дякуємо! Менеджер зв’яжеться з тобою впродовж 2 годин.',
    bookedT: 'Запис прийнято',
  } : {
    eyebrow: 'Online consult',
    title: 'Talk to a dermatologist',
    sub: '30 minutes on Zoom with Olga Lisnyak',
    price: 800,
    duration: '30 min',
    includes: [
      'Detailed skin analysis',
      'Written 6-week protocol',
      'Personal product picks from our catalogue',
      'Routine mistakes checklist',
    ],
    next: 'Next slot: tomorrow, 14:00',
    cta: 'Book · ₴800',
    booked: 'Thank you! A manager will contact you within 2 hours.',
    bookedT: 'Booking received',
  };

  const quizT = lang === 'uk' ? {
    eyebrow: 'Безкоштовно · 60 сек',
    title: 'Пройди швидкий підбір',
    sub: '7 запитань — ритуал з 4 продуктів. Без реєстрації.',
  } : {
    eyebrow: 'Free · 60 sec',
    title: 'Take the quick quiz',
    sub: '7 questions — a 4-product ritual. No sign-up.',
  };

  return (
    <>
      <PageHero {...intro} mobile={mobile}/>

      {/* Reassurance / two-option grid */}
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
          gap: mobile ? 20 : 24,
          alignItems: 'stretch',
        }}>
          {/* LEFT — Free quiz */}
          <div style={{
            background: '#fdfaf4',
            borderRadius: 22,
            padding: mobile ? 24 : 32,
            display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <div>
              <div className="ep-eyebrow" style={{ color: 'var(--ep-accent)' }}>{quizT.eyebrow}</div>
              <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:26, fontWeight: 500, letterSpacing:'-0.02em', margin:'10px 0 6px' }}>{quizT.title}</h2>
              <p style={{ fontSize: 14, color:'var(--ep-ink-2)', margin: 0 }}>{quizT.sub}</p>
            </div>
            <div style={{ flex: 1, minHeight: 480 }}>
              <QuizCallout mobile={mobile} embedded/>
            </div>
          </div>

          {/* RIGHT — Paid consultation */}
          <div style={{
            background: 'var(--ep-surface-2)', color:'var(--ep-ink)',
            borderRadius: 22,
            padding: mobile ? 24 : 32,
            display: 'flex', flexDirection: 'column', gap: 18,
            position: 'relative', overflow: 'hidden',
          }}>
            {/* Decorative accent blob */}
            <div style={{
              position:'absolute', top:'-30%', right:'-20%', width:'70%', height:'140%',
              borderRadius:'50%', background:'var(--ep-accent)', opacity: 0.12,
              filter:'blur(60px)', pointerEvents:'none',
            }}/>

            <div style={{ position:'relative', zIndex: 1 }}>
              <div className="ep-eyebrow" style={{ color:'var(--ep-accent)' }}>{consult.eyebrow}</div>
              <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:26, fontWeight: 500, letterSpacing:'-0.02em', margin:'10px 0 6px' }}>{consult.title}</h2>
              <p style={{ fontSize: 14, color:'var(--ep-ink-2)', margin: 0 }}>{consult.sub}</p>
            </div>

            <div style={{ position:'relative', zIndex: 1, display:'flex', alignItems:'baseline', gap: 12, padding:'8px 0 6px' }}>
              <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 48, fontWeight: 500, letterSpacing:'-0.03em', color:'var(--ep-ink)' }}>{fmt(consult.price)}</div>
              <div style={{ fontSize: 13, color:'var(--ep-ink-3)' }}>· {consult.duration}</div>
            </div>

            <ul style={{ position:'relative', zIndex: 1, listStyle:'none', padding: 0, margin: 0, display:'flex', flexDirection:'column', gap: 8 }}>
              {consult.includes.map((line, i) => (
                <li key={i} style={{ display:'flex', gap: 10, alignItems:'baseline', fontSize: 14, color:'var(--ep-ink)' }}>
                  <span style={{ display:'inline-flex', flex:'none', color:'var(--ep-accent)', transform:'translateY(2px)' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 7"/></svg>
                  </span>
                  <span>{line}</span>
                </li>
              ))}
            </ul>

            <div style={{ position:'relative', zIndex: 1, fontSize: 11, color:'var(--ep-ink-3)', fontFamily:'var(--ep-font-mono)', letterSpacing:'0.08em', textTransform:'uppercase', marginTop:'auto', paddingTop: 12, borderTop:'1px solid var(--ep-line-2)' }}>
              {consult.next}
            </div>

            {!bookingOpen && !booked && (
              <button onClick={() => setBookingOpen(true)}
                style={{
                  position:'relative', zIndex: 1,
                  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',
                  fontFamily:'inherit',
                }}>
                {consult.cta} <I.arrow/>
              </button>
            )}

            {bookingOpen && !booked && (
              <form
                onSubmit={(e) => { e.preventDefault(); setBooked(true); setBookingOpen(false); }}
                style={{
                  position:'relative', zIndex: 1,
                  display:'flex', flexDirection:'column', gap: 10,
                  padding: 16, borderRadius: 14,
                  background:'#fff', border:'1px solid var(--ep-line-2)',
                }}>
                <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-2)' }}>
                  {lang==='uk' ? 'Залиш контакти — підтвердимо слот' : 'Leave your details — we’ll confirm the slot'}
                </div>
                <FormField label={lang==='uk'?'Ім’я':'Name'} type="text"/>
                <FormField label={lang==='uk'?'Телефон':'Phone'} type="tel"/>
                <FormField label="Email" type="email"/>
                <div style={{ display:'flex', gap: 8, marginTop: 4 }}>
                  <button type="button" onClick={() => setBookingOpen(false)}
                    style={{
                      background:'transparent', border:'1px solid var(--ep-line)',
                      padding:'10px 16px', borderRadius: 999, fontSize: 12.5, fontWeight: 500,
                      color:'var(--ep-ink)', cursor:'pointer', fontFamily:'inherit',
                    }}>
                    {lang==='uk'?'Скасувати':'Cancel'}
                  </button>
                  <button type="submit"
                    style={{
                      flex: 1,
                      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, justifyContent:'center',
                      fontFamily:'inherit',
                    }}>
                    {lang==='uk'?'Підтвердити запис':'Confirm booking'} <I.arrow/>
                  </button>
                </div>
              </form>
            )}

            {booked && (
              <div style={{ position:'relative', zIndex: 1, padding: 14, background:'var(--ep-accent-soft)', borderRadius: 12, border:'1px solid rgba(124,155,125,0.4)' }}>
                <div style={{ display:'flex', alignItems:'center', gap: 8, marginBottom: 4, color:'var(--ep-ink)' }}>
                  <span style={{ color:'var(--ep-accent)' }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
                  </span>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{consult.bookedT}</span>
                </div>
                <div style={{ fontSize: 12.5, color:'var(--ep-ink-2)' }}>{consult.booked}</div>
              </div>
            )}
          </div>
        </div>

        {/* Bottom reassurance microcopy */}
        <div style={{ marginTop: mobile?32:48, textAlign:'center', maxWidth: 580, marginLeft:'auto', marginRight:'auto' }}>
          <div className="ep-eyebrow" style={{ marginBottom: 6 }}>{lang === 'uk' ? 'Конфіденційно' : 'Confidential'}</div>
          <p style={{ fontSize: 14, color:'var(--ep-ink-2)', margin: 0, lineHeight: 1.55 }}>
            {lang === 'uk'
              ? 'Усе, що ти розкажеш — лишається між тобою й нашою командою. Ми не передаємо дані третім особам і не шлемо спам.'
              : 'Everything you share stays between you and our team. We don\'t share data with third parties and don\'t send spam.'}
          </p>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── WISHLIST ─────────────────────────────────────
function WishlistPage({ mobile }) {
  const { wishlist, lang, goto } = useStore();
  const items = wishlist.map(id => window.ECOPROF_PRODUCTS.find(p => p.id === id)).filter(Boolean);
  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Улюблене':'Wishlist'}
        title={lang==='uk' ? `Улюблені · ${items.length}` : `Wishlist · ${items.length}`}
        lede={lang==='uk'?'Товари, які ти зберегла на потім.':'Things you saved for later.'}
        breadcrumb={lang==='uk'?'Улюблене':'Wishlist'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        {items.length === 0 ? (
          <div style={{ textAlign:'center', padding:'64px 24px', border:'1px dashed var(--ep-line)', borderRadius: 22 }}>
            <div style={{ width: 56, height: 56, borderRadius:'50%', background:'var(--ep-surface-3)', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom: 14 }}>
              <I.heart/>
            </div>
            <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, marginBottom: 6 }}>
              {lang==='uk'?'Поки що порожньо':'Nothing here yet'}
            </div>
            <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin:'0 0 18px' }}>
              {lang==='uk'?'Натисни ♡ на товарі, і він з’явиться тут.':'Tap ♡ on a product to save it here.'}
            </p>
            <button className="ep-btn" onClick={() => goto({ name: 'catalog' })}>
              {lang==='uk'?'Відкрити каталог':'Open catalogue'} →
            </button>
          </div>
        ) : (
          <div className="ep-grid" style={{ gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)' }}>
            {items.map(p => <ProductCard key={p.id} p={p}/>)}
          </div>
        )}
      </div>
    </>
  );
}

// ─────────────────────────── SEARCH OVERLAY ────────────────────────────────
function SearchOverlay() {
  const { searchOpen, setSearchOpen, lang, goto, fmt } = useStore();
  const [query, setQuery] = React.useState('');
  const inputRef = React.useRef(null);
  React.useEffect(() => {
    if (!searchOpen) return;
    setQuery('');
    setTimeout(() => inputRef.current?.focus(), 80);
    const onKey = (e) => { if (e.key === 'Escape') setSearchOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [searchOpen]);

  const q = query.trim().toLowerCase();
  const hits = q ? window.ECOPROF_PRODUCTS.filter(p =>
    p.name.toLowerCase().includes(q) || window.tr(p.sub, lang).toLowerCase().includes(q)
  ).slice(0, 8) : [];
  const cats = q ? window.ECOPROF_CATEGORIES.filter(c => window.tr(c.name, lang).toLowerCase().includes(q)) : [];
  const trending = ['Retinol', 'SPF 50', 'Vit C', 'Niacinamide', 'Acne'];

  return (
    <div className={`ep-search-overlay ${searchOpen ? 'open' : ''}`}>
      <div className="ep-search-backdrop" onClick={() => setSearchOpen(false)}/>
      <div className="ep-search-panel">
        <div className="ep-search-row">
          <span style={{ color:'var(--ep-ink-3)', display:'inline-flex' }}><I.search/></span>
          <input
            ref={inputRef}
            type="text"
            placeholder={lang==='uk' ? 'Шукай продукт або лінійку...' : 'Search a product or line...'}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <button onClick={() => setSearchOpen(false)} style={{ background:'transparent', border:0, color:'var(--ep-ink-3)', cursor:'pointer', fontFamily:'var(--ep-font-mono)', fontSize: 11, letterSpacing:'0.1em' }}>
            ESC
          </button>
        </div>
        <div className="ep-search-body">
          {!q && (
            <div>
              <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)', marginBottom: 10 }}>
                {lang==='uk'?'Часто шукають':'Trending'}
              </div>
              <div style={{ display:'flex', gap: 6, flexWrap:'wrap' }}>
                {trending.map(t => (
                  <button key={t} className="ep-chip" onClick={() => setQuery(t)}>{t}</button>
                ))}
              </div>
            </div>
          )}
          {q && cats.length > 0 && (
            <div style={{ marginBottom: 18 }}>
              <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)', marginBottom: 8 }}>
                {lang==='uk'?'Лінійки':'Lines'}
              </div>
              <div style={{ display:'flex', gap: 6, flexWrap:'wrap' }}>
                {cats.map(c => (
                  <button key={c.id} className="ep-chip" onClick={() => { goto({ name:'catalog', cat: c.id }); setSearchOpen(false); }}>
                    {window.tr(c.name, lang)}
                  </button>
                ))}
              </div>
            </div>
          )}
          {q && (
            <div>
              <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)', marginBottom: 8 }}>
                {hits.length > 0 ? (lang==='uk'?'Продукти':'Products') : (lang==='uk'?'Нічого не знайдено':'No results')}
              </div>
              {hits.map(p => (
                <div key={p.id} onClick={() => { goto({ name:'product', id: p.id }); setSearchOpen(false); }}
                  className="ep-search-hit">
                  <div className="thumb"><ProductMedia p={p}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 500, color:'var(--ep-ink)' }}>{p.name}</div>
                    <div style={{ fontSize: 12, color:'var(--ep-ink-3)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{window.tr(p.sub, lang)}</div>
                  </div>
                  <div style={{ fontSize: 13, color:'var(--ep-ink-2)' }}>{fmt(p.price)}</div>
                </div>
              ))}
              {hits.length === 0 && (
                <div style={{ fontSize: 13, color:'var(--ep-ink-3)', padding: '12px 0' }}>
                  {lang==='uk'?'Спробуй інший запит або відкрий каталог.':'Try a different query or open the catalogue.'}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────── AUTH (login / register) ───────────────────────
function AuthPage({ mobile }) {
  const { lang, login, goto } = useStore();
  const [mode, setMode] = React.useState('login');
  const handle = (e) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    login({ email: fd.get('email') || 'user@ecoprof.ua', name: fd.get('name') || 'Olena' });
    goto({ name: 'account' });
  };
  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Особистий кабінет':'Account'}
        title={mode === 'login' ? (lang==='uk'?'Привіт. Заходь.':'Welcome back.') : (lang==='uk'?'Створи акаунт.':'Create an account.')}
        lede={mode === 'login'
          ? (lang==='uk'?'Зберігай улюблене, дивись історію замовлень, отримуй бонуси.':'Save favourites, see order history, earn rewards.')
          : (lang==='uk'?'-10% на перше замовлення + доступ до закритих знижок.':'10% off your first order + access to closed deals.')}
        breadcrumb={lang==='uk'?'Кабінет':'Account'}
      />
      <div className="ep-container" style={{ paddingBottom: 80, display:'flex', justifyContent:'center' }}>
        <div style={{ width:'100%', maxWidth: 440 }}>
          <div style={{ display:'flex', gap: 4, padding: 4, background:'var(--ep-surface-3)', borderRadius: 999, marginBottom: 28 }}>
            {[{id:'login', label:lang==='uk'?'Увійти':'Sign in'},{id:'register', label:lang==='uk'?'Реєстрація':'Register'}].map(t => (
              <button key={t.id} onClick={() => setMode(t.id)}
                style={{ flex: 1, padding:'9px 14px', borderRadius: 999, border: 0,
                  background: mode === t.id ? '#fff' : 'transparent',
                  color: mode === t.id ? 'var(--ep-ink)' : 'var(--ep-ink-2)',
                  fontSize: 13, fontWeight: 500, cursor:'pointer', fontFamily:'inherit', transition:'background .15s var(--ep-ease)' }}>{t.label}</button>
            ))}
          </div>
          <form onSubmit={handle} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
            {mode === 'register' && <FormField label={lang==='uk'?'Ім’я':'Name'} type="text"/>}
            <FormField label="Email" type="email"/>
            <FormField label={lang==='uk'?'Пароль':'Password'} type="password"/>
            <button type="submit" className="ep-btn accent" style={{ marginTop: 8 }}>
              {mode === 'login' ? (lang==='uk'?'Увійти':'Sign in') : (lang==='uk'?'Створити акаунт':'Create account')} →
            </button>
            <div style={{ textAlign:'center', fontSize: 12, color:'var(--ep-ink-3)', marginTop: 4 }}>{lang==='uk'?'Або через':'Or with'}</div>
            <div style={{ display:'flex', gap: 8 }}>
              <button type="button" onClick={() => { login({ email:'google@ecoprof.ua', name:'Olena' }); goto({ name:'account' }); }}
              className="ep-oauth-btn google" style={{ flex: 1 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
                <path fill="#4285F4" d="M23.49 12.27c0-.79-.07-1.54-.19-2.27H12v4.51h6.45c-.28 1.46-1.12 2.69-2.38 3.52v2.92h3.85c2.26-2.08 3.57-5.15 3.57-8.68z"/>
                <path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.92-2.92l-3.85-2.99c-1.07.72-2.43 1.16-4.07 1.16-3.13 0-5.78-2.11-6.73-4.96H1.3v3.09C3.26 21.3 7.31 24 12 24z"/>
                <path fill="#FBBC05" d="M5.27 14.29c-.25-.72-.39-1.49-.39-2.29s.14-1.57.39-2.29V6.62H1.3C.47 8.24 0 10.06 0 12s.47 3.76 1.3 5.38l3.97-3.09z"/>
                <path fill="#EA4335" d="M12 4.75c1.77 0 3.35.61 4.6 1.8l3.42-3.42C17.95 1.19 15.24 0 12 0 7.31 0 3.26 2.7 1.3 6.62l3.97 3.09C6.22 6.86 8.87 4.75 12 4.75z"/>
              </svg>
              Google
            </button>
              <button type="button" onClick={() => { login({ email:'apple@ecoprof.ua', name:'Olena' }); goto({ name:'account' }); }}
              className="ep-oauth-btn apple" style={{ flex: 1 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
              </svg>
              Apple
            </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────── ACCOUNT ───────────────────────────────────────
function AccountPage({ mobile }) {
  const { lang, user, logout, goto, wishlist, fmt } = useStore();
  React.useEffect(() => { if (!user) goto({ name: 'auth' }); }, [user]);
  if (!user) return null;
  const sections = lang === 'uk'
    ? [{id:'orders',t:'Замовлення',n:3},{id:'bonus',t:'Бонуси',n:null},{id:'wishlist',t:'Улюблене',n:wishlist.length},{id:'addresses',t:'Адреси',n:1},{id:'profile',t:'Профіль',n:null}]
    : [{id:'orders',t:'Orders',n:3},{id:'bonus',t:'Rewards',n:null},{id:'wishlist',t:'Wishlist',n:wishlist.length},{id:'addresses',t:'Addresses',n:1},{id:'profile',t:'Profile',n:null}];
  const [tab, setTab] = React.useState('orders');
  const [openOrder, setOpenOrder] = React.useState(null);
  const mockOrders = lang === 'uk'
    ? [{id:'ECO-2026-0142',date:'24 травня 2026',sum:2840,shipping:120,payment:'Visa · 4242',status:'Доставлено',delivery:'Нова Пошта · відділення',items:[{id:'p11',qty:1},{id:'p17',qty:1},{id:'p26',qty:1}]},{id:'ECO-2026-0098',date:'12 травня 2026',sum:1480,shipping:0,payment:'Готівка кур’єру',status:'У дорозі',delivery:'Київ · кур’єр',items:[{id:'p27',qty:1}]},{id:'ECO-2026-0042',date:'2 квітня 2026',sum:3210,shipping:0,payment:'Наложений платіж',status:'Доставлено',delivery:'Нова Пошта · відділення',items:[{id:'p18',qty:1},{id:'p38',qty:1},{id:'p07',qty:1}]}]
    : [{id:'ECO-2026-0142',date:'May 24, 2026',sum:2840,shipping:120,payment:'Visa · 4242',status:'Delivered',delivery:'Nova Poshta · pickup',items:[{id:'p11',qty:1},{id:'p17',qty:1},{id:'p26',qty:1}]},{id:'ECO-2026-0098',date:'May 12, 2026',sum:1480,shipping:0,payment:'Cash to courier',status:'In transit',delivery:'Kyiv · courier',items:[{id:'p27',qty:1}]},{id:'ECO-2026-0042',date:'April 2, 2026',sum:3210,shipping:0,payment:'Cash on delivery',status:'Delivered',delivery:'Nova Poshta · pickup',items:[{id:'p18',qty:1},{id:'p38',qty:1},{id:'p07',qty:1}]}];

  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Кабінет':'Account'}
        title={lang==='uk' ? `Привіт, ${user.name}` : `Hi, ${user.name}`}
        lede={user.email}
        breadcrumb={lang==='uk'?'Кабінет':'Account'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '220px 1fr', gap: mobile ? 24 : 56, alignItems:'flex-start' }}>
          <aside style={{ display:'flex', flexDirection:'column', gap: 4 }}>
            {sections.map(s => (
              <button key={s.id} onClick={() => setTab(s.id)} style={{
                display:'flex', justifyContent:'space-between', alignItems:'center',
                padding:'10px 14px', borderRadius: 10, border: 0,
                background: tab === s.id ? 'var(--ep-surface-3)' : 'transparent',
                color:'var(--ep-ink)', fontSize: 14, fontWeight: tab === s.id ? 500 : 400, cursor:'pointer',
                fontFamily:'inherit', textAlign:'left',
              }}>
                <span>{s.t}</span>
                {s.n != null && <span style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{s.n}</span>}
              </button>
            ))}
            <button onClick={() => { logout(); goto({ name:'home' }); }} style={{
              marginTop: 12, padding:'10px 14px', borderRadius: 10, border: 0,
              background:'transparent', color:'var(--ep-ink-3)', fontSize: 13, cursor:'pointer',
              textAlign:'left', fontFamily:'inherit',
            }}>↗ {lang==='uk'?'Вийти':'Sign out'}</button>
          </aside>
          <div>
            {tab === 'orders' && (
              <div>
                <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 18px' }}>{lang==='uk'?'Замовлення':'Orders'}</h2>
                <div style={{ borderTop:'1px solid var(--ep-line-2)' }}>
                  {mockOrders.map(o => (
                    <div key={o.id} style={{
                      display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr 1fr auto',
                      gap: mobile ? 4 : 24, alignItems:'center',
                      padding:'18px 0', borderBottom:'1px solid var(--ep-line-2)',
                    }}>
                      <div>
                        <div style={{ fontFamily:'var(--ep-font-mono)', fontSize: 11, color:'var(--ep-ink-3)' }}>{o.id}</div>
                        <div style={{ fontSize: 13, color:'var(--ep-ink-2)', marginTop: 2 }}>{o.date}</div>
                      </div>
                      <div style={{ fontSize: 13 }}>{o.status}</div>
                      <div style={{ fontSize: 14, fontWeight: 500, fontVariantNumeric:'tabular-nums' }}>{fmt(o.sum)}</div>
                      <button onClick={() => setOpenOrder(o)} style={{ background:'transparent', border:'1px solid var(--ep-line)', padding:'7px 12px', borderRadius: 999, fontSize: 12, color:'var(--ep-ink)', cursor:'pointer', fontFamily:'inherit' }}>{lang==='uk'?'Деталі':'Details'}</button>
                    </div>
                  ))}
                </div>
              </div>
            )}
            {tab === 'bonus' && (
              <div>
                <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 18px' }}>{lang==='uk'?'Бонусний рахунок':'Rewards'}</h2>

                {/* Hero card */}
                <div style={{ position:'relative', overflow:'hidden', borderRadius: 22, padding: mobile ? 24 : 32, background:'linear-gradient(135deg, var(--ep-ink) 0%, #15110d 100%)', color:'#fff', marginBottom: 24 }}>
                  <div style={{ position:'absolute', top:'-30%', right:'-15%', width:'60%', height:'160%', borderRadius:'50%', background:'var(--ep-accent)', opacity: 0.20, filter:'blur(60px)' }}/>
                  <div style={{ position:'relative', zIndex: 1, display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr', gap: 24 }}>
                    <div>
                      <div className="ep-mono" style={{ fontSize: 10.5, color:'rgba(255,255,255,0.7)', marginBottom: 6 }}>{lang==='uk'?'Бали':'Points'}</div>
                      <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 48, fontWeight: 500, letterSpacing:'-0.03em', lineHeight: 1 }}>
                        {(user.points || 0).toLocaleString()}
                      </div>
                      <div style={{ fontSize: 13, color:'rgba(255,255,255,0.6)', marginTop: 6 }}>
                        ≈ {fmt(Math.floor((user.points || 0) / 100))} {lang==='uk'?'до оплати':'redeemable'}
                      </div>
                    </div>
                    <div>
                      <div className="ep-mono" style={{ fontSize: 10.5, color:'rgba(255,255,255,0.7)', marginBottom: 6 }}>{lang==='uk'?'Рівень':'Tier'}</div>
                      <div style={{ display:'inline-flex', alignItems:'center', gap: 8 }}>
                        <span style={{ width: 10, height: 10, borderRadius:'50%', background:'#C0C0C0', boxShadow:'0 0 0 3px rgba(192,192,192,0.25)' }}/>
                        <span style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, textTransform:'capitalize' }}>{user.tier}</span>
                      </div>
                      <div style={{ fontSize: 13, color:'rgba(255,255,255,0.6)', marginTop: 6 }}>
                        {lang==='uk'?`Персональна знижка −${user.tierDiscount}% на всі товари`:`Personal discount −${user.tierDiscount}% on everything`}
                      </div>
                    </div>
                  </div>
                </div>

                {/* Rules */}
                <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr 1fr', gap: 12, marginBottom: 24 }}>
                  {[
                    {t:lang==='uk'?'Як заробити':'How to earn', s:lang==='uk'?'5% від кожного замовлення повертаємо балами':'5% of every order back as points'},
                    {t:lang==='uk'?'Курс':'Rate', s:'1000 ' + (lang==='uk'?'балів':'points') + ' = ' + fmt(10)},
                    {t:lang==='uk'?'Як витратити':'How to spend', s:lang==='uk'?'Списуй на оформленні замовлення':'Apply at checkout'},
                  ].map((r, i) => (
                    <div key={i} style={{ padding: 18, background:'var(--ep-surface-3)', borderRadius: 14 }}>
                      <div className="ep-eyebrow" style={{ marginBottom: 6 }}>{r.t}</div>
                      <div style={{ fontSize: 13, color:'var(--ep-ink-2)', lineHeight: 1.5 }}>{r.s}</div>
                    </div>
                  ))}
                </div>

                {/* Tiers */}
                <h3 style={{ fontFamily:'var(--ep-font-display)', fontSize: 18, fontWeight: 500, letterSpacing:'-0.015em', margin:'0 0 12px' }}>
                  {lang==='uk'?'Рівні':'Tiers'}
                </h3>
                <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
                  {[
                    { t:'bronze', name:lang==='uk'?'Bronze':'Bronze',  d:3, threshold:lang==='uk'?'Від 1 замовлення':'From 1 order',     dot:'#CD7F32' },
                    { t:'silver', name:lang==='uk'?'Silver':'Silver',  d:5, threshold:lang==='uk'?'Від 3 замовлень':'From 3 orders',  dot:'#C0C0C0' },
                    { t:'gold',   name:lang==='uk'?'Gold':'Gold',      d:10, threshold:lang==='uk'?'Від 10 замовлень':'From 10 orders', dot:'#D9A04A' },
                  ].map(tx => {
                    const active = tx.t === user.tier;
                    return (
                      <div key={tx.t} style={{
                        display:'grid', gridTemplateColumns: mobile?'1fr':'auto 1fr auto auto', gap: 16, alignItems:'center',
                        padding:'14px 18px', borderRadius: 12,
                        border: active ? '1.5px solid var(--ep-accent)' : '1px solid var(--ep-line-2)',
                        background: active ? 'var(--ep-accent-soft)' : 'transparent',
                      }}>
                        <span style={{ width: 12, height: 12, borderRadius:'50%', background: tx.dot }}/>
                        <div>
                          <div style={{ fontSize: 14, fontWeight: 500 }}>{tx.name}{active && <span style={{ marginLeft: 8, fontSize: 11, color:'var(--ep-accent)', textTransform:'uppercase', letterSpacing:'0.1em' }}>{lang==='uk'?'Зараз':'Now'}</span>}</div>
                          <div style={{ fontSize: 12, color:'var(--ep-ink-3)' }}>{tx.threshold}</div>
                        </div>
                        <div style={{ fontSize: 13, color:'var(--ep-ink-2)' }}>−{tx.d}%</div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {tab === 'wishlist' && (
              <div>
                <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 18px' }}>{lang==='uk'?'Улюблене':'Wishlist'} · {wishlist.length}</h2>
                {wishlist.length === 0 ? (
                  <div style={{ padding: 32, background:'var(--ep-surface-3)', borderRadius: 14, color:'var(--ep-ink-2)', fontSize: 13.5 }}>{lang==='uk'?'Поки порожньо.':'Nothing here yet.'}</div>
                ) : (
                  <div className="ep-grid" style={{ gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)' }}>
                    {wishlist.map(id => { const p = window.ECOPROF_PRODUCTS.find(p => p.id === id); return p ? <ProductCard key={id} p={p}/> : null; })}
                  </div>
                )}
              </div>
            )}
            {tab === 'addresses' && (
              <div>
                <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 18px' }}>{lang==='uk'?'Адреси доставки':'Shipping addresses'}</h2>
                <div style={{ padding: 22, background:'var(--ep-surface-3)', borderRadius: 14, display:'flex', flexDirection:'column', gap: 6, maxWidth: 480 }}>
                  <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)' }}>{lang==='uk'?'За замовчуванням':'Default'}</div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{user.name}</div>
                  <div style={{ fontSize: 13.5, color:'var(--ep-ink-2)' }}>{lang==='uk'?'м. Київ, вул. Сагайдачного 12, кв. 4':'12 Sahaidachnoho St, apt. 4, Kyiv'}</div>
                  <div style={{ fontSize: 12, color:'var(--ep-ink-3)' }}>+380 67 123 45 67</div>
                </div>
                <button className="ep-btn ghost sm" style={{ marginTop: 16 }}>+ {lang==='uk'?'Додати адресу':'Add address'}</button>
              </div>
            )}
            {tab === 'profile' && (
              <div style={{ maxWidth: 480 }}>
                <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: mobile?22:28, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 18px' }}>{lang==='uk'?'Профіль':'Profile'}</h2>
                <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
                  <FormField label={lang==='uk'?'Ім’я':'Name'} type="text"/>
                  <FormField label="Email" type="email"/>
                  <FormField label={lang==='uk'?'Телефон':'Phone'} type="tel"/>
                  <button className="ep-btn accent" style={{ marginTop: 8 }}>{lang==='uk'?'Зберегти':'Save'}</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      <OrderModal order={openOrder} onClose={() => setOpenOrder(null)}/>
    </>
  );
}

// ─────────────────────────── PRIVACY / TERMS / COOKIES ────────────────────
function PrivacyPage({ mobile }) {
  const { lang } = useStore();
  return (
    <InfoPage mobile={mobile}
      hero={{
        eyebrow: lang==='uk'?'Право':'Legal',
        title: lang==='uk'?'Політика конфіденційності':'Privacy policy',
        lede: lang==='uk'?'Як ми збираємо, зберігаємо й використовуємо твої дані. Оновлено 1 травня 2026.':'How we collect, store, and use your data. Updated May 1, 2026.',
        breadcrumb: 'Privacy',
      }}
      sections={lang==='uk' ? [
        { title:'Які дані ми збираємо', body:'Ім’я, email, телефон, адреса доставки — для оформлення замовлень. Дані браузера (cookies) — для аналітики й рекомендацій. Платіжні дані не зберігаємо — обробляє провайдер Fondy/LiqPay.' },
        { title:'Навіщо', list:[
          'Обробка та доставка замовлень',
          'Email-розсилка (тільки за згодою)',
          'Покращення сайту через аналітику',
          'Відповідь на твої запити',
        ]},
        { title:'Кому передаємо', body:'Жодних третіх сторін поза службами доставки (Нова Пошта / Укрпошта) і платіжними провайдерами. Не продаємо й не обмінюємо дані ніколи.' },
        { title:'Твої права', list:[
          'Запитати, які дані ми про тебе зберігаємо',
          'Виправити або видалити дані',
          'Скасувати email-розсилку (1 клік у будь-якому листі)',
          'Подати скаргу в Уповноваженого ВР з прав людини',
        ]},
        { title:'Контакт', body:'Питання по даним — privacy@ecoprof.ua. Відповідаємо упродовж 30 днів.' },
      ] : [
        { title:'What we collect', body:'Name, email, phone, shipping address — for processing orders. Browser data (cookies) — analytics and recommendations. We don\'t store payment details — handled by Fondy/LiqPay.' },
        { title:'Why', list:[
          'Processing and shipping orders',
          'Email newsletter (consent only)',
          'Improving the site through analytics',
          'Responding to your requests',
        ]},
        { title:'Who we share with', body:'No third parties beyond shipping (Nova Poshta / Ukrposhta) and payment providers. We never sell or trade data.' },
        { title:'Your rights', list:[
          'Request what data we hold',
          'Correct or delete your data',
          'Unsubscribe from email (one click in any email)',
          'File a complaint with the Ukrainian Parliament Commissioner',
        ]},
        { title:'Contact', body:'Data questions — privacy@ecoprof.ua. We respond within 30 days.' },
      ]}
    />
  );
}

function TermsPage({ mobile }) {
  const { lang } = useStore();
  return (
    <InfoPage mobile={mobile}
      hero={{ eyebrow: lang==='uk'?'Право':'Legal', title: lang==='uk'?'Умови використання':'Terms of use', lede: lang==='uk'?'Простими словами — без юридичного жаргону там, де можна.':'Plain language where we can — legal where we must.', breadcrumb:'Terms' }}
      sections={lang==='uk' ? [
        { title:'Замовлення', body:'Замовлення оформлюється натисканням «Оформити замовлення». Оплата приймається картками Visa/Mastercard, Apple Pay, Google Pay. Чек надсилається на email.' },
        { title:'Доставка', body:'Терміни доставки залежать від обраного перевізника. Точну дату надсилаємо разом із трекінг-номером. Якщо замовлення не дійшло протягом 14 днів — зв’яжись із нами, розберемося.' },
        { title:'Повернення', body:'14 днів на повернення з моменту отримання. Деталі — на сторінці «Повернення».' },
        { title:'Ціни', body:'Ціни вказані в гривнях, включають ПДВ. Можемо змінити ціни в будь-який момент, але вже оформлене замовлення йде за початковою ціною.' },
        { title:'Відповідальність', body:'Ми не несемо відповідальності за алергічні реакції або непідходимість продукту. Завжди робимо патч-тест на ділянці шкіри. Якщо реакція з’явилась — повернемо гроші повністю.' },
      ] : [
        { title:'Orders', body:'Orders are placed by clicking "Checkout". Payment accepted via Visa/Mastercard, Apple Pay, Google Pay. Receipt sent to email.' },
        { title:'Shipping', body:'Delivery times depend on the carrier. We send exact date with the tracking number. If your order hasn\'t arrived in 14 days, contact us — we\'ll sort it.' },
        { title:'Returns', body:'14 days to return from receipt. Details on the Returns page.' },
        { title:'Pricing', body:'Prices in Ukrainian hryvnia, VAT included. We may change prices anytime — placed orders honour the original price.' },
        { title:'Liability', body:'We are not liable for allergic reactions or unsuitability. Always do a patch test. If reaction occurs — full refund.' },
      ]}
    />
  );
}

function CookiesPage({ mobile }) {
  const { lang } = useStore();
  return (
    <InfoPage mobile={mobile}
      hero={{ eyebrow: lang==='uk'?'Право':'Legal', title: lang==='uk'?'Політика cookies':'Cookies policy', lede: lang==='uk'?'Які cookies ми використовуємо і навіщо.':'What cookies we use and why.', breadcrumb:'Cookies' }}
      sections={lang==='uk' ? [
        { title:'Необхідні cookies', body:'Зберігають кошик, обрану мову, статус авторизації. Без них сайт не працює — їх не можна вимкнути.' },
        { title:'Аналітика', body:'Google Analytics: знаємо, які сторінки відкриваються, з яких пристроїв. Дані анонімізовані, не зв’язуються з email.' },
        { title:'Маркетинг', body:'Facebook Pixel / Google Ads — показуємо рекламу нашим відвідувачам у соцмережах. Можна відмовитись у банері знизу.' },
        { title:'Як відмовитись', body:'Натисни «Налаштування» у cookie-банері або очисти cookies в налаштуваннях браузера.' },
      ] : [
        { title:'Essential cookies', body:'Store your cart, chosen language, login status. Required for the site to work — can\'t be disabled.' },
        { title:'Analytics', body:'Google Analytics: we see which pages load, from what devices. Data is anonymous, not linked to email.' },
        { title:'Marketing', body:'Facebook Pixel / Google Ads — we show ads to our visitors on social. Opt out in the banner.' },
        { title:'How to opt out', body:'Tap "Settings" in the cookie banner or clear cookies in your browser settings.' },
      ]}
    />
  );
}

// ─────────────────────────── COOKIE BANNER ────────────────────────────────
function CookieBanner() {
  const { lang, goto } = useStore();
  const [closed, setClosed] = React.useState(() => {
    try { return !!localStorage.getItem('ep_cookies_ack'); } catch { return false; }
  });
  if (closed) return null;
  const accept = () => {
    try { localStorage.setItem('ep_cookies_ack', '1'); } catch {}
    setClosed(true);
  };
  return (
    <div className="ep-cookie-banner">
      <div className="ep-cookie-text">
        <strong style={{ fontWeight: 500, color:'var(--ep-ink)' }}>
          {lang==='uk'?'Ми використовуємо cookies':'We use cookies'}
        </strong>
        <span>
          {lang==='uk' ? ' для роботи сайту, аналітики й маркетингу. ' : ' to run the site, analytics and marketing. '}
          <a onClick={() => { goto({ name:'cookies' }); }} style={{ cursor:'pointer', borderBottom:'1px solid var(--ep-line)', color:'var(--ep-ink)' }}>
            {lang==='uk'?'Деталі':'Read more'}
          </a>
        </span>
      </div>
      <div className="ep-cookie-actions">
        <button onClick={accept} className="ep-cookie-btn ghost">{lang==='uk'?'Лише необхідні':'Essential only'}</button>
        <button onClick={accept} className="ep-cookie-btn primary">{lang==='uk'?'Прийняти все':'Accept all'}</button>
      </div>
    </div>
  );
}

// ─────────────────────────── AUTH MODAL ───────────────────────────────────
function AuthModal() {
  const { authOpen, setAuthOpen, lang, login, goto } = useStore();
  const [mode, setMode] = React.useState('login');
  if (!authOpen) return null;
  const handle = (e) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    login({ email: fd.get('email') || 'user@ecoprof.ua', name: fd.get('name') || 'Olena' });
    goto({ name: 'account' });
  };
  return (
    <div className="ep-modal-overlay" onClick={(e) => e.target === e.currentTarget && setAuthOpen(false)}>
      <div className="ep-modal">
        <button onClick={() => setAuthOpen(false)} className="ep-modal-close" aria-label="close">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
        <div className="ep-eyebrow" style={{ marginBottom: 8 }}>{lang==='uk'?'Особистий кабінет':'Account'}</div>
        <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: 26, fontWeight: 500, letterSpacing:'-0.02em', margin:'0 0 6px' }}>
          {mode === 'login' ? (lang==='uk'?'Привіт. Заходь.':'Welcome back.') : (lang==='uk'?'Створи акаунт.':'Create an account.')}
        </h2>
        <p style={{ fontSize: 13.5, color:'var(--ep-ink-2)', margin:'0 0 22px' }}>
          {mode === 'login'
            ? (lang==='uk'?'Зберігай улюблене, дивись історію замовлень, отримуй бонуси.':'Save favourites, see orders, earn rewards.')
            : (lang==='uk'?'-10% на перше замовлення + доступ до закритих знижок.':'10% off first order + closed deals.')}
        </p>

        <div style={{ display:'flex', gap: 4, padding: 4, background:'var(--ep-surface-3)', borderRadius: 999, marginBottom: 20 }}>
          {[{id:'login', label:lang==='uk'?'Увійти':'Sign in'},{id:'register', label:lang==='uk'?'Реєстрація':'Register'}].map(t => (
            <button key={t.id} onClick={() => setMode(t.id)}
              style={{ flex: 1, padding:'9px 14px', borderRadius: 999, border: 0,
                background: mode === t.id ? '#fff' : 'transparent',
                color: mode === t.id ? 'var(--ep-ink)' : 'var(--ep-ink-2)',
                fontSize: 13, fontWeight: 500, cursor:'pointer', fontFamily:'inherit', transition:'background .15s var(--ep-ease)' }}>{t.label}</button>
          ))}
        </div>

        <form onSubmit={handle} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          {mode === 'register' && <FormField label={lang==='uk'?'Ім’я':'Name'} type="text"/>}
          <FormField label="Email" type="email"/>
          <FormField label={lang==='uk'?'Пароль':'Password'} type="password"/>
          <button type="submit" className="ep-btn accent" style={{ marginTop: 8 }}>
            {mode === 'login' ? (lang==='uk'?'Увійти':'Sign in') : (lang==='uk'?'Створити акаунт':'Create account')} →
          </button>
          <div style={{ textAlign:'center', fontSize: 12, color:'var(--ep-ink-3)', marginTop: 4 }}>{lang==='uk'?'Або через':'Or with'}</div>
          <div style={{ display:'flex', gap: 8 }}>
            <button type="button" onClick={() => { login({ email:'google@ecoprof.ua', name:'Olena' }); goto({ name:'account' }); }}
              className="ep-oauth-btn google" style={{ flex: 1 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
                <path fill="#4285F4" d="M23.49 12.27c0-.79-.07-1.54-.19-2.27H12v4.51h6.45c-.28 1.46-1.12 2.69-2.38 3.52v2.92h3.85c2.26-2.08 3.57-5.15 3.57-8.68z"/>
                <path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.92-2.92l-3.85-2.99c-1.07.72-2.43 1.16-4.07 1.16-3.13 0-5.78-2.11-6.73-4.96H1.3v3.09C3.26 21.3 7.31 24 12 24z"/>
                <path fill="#FBBC05" d="M5.27 14.29c-.25-.72-.39-1.49-.39-2.29s.14-1.57.39-2.29V6.62H1.3C.47 8.24 0 10.06 0 12s.47 3.76 1.3 5.38l3.97-3.09z"/>
                <path fill="#EA4335" d="M12 4.75c1.77 0 3.35.61 4.6 1.8l3.42-3.42C17.95 1.19 15.24 0 12 0 7.31 0 3.26 2.7 1.3 6.62l3.97 3.09C6.22 6.86 8.87 4.75 12 4.75z"/>
              </svg>
              Google
            </button>
            <button type="button" onClick={() => { login({ email:'apple@ecoprof.ua', name:'Olena' }); goto({ name:'account' }); }}
              className="ep-oauth-btn apple" style={{ flex: 1 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
              </svg>
              Apple
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─────────────────────────── CHECKOUT ─────────────────────────────────────
function CheckoutPage({ mobile }) {
  const { cart, lang, fmt, subtotal, goto, user, setQty, spendPoints } = useStore();
  const [delivery, setDelivery] = React.useState('np-pickup');
  const [payment, setPayment] = React.useState('online');
  const [promo, setPromo] = React.useState('');
  const [promoApplied, setPromoApplied] = React.useState(false);
  const [usePoints, setUsePoints] = React.useState(0); // points to spend
  const [placed, setPlaced] = React.useState(false);
  const [orderId] = React.useState(() => 'ECO-2026-' + String(Math.floor(Math.random() * 9000 + 1000)));

  // Delivery options + payment links
  const deliveryOptions = lang === 'uk' ? [
    {id:'np-pickup', name:'Нова Пошта · відділення', sub:'1-2 дні · від 70 ₴', price:70, payments:['online','cod']},
    {id:'np-courier', name:'Нова Пошта · кур’єр', sub:'1-2 дні', price:120, payments:['online','cod']},
    {id:'ukr',       name:'Укрпошта · відділення', sub:'2-4 дні', price:50, payments:['online']},
    {id:'kyiv',      name:'Київ · кур’єр сьогодні', sub:'Сьогодні (замовлення до 14:00)', price:120, payments:['online','cash']},
  ] : [
    {id:'np-pickup', name:'Nova Poshta · pickup', sub:'1-2 days · from ₴70', price:70, payments:['online','cod']},
    {id:'np-courier', name:'Nova Poshta · courier', sub:'1-2 days', price:120, payments:['online','cod']},
    {id:'ukr',       name:'Ukrposhta · pickup', sub:'2-4 days', price:50, payments:['online']},
    {id:'kyiv',      name:'Kyiv · same-day courier', sub:'Same day (order before 14:00)', price:120, payments:['online','cash']},
  ];
  const paymentLabels = lang === 'uk' ? {
    online: { name:'Оплата онлайн', sub:'Visa · Mastercard · Apple Pay · Google Pay' },
    cod:    { name:'Наложений платіж', sub:'Оплата при отриманні · комісія Нової Пошти ~20 ₴' },
    cash:   { name:'Готівка кур’єру', sub:'При отриманні · тільки Київ' },
  } : {
    online: { name:'Online payment', sub:'Visa · Mastercard · Apple Pay · Google Pay' },
    cod:    { name:'Cash on delivery', sub:'Pay on pickup · Nova Poshta fee ~₴20' },
    cash:   { name:'Cash to courier', sub:'On pickup · Kyiv only' },
  };

  const sel = deliveryOptions.find(d => d.id === delivery);
  React.useEffect(() => {
    if (sel && !sel.payments.includes(payment)) setPayment(sel.payments[0]);
  }, [delivery]);

  const ship = subtotal === 0 ? 0 : (subtotal >= 1500 ? 0 : sel.price);

  // Personal tier discount + first-order discount
  const userPoints = user?.points || 0;
  const tierDiscountPct = user?.tierDiscount || 0;
  const isFirstOrder = !user;
  const discountPct = isFirstOrder ? 15 : tierDiscountPct;
  const promoOk = promoApplied;

  // Points: 100 points = 1 ₴. Capped at 30% of subtotal to avoid full payment with points.
  const maxPoints = Math.min(userPoints, Math.floor(subtotal * 0.3 * 100));
  const pointsToSpend = Math.min(usePoints, maxPoints);
  const pointsValue = Math.floor(pointsToSpend / 100); // ₴ value

  const totalDiscount =
    Math.round(subtotal * discountPct / 100) +
    (promoOk ? Math.round(subtotal * 10 / 100) : 0) +
    pointsValue;

  const total = Math.max(0, subtotal - totalDiscount) + ship;

  const items = cart.map(it => ({ ...it, p: window.ECOPROF_PRODUCTS.find(p => p.id === it.id) })).filter(x => x.p);

  if (placed) {
    return (
      <div className="ep-container" style={{ padding: '40px 0 80px' }}>
        <div style={{ maxWidth: 560, margin: '0 auto', textAlign: 'center', padding: mobile ? 24 : 48, background: 'var(--ep-surface-2)', borderRadius: 22 }}>
          <div style={{ width: 64, height: 64, borderRadius:'50%', background:'var(--ep-accent)', display:'inline-flex', alignItems:'center', justifyContent:'center', color:'#fff', marginBottom: 18 }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M4 12l5 5L20 7"/></svg>
          </div>
          <h1 style={{ fontFamily:'var(--ep-font-display)', fontSize: 32, fontWeight: 500, letterSpacing:'-0.025em', margin:'0 0 8px' }}>
            {lang==='uk'?'Замовлення прийнято':'Order received'}
          </h1>
          <p style={{ fontSize: 14.5, color:'var(--ep-ink-2)', margin:'0 0 22px' }}>
            {lang==='uk' ? `№ ${orderId} · ми надішлемо підтвердження на email і повідомимо, коли посилка вирушить.` : `№ ${orderId} · we’ll email confirmation and notify when it ships.`}
          </p>
          <div style={{ display:'flex', gap: 10, justifyContent:'center', flexWrap:'wrap' }}>
            <button className="ep-btn accent" onClick={() => goto({ name:'account' })}>
              {lang==='uk'?'Перейти в кабінет':'Go to account'} →
            </button>
            <button className="ep-btn ghost" onClick={() => goto({ name:'catalog' })}>
              {lang==='uk'?'Продовжити покупки':'Keep shopping'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="ep-container" style={{ padding: '40px 0 80px', textAlign:'center' }}>
        <h1 className="ep-section-title" style={{ marginBottom: 12 }}>{lang==='uk'?'Кошик порожній':'Bag is empty'}</h1>
        <p style={{ color:'var(--ep-ink-2)', marginBottom: 18 }}>{lang==='uk'?'Додай товари в кошик, щоб оформити замовлення.':'Add products to your bag to place an order.'}</p>
        <button className="ep-btn accent" onClick={() => goto({ name:'catalog' })}>{lang==='uk'?'Відкрити каталог':'Open catalogue'} →</button>
      </div>
    );
  }

  return (
    <>
      <PageHero mobile={mobile}
        eyebrow={lang==='uk'?'Оформлення':'Checkout'}
        title={lang==='uk'?'Останній крок.':'One last step.'}
        lede={lang==='uk'?'Перевір деталі — і відправляй.':'Check the details — then place the order.'}
        breadcrumb={lang==='uk'?'Оформлення':'Checkout'}
      />
      <div className="ep-container" style={{ paddingBottom: 80 }}>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1.4fr 1fr', gap: mobile ? 32 : 48, alignItems:'flex-start' }}>
          {/* LEFT — form sections */}
          <div style={{ display:'flex', flexDirection:'column', gap: 32 }}>
            {/* Contact */}
            <CheckoutSection num="1" title={lang==='uk'?'Контакти':'Contact'}>
              <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 12 }}>
                <FormField label={lang==='uk'?'Ім’я та прізвище':'Full name'} type="text"/>
                <FormField label={lang==='uk'?'Телефон':'Phone'} type="tel"/>
                <div style={{ gridColumn: mobile ? 'auto' : 'span 2' }}>
                  <FormField label="Email" type="email"/>
                </div>
              </div>
            </CheckoutSection>

            {/* Delivery */}
            <CheckoutSection num="2" title={lang==='uk'?'Доставка':'Shipping'}>
              <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
                {deliveryOptions.map(opt => {
                  const active = delivery === opt.id;
                  const optShip = subtotal >= 1500 ? 0 : opt.price;
                  return (
                    <label key={opt.id} onClick={() => setDelivery(opt.id)}
                      style={{
                        display:'flex', alignItems:'center', gap: 12,
                        padding: '14px 16px', borderRadius: 12,
                        border: active ? '1.5px solid var(--ep-accent)' : '1px solid var(--ep-line-2)',
                        background: active ? 'var(--ep-accent-soft)' : 'transparent',
                        cursor:'pointer', transition:'all .15s var(--ep-ease)',
                      }}>
                      <span style={{
                        width: 18, height: 18, borderRadius:'50%', flex:'none',
                        border: active ? '5px solid var(--ep-accent)' : '1.5px solid var(--ep-line)',
                        background:'#fff',
                      }}/>
                      <div style={{ flex:1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 500, color:'var(--ep-ink)' }}>{opt.name}</div>
                        <div style={{ fontSize: 12, color:'var(--ep-ink-3)', marginTop: 2 }}>{opt.sub}</div>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 500, color:'var(--ep-ink)', whiteSpace:'nowrap' }}>
                        {optShip === 0 ? (lang==='uk'?'безкоштовно':'free') : fmt(optShip)}
                      </div>
                    </label>
                  );
                })}
              </div>
              <div style={{ marginTop: 14, display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 12 }}>
                {(delivery === 'np-pickup' || delivery === 'ukr') ? (
                  <>
                    <FormField label={lang==='uk'?'Місто':'City'} type="text"/>
                    <FormField label={lang==='uk'?'Відділення №':'Branch №'} type="text"/>
                  </>
                ) : (
                  <>
                    <FormField label={lang==='uk'?'Місто':'City'} type="text"/>
                    <FormField label={lang==='uk'?'Адреса':'Address'} type="text"/>
                  </>
                )}
              </div>
            </CheckoutSection>

            {/* Payment */}
            <CheckoutSection num="3" title={lang==='uk'?'Оплата':'Payment'}>
              <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
                {sel.payments.map(pid => {
                  const opt = paymentLabels[pid];
                  const active = payment === pid;
                  return (
                    <label key={pid} onClick={() => setPayment(pid)}
                      style={{
                        display:'flex', alignItems:'center', gap: 12,
                        padding: '14px 16px', borderRadius: 12,
                        border: active ? '1.5px solid var(--ep-accent)' : '1px solid var(--ep-line-2)',
                        background: active ? 'var(--ep-accent-soft)' : 'transparent',
                        cursor:'pointer', transition:'all .15s var(--ep-ease)',
                      }}>
                      <span style={{
                        width: 18, height: 18, borderRadius:'50%', flex:'none',
                        border: active ? '5px solid var(--ep-accent)' : '1.5px solid var(--ep-line)',
                        background:'#fff',
                      }}/>
                      <div style={{ flex:1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 500, color:'var(--ep-ink)' }}>{opt.name}</div>
                        <div style={{ fontSize: 12, color:'var(--ep-ink-3)', marginTop: 2 }}>{opt.sub}</div>
                      </div>
                    </label>
                  );
                })}
              </div>
              <p style={{ fontSize: 11.5, color:'var(--ep-ink-3)', marginTop: 12, lineHeight: 1.5 }}>
                {lang==='uk'?'Доступні способи оплати залежать від вибраної доставки. Усі онлайн-платежі захищено 3D Secure.':'Available payment methods depend on shipping. All online payments protected by 3D Secure.'}
              </p>
            </CheckoutSection>

            {/* Promo */}
            <CheckoutSection num="4" title={lang==='uk'?'Знижки та бали':'Discounts & points'} optional>
              {/* Promo code */}
              <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-2)', marginBottom: 8 }}>{lang==='uk'?'Промо-код':'Promo code'}</div>
              <div style={{ display:'flex', gap: 8, marginBottom: 18 }}>
                <input type="text" value={promo} onChange={(e) => setPromo(e.target.value.toUpperCase())}
                  placeholder="ECOPROF10"
                  style={{
                    flex: 1, height: 44, padding:'0 14px', border:'1px solid var(--ep-line-2)', borderRadius: 10,
                    background:'#fff', font:'14px var(--ep-font)', color:'var(--ep-ink)', outline:'none', letterSpacing:'0.05em',
                  }}/>
                <button onClick={() => setPromoApplied(!!promo)} className="ep-btn ghost">
                  {promoOk ? (lang==='uk'?'✓ Активовано':'✓ Applied') : (lang==='uk'?'Активувати':'Apply')}
                </button>
              </div>
              {promoOk && (
                <div style={{ fontSize: 12.5, color:'var(--ep-accent)', marginTop: -10, marginBottom: 18 }}>
                  ✓ {lang==='uk'?'Знижка -10% активована':'-10% discount applied'}
                </div>
              )}

              {/* Points */}
              {user && userPoints > 0 && (
                <div style={{ padding: 16, background:'var(--ep-surface-3)', borderRadius: 14 }}>
                  <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 10 }}>
                    <div>
                      <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-2)' }}>{lang==='uk'?'Бонусні бали':'Reward points'}</div>
                      <div style={{ fontSize: 14, color:'var(--ep-ink)', marginTop: 2 }}>
                        {lang==='uk'?`Доступно ${userPoints.toLocaleString()} балів · максимум до сплати:`:`You have ${userPoints.toLocaleString()} points · max usable:`} <strong style={{ color:'var(--ep-accent)' }}>{fmt(Math.floor(maxPoints / 100))}</strong>
                      </div>
                    </div>
                  </div>
                  <input type="range" min="0" max={maxPoints} step="100" value={pointsToSpend}
                    onChange={(e) => setUsePoints(Number(e.target.value))}
                    style={{ width:'100%', '--fill': (maxPoints > 0 ? (pointsToSpend / maxPoints * 100) : 0) + '%' }}/>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize: 12, color:'var(--ep-ink-2)', marginTop: 4 }}>
                    <span>0</span>
                    <span style={{ fontWeight: 500, color:'var(--ep-ink)' }}>
                      {pointsToSpend.toLocaleString()} {lang==='uk'?'балів':'pts'} = -{fmt(pointsValue)}
                    </span>
                    <span>{maxPoints.toLocaleString()}</span>
                  </div>
                  <div style={{ fontSize: 11, color:'var(--ep-ink-3)', marginTop: 8 }}>
                    {lang==='uk'?'100 балів = 1 ₴ · можна використати до 30% від суми':'100 points = ₴1 · up to 30% of subtotal'}
                  </div>
                </div>
              )}

              {!user && (
                <div style={{ padding: 14, background:'var(--ep-accent-soft)', borderRadius: 12, fontSize: 13, color:'var(--ep-ink)' }}>
                  {lang==='uk' ? <>✦ <a onClick={() => useStore().setAuthOpen?.(true)} style={{ borderBottom:'1px solid var(--ep-line)', cursor:'pointer' }}>Увійди в кабінет</a>, щоб тратити бали і отримати персональну знижку</> : <>✦ <a style={{ borderBottom:'1px solid var(--ep-line)', cursor:'pointer' }}>Sign in</a> to spend points and unlock personal discount</>}
                </div>
              )}
            </CheckoutSection>
          </div>

          {/* RIGHT — order summary */}
          <aside style={{ position: mobile ? 'static' : 'sticky', top: 96 }}>
            <div style={{ background:'var(--ep-surface-2)', borderRadius: 22, padding: mobile ? 24 : 28 }}>
              <div className="ep-eyebrow" style={{ marginBottom: 14 }}>{lang==='uk'?'Замовлення':'Your order'}</div>

              <div style={{ display:'flex', flexDirection:'column', gap: 12, maxHeight: 280, overflowY:'auto', paddingRight: 4 }}>
                {items.map(({ p, qty }) => (
                  <div key={p.id} style={{ display:'flex', gap: 10, alignItems:'center' }}>
                    <div style={{ width: 48, height: 48, borderRadius: 8, 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: 13, fontWeight: 500, color:'var(--ep-ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{p.name}</div>
                      <div style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{qty} × {fmt(p.price)}</div>
                    </div>
                    <div style={{ fontSize: 13, fontVariantNumeric:'tabular-nums' }}>{fmt(p.price * qty)}</div>
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 20, paddingTop: 16, borderTop:'1px solid var(--ep-line-2)', display:'flex', flexDirection:'column', gap: 8 }}>
                <SumRow label={lang==='uk'?'Сума':'Subtotal'} value={fmt(subtotal)}/>
                {discountPct > 0 && (
                  <SumRow accent label={`${lang==='uk'?'Знижка -':'Discount -'}${discountPct}% (${isFirstOrder ? (lang==='uk'?'перше замовлення':'first order') : (lang==='uk'?'твій рівень':'your tier')})`} value={'-' + fmt(Math.round(subtotal * discountPct / 100))}/>
                )}
                {promoOk && (
                  <SumRow accent label={`${lang==='uk'?'Промо-код':'Promo'} -10%`} value={'-' + fmt(Math.round(subtotal * 10 / 100))}/>
                )}
                {pointsValue > 0 && (
                  <SumRow accent label={`${lang==='uk'?'Бали':'Points'} · ${pointsToSpend.toLocaleString()}`} value={'-' + fmt(pointsValue)}/>
                )}
                <SumRow label={lang==='uk'?'Доставка':'Shipping'} value={ship === 0 ? (lang==='uk'?'безкоштовно':'free') : fmt(ship)}/>
                <div style={{ display:'flex', justifyContent:'space-between', marginTop: 8, paddingTop: 12, borderTop:'1px dashed var(--ep-line)' }}>
                  <span style={{ fontSize: 15, fontWeight: 500 }}>{lang==='uk'?'Разом':'Total'}</span>
                  <span style={{ fontSize: 22, fontFamily:'var(--ep-font-display)', fontWeight: 500, fontVariantNumeric:'tabular-nums' }}>{fmt(total)}</span>
                </div>
              </div>

              <button className="ep-btn accent full lg" style={{ marginTop: 20 }} onClick={() => { if (pointsToSpend > 0) spendPoints(pointsToSpend); setPlaced(true); }}>
                {lang==='uk'?'Оформити замовлення':'Place order'} →
              </button>

              {/* Loyalty bonus preview */}
              <div style={{ marginTop: 16, padding:'12px 14px', background:'#fff', borderRadius: 12, border:'1px solid var(--ep-line-2)' }}>
                <div className="ep-mono" style={{ fontSize: 10, color:'var(--ep-ink-3)', marginBottom: 4 }}>
                  {lang==='uk'?'Бонуси':'Rewards'}
                </div>
                <div style={{ fontSize: 13, color:'var(--ep-ink)' }}>
                  {lang==='uk' ? <>За це замовлення нарахуємо <strong style={{ color:'var(--ep-accent)' }}>{Math.round(total * 0.05)} балів</strong> на наступну покупку</> : <>You earn <strong style={{ color:'var(--ep-accent)' }}>{Math.round(total * 0.05)} points</strong> for your next order</>}
                </div>
              </div>

              <div style={{ marginTop: 14, fontSize: 11, color:'var(--ep-ink-3)', textAlign:'center', lineHeight: 1.5 }}>
                {lang==='uk' ? 'Натискаючи кнопку, ти приймаєш ' : 'By placing the order you accept our '}
                <a onClick={() => goto({ name:'terms' })} style={{ borderBottom:'1px solid var(--ep-line)', cursor:'pointer' }}>{lang==='uk'?'умови використання':'terms'}</a>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </>
  );
}

function CheckoutSection({ num, title, optional, children }) {
  const { lang } = useStore();
  return (
    <section>
      <div style={{ display:'flex', alignItems:'baseline', gap: 10, marginBottom: 16 }}>
        <span className="ep-mono" style={{ fontSize: 11, color:'var(--ep-accent)', fontWeight: 600, letterSpacing:'0.1em' }}>{num.padStart(2,'0')}</span>
        <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, letterSpacing:'-0.02em', margin: 0 }}>{title}</h2>
        {optional && <span style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>({lang==='uk'?'опційно':'optional'})</span>}
      </div>
      {children}
    </section>
  );
}

function SumRow({ label, value, accent }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', fontSize: 13, color: accent ? 'var(--ep-accent)' : 'var(--ep-ink-2)', fontWeight: accent ? 500 : 400 }}>
      <span>{label}</span>
      <span style={{ fontVariantNumeric:'tabular-nums' }}>{value}</span>
    </div>
  );
}

// ─────────────────────────── ORDER DETAIL MODAL ────────────────────────────
function OrderModal({ order, onClose }) {
  const { lang, fmt, addToCart, goto } = useStore();
  if (!order) return null;
  const items = order.items.map(it => ({ ...it, p: window.ECOPROF_PRODUCTS.find(p => p.id === it.id) })).filter(x => x.p);
  const reorder = () => {
    items.forEach(({ id, qty }) => addToCart(id, qty));
    onClose();
    goto({ name:'checkout' });
  };
  return (
    <div className="ep-modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="ep-modal" style={{ maxWidth: 560 }}>
        <button onClick={onClose} className="ep-modal-close" aria-label="close">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
        <div className="ep-mono" style={{ fontSize: 11, color:'var(--ep-ink-3)' }}>{order.id}</div>
        <h2 style={{ fontFamily:'var(--ep-font-display)', fontSize: 26, fontWeight: 500, letterSpacing:'-0.02em', margin:'6px 0 4px' }}>
          {order.date}
        </h2>
        <div style={{ fontSize: 13, color:'var(--ep-ink-2)', marginBottom: 18 }}>
          {order.status} · {lang==='uk'?'Доставка':'Delivery'}: {order.delivery}
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap: 12, marginBottom: 20 }}>
          {items.map(({ p, qty }) => (
            <div key={p.id}
              onClick={() => { onClose(); goto({ name:'product', id: p.id }); }}
              style={{ display:'flex', gap: 12, alignItems:'center', padding: '10px 0', borderTop:'1px solid var(--ep-line-2)', cursor:'pointer', transition:'opacity .15s var(--ep-ease)' }}
              onMouseEnter={(e) => e.currentTarget.style.opacity = '0.72'}
              onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
            >
              <div style={{ width: 54, height: 54, borderRadius: 8, background:'#fff', border:'1px solid var(--ep-line-2)', flex:'none', overflow:'hidden', display:'flex' }}>
                <ProductMedia p={p}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{p.name}</div>
                <div style={{ fontSize: 11.5, color:'var(--ep-ink-3)' }}>{qty} × {fmt(p.price)}</div>
              </div>
              <div style={{ fontSize: 13, fontVariantNumeric:'tabular-nums' }}>{fmt(p.price * qty)}</div>
            </div>
          ))}
          <div style={{ paddingTop: 12, borderTop:'1px solid var(--ep-line-2)', display:'flex', flexDirection:'column', gap: 6 }}>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize: 13, color:'var(--ep-ink-2)' }}>
              <span>{lang==='uk'?'Сума':'Subtotal'}</span>
              <span style={{ fontVariantNumeric:'tabular-nums' }}>{fmt(order.sum - (order.shipping || 0))}</span>
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize: 13, color:'var(--ep-ink-2)' }}>
              <span>{lang==='uk'?'Доставка':'Shipping'}</span>
              <span style={{ fontVariantNumeric:'tabular-nums' }}>{order.shipping === 0 ? (lang==='uk'?'безкоштовно':'free') : fmt(order.shipping || 0)}</span>
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize: 13, color:'var(--ep-ink-2)' }}>
              <span>{lang==='uk'?'Оплата':'Payment'}</span>
              <span>{order.payment}</span>
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', paddingTop: 10, marginTop: 4, borderTop:'1px dashed var(--ep-line)' }}>
              <span style={{ fontSize: 14, fontWeight: 500 }}>{lang==='uk'?'Разом':'Total'}</span>
              <span style={{ fontSize: 16, fontFamily:'var(--ep-font-display)', fontWeight: 500 }}>{fmt(order.sum)}</span>
            </div>
          </div>
        </div>

        <div style={{ display:'flex', gap: 10, flexWrap:'wrap' }}>
          <button onClick={reorder} className="ep-btn accent" style={{ flex: 1, minWidth: 180 }}>
            ↻ {lang==='uk'?'Повторити замовлення':'Reorder'}
          </button>
          <button onClick={onClose} className="ep-btn ghost">
            {lang==='uk'?'Закрити':'Close'}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  PageHero, InfoPage, FAQList,
  AboutPage, JournalPage, ArticlePage, ContactPage,
  ShippingPage, ReturnsPage, FAQPage,
  GiftCardsPage, CareersPage, RolePage, QuizPage,
  WishlistPage, SearchOverlay, AuthPage, AccountPage,
  PrivacyPage, TermsPage, CookiesPage, CookieBanner,
  AuthModal, CheckoutPage, OrderModal, CheckoutSection, SumRow,
  JOURNAL_ARTICLES, ROLES,
});
