/* ===========================================================
   KooshaNews — Website (home). Composes the design-system bundle.
   data-wbc-module / data-wbc-bind attributes map each block to
   the central webcasting modules (markets · news · ads · media · live).
   =========================================================== */
const { Button, Badge, Chip, Card, NewsCard, Icon, MarketStat, Spark, Ticker, Logo } = window.DesignSystem_7abc08;
const BrandLogo = Logo || function ({ size = 38 }) {
  return React.createElement('span', { style: { display: 'flex', alignItems: 'center', gap: 9 } },
    React.createElement('span', { style: { width: size, height: size, borderRadius: 'var(--r-sm)', display: 'grid', placeItems: 'center', background: 'linear-gradient(150deg, var(--gold), var(--gold-600))', color: 'var(--on-gold)', fontWeight: 900, fontSize: size*0.5 } }, 'ک'),
    React.createElement('b', { style: { fontSize: 'var(--t-h4)', fontWeight: 900, letterSpacing: '-0.02em' } }, 'کوشا', React.createElement('span', { style: { color: 'var(--gold)' } }, 'نیوز'))
  );
};
const D = window.KOOSHA;
const t = (s) => (window.KI18N ? window.KI18N.t(s) : s);
const tnum = (s) => (window.KI18N && window.KI18N.getLang() === 'en' ? window.KI18N.digits(String(s)) : s);
const CAT = Object.fromEntries(D.categories.map(c => [c.key, c.label]));
const HUE = { econ:'var(--c-econ)', market:'var(--c-market)', world:'var(--c-world)', energy:'var(--c-energy)', tech:'var(--c-tech)', gold:'var(--c-gold)', sport:'var(--c-sport)', social:'var(--c-social)', culture:'var(--c-culture)' };

/* ---------- Header ---------- */
function MarketBar() {
  return (
    <div className="market-bar scroll" data-wbc-module="markets" data-wbc-bind="ticker">
      {D.markets.map(m => (
        <div className="market-cell" key={m.symbol}>
          <span className="mc-label">{t(m.label)}</span>
          <span className="mc-value">{tnum(m.value)}</span>
          <span className={'chg ' + (m.change >= 0 ? 'is-up' : 'is-down')} style={{ padding:'1px 5px', fontSize:'var(--t-2xs)' }}>
            {m.change >= 0 ? '▲' : '▼'} {Math.abs(m.change).toFixed(2)}٪
          </span>
        </div>
      ))}
    </div>
  );
}

function go(hash) { try { window.location.hash = hash; } catch (e) {} }
function Header({ theme, onTheme, user, lang, onLang }) {
  return (
    <header style={{ position:'sticky', top:0, zIndex:40, background:'var(--bg-0)', borderBottom:'1px solid var(--line)' }}>
      <Ticker items={D.breaking.map(t)} />
      <MarketBar />
      <div className="wrap-max row between" style={{ height:'var(--header-h)', gap:18 }}>
        <a href="#/" className="row" style={{ gap:11, textDecoration:'none' }}>
          <BrandLogo size={40} />
        </a>
        <nav className="row nav-scroll" style={{ gap:2 }}>
          <a href="#/live" className="nav-link nav-live" style={{ whiteSpace:'nowrap' }}><span className="live-dot" style={{ background:'var(--live)' }}></span> {t('پخش زنده')}</a>
          {D.categories.map((c,i) => (
            <a key={c.key} href={'#/cat/'+c.key} className="nav-link" style={{ '--cat':HUE[c.key], whiteSpace:'nowrap' }}>{t(c.label)}</a>
          ))}
        </nav>
        <div className="row" style={{ gap:8 }}>
          <button className="btn btn-icon btn-ghost" aria-label={t('جستجو')}><Icon name="search" size={18} /></button>
          <button className="btn btn-icon btn-ghost" aria-label="حالت روشن/تیره" onClick={onTheme}>
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={18} />
          </button>
          <button className="btn btn-ghost btn-sm lang-switch" onClick={onLang} aria-label="language">{lang === 'fa' ? 'EN' : 'فا'}</button>
          {user
            ? <Button variant="ghost" size="sm" icon="user" onClick={() => go('#/profile')}>{(user.name && String(user.name).split(/\s+/)[0]) || t('حساب من')}</Button>
            : <Button variant="ghost" size="sm" icon="user" onClick={() => go('#/login')}>{t('ورود')}</Button>}
          <Button variant="gold" size="sm" onClick={() => go('#/subscribe')}>{t('اشتراک ویژه')}</Button>
        </div>
      </div>
    </header>
  );
}

/* ---------- Hero ---------- */
function Hero() {
  const lead = D.lead;
  return (
    <section className="wrap-max" style={{ paddingTop:24 }} data-wbc-module="news" data-wbc-bind="lead">
      <div className="hero-grid">
        <article className="news-card rise" style={{ cursor:'pointer' }}>
          <div className="nc-media" style={{ aspectRatio:'16/8' }}>
            <div className="media-ph" style={{ width:'100%', height:'100%', background:`linear-gradient(135deg, color-mix(in srgb, ${HUE[lead.category]} 30%, var(--bg-2)), var(--bg-1))` }}>
              <Icon name="coin" size={64} style={{ color:HUE[lead.category], opacity:.55 }} />
            </div>
            <div style={{ position:'absolute', insetInlineStart:14, top:14 }}><Badge category={lead.category}>{t(CAT[lead.category])}</Badge></div>
          </div>
          <div className="nc-body" style={{ padding:'20px 22px 24px', gap:12 }}>
            <div className="kicker">{t('خبر اصلی')}</div>
            <h1 className="display" style={{ fontSize:'var(--t-display)' }}>{t(lead.title)}</h1>
            <p className="lead-text">{t(lead.lead)}</p>
            <div className="nc-meta" style={{ marginTop:4 }}>
              <span className="row" style={{ gap:4 }}><Icon name="clock" size={14} />{t(lead.time)}</span>
              <span className="row" style={{ gap:4 }}><Icon name="eye" size={14} />{t(lead.views)} {t('بازدید')}</span>
            </div>
          </div>
        </article>
        <aside className="col" style={{ gap:14 }} data-wbc-bind="important">
          <div className="section-head" style={{ marginBottom:2 }}><h2 style={{ fontSize:'var(--t-h3)' }}>{t('مهم‌ترین‌ها')}</h2></div>
          {D.important.map((n,i) => (
            <a key={n.id} href={'#/news/'+n.id} className="imp-item">
              <span className="imp-num num">{tnum((i+1).toLocaleString('fa'))}</span>
              <span className="col" style={{ gap:6 }}>
                <span className="imp-title">{t(n.title)}</span>
                <span className="row" style={{ gap:8 }}>
                  <Badge category={n.category}>{t(CAT[n.category])}</Badge>
                  <span style={{ fontSize:'var(--t-xs)', color:'var(--text-3)' }}>{t(n.time)}</span>
                </span>
              </span>
            </a>
          ))}
        </aside>
      </div>
    </section>
  );
}

/* ---------- Market watch ---------- */
function MarketWatch() {
  const top = D.markets.slice(0,4);
  return (
    <section className="wrap-max sec" data-wbc-module="markets" data-wbc-bind="snapshot">
      <div className="section-head">
        <Icon name="candles" size={22} style={{ color:'var(--gold)' }} />
        <h2>{t('دیدبان بازار')}</h2>
        <span className="sh-rule"></span>
        <Button variant="ghost" size="sm" iconEnd="chevLeft">{t('همهٔ بازارها')}</Button>
      </div>
      <div className="mw-grid">
        {top.map(m => (
          <MarketStat key={m.symbol} icon={m.type==='crypto'?'cpu':m.type==='currency'?'dollar':m.type==='index'?'chart':'coin'}
            asset={{ label:t(m.label), value:tnum(m.value), change:m.change, spark:m.spark }} />
        ))}
      </div>
    </section>
  );
}

/* ---------- Latest rail ---------- */
function Latest() {
  return (
    <section className="wrap-max sec" data-wbc-module="news" data-wbc-bind="latest">
      <div className="section-head">
        <h2>{t('تازه‌ترین‌ها')}</h2><span className="sh-rule"></span>
        <div className="row" style={{ gap:6 }}>
          {D.categories.slice(0,4).map((c,i) => <Chip key={c.key} active={i===0}>{t(c.label)}</Chip>)}
        </div>
      </div>
      <div className="rail-grid">
        {D.latest.map(n => (
          <NewsCard key={n.id} title={t(n.title)} category={n.category} categoryLabel={t(CAT[n.category])} time={t(n.time)} views={t(n.views)} />
        ))}
      </div>
    </section>
  );
}

/* ---------- Ad slot ---------- */
function AdSlot({ spec, sticky }) {
  return (
    <div data-wbc-module="ads" data-wbc-bind={spec === D.ads.leaderboard ? 'leaderboard' : 'sidebar'}
      className="ad-slot" style={{ aspectRatio:`${spec.w} / ${spec.h}`, maxWidth:spec.w }}>
      <span className="dim" style={{ fontSize:'var(--t-xs)' }}><Icon name="grid" size={14} style={{ verticalAlign:'-2px', marginInlineEnd:6 }} />{t(spec.label)}</span>
    </div>
  );
}

/* ---------- Two column: most read + analysis | sidebar ---------- */
function Digest() {
  return (
    <section className="wrap-max sec">
      <div className="digest-grid">
        <div className="col" style={{ gap:34 }}>
          <div data-wbc-module="news" data-wbc-bind="mostRead">
            <div className="section-head"><Icon name="fire" size={20} style={{ color:'var(--c-energy)' }} /><h2 style={{ fontSize:'var(--t-h2)' }}>{t('پربازدیدترین')}</h2><span className="sh-rule"></span></div>
            <ol className="mostread">
              {D.mostRead.map((n,i) => (
                <li key={n.id}><a href="#" className="mr-item">
                  <span className="mr-rank num">{tnum((i+1).toLocaleString('fa'))}</span>
                  <span className="mr-title">{t(n.title)}</span>
                  <span className="mr-views num"><Icon name="eye" size={13} />{t(n.views)}</span>
                </a></li>
              ))}
            </ol>
          </div>
          <div data-wbc-module="news" data-wbc-bind="analysis">
            <div className="section-head"><Icon name="dossier" size={20} style={{ color:'var(--c-tech)' }} /><h2 style={{ fontSize:'var(--t-h2)' }}>{t('تحلیل و یادداشت')}</h2><span className="sh-rule"></span></div>
            <div className="rail-grid" style={{ gridTemplateColumns:'repeat(2,1fr)' }}>
              {D.analysis.map(a => (
                <article key={a.id} className="news-card" style={{ cursor:'pointer' }}>
                  <div className="nc-body" style={{ gap:10 }}>
                    <Badge category={a.category}>{t(a.time)}</Badge>
                    <h3 className="nc-title">{t(a.title)}</h3>
                    <span className="row" style={{ gap:7, color:'var(--text-3)', fontSize:'var(--t-xs)' }}><Icon name="user" size={13} />{t(a.author)}</span>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </div>
        <aside className="col" style={{ gap:24 }}>
          <div className="panel" style={{ padding:18 }} data-wbc-module="markets" data-wbc-bind="prices">
            <div className="row between" style={{ marginBottom:6 }}>
              <b style={{ fontSize:'var(--t-h4)' }}>{t('قیمت‌های لحظه‌ای')}</b>
              <span className="live-badge" style={{ background:'var(--up-soft)', color:'var(--up)' }}><span className="live-dot" style={{ background:'var(--up)' }}></span>{t('زنده')}</span>
            </div>
            {D.markets.slice(0,6).map(m => (
              <MarketStat key={m.symbol} variant="row" icon={m.type==='crypto'?'cpu':m.type==='currency'?'dollar':'coin'} asset={{ label:t(m.label), value:tnum(m.value), change:m.change }} />
            ))}
          </div>
          <AdSlot spec={D.ads.sidebar} />
          <div className="panel" style={{ padding:18 }} data-wbc-module="media" data-wbc-bind="videos">
            <div className="section-head" style={{ marginBottom:14 }}><Icon name="video" size={18} style={{ color:'var(--gold)' }} /><b style={{ fontSize:'var(--t-h4)' }}>{t('ویدیوها')}</b></div>
            <div className="col" style={{ gap:12 }}>
              {D.videos.slice(0,3).map(v => (
                <a key={v.id} href="#" className="vid-item">
                  <span className="vid-thumb" style={{ background:`linear-gradient(135deg, color-mix(in srgb, ${HUE[v.category]} 28%, var(--bg-2)), var(--bg-1))` }}>
                    <Icon name="play" size={18} style={{ color:'#fff' }} /><span className="vid-dur num">{tnum(v.dur)}</span>
                  </span>
                  <span className="vid-title">{t(v.title)}</span>
                </a>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}

/* ---------- Category blocks (sport / social / culture + more) ---------- */
function CategoryBlocks() {
  const keys = ['sport','social','culture'];
  return (
    <section className="wrap-max sec" data-wbc-module="news" data-wbc-bind="byCategory">
      <div className="cat-blocks">
        {keys.map(k => (
          <div className="cat-block" key={k} style={{ '--cat':HUE[k] }}>
            <div className="cat-block-head">
              <span className="cat-dot"></span>
              <h2 style={{ fontSize:'var(--t-h3)' }}>{t(CAT[k])}</h2>
              <span className="sh-rule"></span>
              <a href={'#/cat/'+k} className="cat-more" style={{ fontSize:'var(--t-xs)', color:'var(--text-3)' }}>{t('بیشتر')}</a>
            </div>
            <div className="col" style={{ gap:2 }}>
              {(D.byCategory[k]||[]).map((n,i) => (
                <a key={n.id} href="#" className="cat-item">
                  {i===0 ? (
                    <span className="cat-lead-thumb" style={{ background:`linear-gradient(135deg, color-mix(in srgb, ${HUE[k]} 30%, var(--bg-2)), var(--bg-1))` }}></span>
                  ) : null}
                  <span className="col" style={{ gap:5 }}>
                    <span className={i===0 ? 'cat-lead-title' : 'cat-row-title'}>{t(n.title)}</span>
                    <span style={{ fontSize:'var(--t-xs)', color:'var(--text-3)' }}>{t(n.time)}</span>
                  </span>
                </a>
              ))}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- Live strip + playlist ---------- */
function LiveStrip() {
  const L = D.live;
  const [cur, setCur] = React.useState(0);
  const list = L.playlist || [];
  const active = list[cur] || L.onAir;
  return (
    <section className="wrap-max sec" data-wbc-module="live" data-wbc-bind="player">
      <div className="section-head"><Icon name="broadcast" size={22} style={{ color:'var(--live)' }} /><h2>{t('پخش زنده و پلی‌لیست')}</h2><span className="sh-rule"></span></div>
      <div className="live-strip">
        <div className="live-player" data-hls={L.onAir.hls}>
          <div className="media-ph" style={{ position:'absolute', inset:0, background:`linear-gradient(135deg, color-mix(in srgb, var(--live) ${active.live?22:14}%, var(--bg-1)), var(--bg-0))` }}></div>
          <div style={{ position:'relative', zIndex:1 }} className="col center gap-3">
            <button className="play-fab"><Icon name="play" size={30} style={{ color:'#fff' }} /></button>
            {active.live ? <Badge live>{t('زنده')} · HLS</Badge> : <span className="cat-badge" style={{ '--cat':'var(--gold)' }}>{active.type || 'VOD'}</span>}
          </div>
          <div className="live-caption">
            <b>{t(active.title)}</b>
            <span className="dim num" style={{ fontSize:'var(--t-xs)' }}>
              {active.live ? <React.Fragment><Icon name="eye" size={13} style={{ verticalAlign:'-2px' }} /> {tnum(L.onAir.viewers)} {t('بیننده')}</React.Fragment> : tnum(active.dur)}
            </span>
          </div>
        </div>
        <div className="panel" style={{ padding:14 }} data-wbc-bind="playlist">
          <div className="section-head" style={{ marginBottom:10 }}><Icon name="play" size={16} style={{ color:'var(--gold)' }} /><b style={{ fontSize:'var(--t-h4)' }}>{t('پلی‌لیست')}</b><span className="sh-rule"></span><span style={{ fontSize:'var(--t-xs)', color:'var(--text-3)' }} className="num">{tnum(list.length.toLocaleString('fa'))} {t('برنامه')}</span></div>
          <div className="col" style={{ gap:2, maxHeight:280, overflow:'auto' }}>
            {list.map((p,i) => (
              <button key={p.id} className={'pl-row' + (i===cur?' is-active':'')} onClick={() => setCur(i)}>
                <span className="pl-ico">{p.live ? <span className="live-dot" style={{ background:'var(--live)' }}></span> : <Icon name="play" size={13} />}</span>
                <span className="pl-title">{t(p.title)}</span>
                <span className="num" style={{ fontSize:'var(--t-2xs)', color:p.live?'var(--live)':'var(--text-3)' }}>{tnum(p.dur)}</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer (data-driven — تغذیه از D.footer / CMS، با فالبکِ امن) ---------- */
function asLink(x) { return typeof x === 'string' ? { label: x, href: '#' } : (x || { label: '', href: '#' }); }
function Footer() {
  const F = (D && D.footer) || {};
  const sectionsTitle = F.sectionsTitle || 'بخش‌ها';
  const services = (Array.isArray(F.services) && F.services.length ? F.services : ['اشتراک ویژه', 'خبرنامه', 'اپلیکیشن', 'API بازار']).map(asLink);
  const about = (Array.isArray(F.about) && F.about.length ? F.about : [{ label: 'دربارهٔ ما', href: '#/about' }, { label: 'تماس با ما', href: '#/contact' }, { label: 'تبلیغات', href: '#' }, { label: 'قوانین', href: '#' }]).map(asLink);
  const cols = [
    { t: sectionsTitle, items: D.categories.map(c => ({ label: c.label, href: '#/cat/' + c.key })) },
    { t: F.servicesTitle || 'خدمات', items: services },
    { t: F.aboutTitle || 'کوشا ۲۴', items: about },
  ];
  const brandText = F.brand || 'پلتفرم خبری اقتصادمحور و ویدیو-محور؛ دیدبان لحظه‌ای بازار، آرشیو ویدیویی و پخش زنده.';
  const year = F.year || '۱۴۰۴';
  const copyright = F.copyright || 'تمامی حقوق محفوظ است.';
  const domain = F.domain || 'kooshanews.ir';
  return (
    <footer style={{ borderTop:'1px solid var(--line)', marginTop:48, background:'var(--bg-1)' }}>
      <div className="wrap-max" style={{ padding:'40px 20px 28px', display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr 1fr', gap:28 }}>
        <div className="col" style={{ gap:12 }}>
          <BrandLogo size={36} />
          <p className="body-text" style={{ fontSize:'var(--t-sm)', maxWidth:300 }}>{t(brandText)}</p>
        </div>
        {cols.map(col => (
          <div className="col" style={{ gap:10 }} key={col.t}>
            <b style={{ fontSize:'var(--t-sm)', color:'var(--text-1)' }}>{t(col.t)}</b>
            {col.items.map((x, i) => <a key={(x.label || '') + i} href={x.href || '#'} style={{ fontSize:'var(--t-sm)', color:'var(--text-3)' }}>{t(x.label)}</a>)}
          </div>
        ))}
      </div>
      <div className="wrap-max row between" style={{ padding:'16px 20px', borderTop:'1px solid var(--line)', fontSize:'var(--t-xs)', color:'var(--text-3)' }}>
        <span>© {tnum(year)} {t('کوشا ۲۴')} — {t(copyright)}</span>
        <span>{domain}</span>
      </div>
    </footer>
  );
}

/* ---------- Category / About / Contact pages ---------- */
function catItems(key) {
  const fromLatest = D.latest.filter(n => n.category === key);
  const fromBy = (D.byCategory[key] || []).map(n => ({ ...n, category:key }));
  const merged = [...fromLatest, ...fromBy];
  return merged.length ? merged : D.latest.map(n => ({ ...n }));
}
function catVideos(key) {
  const v = D.videos.filter(x => x.category === key);
  return v.length ? v : D.videos;
}

function CategoryPage({ catKey }) {
  const label = CAT[catKey] || 'دسته';
  const hue = HUE[catKey] || 'var(--gold)';
  const items = catItems(catKey);
  const featured = items.slice(0, Math.min(4, items.length));
  const vids = catVideos(catKey);
  const [si, setSi] = React.useState(0);
  React.useEffect(() => {
    setSi(0);
    const t = setInterval(() => setSi(i => featured.length ? (i + 1) % featured.length : 0), 5500);
    return () => clearInterval(t);
  }, [catKey]);
  const f = featured[si] || featured[0] || items[0];
  return (
    <main className="wrap-max" style={{ paddingTop:18 }} data-wbc-module="news" data-wbc-bind="category">
      <nav className="crumbs"><a href="#/">خانه</a><Icon name="chevLeft" size={13} /><span style={{ color:hue }}>{label}</span></nav>
      <header className="cat-page-head" style={{ '--cat':hue }}>
        <span className="cat-dot"></span>
        <h1 style={{ fontSize:'var(--t-display)' }}>{label}</h1>
        <span className="sh-rule"></span>
        <span className="dim num" style={{ fontSize:'var(--t-sm)' }}>{items.length.toLocaleString('fa')} خبر</span>
      </header>
      <div className="cat-layout">
        <div className="col" style={{ gap:26 }}>
          <section className="slider" style={{ '--cat':hue }} data-wbc-bind="latest">
            <div className="slide-media" style={{ background:`linear-gradient(135deg, color-mix(in srgb, ${hue} 32%, var(--bg-2)), var(--bg-1))` }}>
              <button className="play-fab"><Icon name="play" size={28} style={{ color:'#fff' }} /></button>
              <span className="slide-tag"><Badge category={catKey}>{label}</Badge></span>
              <span className="slide-vidflag num"><Icon name="video" size={13} /> ویدیو</span>
            </div>
            <div className="slide-cap">
              <div className="kicker">آخرین خبر</div>
              <h2 style={{ fontSize:'var(--t-h1)' }}>{f && f.title}</h2>
              <span className="dim num" style={{ fontSize:'var(--t-xs)' }}><Icon name="clock" size={13} style={{ verticalAlign:'-2px' }} /> {f && f.time}{f && f.views ? ` · ${f.views} بازدید` : ''}</span>
            </div>
            <div className="slide-nav">
              <button onClick={() => setSi(i => (i - 1 + featured.length) % featured.length)} aria-label="قبلی"><Icon name="chevRight" size={18} /></button>
              <div className="dots">{featured.map((_, i) => <span key={i} className={'dot' + (i === si ? ' on' : '')} onClick={() => setSi(i)}></span>)}</div>
              <button onClick={() => setSi(i => (i + 1) % featured.length)} aria-label="بعدی"><Icon name="chevLeft" size={18} /></button>
            </div>
          </section>
          <section data-wbc-bind="list">
            <div className="section-head"><h2>تیتر اخبار {label}</h2><span className="sh-rule"></span></div>
            <ol className="title-list">
              {items.map((n, i) => (
                <li key={(n.id || 'x') + '-' + i}><a href="#" className="tl-item">
                  <span className="tl-bullet" style={{ background:hue }}></span>
                  <span className="tl-title">{n.title}</span>
                  <span className="tl-time num">{n.time}</span>
                </a></li>
              ))}
            </ol>
          </section>
        </div>
        <aside className="col" style={{ gap:14 }} data-wbc-module="media" data-wbc-bind="visual">
          <div className="section-head" style={{ marginBottom:2 }}><Icon name="video" size={18} style={{ color:hue }} /><h2 style={{ fontSize:'var(--t-h3)' }}>خبرهای تصویری</h2></div>
          {vids.map((v, i) => (
            <a key={(v.id || 'v') + i} href="#" className="visual-card">
              <span className="vc-thumb" style={{ background:`linear-gradient(135deg, color-mix(in srgb, ${HUE[v.category] || hue} 30%, var(--bg-2)), var(--bg-1))` }}>
                <Icon name="play" size={20} style={{ color:'#fff' }} />
                <span className="vc-dur num">{v.dur}</span>
              </span>
              <span className="vc-title">{v.title}</span>
            </a>
          ))}
          <AdSlot spec={D.ads.sidebar} />
        </aside>
      </div>
    </main>
  );
}

function AboutPage() {
  return (
    <main className="wrap-max" style={{ paddingTop:18 }} data-wbc-module="pages" data-wbc-bind="about">
      <nav className="crumbs"><a href="#/">خانه</a><Icon name="chevLeft" size={13} /><span>دربارهٔ ما</span></nav>
      <header className="cat-page-head"><h1 style={{ fontSize:'var(--t-display)' }}>دربارهٔ کوشا ۲۴</h1><span className="sh-rule"></span></header>
      <p className="lead-text" style={{ maxWidth:760 }}>کوشا ۲۴ یک پلتفرم خبری اقتصادمحور و ویدیو-محور است؛ دیدبان لحظه‌ای بازار، آرشیو ویدیویی، پخش زندهٔ رویدادها و پوشش دسته‌های ورزشی، اجتماعی و فرهنگی.</p>
      <div className="about-grid">
        {[['bolt','مأموریت','گزارش دقیق، سریع و بی‌طرفِ بازار و جامعه.'],['video','ویدیو-محور','هر خبر مهم با روایت تصویری و پخش زنده.'],['users','اعتماد','راستی‌آزمایی منابع و شفافیت داده‌ها.']].map(([ic,t,d]) => (
          <div className="panel col" style={{ padding:20, gap:8 }} key={t}><Icon name={ic} size={22} style={{ color:'var(--gold)' }} /><b style={{ fontSize:'var(--t-h4)' }}>{t}</b><span className="dim" style={{ fontSize:'var(--t-sm)' }}>{d}</span></div>
        ))}
      </div>
    </main>
  );
}

function ContactPage() {
  return (
    <main className="wrap-max" style={{ paddingTop:18 }} data-wbc-module="pages" data-wbc-bind="contact">
      <nav className="crumbs"><a href="#/">خانه</a><Icon name="chevLeft" size={13} /><span>تماس با ما</span></nav>
      <header className="cat-page-head"><h1 style={{ fontSize:'var(--t-display)' }}>تماس با ما</h1><span className="sh-rule"></span></header>
      <div className="contact-grid">
        <form className="panel" style={{ padding:22 }} onSubmit={e => e.preventDefault()}>
          <div className="col" style={{ gap:14 }}>
            <label className="fld"><span>نام</span><input className="inp" placeholder="نام شما" /></label>
            <label className="fld"><span>ایمیل</span><input className="inp" placeholder="email@example.com" /></label>
            <label className="fld"><span>پیام</span><textarea className="inp" rows={5} placeholder="پیام شما…"></textarea></label>
            <Button variant="gold">ارسال پیام</Button>
          </div>
        </form>
        <aside className="col" style={{ gap:12 }}>
          {[['comment','ایمیل','info@kooshanews.ir'],['broadcast','تلفن','۰۲۱-۹۱۰۰۰۰۰۰'],['globe','نشانی','تهران، خیابان آزادی']].map(([ic,t,v]) => (
            <div className="panel row" style={{ padding:16, gap:12, alignItems:'center' }} key={t}><Icon name={ic} size={20} style={{ color:'var(--gold)' }} /><div className="col" style={{ gap:2 }}><b style={{ fontSize:'var(--t-sm)' }}>{t}</b><span className="dim num" style={{ fontSize:'var(--t-sm)' }}>{v}</span></div></div>
          ))}
        </aside>
      </div>
    </main>
  );
}

function LivePage() {
  const L = D.live;
  return (
    <main className="wrap-max" style={{ paddingTop:18 }} data-wbc-module="live" data-wbc-bind="page">
      <nav className="crumbs"><a href="#/">خانه</a><Icon name="chevLeft" size={13} /><span style={{ color:'var(--live)' }}>پخش زنده</span></nav>
      <header className="cat-page-head" style={{ '--cat':'var(--live)' }}>
        <span className="live-dot" style={{ background:'var(--live)', width:11, height:11 }}></span>
        <h1 style={{ fontSize:'var(--t-display)' }}>پخش زنده و آرشیو ویدیو</h1>
        <span className="sh-rule"></span>
        <span className="dim num" style={{ fontSize:'var(--t-sm)' }}>{L.onAir.viewers} بیننده</span>
      </header>
      <LiveStrip />
    </main>
  );
}

/* ---------- App + hash router ---------- */
function useHashRoute() {
  const [route, setRoute] = React.useState(() => window.location.hash || '#/');
  React.useEffect(() => {
    const on = () => { setRoute(window.location.hash || '#/'); window.scrollTo(0, 0); };
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  return route;
}

/* ---------- AI / Tech news section (sourced from reputable AI sites) ---------- */
function AINews() {
  const items = D.aiNews || [];
  const lead = items[0]; const rest = items.slice(1);
  return (
    <section className="wrap-max sec" data-wbc-module="news" data-wbc-bind="aiNews">
      <div className="section-head">
        <Icon name="cpu" size={22} style={{ color:'var(--c-tech)' }} />
        <h2 style={{ fontSize:'var(--t-h2)' }}>{t('فناوری و هوش مصنوعی')}</h2>
        <span className="ai-auto"><Icon name="bolt" size={12} /> {t('به‌روزرسانی خودکار از منابع معتبر')}</span>
        <span className="sh-rule"></span>
        <a href="#/ai" className="cat-more" style={{ fontSize:'var(--t-xs)', color:'var(--text-3)' }}>{t('همه')}</a>
      </div>
      <div className="ai-grid">
        <a href={'#/news/'+lead.id} className="ai-lead" style={{ '--cat':'var(--c-tech)' }}>
          <span className="ai-lead-thumb"><Icon name="cpu" size={52} style={{ color:'var(--c-tech)', opacity:.5 }} /></span>
          <div className="col" style={{ gap:8, padding:'4px 2px' }}>
            <span className="cat-badge" style={{ '--cat':'var(--c-tech)' }}>{t(lead.tag)}</span>
            <h3 style={{ fontSize:'var(--t-h3)', lineHeight:1.4 }}>{t(lead.title)}</h3>
            <span className="ai-src"><Icon name="link" size={12} /> {lead.source} · {t(lead.time)}</span>
          </div>
        </a>
        <ul className="ai-list">
          {rest.map(n => (
            <li key={n.id}><a href={'#/news/'+n.id} className="ai-row">
              <span className="ai-tag">{t(n.tag)}</span>
              <span className="ai-row-title">{t(n.title)}</span>
              <span className="ai-src"><Icon name="link" size={11} /> {n.source} · {t(n.time)}</span>
            </a></li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ---------- Subscription + coin wallet (webcasting coin module) ---------- */
function Subscribe() {
  const C = D.coin; const S = D.subscription;
  return (
    <section className="wrap-max sec" id="subscribe" data-wbc-module="coin" data-wbc-bind="subscription">
      <div className="section-head">
        <Icon name="coin" size={22} style={{ color:'var(--gold)' }} />
        <h2 style={{ fontSize:'var(--t-h2)' }}>{t('اشتراک ویژه و کیف پول سکه')}</h2>
        <span className="sh-rule"></span>
        <span className="coin-bal"><Icon name="coin" size={15} /> {t('موجودی')}: <b className="num">{tnum(C.balance.toLocaleString('fa'))}</b> {t('سکه')}</span>
      </div>

      <div className="sub-grid">
        {/* tiers */}
        <div className="tiers">
          {S.tiers.map(tr => (
            <div className={'tier' + (tr.hot ? ' hot' : '')} key={tr.key}>
              {tr.hot && <span className="tier-flag">{t('پیشنهاد ویژه')}</span>}
              <div className="tier-name">{t(tr.name)}</div>
              <div className="tier-price num">{t(tr.price)}</div>
              <ul className="tier-feats">
                {tr.feats.map(f => <li key={f}><Icon name="check" size={14} style={{ color:'var(--gold)' }} />{t(f)}</li>)}
              </ul>
              <Button variant={tr.hot ? 'gold' : 'ghost'} block icon={tr.coins ? 'coin' : 'user'} onClick={() => {
                if (!tr.coins) { go('#/login'); return; }
                var pk = (C.packages || []).filter(function (p) { return p.coins >= tr.coins; }).sort(function (a, b) { return a.coins - b.coins; })[0] || (C.packages || [])[0];
                if (pk) go('#/subscribe/buy/' + pk.id);
              }}>{t(tr.cta)}</Button>
            </div>
          ))}
        </div>

        {/* wallet */}
        <aside className="wallet" data-wbc-bind="wallet">
          <div className="wallet-head">
            <div>
              <span className="dim" style={{ fontSize:'var(--t-xs)' }}>{t('موجودی کیف پول')}</span>
              <div className="wallet-bal num"><Icon name="coin" size={22} style={{ color:'var(--gold)' }} /> {tnum(C.balance.toLocaleString('fa'))}</div>
              <span className="dim num" style={{ fontSize:'var(--t-xs)' }}>≈ {tnum(C.rial)} {t('ریال')}</span>
            </div>
            <span className="wbind-tag">coin · مخزن</span>
          </div>
          <div className="coin-packs">
            {C.packages.map(p => (
              <button className={'coin-pack' + (p.tag==='محبوب'?' best':'')} key={p.id} onClick={() => go('#/subscribe/buy/' + p.id)}>
                {p.tag && <span className="pack-tag">{t(p.tag)}</span>}
                <span className="pack-coins num"><Icon name="coin" size={15} style={{ color:'var(--gold)' }} /> {tnum(p.coins.toLocaleString('fa'))}</span>
                {p.bonus>0 && <span className="pack-bonus num">+{tnum(p.bonus.toLocaleString('fa'))} {t('هدیه')}</span>}
                <span className="pack-price num">{tnum(p.price)} ت</span>
              </button>
            ))}
          </div>
          <div className="unlocks">
            <span className="dim" style={{ fontSize:'var(--t-xs)' }}>{t('سکه‌ها را خرج کنید:')}</span>
            {C.unlocks.map(u => (
              <div className="unlock-row" key={u.title}>
                <span className="unlock-ic"><Icon name={u.icon} size={14} /></span>
                <span className="unlock-title">{t(u.title)}</span>
                <span className="unlock-cost num"><Icon name="coin" size={12} style={{ color:'var(--gold)' }} /> {tnum(u.cost.toLocaleString('fa'))}<i> / {t(u.note)}</i></span>
              </div>
            ))}
          </div>
        </aside>
      </div>
    </section>
  );
}

/* ---------- Single-article page ---------- */
function findArticle(id) {
  const D2 = D;
  const pools = [[D2.lead], D2.important, D2.latest, D2.analysis, D2.aiNews, ...Object.values(D2.byCategory || {})];
  for (const p of pools) { const f = (p || []).find(x => x.id === id); if (f) return f; }
  return D2.lead;
}
function ArticlePage({ id }) {
  const a = findArticle(id);
  const cat = a.category || 'tech';
  const hue = HUE[cat] || 'var(--c-tech)';
  const body = a.lead
    ? [t(a.lead), t('بر پایهٔ گزارش‌های دریافتی، این خبر به‌صورت خودکار از منبع اصلی استخراج و بازنویسی شده است. جزئیات بیشتر در حال پیگیری است.'), t('کارشناسان معتقدند پیامدهای این رویداد در روزهای آینده روشن‌تر خواهد شد؛ کوشا ۲۴ این موضوع را دنبال می‌کند.')]
    : [t('متن کامل این خبر در دسترس است.')];
  const related = (D.latest || []).filter(x => x.id !== id).slice(0, 4);
  const socials = ['telegram','instagram','x','whatsapp','link'];
  const sIcon = { telegram:'share', instagram:'image', x:'share', whatsapp:'comment', link:'link' };
  return (
    <main className="wrap-max article" style={{ paddingTop:18 }} data-wbc-module="news" data-wbc-bind="article">
      <div className="art-grid">
        <article>
          <a href={'#/cat/'+cat} className="cat-badge" style={{ '--cat':hue }}>{t(CAT[cat] || 'خبر')}</a>
          <h1 className="display art-title">{t(a.title)}</h1>
          <div className="art-meta">
            <span className="row" style={{ gap:5 }}><Icon name="clock" size={14} />{t(a.time || 'به‌تازگی')}</span>
            {a.views && <span className="row" style={{ gap:5 }}><Icon name="eye" size={14} />{t(a.views)} {t('بازدید')}</span>}
            {a.source && <span className="row" style={{ gap:5 }}><Icon name="link" size={13} /> {t('منبع:')} <code>{a.source}</code></span>}
            {a.author && <span className="row" style={{ gap:5 }}><Icon name="user" size={13} />{t(a.author)}</span>}
          </div>
          <div className="art-cover" style={{ background:`linear-gradient(135deg, color-mix(in srgb, ${hue} 30%, var(--bg-2)), var(--bg-1))` }}>
            <Icon name={cat==='tech'?'cpu':'coin'} size={64} style={{ color:hue, opacity:.5 }} />
          </div>
          <div className="art-body">
            {body.map((p,i) => <p key={i}>{p}</p>)}
          </div>
          <div className="art-share">
            <span className="dim" style={{ fontSize:'var(--t-sm)' }}>{t('اشتراک‌گذاری:')}</span>
            {socials.map(s => <button key={s} className="share-btn" aria-label={s}><Icon name={sIcon[s]} size={16} /></button>)}
            <span className="art-src-note"><Icon name="link" size={12} /> {t('بازنشر با ذکر منبع کوشا ۲۴')}</span>
          </div>
        </article>
        <aside className="col" style={{ gap:20 }}>
          <div className="panel" style={{ padding:18 }} data-wbc-module="markets" data-wbc-bind="prices">
            <b style={{ fontSize:'var(--t-h4)' }}>{t('دادهٔ بازار')}</b>
            <div style={{ marginTop:10 }}>
              {D.markets.slice(0,4).map(m => (
                <MarketStat key={m.symbol} variant="row" icon={m.type==='crypto'?'cpu':m.type==='currency'?'dollar':'coin'} asset={{ label:t(m.label), value:tnum(m.value), change:m.change }} />
              ))}
            </div>
          </div>
          <div className="panel" style={{ padding:18 }}>
            <div className="section-head" style={{ marginBottom:12 }}><Icon name="fire" size={16} style={{ color:'var(--c-energy)' }} /><b style={{ fontSize:'var(--t-h4)' }}>{t('مرتبط')}</b></div>
            <div className="col" style={{ gap:2 }}>
              {related.map(r => (
                <a key={r.id} href={'#/news/'+r.id} className="tl-item" style={{ padding:'10px 2px' }}>
                  <span className="tl-bullet" style={{ background:HUE[r.category] }}></span>
                  <span className="col" style={{ gap:3 }}><span style={{ fontSize:'var(--t-sm)', lineHeight:1.5 }}>{t(r.title)}</span><span style={{ fontSize:'var(--t-xs)', color:'var(--text-3)' }}>{t(r.time)}</span></span>
                </a>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </main>
  );
}

function HomePage() {
  return (
    <main>
      <Hero />
      <div className="wrap-max sec"><AdSlot spec={D.ads.leaderboard} /></div>
      <MarketWatch />
      <Latest />
      <CategoryBlocks />
      <AINews />
      <LiveStrip />
      <Subscribe />
      <Digest />
    </main>
  );
}

/* ---------- Auth modal (login / special-subscription signup) ---------- */
function AuthModal({ mode, onClose, onSwitch }) {
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => { setSent(false); }, [mode]);
  if (!mode) return null;
  const isSignup = mode === 'signup';
  return (
    <div className="auth-overlay" onClick={onClose}>
      <div className="auth-card" onClick={e => e.stopPropagation()} data-wbc-module="users" data-wbc-bind="auth">
        <button className="auth-x" onClick={onClose} aria-label="بستن"><Icon name="close" size={18} /></button>
        <div className="auth-head">
          <BrandLogo size={34} />
          <h3 className="display">{isSignup ? 'اشتراک ویژهٔ کوشا ۲۴' : 'ورود به حساب'}</h3>
          <p className="auth-sub">
            {isSignup
              ? 'برای دریافت خبرهای ویژه، تحلیل‌ها و خبرنامهٔ بازار عضو شوید.'
              : 'با شمارهٔ موبایل، کد ورود و رمز عبور وارد شوید.'}
          </p>
        </div>

        <div className="auth-body">
          {isSignup && (
            <label className="auth-field">
              <span>نام و نام خانوادگی</span>
              <input type="text" placeholder="مثلاً سارا کاویانی" />
            </label>
          )}
          <label className="auth-field">
            <span>موبایل یا ایمیل</span>
            <input type="text" placeholder="۰۹۱۲۳۴۵۶۷۸۹" dir="ltr" />
          </label>

          <label className="auth-field">
            <span>کد ورود (پیامک‌شده)</span>
            <div className="auth-code">
              <input type="text" placeholder="— — — — — —" dir="ltr" maxLength={6} />
              <button className="auth-code-btn" onClick={() => setSent(true)}>
                {sent ? 'کد ارسال شد ✓' : 'ارسال کد'}
              </button>
            </div>
          </label>

          <label className="auth-field">
            <span>رمز عبور</span>
            <input type="password" placeholder="••••••••" dir="ltr" />
          </label>

          <Button variant="gold" icon="arrow" block>{isSignup ? 'ثبت‌نام و فعال‌سازی اشتراک' : 'ورود'}</Button>

          <div className="auth-alt">
            <span>روش جایگزین:</span>
            <button className="auth-link">ورود با گوگل</button>
          </div>
        </div>

        <div className="auth-foot">
          {isSignup ? (
            <span>حساب دارید؟ <button className="auth-link" onClick={() => onSwitch('login')}>وارد شوید</button></span>
          ) : (
            <span>هنوز عضو نیستید؟ <button className="auth-link" onClick={() => onSwitch('signup')}>اشتراک ویژه بگیرید</button></span>
          )}
        </div>
        <div className="auth-note"><Icon name="lock" size={12} /> ورود امن مطابق سامانهٔ یکپارچهٔ وب‌کستینگ — کد و رمز هم‌زمان</div>
      </div>
    </div>
  );
}

/* ---------- Auth helper (پلِ احرازِ هویتِ بازدیدکننده؛ هم‌کلیدِ ماژول‌های مرکزی) ----------
   از helperهای WCAuth (apiBase/siteId) استفاده می‌کند اگر آماده باشند؛ وگرنه خودش
   public-meta را می‌گیرد. توکن با همان کلیدِ مرکزی (wc_visitor_<siteId>) ذخیره می‌شود
   تا وضعیت با wc-auth/wc-account هم‌گام بماند. */
const AUTH = {
  api: function () { try { return (window.WCAuth && WCAuth.apiBase && WCAuth.apiBase()) || '/api/v1'; } catch (e) { return '/api/v1'; } },
  slug: function () { return (window.WC_SITE && window.WC_SITE.slug) || 'kushanews'; },
  _sid: null, _sidP: null,
  siteId: function () {
    if (this._sid) return Promise.resolve(this._sid);
    try { var s = window.WCAuth && WCAuth.siteId && WCAuth.siteId(); if (s) { this._sid = s; return Promise.resolve(s); } } catch (e) {}
    if (this._sidP) return this._sidP;
    var self = this;
    this._sidP = fetch(this.api() + '/sites/slug/' + encodeURIComponent(this.slug()) + '/public-meta', { cache: 'no-store' })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (m) { self._sid = (m && m.id) || null; return self._sid; })
      .catch(function () { return null; });
    return this._sidP;
  },
  tkey: function (sid) { return 'wc_visitor_' + (sid || this._sid || this.slug()); },
  token: function () { try { return localStorage.getItem(this.tkey(this._sid)); } catch (e) { return null; } },
  setToken: function (sid, tok) { try { localStorage.setItem('wc_visitor_' + sid, tok); } catch (e) {} },
  clear: function () { try { localStorage.removeItem(this.tkey(this._sid)); } catch (e) {} },
  me: function () {
    var self = this;
    return this.siteId().then(function (sid) {
      if (!sid) return null;
      var tok = null; try { tok = localStorage.getItem('wc_visitor_' + sid); } catch (e) {}
      if (!tok) return null;
      return fetch(self.api() + '/sites/' + sid + '/visitor-auth/me', { headers: { Authorization: 'Bearer ' + tok }, cache: 'no-store' })
        .then(function (r) { return r.ok ? r.json() : null; })
        .then(function (d) { return (d && d.visitor) || null; })
        .catch(function () { return null; });
    });
  },
};

/* ---------- SHOP helper — محصولاتِ عمومیِ سایت (بستهٔ سکه) از /public/products ----------
   بستهٔ سکه‌ای که در پنل به‌عنوان «محصول» تعریف شده باشد را با شمارهٔ سکه یا slug
   (coin-<n>) به بستهٔ استاتیکِ نمایشی نگاشت می‌کند. اگر محصولِ واقعی موجود نبود،
   خریدِ آنلاین «هنوز فعال نشده» نشان داده می‌شود (بدون فراخوانیِ خطازا). */
const SHOP = {
  _p: null,
  products: function () {
    if (this._p) return this._p;
    var self = this;
    this._p = AUTH.siteId().then(function (sid) {
      if (!sid) return [];
      return fetch(AUTH.api() + '/sites/' + sid + '/public/products', { cache: 'no-store' })
        .then(function (r) { return r.ok ? r.json() : []; })
        .then(function (list) { return Array.isArray(list) ? list : []; })
        .catch(function () { return []; });
    });
    return this._p;
  },
  // محصولِ واقعیِ سکه را برای یک بستهٔ استاتیک پیدا می‌کند (بر پایهٔ attributes.coins یا slug=coin-<n>)
  matchCoinProduct: function (list, pack) {
    if (!Array.isArray(list) || !pack) return null;
    var coins = Number(pack.coins) || 0;
    var slug = 'coin-' + coins;
    return list.find(function (p) {
      var a = (p && p.attributes) || {};
      return Number(a.coins || 0) === coins || (p.slug || '') === slug;
    }) || null;
  },
};

/* ---------- LoginView — ویوِ تمام‌صفحه (spa) با chrome/برندِ کوشا ۲۴ ---------- */
function LoginView() {
  const [mode, setMode] = React.useState('login');   // login | register
  const [via, setVia] = React.useState('mobile');    // email | mobile (register only)
  const [vals, setVals] = React.useState({ id: '', pass: '', name: '', email2: '' });
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [me, setMe] = React.useState(undefined);     // undefined=loading · null=guest · obj=user
  React.useEffect(() => { let a = true; AUTH.me().then(u => { if (a) setMe(u || null); }); return () => { a = false; }; }, []);
  function set(k, v) { setVals(s => Object.assign({}, s, { [k]: v })); }
  function submit(e) {
    e.preventDefault(); setErr('');
    const id = (vals.id || '').trim(), pass = vals.pass || '', name = (vals.name || '').trim(), email2 = (vals.email2 || '').trim();
    if (!id) { setErr(mode === 'register' && via === 'mobile' ? 'شمارهٔ موبایل را وارد کنید.' : 'شناسه را وارد کنید.'); return; }
    if (pass.length < 6) { setErr('رمز عبور حداقل ۶ کاراکتر باشد.'); return; }
    setBusy(true);
    AUTH.siteId().then(function (sid) {
      if (!sid) { setErr('سایت در دسترس نیست؛ کمی بعد دوباره تلاش کنید.'); setBusy(false); return; }
      var path = mode === 'register' ? 'register' : 'login';
      var body = mode === 'register'
        ? (via === 'mobile' ? { name: name, phone: id, email: email2 || undefined, password: pass } : { name: name, email: id, password: pass })
        : { identifier: id, password: pass };
      fetch(AUTH.api() + '/sites/' + sid + '/visitor-auth/' + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
        .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
        .then(function (res) {
          if (!res.ok) throw new Error((res.j && (res.j.message || res.j.error)) || 'خطا در ورود');
          AUTH.setToken(sid, res.j.token);
          try { if (window.WCAuth && WCAuth.welcome) WCAuth.welcome(res.j.visitor && res.j.visitor.name); } catch (e2) {}
          go('#/profile');
        })
        .catch(function (e2) { setErr(e2.message || 'خطا رخ داد'); setBusy(false); });
    });
  }
  const reg = mode === 'register';
  return (
    <main className="auth-view">
      <div className="auth-shell">
        <div className="panel">
          <div className="auth-brand">
            <BrandLogo size={42} />
            <span className="sub">{me ? t('شما وارد حساب خود هستید.') : (reg ? t('حساب تازه بسازید و اشتراکِ ویژه را فعال کنید.') : t('به حسابِ کوشا ۲۴ِ خود وارد شوید.'))}</span>
          </div>
          {me ? (
            <div className="col" style={{ gap: 12 }}>
              <Button variant="gold" icon="user" block onClick={() => go('#/profile')}>{t('ورود به حساب کاربری')}</Button>
              <Button variant="ghost" block onClick={() => { AUTH.clear(); try { if (window.WCAuth && WCAuth.logout) WCAuth.logout(); } catch (e) {} setMe(null); }}>{t('خروج از حساب')}</Button>
            </div>
          ) : (
            <React.Fragment>
              <div className="seg">
                <button className={!reg ? 'on' : ''} onClick={() => { setMode('login'); setErr(''); }}>{t('ورود')}</button>
                <button className={reg ? 'on' : ''} onClick={() => { setMode('register'); setErr(''); }}>{t('ساخت حساب')}</button>
              </div>
              {reg && (
                <div className="seg via">
                  <button className={via === 'mobile' ? 'on' : ''} onClick={() => setVia('mobile')}>📱 {t('موبایل')}</button>
                  <button className={via === 'email' ? 'on' : ''} onClick={() => setVia('email')}>✉ {t('ایمیل')}</button>
                </div>
              )}
              <form onSubmit={submit}>
                {reg && <label className="fld"><span>{t('نام و نام خانوادگی')}</span><input className="inp" value={vals.name} onChange={e => set('name', e.target.value)} placeholder="مثلاً سارا کاویانی" autoComplete="name" /></label>}
                <label className="fld">
                  <span>{reg ? (via === 'mobile' ? t('شمارهٔ موبایل') : t('ایمیل')) : t('ایمیل یا موبایل')}</span>
                  <input className="inp" dir="ltr" value={vals.id} onChange={e => set('id', e.target.value)} placeholder={reg ? (via === 'mobile' ? '۰۹۱۲۳۴۵۶۷۸۹' : 'you@example.com') : 'you@example.com یا ۰۹۱۲…'} autoComplete="username" />
                </label>
                {reg && via === 'mobile' && <label className="fld"><span>{t('ایمیل (اختیاری)')}</span><input className="inp" dir="ltr" type="email" value={vals.email2} onChange={e => set('email2', e.target.value)} placeholder="you@example.com" autoComplete="email" /></label>}
                <label className="fld"><span>{t('رمز عبور')}</span><input className="inp" type="password" value={vals.pass} onChange={e => set('pass', e.target.value)} placeholder="حداقل ۶ کاراکتر" autoComplete={reg ? 'new-password' : 'current-password'} /></label>
                {err && <div className="auth-msg">{err}</div>}
                <button type="submit" className="btn btn-gold btn-block" disabled={busy} style={{ marginTop: 8 }}>{busy ? t('لطفاً صبر کنید…') : (reg ? t('ساخت حساب') : t('ورود به حساب'))}</button>
              </form>
              <div className="auth-hint">{t('ورودِ امن مطابقِ سامانهٔ یکپارچهٔ وب‌کستینگ — با رمز عبور.')}</div>
            </React.Fragment>
          )}
          <a className="auth-back" href="#/">‹ {t('بازگشت به سایت')}</a>
        </div>
      </div>
    </main>
  );
}

/* ---------- ProfileView — صفحهٔ کاملِ حساب (نه مودال) ---------- */
function ProfileView() {
  const [u, setU] = React.useState(undefined);   // undefined=loading · null=unavailable
  const [tab, setTab] = React.useState('profile');
  const [form, setForm] = React.useState({ name: '', phone: '', email: '', address: '', gender: '', ageRange: '' });
  const [orders, setOrders] = React.useState(undefined);
  const [ok, setOk] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const sidRef = React.useRef(null);
  React.useEffect(() => {
    let alive = true;
    AUTH.siteId().then(function (sid) {
      if (!alive) return;
      sidRef.current = sid;
      if (!sid) { setU(null); return; }
      var tok = null; try { tok = localStorage.getItem('wc_visitor_' + sid); } catch (e) {}
      if (!tok) { go('#/login'); return; }
      fetch(AUTH.api() + '/sites/' + sid + '/visitor-auth/me', { headers: { Authorization: 'Bearer ' + tok }, cache: 'no-store' })
        .then(function (r) { if (!r.ok) throw 0; return r.json(); })
        .then(function (d) { if (!alive) return; var v = d.visitor || {}; setU(v); setForm({ name: v.name || '', phone: v.phone || '', email: v.email || '', address: v.address || '', gender: v.gender || '', ageRange: v.ageRange || '' }); })
        .catch(function () { try { localStorage.removeItem('wc_visitor_' + sid); } catch (e) {} go('#/login'); });
    });
    return function () { alive = false; };
  }, []);
  React.useEffect(() => {
    if (tab !== 'orders' || orders !== undefined) return;
    var sid = sidRef.current; if (!sid) { setOrders([]); return; }
    var tok = null; try { tok = localStorage.getItem('wc_visitor_' + sid); } catch (e) {}
    fetch(AUTH.api() + '/sites/' + sid + '/visitor-auth/orders', { headers: { Authorization: 'Bearer ' + tok }, cache: 'no-store' })
      .then(function (r) { return r.ok ? r.json() : []; }).then(function (list) { setOrders(Array.isArray(list) ? list : []); })
      .catch(function () { setOrders([]); });
  }, [tab]);
  function setF(k, v) { setForm(s => Object.assign({}, s, { [k]: v })); }
  function save(e) {
    e.preventDefault();
    var sid = sidRef.current; var tok = null; try { tok = localStorage.getItem('wc_visitor_' + sid); } catch (e2) {}
    if (!sid || !tok) return;
    if (!form.name || form.name.trim().length < 2) { setF('name', form.name); return; }
    setSaving(true); setOk(false);
    fetch(AUTH.api() + '/sites/' + sid + '/visitor-auth/me', { method: 'PATCH', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tok }, body: JSON.stringify({ name: form.name.trim(), phone: form.phone.trim(), email: form.email.trim(), address: form.address.trim(), gender: form.gender, ageRange: form.ageRange }) })
      .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
      .then(function (res) { setSaving(false); if (res.ok && res.j.visitor) { setU(res.j.visitor); setOk(true); try { if (window.WCAuth && WCAuth.refresh) WCAuth.refresh(); } catch (e3) {} setTimeout(function () { setOk(false); }, 2200); } })
      .catch(function () { setSaving(false); });
  }
  function logout() {
    var sid = sidRef.current; try { localStorage.removeItem('wc_visitor_' + (sid || '')); } catch (e) {}
    try { if (window.WCAuth && WCAuth.logout) WCAuth.logout(); } catch (e) {}
    go('#/');
  }
  if (u === undefined) return <main className="account-view"><div className="account-empty">{t('در حال بارگذاری…')}</div></main>;
  if (u === null) return <main className="account-view"><div className="account-empty">{t('سایت در دسترس نیست')}</div></main>;
  const missing = [];
  if (!u.phone) missing.push('موبایل');
  if (!u.email) missing.push('ایمیل');
  if (!u.address) missing.push('آدرس');
  const first = (u.name && String(u.name).split(/\s+/)[0]) || '';
  return (
    <main className="account-view">
      <div className="account-head">
        <a href="#/" style={{ color: 'var(--text-2)', textDecoration: 'none', fontSize: 'var(--t-sm)' }}>‹ {t('بازگشت به سایت')}</a>
        <button className="btn btn-ghost btn-sm" onClick={logout}>⎋ {t('خروج از حساب')}</button>
      </div>
      <h1 className="display" style={{ fontSize: 'var(--t-h1)', marginBottom: 6 }}>{t('سلام')} {first} 👋</h1>
      <div className="account-tabs">
        <button className={tab === 'profile' ? 'on' : ''} onClick={() => setTab('profile')}>👤 {t('مشخصات')}</button>
        <button className={tab === 'orders' ? 'on' : ''} onClick={() => setTab('orders')}>🧾 {t('سفارش‌های من')}</button>
      </div>
      {tab === 'profile' && (
        <div className="account-pane">
          {missing.length > 0 && <div className="miss-alert">⚠️ {t('برای تجربهٔ کامل این موارد را تکمیل کنید:')} {missing.join('، ')}</div>}
          <form className="panel" onSubmit={save}>
            <h3>{t('مشخصاتِ حساب')}</h3>
            <label className="fld"><span>{t('نام و نام خانوادگی')}</span><input className="inp" value={form.name} onChange={e => setF('name', e.target.value)} /></label>
            <label className="fld"><span>{t('موبایل')}</span><input className={'inp' + (!u.phone ? ' miss' : '')} dir="ltr" value={form.phone} onChange={e => setF('phone', e.target.value)} placeholder="۰۹۱۲…" /></label>
            <label className="fld"><span>{t('ایمیل')}</span><input className={'inp' + (!u.email ? ' miss' : '')} dir="ltr" type="email" value={form.email} onChange={e => setF('email', e.target.value)} placeholder="you@example.com" /></label>
            <label className="fld"><span>{t('آدرسِ تحویل')}</span><textarea className="inp" rows={3} value={form.address} onChange={e => setF('address', e.target.value)} placeholder="استان، شهر، خیابان، پلاک، کدپستی" /></label>
            <div className="row" style={{ gap: 12 }}>
              <label className="fld" style={{ flex: 1 }}><span>{t('جنسیت')}</span>
                <select className="inp" value={form.gender} onChange={e => setF('gender', e.target.value)}>
                  <option value="">{t('انتخاب کنید…')}</option><option value="female">خانم</option><option value="male">آقا</option><option value="other">سایر</option>
                </select></label>
              <label className="fld" style={{ flex: 1 }}><span>{t('رنج سنی')}</span>
                <select className="inp" value={form.ageRange} onChange={e => setF('ageRange', e.target.value)}>
                  <option value="">{t('انتخاب کنید…')}</option><option value="under18">زیر ۱۸</option><option value="18-25">۱۸ تا ۲۵</option><option value="26-35">۲۶ تا ۳۵</option><option value="36-45">۳۶ تا ۴۵</option><option value="46-60">۴۶ تا ۶۰</option><option value="60plus">بالای ۶۰</option>
                </select></label>
            </div>
            <button type="submit" className="btn btn-gold btn-block" disabled={saving} style={{ marginTop: 8 }}>{saving ? t('در حال ذخیره…') : t('ذخیرهٔ تغییرات')}</button>
            {ok && <div className="ok-msg">✓ {t('ذخیره شد')}</div>}
          </form>
        </div>
      )}
      {tab === 'orders' && (
        <div className="account-pane">
          {orders === undefined && <div className="account-empty">{t('در حال بارگذاری…')}</div>}
          {orders && orders.length === 0 && <div className="account-empty">🧾<p style={{ marginTop: 10 }}>{t('هنوز سفارشی ثبت نکرده‌اید.')}</p></div>}
          {orders && orders.length > 0 && orders.map(function (o) {
            var cls = o.status === 'PAID' ? 'paid' : (o.status === 'PENDING' ? 'pend' : 'other');
            var lbl = o.status === 'PAID' ? 'پرداخت‌شده' : (o.status === 'PENDING' ? 'در انتظار پرداخت' : o.status);
            return (
              <div className="ord-card" key={o.orderNumber || o.id}>
                <div className="top"><span className="num">{o.orderNumber || ''}</span><span className={'ord-badge ' + cls}>{lbl}</span></div>
                {(o.items || []).map(function (it, ix) { return <div className="it" key={ix}>• {(it.title && (it.title.fa || it.title)) || 'محصول'} ×{(Number(it.quantity) || 1).toLocaleString('fa-IR')}</div>; })}
                <div className="tot">{t('مبلغ:')} {(Number(o.totalPrice) || 0).toLocaleString('fa-IR')} {t('تومان')}</div>
                {o.trackingCode && <div className="it">{t('کد رهگیری:')} <b dir="ltr">{o.trackingCode}</b></div>}
              </div>
            );
          })}
        </div>
      )}
    </main>
  );
}

/* ---------- CheckoutView — خریدِ بستهٔ سکه (سفرِ خرید منطبق با مدلِ اشتراکِ سکه‌ای) ----------
   فلو: انتخابِ بستهٔ سکه → ورودِ visitor-auth (اگر توکن نبود → #/login) → تکمیل/ذخیرهٔ
   مشخصات (PATCH me) + کدِ تخفیفِ اختیاری (/public/coupons/validate) → POST /public/checkout
   → paymentUrl → درگاه. تنها اندپوینت‌های موجود سیم‌کشی شده‌اند. اگر محصولِ سکه در پنل
   seed نشده باشد، دکمهٔ پرداخت با پیامِ روشن غیرفعال می‌ماند (backendGap). */
function CheckoutView({ packId }) {
  const C = D.coin;
  const pack = (C.packages || []).find(p => p.id === packId) || (C.packages || [])[0] || { coins: 0, price: '—', id: 'x' };
  const [me, setMe] = React.useState(undefined);        // undefined=loading · null=unavailable
  const [prod, setProd] = React.useState(undefined);    // undefined=loading · null=not-seeded · obj=real product
  const [form, setForm] = React.useState({ name: '', phone: '', email: '', address: '' });
  const [coupon, setCoupon] = React.useState('');
  const [applied, setApplied] = React.useState(null);   // {code, discount}
  const [cpnMsg, setCpnMsg] = React.useState('');
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const sidRef = React.useRef(null);
  React.useEffect(() => {
    let alive = true;
    AUTH.siteId().then(function (sid) {
      if (!alive) return;
      sidRef.current = sid;
      if (!sid) { setMe(null); return; }
      var tok = null; try { tok = localStorage.getItem('wc_visitor_' + sid); } catch (e) {}
      if (!tok) { go('#/login'); return; }
      fetch(AUTH.api() + '/sites/' + sid + '/visitor-auth/me', { headers: { Authorization: 'Bearer ' + tok }, cache: 'no-store' })
        .then(function (r) { if (!r.ok) throw 0; return r.json(); })
        .then(function (d) { if (!alive) return; var v = d.visitor || {}; setMe(v); setForm({ name: v.name || '', phone: v.phone || '', email: v.email || '', address: v.address || '' }); })
        .catch(function () { try { localStorage.removeItem('wc_visitor_' + sid); } catch (e) {} go('#/login'); });
    });
    SHOP.products().then(function (list) { if (!alive) return; setProd(SHOP.matchCoinProduct(list, pack) || null); });
    return function () { alive = false; };
  }, [packId]);
  function setF(k, v) { setForm(s => Object.assign({}, s, { [k]: v })); }
  function applyCoupon() {
    var code = (coupon || '').trim().toUpperCase();
    if (!code) { setCpnMsg(t('کدِ تخفیف را وارد کنید.')); return; }
    var sid = sidRef.current; if (!sid) return;
    var base = prod ? (Number(prod.price) || 0) : 0;
    setCpnMsg(t('در حال بررسی…'));
    fetch(AUTH.api() + '/sites/' + sid + '/public/coupons/validate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: code, scope: 'order', amount: base }) })
      .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
      .then(function (res) {
        if (res.ok && res.j && res.j.valid) { setApplied({ code: res.j.code, discount: res.j.discount || 0 }); setCpnMsg(''); }
        else { setApplied(null); setCpnMsg((res.j && res.j.message) || t('کدِ تخفیف نامعتبر است.')); }
      })
      .catch(function () { setCpnMsg(t('خطا در بررسیِ کد.')); });
  }
  function pay() {
    setErr('');
    var sid = sidRef.current; var tok = null; try { tok = localStorage.getItem('wc_visitor_' + sid); } catch (e) {}
    if (!sid || !tok) { go('#/login'); return; }
    if (!prod) { setErr(t('این بسته هنوز برای خریدِ آنلاین فعال نشده است.')); return; }
    var name = (form.name || '').trim(), phone = (form.phone || '').trim(), email = (form.email || '').trim(), address = (form.address || '').trim();
    if (!name || !phone || !address) { setErr(t('نام، موبایل و آدرس الزامی است.')); return; }
    setBusy(true);
    fetch(AUTH.api() + '/sites/' + sid + '/visitor-auth/me', { method: 'PATCH', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tok }, body: JSON.stringify({ name: name, phone: phone, email: email, address: address }) }).catch(function () {});
    var body = { items: [{ productId: prod.id, quantity: 1 }], customerName: name, customerPhone: phone, customerEmail: email, customerAddress: address, callbackUrl: location.origin + location.pathname + '#/subscribe/complete' };
    if (applied && applied.code) body.couponCode = applied.code;
    fetch(AUTH.api() + '/sites/' + sid + '/public/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
      .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
      .then(function (res) { if (res.j && res.j.paymentUrl) { location.href = res.j.paymentUrl; } else { setBusy(false); setErr((res.j && res.j.message) || t('خطا در ثبتِ سفارش')); } })
      .catch(function () { setBusy(false); setErr(t('خطا در اتصال به درگاه')); });
  }
  if (me === undefined || prod === undefined) return <main className="account-view"><div className="account-empty">{t('در حال بارگذاری…')}</div></main>;
  if (me === null) return <main className="account-view"><div className="account-empty">{t('سایت در دسترس نیست')}</div></main>;
  const price = prod ? (Number(prod.price) || 0) : null;
  const disc = applied ? (applied.discount || 0) : 0;
  const total = price != null ? Math.max(0, price - disc) : null;
  const fa = (n) => (Number(n) || 0).toLocaleString('fa-IR');
  return (
    <main className="wrap-max" style={{ paddingTop: 18, maxWidth: 720 }} data-wbc-module="coin" data-wbc-bind="checkout">
      <nav className="crumbs"><a href="#/">{t('خانه')}</a><Icon name="chevLeft" size={13} /><a href="#/subscribe">{t('اشتراک ویژه')}</a><Icon name="chevLeft" size={13} /><span style={{ color: 'var(--gold)' }}>{t('پرداخت')}</span></nav>
      <header className="cat-page-head"><Icon name="coin" size={22} style={{ color: 'var(--gold)' }} /><h1 style={{ fontSize: 'var(--t-h1)' }}>{t('خریدِ بستهٔ سکه')}</h1><span className="sh-rule"></span></header>
      {!prod && <div className="miss-alert">⚠️ {t('خریدِ آنلاینِ این بسته هنوز فعال نشده است. برای فعال‌سازی باید بستهٔ سکه به‌عنوان محصول در پنل تعریف شود.')}</div>}
      <div className="panel" style={{ padding: 20, marginBottom: 16 }}>
        <div className="row between" style={{ marginBottom: 12 }}>
          <b style={{ fontSize: 'var(--t-h4)' }}>{t('خلاصهٔ سفارش')}</b>
          {pack.tag && <span className="pack-tag" style={{ position: 'static' }}>{t(pack.tag)}</span>}
        </div>
        <div className="row between" style={{ padding: '6px 0' }}>
          <span className="row" style={{ gap: 8 }}><Icon name="coin" size={16} style={{ color: 'var(--gold)' }} /> {tnum((Number(pack.coins) || 0).toLocaleString('fa'))} {t('سکه')}{pack.bonus > 0 ? ' + ' + tnum((pack.bonus).toLocaleString('fa')) + ' ' + t('هدیه') : ''}</span>
          <span className="num">{price != null ? fa(price) + ' ' + t('تومان') : tnum(pack.price) + ' ت'}</span>
        </div>
        {disc > 0 && <div className="row between" style={{ padding: '6px 0', color: 'var(--up)' }}><span>{t('تخفیف')}</span><span className="num">− {fa(disc)} {t('تومان')}</span></div>}
        {total != null && <div className="row between" style={{ padding: '10px 0 0', borderTop: '1px solid var(--line)', marginTop: 6 }}><b>{t('مبلغ قابل پرداخت')}</b><b className="num" style={{ color: 'var(--gold)' }}>{fa(total)} {t('تومان')}</b></div>}
      </div>
      <div className="panel" style={{ padding: 20 }}>
        <b style={{ fontSize: 'var(--t-h4)' }}>👤 {t('مشخصاتِ خریدار')}</b>
        {(function () { var miss = []; if (!me.phone) miss.push('موبایل'); if (!me.email) miss.push('ایمیل'); if (!me.address) miss.push('آدرس'); return miss.length ? <div className="miss-alert" style={{ marginTop: 10 }}>⚠️ {t('برای تکمیلِ خرید این موارد لازم است:')} {miss.join('، ')}</div> : null; })()}
        <label className="fld"><span>{t('نام و نام خانوادگی')}</span><input className="inp" value={form.name} onChange={e => setF('name', e.target.value)} /></label>
        <label className="fld"><span>{t('موبایل')}</span><input className={'inp' + (!me.phone ? ' miss' : '')} dir="ltr" value={form.phone} onChange={e => setF('phone', e.target.value)} placeholder="۰۹۱۲…" /></label>
        <label className="fld"><span>{t('ایمیل')}</span><input className={'inp' + (!me.email ? ' miss' : '')} dir="ltr" type="email" value={form.email} onChange={e => setF('email', e.target.value)} placeholder="you@example.com" /></label>
        <label className="fld"><span>{t('آدرس')}</span><textarea className={'inp' + (!me.address ? ' miss' : '')} rows={2} value={form.address} onChange={e => setF('address', e.target.value)} placeholder="استان، شهر، خیابان، پلاک، کدپستی" /></label>
        <label className="fld"><span>{t('کدِ تخفیف (اختیاری)')}</span>
          <div className="row" style={{ gap: 8 }}>
            <input className="inp" dir="ltr" value={coupon} onChange={e => setCoupon(e.target.value)} placeholder="KOOSHA10" style={{ flex: 1 }} disabled={!prod} />
            <button type="button" className="btn btn-ghost" onClick={applyCoupon} disabled={!prod}>{t('اعمال')}</button>
          </div>
        </label>
        {cpnMsg && <div className="auth-msg" style={{ marginTop: 4 }}>{cpnMsg}</div>}
        {applied && <div className="ok-msg">✓ {t('کدِ تخفیف')} <b>{applied.code}</b> {t('اعمال شد')}</div>}
        {err && <div className="auth-msg" style={{ marginTop: 8 }}>{err}</div>}
        <button type="button" className="btn btn-gold btn-block" style={{ marginTop: 14 }} disabled={busy || !prod} onClick={pay}>
          {busy ? t('در حال انتقال به درگاه…') : (prod ? (t('پرداخت') + (total != null ? ' — ' + fa(total) + ' ' + t('تومان') : '')) : t('خرید آنلاین به‌زودی'))}
        </button>
        <div className="auth-hint" style={{ marginTop: 10 }}><Icon name="lock" size={12} /> {t('پرداختِ امن از طریقِ درگاهِ سامانهٔ یکپارچهٔ وب‌کستینگ.')}</div>
      </div>
      <a className="auth-back" href="#/subscribe" style={{ display: 'inline-block', marginTop: 14 }}>‹ {t('بازگشت به بسته‌ها')}</a>
    </main>
  );
}

/* ---------- CompleteView — بازگشت از درگاه: تأیید پرداخت (/public/checkout/:id/verify) ---------- */
function CompleteView() {
  const [state, setState] = React.useState('verifying'); // verifying | ok | fail
  const [res, setRes] = React.useState(null);
  React.useEffect(() => {
    var qs = '';
    try { var h = window.location.hash || ''; var qi = h.indexOf('?'); if (qi >= 0) qs = h.slice(qi + 1); } catch (e) {}
    if (!qs) { try { qs = (window.location.search || '').replace(/^\?/, ''); } catch (e) {} }
    var params = {};
    qs.split('&').forEach(function (kv) { if (!kv) return; var i = kv.indexOf('='); var k = i >= 0 ? kv.slice(0, i) : kv; var v = i >= 0 ? decodeURIComponent(kv.slice(i + 1)) : ''; params[k] = v; });
    var status = params.Status || params.status || '';
    var orderId = params.orderId || '';
    var authority = params.Authority || params.authority || '';
    if (!orderId) { setState('fail'); return; }
    AUTH.siteId().then(function (sid) {
      if (!sid) { setState('fail'); return; }
      fetch(AUTH.api() + '/sites/' + sid + '/public/checkout/' + orderId + '/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: status, authority: authority }) })
        .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
        .then(function (out) { var paid = out.ok && out.j && out.j.ok === true; setRes(out.j || null); setState(paid ? 'ok' : 'fail'); })
        .catch(function () { setState('fail'); });
    });
  }, []);
  return (
    <main className="account-view" data-wbc-module="coin" data-wbc-bind="checkout-complete">
      <div className="panel col center" style={{ padding: 40, gap: 16, textAlign: 'center', maxWidth: 480, margin: '0 auto' }}>
        {state === 'verifying' && <React.Fragment><div style={{ fontSize: 40 }}>⏳</div><b style={{ fontSize: 'var(--t-h3)' }}>{t('در حال تأیید پرداخت…')}</b></React.Fragment>}
        {state === 'ok' && <React.Fragment>
          <div style={{ fontSize: 48 }}>✅</div>
          <b style={{ fontSize: 'var(--t-h2)' }}>{t('پرداخت با موفقیت انجام شد')}</b>
          {res && res.orderNumber && <span className="dim num">{t('شمارهٔ سفارش:')} {res.orderNumber}</span>}
          <span className="dim" style={{ fontSize: 'var(--t-sm)' }}>{t('سکه‌ها به‌زودی به کیف پولِ شما افزوده می‌شود.')}</span>
          <div className="row center" style={{ gap: 10, marginTop: 6 }}>
            <Button variant="gold" icon="user" onClick={() => go('#/profile')}>{t('سفارش‌های من')}</Button>
            <Button variant="ghost" onClick={() => go('#/')}>{t('بازگشت به سایت')}</Button>
          </div>
        </React.Fragment>}
        {state === 'fail' && <React.Fragment>
          <div style={{ fontSize: 48 }}>⚠️</div>
          <b style={{ fontSize: 'var(--t-h2)' }}>{t('پرداخت ناموفق یا لغو شد')}</b>
          <span className="dim" style={{ fontSize: 'var(--t-sm)' }}>{(res && res.message) || t('در صورت کسرِ وجه، مبلغ تا ۷۲ ساعت بازگردانده می‌شود.')}</span>
          <div className="row center" style={{ gap: 10, marginTop: 6 }}>
            <Button variant="gold" onClick={() => go('#/subscribe')}>{t('تلاش مجدد')}</Button>
            <Button variant="ghost" onClick={() => go('#/')}>{t('بازگشت به سایت')}</Button>
          </div>
        </React.Fragment>}
      </div>
    </main>
  );
}

function App() {
  const [theme, setTheme] = React.useState(() => {
    try { return localStorage.getItem('kushanews_theme') === 'light' ? 'light' : 'dark'; } catch (e) { return 'dark'; }
  });
  const [, force] = React.useReducer(x => x + 1, 0);
  const [authUser, setAuthUser] = React.useState(null);
  const lastTok = React.useRef(undefined);
  const lang = window.KI18N ? window.KI18N.getLang() : 'fa';
  const route = useHashRoute();
  React.useEffect(() => {
    if (theme === 'light') document.documentElement.setAttribute('data-theme','light');
    else document.documentElement.removeAttribute('data-theme');
    try { localStorage.setItem('kushanews_theme', theme); } catch (e) {}
  }, [theme]);
  // وضعیتِ کاربر: همگام با ماژول‌های مرکزی + ارزیابیِ اولیه
  React.useEffect(() => {
    let alive = true;
    try { if (window.WCAuth && WCAuth.onChange) WCAuth.onChange(function (v) { if (alive) setAuthUser(v || null); }); } catch (e) {}
    AUTH.me().then(function (v) { if (alive && v) setAuthUser(v); });
    return function () { alive = false; };
  }, []);
  // پس از ورود/خروج از طریقِ ویوهای spa: فقط وقتی توکن تغییر کرد، دوباره بخوان
  React.useEffect(() => {
    let alive = true;
    var tok = AUTH.token();
    if (tok === lastTok.current) return;
    lastTok.current = tok;
    if (!tok) { setAuthUser(null); return; }
    AUTH.me().then(function (v) { if (alive) setAuthUser(v || null); });
    return function () { alive = false; };
  }, [route]);
  const toggleLang = () => { if (window.KI18N) window.KI18N.setLang(lang === 'fa' ? 'en' : 'fa'); force(); };
  let page;
  if (route.startsWith('#/cat/')) {
    const key = route.slice('#/cat/'.length);
    page = <CategoryPage catKey={key} key={key} />;
  } else if (route.startsWith('#/news/')) {
    const id = route.slice('#/news/'.length);
    page = <ArticlePage id={id} key={id} />;
  } else if (route === '#/ai') page = <main><AINews /></main>;
  else if (route.startsWith('#/subscribe/complete')) page = <CompleteView key="cc" />;
  else if (route.startsWith('#/subscribe/buy/')) { const pid = route.slice('#/subscribe/buy/'.length); page = <CheckoutView packId={pid} key={pid} />; }
  else if (route === '#/subscribe') page = <main><Subscribe /></main>;
  else if (route === '#/about') page = <AboutPage />;
  else if (route === '#/contact') page = <ContactPage />;
  else if (route === '#/live') page = <LivePage />;
  else if (route === '#/login' || route.startsWith('#/login')) page = <LoginView key="login" />;
  else if (route === '#/profile' || route === '#/account' || route.startsWith('#/profile') || route.startsWith('#/account')) page = <ProfileView key="profile" />;
  else page = <HomePage />;
  return (
    <React.Fragment key={lang}>
      <Header theme={theme} onTheme={() => setTheme(t => t === 'dark' ? 'light' : 'dark')} user={authUser} lang={lang} onLang={toggleLang} />
      {page}
      <Footer />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
