// KWEE — Editorial Luxe (responsive: mobile + desktop)
const { useState, useEffect, useRef } = React;
const D = window.KWEE_DATA;

const MOBILE_BREAKPOINT = 900;

// ─── Icons ─────────────────────────────────────────────────────
const Icon = {
  menu:    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M4 8h16M4 16h12"/></svg>,
  search:  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  close:   <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M6 6l12 12M6 18 18 6"/></svg>,
  bookmark:<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M6 4h12v18l-6-4-6 4z"/></svg>,
  arrow:   <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>,
  arrowSm: <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>,
  home:    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-7 9 7v9a2 2 0 0 1-2 2h-4v-6h-6v6H5a2 2 0 0 1-2-2z"/></svg>,
  grid:    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="4" y="4" width="7" height="7" rx="1"/><rect x="13" y="4" width="7" height="7" rx="1"/><rect x="4" y="13" width="7" height="7" rx="1"/><rect x="13" y="13" width="7" height="7" rx="1"/></svg>,
  shop:    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 7h14l-1 13H6zM9 7V5a3 3 0 0 1 6 0v2"/></svg>,
  saved:   <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 4h12v18l-6-4-6 4z"/></svg>,
  back:    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M15 5l-7 7 7 7"/></svg>,
};

// ─── Brutalist splash (shared) ─────────────────────────────────
function Splash({ gone, desktop }) {
  return (
    <div className={'splash' + (gone ? ' gone' : '')}>
      <div className="marker tl">★ KWEE</div>
      <div className="marker tr">ISSUE №184</div>
      <div className="marker bl">EST. 2018</div>
      <div className="marker br">{desktop ? `YGN · MM · ${D.brand.tagline_my}` : 'YGN · MM'}</div>
      <div className="splash-logo">
        <span>K</span><span>W</span><span>E</span><span>E</span>
      </div>
      <div className="splash-bar" />
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
//  MOBILE
// ════════════════════════════════════════════════════════════════

function MobileTopBar({ scrolled, onMenu, onLogo }) {
  return (
    <div className={'topbar' + (scrolled ? ' scrolled' : '')}>
      <button className="icon-btn" onClick={onMenu} aria-label="menu">{Icon.menu}</button>
      <button className="logo" onClick={onLogo} style={{cursor: 'pointer'}} aria-label="KWEE home">
        <img className="logo-img" src="brand/logo.png" alt="KWEE" />
      </button>
      <button className="icon-btn" aria-label="search">{Icon.search}</button>
    </div>
  );
}

function MobileTicker() {
  const items = D.ticker;
  const repeated = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        <span>{repeated.map((t, i) => <React.Fragment key={i}><span>{t}</span><span className="dot">✦</span></React.Fragment>)}</span>
        <span>{repeated.map((t, i) => <React.Fragment key={'b'+i}><span>{t}</span><span className="dot">✦</span></React.Fragment>)}</span>
      </div>
    </div>
  );
}

function MobileCover({ onOpen, scrollerRef }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const img = el.querySelector('.cover-img');
    const sc = scrollerRef.current;
    const onScroll = () => {
      const rect = el.getBoundingClientRect();
      const p = Math.max(-1, Math.min(1, (rect.top + rect.height / 2 - window.innerHeight / 2) / window.innerHeight));
      img.style.transform = `scale(1.08) translateY(${p * 18}px)`;
    };
    onScroll();
    const target = sc || window;
    target.addEventListener('scroll', onScroll, { passive: true });
    return () => target.removeEventListener('scroll', onScroll);
  }, []);
  const titleWords = D.cover.title_my.split(' ');
  return (
    <article className="cover" ref={ref} onClick={onOpen}>
      <div className="cover-img" style={{backgroundImage: `url(${D.cover.image})`}} />
      <div className="cover-overlay" />
      <div className="cover-grain" />
      <div className="cover-mast">
        <span className="l"><span>KWEE</span><span>·</span><span>{D.brand.issue_short}</span></span>
        <span>EST. 2018</span>
      </div>
      <div className="cover-tags">
        <span>{D.cover.date}</span>
        <span>{D.cover.read_time}</span>
      </div>
      <button className="bookmark-x" aria-label="save">{Icon.bookmark}</button>
      <div className="cover-title">
        <div className="eb">{D.cover.eyebrow_my}</div>
        <h1 className="ti">
          {titleWords.map((w, i) => (
            <span key={i} style={{overflow: 'hidden', display: 'inline-block', marginRight: '0.25em'}}>
              <span className="word" style={{animationDelay: `${0.5 + i * 0.05}s`}}>{w}</span>
            </span>
          ))}
        </h1>
        <p className="sub">{D.cover.subtitle_my}</p>
      </div>
    </article>
  );
}

function MobileCategoryStrip({ active, onPick }) {
  return (
    <div className="cats">
      {D.nav.filter(n => !['home', 'shop'].includes(n.id)).map(n => (
        <button key={n.id}
                className={'cat-chip' + (active === n.id ? ' active' : '')}
                onClick={() => onPick(n.id)}>
          {active !== n.id && <span className="dot" />}
          {n.my}
        </button>
      ))}
    </div>
  );
}

function MobileEditorPick({ article, onOpen }) {
  return (
    <div className="editor-pick" onClick={onOpen}>
      <div className="text">
        <span className="eb">{article.eyebrow_my}</span>
        <h3>{article.title_my}</h3>
        <p>{article.excerpt_my}</p>
        <div className="meta">
          <span>{article.author}</span>
          <span>·</span>
          <span>{article.read_time}</span>
        </div>
      </div>
      <div className="img" style={{backgroundImage: `url(${article.image})`}} />
    </div>
  );
}

function MobileFeaturedScroll({ onOpen }) {
  return (
    <React.Fragment>
      <div className="sec-head">
        <h2 className="sec-title">Featured <em>—</em> ဆောင်းပါးများ</h2>
        <button className="sec-more">All <span className="arrow">→</span></button>
      </div>
      <div className="h-scroll">
        {D.features.map(f => (
          <article key={f.id} className="feat-card" onClick={() => onOpen(f)}>
            <div className="img" style={{backgroundImage: `url(${f.image})`}} />
            <div className="body">
              <span className="eb">{f.eyebrow_my}</span>
              <h3 className="ti">{f.title_my}</h3>
              <p className="ex">{f.excerpt_my}</p>
              <div className="meta">
                <span>{f.author}</span>
                <span>·</span>
                <span>{f.read_time}</span>
              </div>
            </div>
          </article>
        ))}
      </div>
    </React.Fragment>
  );
}

function MobileLatestGrid({ onOpen, items }) {
  const items_ = items || D.latest;
  const refs = useRef([]);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('revealed'); });
    }, { threshold: 0.2 });
    refs.current.forEach(el => el && io.observe(el));
    return () => io.disconnect();
  }, [items_]);
  return (
    <div className="grid">
      {items_.map((a, i) => (
        <div key={a.id} className="grid-card" ref={el => refs.current[i] = el}
             onClick={() => onOpen(a)}>
          <div className="img" style={{
            backgroundImage: `url(${a.image})`,
            transitionDelay: `${i * 0.05}s`
          }} />
          <span className="eb">{a.cat_label} · {a.date}</span>
          <div className="ti">{a.title_my}</div>
        </div>
      ))}
    </div>
  );
}

function MobilePartners() {
  const partners = [...D.partners, ...D.partners];
  return (
    <section className="partners-wrap">
      <div className="partners-head">
        <span className="l">Our <em>Partners</em></span>
        <button className="sec-more">View <span className="arrow">→</span></button>
      </div>
      <div className="partners-marquee">
        {partners.map((p, i) => (
          <span key={i} className="partner-pill">
            <span className="tag">{p.tag}</span>
            {p.name}
          </span>
        ))}
      </div>
    </section>
  );
}

function MobileEvents() {
  return (
    <section>
      <div className="sec-head">
        <h2 className="sec-title">Parties <em>&amp;</em> Events</h2>
        <button className="sec-more">All <span className="arrow">→</span></button>
      </div>
      <div className="events">
        {D.events.map((e, i) => (
          <div key={e.id} className="event-row">
            <span className="num">/ {String(i + 1).padStart(2, '0')}</span>
            <div>
              <div className="title">{e.title_my}</div>
              <div className="venue">{e.venue}</div>
            </div>
            <span className="date">{e.date}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

function MobileShopTeaser({ onShop }) {
  return (
    <section className="shop" onClick={onShop} style={{cursor: 'pointer'}}>
      <div className="eyebrow" style={{color: '#1a140d99', marginBottom: 14}}>KWEE STORE</div>
      <h3>Issue 184 — out now.</h3>
      <p>Limited print collector's edition. ICONS feature, 180 pages.</p>
      <span className="cta">Shop the issue {Icon.arrowSm}</span>
      <div style={{
        position: 'absolute', right: -20, top: -20,
        fontSize: 140, fontFamily: 'Fraunces',
        color: '#1a140d18', fontVariationSettings: '"opsz" 144'
      }}>K</div>
    </section>
  );
}

function MobileNewsletter() {
  return (
    <section className="nl">
      <span className="eb">JOIN THE LIST</span>
      <h3>The <em>Saturday</em> Edition.</h3>
      <p>လစဥ်ထွက်ရှိနေတဲ့ ဆောင်းပါးအသစ်တွေ၊ ပါတီပွဲတွေ၊ ဈေးကွက်ထဲက အကြောင်းအရာတွေ။</p>
      <form onSubmit={e => e.preventDefault()}>
        <input type="email" placeholder="your.email@kwee.co" />
        <button>Join</button>
      </form>
    </section>
  );
}

function MobileFooter() {
  return (
    <footer className="foot">
      <div className="logo-l">Kwee.</div>
      <p className="about">{D.brand.about_my}</p>
      <div className="cols">
        <div className="col">
          <h5>Sections</h5>
          {D.nav.slice(0, 5).map(n => <a href="#" key={n.id}>{n.my}</a>)}
        </div>
        <div className="col">
          <h5>Connect</h5>
          <a href="#">Telegram</a>
          <a href="#">Viber</a>
          <a href="#">Facebook</a>
          <a href="#">Advertise</a>
        </div>
      </div>
      <div className="legal">
        <span>© 2018 — 2025</span>
        <span>YANGON</span>
      </div>
    </footer>
  );
}

function MobileTabBar({ page, onChange }) {
  const tabs = [
    { id: 'home',   my: 'ပင်မ',   icon: Icon.home },
    { id: 'browse', my: 'ဆောင်းပါး', icon: Icon.grid },
    { id: 'shop',   my: 'ဈေး',    icon: Icon.shop },
    { id: 'saved',  my: 'သိမ်း', icon: Icon.saved },
  ];
  return (
    <nav className="tabbar">
      {tabs.map(t => (
        <button key={t.id} className={'tab' + (page === t.id ? ' active' : '')}
                onClick={() => onChange(t.id)}>
          {t.icon}
          <span>{t.my}</span>
        </button>
      ))}
    </nav>
  );
}

function MobileDrawer({ open, onClose, onNav }) {
  return (
    <div className={'drawer' + (open ? ' open' : '')}>
      <div className="drawer-back" onClick={onClose} />
      <aside className="drawer-panel">
        <button className="drawer-close" onClick={onClose}>{Icon.close}</button>
        <div className="eb">Navigation · {D.brand.issue_short}</div>
        <nav className="drawer-nav">
          {D.nav.map((n, i) => (
            <a key={n.id} href="#" style={{'--i': i}}
               onClick={(e) => { e.preventDefault(); onNav(n.id); }}>
              <span>{n.my}</span>
              <span className="num">/ {String(i + 1).padStart(2, '0')}</span>
            </a>
          ))}
        </nav>
        <div className="drawer-foot">
          <span>{D.brand.tagline_my}</span>
          <span>EST. 2018 · YANGON</span>
        </div>
      </aside>
    </div>
  );
}

function MobileArticlePage({ article, onBack }) {
  const a = article;
  const body = (a.body_my && a.body_my.length) ? a.body_my : D.articleBody_my;
  const quoteText = a.excerpt_my || a.subtitle_my || '';
  const pullQuoteAt = body.length > 4 ? 2 : 1;
  return (
    <div className="page article">
      <div className="article-hero" style={{backgroundImage: `url(${a.image})`}}>
        <button className="icon-btn" onClick={onBack}
                style={{
                  position: 'absolute', top: 16, left: 14,
                  background: 'rgba(255,255,255,0.15)',
                  backdropFilter: 'blur(10px)', color: '#fff'
                }}>
          {Icon.back}
        </button>
        <div className="meta">
          <div className="eb">{a.eyebrow_my || a.cat_label}</div>
          <h1>{a.title_my}</h1>
          <div className="byline">
            <span>{a.author || 'KWEE'}</span>
            <span>·</span>
            <span>{a.date || '2025'}</span>
            <span>·</span>
            <span>{a.read_time || '5 မိနစ်'}</span>
          </div>
        </div>
      </div>
      <div className="article-body">
        {body.map((p, i) => (
          <React.Fragment key={i}>
            {i === 0
              ? <p className="dropcap">{p}</p>
              : <p>{p}</p>}
            {i === pullQuoteAt && quoteText && (
              <blockquote style={{
                margin: '24px 0', paddingLeft: 18,
                borderLeft: '2px solid var(--accent)',
                fontStyle: 'italic', fontSize: 18, lineHeight: 1.5, color: 'var(--ink-2)'
              }}>
                "{quoteText}"
              </blockquote>
            )}
          </React.Fragment>
        ))}
      </div>
      <div className="article-tags">
        {['#fashion', '#90s', '#urban', '#streetwear'].map(t =>
          <span key={t} className="tag-chip">{t}</span>
        )}
      </div>
      <div style={{padding: '24px 16px'}}>
        <div className="sec-head" style={{padding: '12px 0 14px'}}>
          <h2 className="sec-title">Read <em>more</em></h2>
        </div>
        <MobileLatestGrid items={D.latest.slice(0, 4)} onOpen={() => {}} />
      </div>
    </div>
  );
}

function MobileCategoryPage({ catId, onOpen, onBack }) {
  const cat = D.nav.find(n => n.id === catId);
  if (!cat) return null;
  const items = D.latest.filter(l => l.cat === catId).concat(D.latest);
  return (
    <div className="page">
      <div style={{padding: '32px 22px 14px', display: 'flex', alignItems: 'center', gap: 12}}>
        <button className="icon-btn" onClick={onBack}>{Icon.back}</button>
        <span className="eyebrow">{cat.label}</span>
      </div>
      <div style={{padding: '0 22px 24px'}}>
        <h1 style={{
          fontFamily: 'var(--serif)', fontSize: 54, lineHeight: 0.95, margin: '0 0 14px',
          fontVariationSettings: '"opsz" 144, "SOFT" 30', letterSpacing: '-0.03em'
        }}>
          {cat.my}
        </h1>
        <p style={{
          fontSize: 14, lineHeight: 1.5, color: 'var(--ink-2)', margin: 0,
          fontStyle: 'italic', fontFamily: 'var(--serif)'
        }}>
          {items.length} ဆောင်းပါး · {cat.label}
        </p>
      </div>
      <MobileEditorPick article={D.features[0]} onOpen={() => onOpen(D.features[0])} />
      <div className="sec-head">
        <h2 className="sec-title">All <em>—</em> ဆောင်းပါး</h2>
      </div>
      <MobileLatestGrid items={items} onOpen={onOpen} />
      <div style={{height: 80}} />
    </div>
  );
}

const shopFindCategory = (catId) => (D.shop_categories || []).find(c => c.id === catId);
const shopProductsInCategory = (catId) => (D.shop_products || []).filter(p => (p.cat_ids || []).includes(catId));

function MobileShopLanding({ onPick }) {
  const cats = D.shop_categories || [];
  const totalProducts = (D.shop_products || []).length;
  return (
    <div className="page">
      <div style={{padding: '32px 22px 6px'}}>
        <span className="eyebrow">KWEE Store</span>
      </div>
      <div style={{padding: '0 22px 24px'}}>
        <h1 style={{
          fontFamily: 'var(--serif)', fontSize: 48, lineHeight: 1.05, margin: '0 0 14px',
          fontVariationSettings: '"opsz" 144, "SOFT" 30', letterSpacing: '-0.025em'
        }}>
          The <em style={{color: 'var(--accent)', fontStyle: 'italic', fontWeight: 300}}>Shop</em>
        </h1>
        <p style={{
          fontFamily: 'var(--serif)', fontStyle: 'italic',
          fontSize: 14, color: 'var(--ink-2)', margin: 0
        }}>
          {totalProducts} products in {cats.length} collections · curated by KWEE
        </p>
      </div>
      <div className="shop-cats">
        {cats.map(c => (
          <a key={c.id} className="shop-cat-tile"
             onClick={(e) => { e.preventDefault(); onPick(c.id); }}
             href="#"
             aria-label={`${c.name} — ${c.count} {c.count === 1 ? 'product' : 'products'}`}>
            <div className="shop-cat-img"
                 style={{backgroundImage: c.image ? `url(${c.image})` : 'none'}} />
            <div className="shop-cat-meta">
              <span className="eb">{c.count} {c.count === 1 ? 'product' : 'products'}</span>
              <h3>{c.name}</h3>
            </div>
            <span className="shop-cat-arrow">→</span>
          </a>
        ))}
      </div>
    </div>
  );
}

function MobileShopCategory({ catId, onProduct, onBack }) {
  const cat = shopFindCategory(catId);
  const products = shopProductsInCategory(catId);
  const total = products.length;
  return (
    <div className="page">
      <div style={{padding: '32px 22px 14px', display: 'flex', alignItems: 'center', gap: 12}}>
        <button className="icon-btn" onClick={onBack}>{Icon.back}</button>
        <span className="eyebrow">{cat?.name || 'KWEE Store'}</span>
      </div>
      <div style={{padding: '0 22px 24px'}}>
        <h1 style={{
          fontFamily: 'var(--serif)', fontSize: 44, lineHeight: 1.05, margin: '0 0 14px',
          fontVariationSettings: '"opsz" 144, "SOFT" 30', letterSpacing: '-0.025em'
        }}>
          {cat?.name || 'Shop'}
        </h1>
        <p style={{
          fontFamily: 'var(--serif)', fontStyle: 'italic',
          fontSize: 14, color: 'var(--ink-2)', margin: 0
        }}>
          {total} products
        </p>
      </div>
      <div className="grid" style={{paddingBottom: 80}}>
        {products.map((p, i) => (
          <a key={p.id} className="grid-card sold-out"
             onClick={(e) => { e.preventDefault(); onProduct(p, catId); }}
             href="#"
             aria-label={`${p.name} — sold out`}
             style={{textDecoration: 'none', color: 'inherit'}}>
            <div className="img" style={{
              backgroundImage: p.image ? `url(${p.image})` : 'none',
              backgroundColor: 'var(--paper)',
              backgroundSize: 'cover', backgroundPosition: 'center'
            }}>
              <span style={{
                position: 'absolute', top: 10, left: 10, zIndex: 2,
                fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.16em',
                background: 'rgba(250,246,236,0.92)', color: 'var(--ink)',
                padding: '5px 10px', borderRadius: 100
              }}>
                {p.tag} · {String(i + 1).padStart(2, '0')}/{String(total).padStart(2, '0')}
              </span>
              <span className="shop-stock">Sold Out</span>
            </div>
            {p.sub && <span className="eb">{p.sub}</span>}
            <div className="ti" style={{marginBottom: 6}}>{p.name}</div>
            <span className="mono shop-price--out" style={{
              fontSize: 11, color: 'var(--accent)', letterSpacing: '0.12em',
              fontFamily: 'var(--mono)'
            }}>{p.price}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

function MobileShopProduct({ product, onBack }) {
  const p = product;
  return (
    <div className="page product-detail">
      <div className="pd-img" style={{backgroundImage: p.image ? `url(${p.image})` : 'none'}}>
        <button className="icon-btn" onClick={onBack}
                style={{
                  position: 'absolute', top: 16, left: 14, zIndex: 3,
                  background: 'rgba(255,255,255,0.85)',
                  backdropFilter: 'blur(10px)', color: 'var(--ink)'
                }}>
          {Icon.back}
        </button>
        <span className="shop-stock">Sold Out</span>
      </div>
      <div className="pd-body">
        <div className="pd-tag">{p.tag}</div>
        <h1 className="pd-name">{p.name}</h1>
        <span className="pd-price shop-price--out">{p.price}</span>
        {p.description && <p className="pd-desc">{p.description}</p>}
        {p.sub && <div className="pd-sub">{p.sub}</div>}
      </div>
    </div>
  );
}

function MobileHomePage({ onOpen, onCat, onShop, scrollerRef }) {
  const [activeCat, setActiveCat] = useState('sports');
  return (
    <div className="page">
      <MobileTicker />
      <div style={{padding: '8px 20px 6px'}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'}}>
          <span className="eyebrow">{D.brand.issue}</span>
          <span className="eyebrow">VOL. XII</span>
        </div>
      </div>
      <MobileCover onOpen={() => onOpen(D.cover)} scrollerRef={scrollerRef} />
      <MobileCategoryStrip active={activeCat} onPick={(c) => { setActiveCat(c); onCat(c); }} />
      <div className="sec-head">
        <h2 className="sec-title">Editor's <em>pick</em></h2>
      </div>
      <MobileEditorPick article={D.features[1]} onOpen={() => onOpen(D.features[1])} />
      <MobileFeaturedScroll onOpen={onOpen} />
      <div className="sec-head" style={{marginTop: 12}}>
        <h2 className="sec-title">Latest <em>—</em> နောက်ဆုံး</h2>
        <button className="sec-more">View all <span className="arrow">→</span></button>
      </div>
      <MobileLatestGrid onOpen={onOpen} />
      <MobilePartners />
      <MobileEvents />
      <MobileShopTeaser onShop={onShop} />
      <MobileNewsletter />
      <MobileFooter />
    </div>
  );
}

function MobileApp() {
  const [page, setPage] = useState({ name: 'home' });
  const [drawer, setDrawer] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [splashGone, setSplashGone] = useState(false);
  const scrollerRef = useRef(null);

  useEffect(() => {
    const t = setTimeout(() => setSplashGone(true), 1800);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    const el = scrollerRef.current;
    if (!el) return;
    const onScroll = () => setScrolled(el.scrollTop > 20);
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, [page]);

  const scrollTop = () => requestAnimationFrame(() => scrollerRef.current?.scrollTo({ top: 0 }));
  const goCat = (cid) => { setPage({ name: 'category', cat: cid }); scrollTop(); };
  const goArticle = (a) => { setPage({ name: 'article', article: a }); scrollTop(); };
  const goShop = () => { setPage({ name: 'shop' }); scrollTop(); };
  const goShopCat = (catId) => { setPage({ name: 'shop_cat', catId }); scrollTop(); };
  const goShopProduct = (product, catId) => { setPage({ name: 'shop_product', product, catId }); scrollTop(); };
  const goHome = () => { setPage({ name: 'home' }); scrollTop(); };
  const backFromProduct = () => {
    if (page.catId != null) goShopCat(page.catId);
    else goShop();
  };

  const onTab = (id) => {
    if (id === 'home') goHome();
    else if (id === 'shop') goShop();
    else if (id === 'browse') setPage({ name: 'category', cat: 'sports' });
    else goHome();
  };

  const onDrawerNav = (id) => {
    setDrawer(false);
    if (id === 'home') goHome();
    else if (id === 'shop') goShop();
    else setPage({ name: 'category', cat: id });
    scrollTop();
  };

  const tabKey = page.name === 'home' ? 'home'
               : (page.name === 'shop' || page.name === 'shop_cat' || page.name === 'shop_product') ? 'shop'
               : 'browse';

  return (
    <div className="mobile-view">
      <Splash gone={splashGone} desktop={false} />
      <div className="scroller" ref={scrollerRef}>
        <MobileTopBar scrolled={scrolled} onMenu={() => setDrawer(true)} onLogo={goHome} />
        {page.name === 'home' && <MobileHomePage onOpen={goArticle} onCat={goCat} onShop={goShop} scrollerRef={scrollerRef} />}
        {page.name === 'category' && <MobileCategoryPage catId={page.cat} onOpen={goArticle} onBack={goHome} />}
        {page.name === 'article' && <MobileArticlePage article={page.article} onBack={goHome} />}
        {page.name === 'shop' && <MobileShopLanding onPick={goShopCat} />}
        {page.name === 'shop_cat' && <MobileShopCategory catId={page.catId} onProduct={goShopProduct} onBack={goShop} />}
        {page.name === 'shop_product' && <MobileShopProduct product={page.product} onBack={backFromProduct} />}
      </div>
      <MobileTabBar page={tabKey} onChange={onTab} />
      <MobileDrawer open={drawer} onClose={() => setDrawer(false)} onNav={onDrawerNav} />
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
//  DESKTOP
// ════════════════════════════════════════════════════════════════

function useDesktopCursor() {
  useEffect(() => {
    const cursor = document.getElementById('cursor');
    if (!cursor) return;
    let mx = 0, my = 0, cx = 0, cy = 0;
    const onMove = (e) => { mx = e.clientX; my = e.clientY; };
    document.addEventListener('mousemove', onMove);
    let raf;
    const tick = () => {
      cx += (mx - cx) * 0.18;
      cy += (my - cy) * 0.18;
      cursor.style.transform = `translate(${cx}px, ${cy}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();

    const onOver = (e) => {
      const t = e.target.closest('[data-magnetic]');
      if (t) {
        cursor.classList.add(t.dataset.magnetic === 'read' ? 'read' : 'magnetic');
        cursor.dataset.label = t.dataset.cursorLabel || 'READ';
      } else if (e.target.closest('a, button, .grid-card, .feat-card, .editor-spread, .nav-link')) {
        cursor.classList.remove('magnetic', 'read');
        cursor.classList.add('dot');
        cursor.dataset.label = '';
      } else {
        cursor.classList.remove('magnetic', 'read', 'dot');
        cursor.dataset.label = '';
      }
    };
    document.addEventListener('mouseover', onOver);

    return () => {
      cancelAnimationFrame(raf);
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseover', onOver);
    };
  }, []);
}

function DesktopUtilBar() {
  return (
    <div className="util">
      <div className="l">
        <span><span className="dot">●</span>YANGON · 28°C</span>
        <span>EST. 2018</span>
        <span>{D.brand.tagline_my}</span>
      </div>
      <div className="l">
        <span>EN / မြန်မာ</span>
        <span>SUBSCRIBE</span>
        <span>LOGIN</span>
      </div>
    </div>
  );
}

function DesktopTopBar({ scrolled, page, onMenu, onLogo, onCat, onShop }) {
  const left = D.nav.slice(1, 4);
  const right = D.nav.slice(4, 7);
  return (
    <div className={'topbar' + (scrolled ? ' scrolled' : '')}>
      <div className="nav-left">
        {left.map(n => (
          <a key={n.id} className={'nav-link' + (page === n.id ? ' active' : '')}
             onClick={() => onCat(n.id)}>{n.label}</a>
        ))}
      </div>
      <button className="logo" onClick={onLogo} aria-label="KWEE home">
        <img className="logo-img" src="brand/logo.png" alt="KWEE" />
      </button>
      <div className="nav-right">
        {right.map(n => (
          <a key={n.id} className={'nav-link' + (page === n.id ? ' active' : '')}
             onClick={() => onCat(n.id)}>{n.label}</a>
        ))}
        <button className="subscribe-btn" data-magnetic data-cursor-label="SHOP" onClick={onShop}>Shop</button>
        <button className="icon-btn">{Icon.search}</button>
        <button className="icon-btn" onClick={onMenu}>{Icon.menu}</button>
      </div>
    </div>
  );
}

function splitTitle(title, lines = 3) {
  const words = (title || '').trim().split(/\s+/).filter(Boolean);
  if (words.length <= lines) {
    return [...words, ...Array(Math.max(0, lines - words.length)).fill('')].slice(0, lines);
  }
  const total = words.reduce((n, w) => n + w.length + 1, 0);
  const target = total / lines;
  const out = [[]];
  let cur = 0;
  for (const w of words) {
    const next = cur + w.length + (out[out.length - 1].length ? 1 : 0);
    if (out.length < lines && cur > 0 && next > target * 0.95) {
      out.push([]);
      cur = 0;
    }
    out[out.length - 1].push(w);
    cur += w.length + 1;
  }
  while (out.length < lines) out.push([]);
  return out.map(a => a.join(' '));
}

function DesktopHero({ onOpen }) {
  const coverRef = useRef(null);
  useEffect(() => {
    const el = coverRef.current;
    if (!el) return;
    const onScroll = () => {
      const y = window.scrollY;
      el.style.transform = `scale(1.08) translateY(${y * 0.2}px)`;
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const titleParts = splitTitle(D.cover.title_my, 3);

  return (
    <section className="hero">
      <div className="hero-text">
        <div>
          <div className="hero-eyebrow"><span>COVER STORY · {D.cover.cat_label}</span></div>
          <h1 className="hero-title">
            <span className="ln"><em>{titleParts[0]}</em></span>
            <span className="ln"><em>{titleParts[1]}</em></span>
            <span className="ln"><em>{titleParts[2]}</em></span>
          </h1>
          <p className="hero-sub">{D.cover.subtitle_my}</p>
        </div>
        <div className="hero-meta">
          <div className="cell">
            <span className="k">Author</span>
            <span className="v">Pyae Phyo</span>
          </div>
          <div className="cell">
            <span className="k">Date</span>
            <span className="v">{D.cover.date}</span>
          </div>
          <div className="cell">
            <span className="k">Reading</span>
            <span className="v">{D.cover.read_time}</span>
          </div>
          <span></span>
          <button className="read-btn" onClick={() => onOpen(D.cover)}
                  data-magnetic data-cursor-label="READ">
            Read the cover {Icon.arrow}
          </button>
        </div>
      </div>
      <div className="hero-cover" onClick={() => onOpen(D.cover)}
           data-magnetic data-cursor-label="OPEN">
        <div className="hero-cover-img" ref={coverRef}
             style={{backgroundImage: `url(${D.cover.image})`}} />
        <div className="hero-cover-overlay" />
        <div className="hero-cover-grain" />
        <div className="hero-cover-mast">
          <span>KWEE · {D.brand.issue_short}</span>
          <span>VOL. XII</span>
        </div>
        <div className="hero-cover-cap">
          <div className="eb">{D.cover.eyebrow_my}</div>
          <p className="ti">"{D.cover.title_my}"</p>
        </div>
      </div>
    </section>
  );
}

function DesktopTicker() {
  const items = D.ticker;
  return (
    <div className="ticker">
      <div className="ticker-track">
        <span>{[...items, ...items].map((t, i) => <React.Fragment key={i}><span>{t}</span><span className="dot">✦</span></React.Fragment>)}</span>
        <span>{[...items, ...items].map((t, i) => <React.Fragment key={'b'+i}><span>{t}</span><span className="dot">✦</span></React.Fragment>)}</span>
      </div>
    </div>
  );
}

function DesktopCats({ active, onPick }) {
  return (
    <div className="cats">
      {D.nav.filter(n => !['home', 'shop'].includes(n.id)).map(n => (
        <button key={n.id}
                className={'cat-chip' + (active === n.id ? ' active' : '')}
                onClick={() => onPick(n.id)}>
          {active !== n.id && <span className="dot" />}
          {n.my}
        </button>
      ))}
    </div>
  );
}

function DesktopEditorSpread({ article, onOpen }) {
  return (
    <article className="editor-spread" onClick={() => onOpen(article)}>
      <div className="img-w">
        <div className="img" style={{backgroundImage: `url(${article.image})`}} />
        <span className="num">№ 01 · EDITOR'S PICK</span>
      </div>
      <div className="text">
        <div className="eb">{article.eyebrow_my}</div>
        <h3>{article.title_my}</h3>
        <p>{article.excerpt_my}</p>
        <div className="meta">
          <span>{article.author}</span>
          <span>·</span>
          <span>{article.read_time}</span>
          <span>·</span>
          <span>{article.date}</span>
        </div>
        <a className="read-link">Read the story {Icon.arrow}</a>
      </div>
    </article>
  );
}

function DesktopFeatGrid({ items, onOpen }) {
  const refs = useRef([]);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('revealed'); });
    }, { threshold: 0.2 });
    refs.current.forEach(el => el && io.observe(el));
    return () => io.disconnect();
  }, []);
  return (
    <div className="feat-grid">
      {items.map((f, i) => (
        <article key={f.id} className="feat-card" ref={el => refs.current[i] = el}
                 onClick={() => onOpen(f)}>
          <div className="img" style={{backgroundImage: `url(${f.image})`}}>
            <div className="img-inner" style={{backgroundImage: `url(${f.image})`}} />
            <div className="img-mask" />
          </div>
          <div className="eb">{f.eyebrow_my}</div>
          <h3>{f.title_my}</h3>
          <p>{f.excerpt_my}</p>
          <div className="meta">
            <span>{f.author}</span>
            <span>·</span>
            <span>{f.read_time}</span>
            <span>·</span>
            <span>{f.date}</span>
          </div>
        </article>
      ))}
    </div>
  );
}

function DesktopLatestGrid({ items, onOpen }) {
  const refs = useRef([]);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('revealed'); });
    }, { threshold: 0.2 });
    refs.current.forEach(el => el && io.observe(el));
    return () => io.disconnect();
  }, [items]);
  return (
    <div className="grid">
      {items.map((a, i) => (
        <article key={a.id} className="grid-card" ref={el => refs.current[i] = el}
                 onClick={() => onOpen(a)}>
          <div className="img-w">
            <div className="img" style={{backgroundImage: `url(${a.image})`}} />
            <div className="img-mask" />
          </div>
          <span className="eb">{a.cat_label} · {a.date}</span>
          <div className="ti">{a.title_my}</div>
        </article>
      ))}
    </div>
  );
}

function DesktopPartners() {
  const partners = [...D.partners, ...D.partners];
  return (
    <section className="partners-wrap">
      <div className="partners-head">
        <span className="l">Our <em>Partners</em> &amp; brands</span>
        <button className="sec-more">View all {Icon.arrow}</button>
      </div>
      <div className="partners-marquee">
        {partners.map((p, i) => (
          <span key={i} className="partner-pill">
            <span className="tag">{p.tag}</span>
            {p.name}
          </span>
        ))}
      </div>
    </section>
  );
}

function DesktopEvents() {
  return (
    <section className="events">
      <div className="sec-head" style={{padding: 0, marginBottom: 32}}>
        <div className="left">
          <span className="n">№ 03</span>
          <h2 className="sec-title">Parties <em>&amp;</em> Events</h2>
        </div>
        <button className="sec-more">All events {Icon.arrow}</button>
      </div>
      {D.events.map((e, i) => (
        <div key={e.id} className="event-row">
          <span className="num">/ {String(i + 1).padStart(2, '0')}</span>
          <div>
            <div className="title">{e.title_my}</div>
          </div>
          <span className="venue">{e.venue}</span>
          <span className="date">{e.date}</span>
        </div>
      ))}
    </section>
  );
}

function DesktopShopBanner({ onShop }) {
  return (
    <section className="shop-banner" onClick={onShop}
             data-magnetic data-cursor-label="SHOP">
      <div className="left">
        <div className="eb">KWEE STORE · LIMITED EDITION</div>
        <h3>Issue 184 <em>— out now.</em></h3>
        <p>Collector's print, 180 pages, numbered to 500. Featuring Ty Dolla $ign cover story and exclusive editorial.</p>
        <span className="cta">Shop the issue {Icon.arrow}</span>
      </div>
      <div className="right">
        <div className="price">12K</div>
        <div className="price-sub">MMK · FREE SHIPPING IN YGN</div>
      </div>
    </section>
  );
}

function DesktopNewsletter() {
  return (
    <section className="nl">
      <div className="eb">THE SATURDAY EDITION</div>
      <h3>Join <em>the</em> list.</h3>
      <p>လစဥ်ထွက်ရှိနေတဲ့ ဆောင်းပါးအသစ်တွေ၊ ပါတီပွဲတွေ — တနင်္ဂနွေနေ့တိုင်း mailbox ထဲ။</p>
      <form onSubmit={e => e.preventDefault()}>
        <input type="email" placeholder="your.email@kwee.co" />
        <button>Subscribe</button>
      </form>
    </section>
  );
}

function DesktopFooter({ onCat, onShop }) {
  return (
    <footer className="foot">
      <div className="row1">
        <div>
          <div className="logo-l">Kwee<span className="dot">.</span></div>
          <p className="about">{D.brand.about_my}</p>
        </div>
        <div className="col">
          <h5>Sections</h5>
          {D.nav.filter(n => n.id !== 'home' && n.id !== 'shop').map(n => (
            <a key={n.id} href="#"
               onClick={(e) => { e.preventDefault(); onCat(n.id); }}>{n.label}</a>
          ))}
        </div>
        <div className="col">
          <h5>Brands</h5>
          {D.partners.slice(0, 5).map(p => <a key={p.id} href="#">{p.name}</a>)}
        </div>
        <div className="col">
          <h5>Connect</h5>
          <a href="#">Telegram</a>
          <a href="#">Viber</a>
          <a href="#">Facebook</a>
          <a href="#">Advertise with KWEE</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onShop(); }}>Shop</a>
        </div>
      </div>
      <div className="legal">
        <span>© 2018 — 2025 KWEE · All rights reserved</span>
        <span>YANGON · MYANMAR</span>
        <span>SITE BY KWEE STUDIO</span>
      </div>
    </footer>
  );
}

function DesktopDrawer({ open, onClose, onNav }) {
  return (
    <div className={'drawer-d' + (open ? ' open' : '')}>
      <div className="back" onClick={onClose} />
      <aside className="panel">
        <button className="icon-btn close" onClick={onClose}>{Icon.close}</button>
        <div className="eb">Navigation · {D.brand.issue_short}</div>
        <nav>
          {D.nav.map((n, i) => (
            <a key={n.id} href="#" style={{'--i': i}}
               onClick={(e) => { e.preventDefault(); onNav(n.id); }}>
              <span>{n.my}</span>
              <span className="num">/ {String(i + 1).padStart(2, '0')}</span>
            </a>
          ))}
        </nav>
        <div className="side">
          <h6>Featured this week</h6>
          <div className="featured" style={{backgroundImage: `url(${D.cover.image})`}}>
            <div className="cap">
              <div className="eb">{D.cover.eyebrow_my}</div>
              <div className="ti">{D.cover.title_my}</div>
            </div>
          </div>
          <h6 style={{marginTop: 12}}>Issue 184 — out now</h6>
        </div>
      </aside>
    </div>
  );
}

function DesktopArticlePage({ article, onBack }) {
  const a = article;
  const body = (a.body_my && a.body_my.length) ? a.body_my : D.articleBody_my;
  const quoteText = a.excerpt_my || a.subtitle_my || '';
  const pullQuoteAt = body.length > 5 ? 2 : 1;
  return (
    <div className="page article">
      <div className="article-hero" style={{backgroundImage: `url(${a.image})`}}>
        <button className="icon-btn" onClick={onBack}
                style={{
                  position: 'absolute', top: '120px', left: '56px',
                  background: 'rgba(255,255,255,0.12)',
                  backdropFilter: 'blur(10px)', color: '#fff',
                  borderColor: 'rgba(255,255,255,0.2)'
                }}>
          {Icon.back}
        </button>
        <div className="meta">
          <div className="eb">{a.eyebrow_my || a.cat_label}</div>
          <h1>{a.title_my}</h1>
          <div className="byline">
            <span>BY {a.author || 'KWEE'}</span>
            <span>·</span>
            <span>{a.date || '2025'}</span>
            <span>·</span>
            <span>{a.read_time || '5 မိနစ်'}</span>
          </div>
        </div>
      </div>
      <div className="article-body">
        {body.map((p, i) => (
          <React.Fragment key={i}>
            <p>{p}</p>
            {i === pullQuoteAt && quoteText && <blockquote>"{quoteText}"</blockquote>}
          </React.Fragment>
        ))}
      </div>
      <div className="article-tags">
        {['#fashion', '#90s', '#urban', '#streetwear', '#' + a.cat].map(t =>
          <span key={t} className="tag-chip">{t}</span>
        )}
      </div>
      <div style={{padding: '40px 56px 0'}}>
        <div className="sec-head" style={{padding: '0 0 32px'}}>
          <div className="left">
            <span className="n">CONTINUE</span>
            <h2 className="sec-title">Read <em>more</em></h2>
          </div>
        </div>
        <DesktopLatestGrid items={D.latest.slice(0, 4)} onOpen={() => {}} />
      </div>
    </div>
  );
}

function DesktopCategoryPage({ catId, onOpen }) {
  const cat = D.nav.find(n => n.id === catId);
  if (!cat) return null;
  const items = D.latest.filter(l => l.cat === catId).concat(D.latest).slice(0, 12);
  return (
    <div className="page">
      <div className="cat-head">
        <div>
          <div className="eb">/ {cat.label.toUpperCase()}</div>
          <h1>{cat.my}</h1>
        </div>
        <div className="sub">{items.length} ဆောင်းပါး<br />curated by KWEE</div>
      </div>
      <div style={{padding: '80px 0 0'}}>
        <DesktopEditorSpread article={D.features[0]} onOpen={onOpen} />
      </div>
      <div className="sec-head">
        <div className="left">
          <span className="n">№ 02</span>
          <h2 className="sec-title">All <em>—</em> ဆောင်းပါးများ</h2>
        </div>
        <button className="sec-more">Filter {Icon.arrow}</button>
      </div>
      <DesktopLatestGrid items={items} onOpen={onOpen} />
    </div>
  );
}

function DesktopShopLanding({ onPick }) {
  const cats = D.shop_categories || [];
  const totalProducts = (D.shop_products || []).length;
  return (
    <div className="page">
      <div className="cat-head">
        <div>
          <div className="eb">/ KWEE STORE</div>
          <h1>Shop</h1>
        </div>
        <div className="sub">
          {totalProducts} products in {cats.length} collections<br />
          curated by KWEE
        </div>
      </div>
      <div style={{padding: '80px 0 0'}}>
        <div className="shop-cats">
          {cats.map(c => (
            <a key={c.id} className="shop-cat-tile"
               onClick={(e) => { e.preventDefault(); onPick(c.id); }}
               href="#"
               data-magnetic data-cursor-label="OPEN"
               aria-label={`${c.name} — ${c.count} {c.count === 1 ? 'product' : 'products'}`}>
              <div className="shop-cat-img"
                   style={{backgroundImage: c.image ? `url(${c.image})` : 'none'}}>
                <span className="shop-cat-count">{c.count} {c.count === 1 ? 'product' : 'products'}</span>
              </div>
              <div className="shop-cat-meta">
                <h3>{c.name}</h3>
                <span className="shop-cat-arrow">→</span>
              </div>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function DesktopShopCategory({ catId, onProduct, onBack }) {
  const cat = shopFindCategory(catId);
  const products = shopProductsInCategory(catId);
  const total = products.length;
  const refs = useRef([]);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('revealed'); });
    }, { threshold: 0.2 });
    refs.current.forEach(el => el && io.observe(el));
    return () => io.disconnect();
  }, [catId]);
  return (
    <div className="page">
      <div className="cat-head">
        <div>
          <div className="eb">/ {cat?.name?.toUpperCase() || 'KWEE STORE'}</div>
          <h1>{cat?.name || 'Shop'}</h1>
        </div>
        <div className="sub">
          {total} products<br />
          <a href="#" onClick={(e) => { e.preventDefault(); onBack(); }}
             style={{color: 'var(--ink-2)', borderBottom: '1px solid var(--line)'}}>
            ← all collections
          </a>
        </div>
      </div>
      <div style={{padding: '80px 0'}}>
        <div className="grid">
          {products.map((p, i) => (
            <a key={p.id} className="grid-card sold-out"
               ref={el => refs.current[i] = el}
               onClick={(e) => { e.preventDefault(); onProduct(p, catId); }}
               href="#"
               aria-label={`${p.name} — sold out`}
               style={{textDecoration: 'none', color: 'inherit'}}>
              <div className="img-w">
                <div className="img" style={{
                  backgroundImage: p.image ? `url(${p.image})` : 'linear-gradient(135deg, var(--bg-2), var(--accent-soft))',
                  backgroundColor: 'var(--paper)'
                }} />
                <div className="img-mask" />
                <span style={{
                  position: 'absolute', top: 18, left: 18,
                  fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.2em',
                  background: 'rgba(250,246,236,0.92)', color: 'var(--ink)',
                  padding: '6px 12px', borderRadius: 100, zIndex: 2
                }}>
                  {p.tag} · {String(i + 1).padStart(2, '0')}/{String(total).padStart(2, '0')}
                </span>
                <span className="shop-stock">Sold Out</span>
              </div>
              {p.sub && <span className="eb">{p.sub}</span>}
              <div className="ti" style={{marginBottom: 8}}>{p.name}</div>
              <span className="mono shop-price--out" style={{
                fontSize: 12, color: 'var(--accent)', letterSpacing: '0.14em',
                fontFamily: 'var(--mono)'
              }}>{p.price}</span>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function DesktopShopProduct({ product, onBack }) {
  const p = product;
  return (
    <div className="page product-detail">
      <div className="pd-img-wrap">
        <div className="pd-img" style={{backgroundImage: p.image ? `url(${p.image})` : 'none'}} />
        <span className="shop-stock">Sold Out</span>
      </div>
      <div className="pd-info">
        <button onClick={onBack}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 10,
                  marginBottom: 28,
                  fontFamily: 'var(--mono)', fontSize: 11,
                  letterSpacing: '0.18em', textTransform: 'uppercase',
                  color: 'var(--ink-2)', cursor: 'pointer'
                }}>
          ← Back to collection
        </button>
        <div className="pd-tag">{p.tag}</div>
        <h1 className="pd-name">{p.name}</h1>
        <span className="pd-price shop-price--out">{p.price}</span>
        {p.description && <p className="pd-desc">{p.description}</p>}
        {p.sub && <div className="pd-sub">{p.sub}</div>}
      </div>
    </div>
  );
}

function DesktopHomePage({ onOpen, onCat, onShop }) {
  const [activeCat, setActiveCat] = useState(null);
  return (
    <div className="page">
      <DesktopHero onOpen={onOpen} />
      <DesktopTicker />
      <DesktopCats active={activeCat} onPick={(c) => { setActiveCat(c); onCat(c); }} />
      <div className="sec-head">
        <div className="left">
          <span className="n">№ 01</span>
          <h2 className="sec-title">Editor's <em>pick</em></h2>
        </div>
        <button className="sec-more">All picks {Icon.arrow}</button>
      </div>
      <DesktopEditorSpread article={D.features[1]} onOpen={onOpen} />
      <div className="sec-head">
        <div className="left">
          <span className="n">№ 02</span>
          <h2 className="sec-title">Featured <em>—</em> ဆောင်းပါးများ</h2>
        </div>
        <button className="sec-more">View all {Icon.arrow}</button>
      </div>
      <DesktopFeatGrid items={D.features} onOpen={onOpen} />
      <div className="sec-head">
        <div className="left">
          <span className="n">№ 03</span>
          <h2 className="sec-title">Latest <em>—</em> နောက်ဆုံး</h2>
        </div>
        <button className="sec-more">All articles {Icon.arrow}</button>
      </div>
      <DesktopLatestGrid items={D.latest} onOpen={onOpen} />
      <DesktopPartners />
      <DesktopEvents />
      <DesktopShopBanner onShop={onShop} />
      <DesktopNewsletter />
    </div>
  );
}

function DesktopApp() {
  const [page, setPage] = useState({ name: 'home' });
  const [scrolled, setScrolled] = useState(false);
  const [drawer, setDrawer] = useState(false);
  const [splashGone, setSplashGone] = useState(false);
  useDesktopCursor();

  useEffect(() => {
    const t = setTimeout(() => setSplashGone(true), 1900);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const goHome = () => { setPage({ name: 'home' }); window.scrollTo({ top: 0 }); };
  const goCat = (cid) => { setPage({ name: 'category', cat: cid }); window.scrollTo({ top: 0 }); };
  const goArticle = (a) => { setPage({ name: 'article', article: a }); window.scrollTo({ top: 0 }); };
  const goShop = () => { setPage({ name: 'shop' }); window.scrollTo({ top: 0 }); };
  const goShopCat = (catId) => { setPage({ name: 'shop_cat', catId }); window.scrollTo({ top: 0 }); };
  const goShopProduct = (product, catId) => { setPage({ name: 'shop_product', product, catId }); window.scrollTo({ top: 0 }); };
  const backFromProduct = () => {
    if (page.catId != null) goShopCat(page.catId);
    else goShop();
  };

  const onDrawerNav = (id) => {
    setDrawer(false);
    if (id === 'home') goHome();
    else if (id === 'shop') goShop();
    else goCat(id);
  };

  return (
    <div className="desktop-view">
      <Splash gone={splashGone} desktop={true} />
      <div className="cursor" id="cursor"></div>
      <DesktopUtilBar />
      <DesktopTopBar scrolled={scrolled} page={page.cat || page.name}
                     onMenu={() => setDrawer(true)} onLogo={goHome}
                     onCat={goCat} onShop={goShop} />
      {page.name === 'home' && <DesktopHomePage onOpen={goArticle} onCat={goCat} onShop={goShop} />}
      {page.name === 'category' && <DesktopCategoryPage catId={page.cat} onOpen={goArticle} />}
      {page.name === 'article' && <DesktopArticlePage article={page.article} onBack={goHome} />}
      {page.name === 'shop' && <DesktopShopLanding onPick={goShopCat} />}
      {page.name === 'shop_cat' && <DesktopShopCategory catId={page.catId} onProduct={goShopProduct} onBack={goShop} />}
      {page.name === 'shop_product' && <DesktopShopProduct product={page.product} onBack={backFromProduct} />}
      <DesktopFooter onCat={goCat} onShop={goShop} />
      <DesktopDrawer open={drawer} onClose={() => setDrawer(false)} onNav={onDrawerNav} />
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
//  Root — picks mobile or desktop based on viewport
// ════════════════════════════════════════════════════════════════

function Root() {
  const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
  useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return isMobile ? <MobileApp /> : <DesktopApp />;
}

ReactDOM.createRoot(document.getElementById('app')).render(<Root />);
