/* ============================================================
   CHAINUS — Market Intelligence (native data-viz) + Marketplace
   ============================================================ */

function MarketOrbit({ t, pair }) {
  const labels = t.dir === 'zh'
    ? ['价格', '情绪', '流动性', '新闻', '预测', '社区热度']
    : ['Price', 'Mood', 'Liquidity', 'News', 'Forecast', 'Community heat'];
  return (
    <Reveal scale className="market-orbit" delay={80}>
      <svg viewBox="0 0 100 100" aria-hidden="true">
        <circle cx="50" cy="50" r="32" />
        <circle cx="50" cy="50" r="44" />
        <path d="M50 6v88M6 50h88M19 19l62 62M81 19L19 81" />
      </svg>
      <div className="orbit-core">
        <span>{pair.sym}</span>
        <b className="tnum">{pair.px}</b>
        <em className={pair.c >= 0 ? 'pos' : 'neg'}>{pair.c >= 0 ? '+' : ''}{pair.c}%</em>
      </div>
      {labels.map((l, i) => <span key={l} className={`orbit-node on-${i}`}>{l}</span>)}
    </Reveal>
  );
}

function MarketIntel({ t }) {
  const m = t.market;
  const [tab, setTab] = useState(0);
  const [range, setRange] = useState(1);
  const seed = (tab + 1) * 13 + (range + 1) * 7;
  const pair = m.pairs[tab];
  const news = m.news.concat(m.news);

  return (
    <section className="section market" id="market">
      <div className="wrap">
        <div className="market-head">
          <div>
            <Reveal as="h2" className="h2" delay={70} style={{ marginTop: 14, maxWidth: '16ch' }}>{m.title[0]} <span className="brand-text">{m.title[1]}</span></Reveal>
          </div>
          <Reveal className="lead" delay={120} style={{ maxWidth: '40ch' }}>{m.sub}</Reveal>
        </div>

        <MarketOrbit t={t} pair={pair} />

        {/* top stat strip */}
        <Reveal className="mkt-stats" delay={60}>
          {m.stats.map((s, i) => (
            <div key={i} className="mkt-stat well">
              <span className="tag">{s.k}</span>
              <span className="mkt-stat-v tnum">{s.v}</span>
              <span className={`mkt-stat-c tnum ${s.c >= 0 ? 'pos' : 'neg'}`}>{s.c >= 0 ? '+' : ''}{s.c}%</span>
            </div>
          ))}
        </Reveal>

        <div className="mkt-grid">
          {/* main chart */}
          <Reveal scale className="mkt-chart card card-hi">
            <div className="mkt-chart-bar">
              <div className="mkt-pair">
                <span className="mkt-pair-sym">{pair.sym}</span>
                <div>
                  <b className="mkt-pair-name">{pair.name}</b>
                  <span className="mkt-pair-px"><b className="tnum">{pair.px}</b> <span className={`tnum ${pair.c >= 0 ? 'pos' : 'neg'}`}>{pair.c >= 0 ? '+' : ''}{pair.c}%</span></span>
                </div>
              </div>
              <div className="seg seg-sm">
                {m.pairs.map((p, i) => <button key={i} className={tab === i ? 'on' : ''} onClick={() => setTab(i)}>{p.sym}</button>)}
              </div>
            </div>
            <div className="mkt-chart-body">
              <CandleChart seed={seed} height={278} />
            </div>
            <div className="mkt-chart-foot">
              <div className="seg seg-xs">
                {m.ranges.map((r, i) => <button key={i} className={range === i ? 'on' : ''} onClick={() => setRange(i)}>{r}</button>)}
              </div>
              <span className="tag">{m.modules.liquidity}</span>
              <div className="mkt-liq-inline"><LiquidityBars seed={seed + 5} count={20} /></div>
            </div>
          </Reveal>

          {/* side modules */}
          <div className="mkt-side">
            <Reveal scale delay={80} className="mkt-mod card card-hi">
              <span className="tag">{m.modules.sentiment}</span>
              <Gauge value={m.sentiment.value} label={m.sentiment.label} />
              <p className="mkt-mod-note faint">{m.sentiment.note}</p>
            </Reveal>
            <Reveal scale delay={140} className="mkt-mod card card-hi">
              <span className="tag">{m.modules.alloc}</span>
              <div className="mkt-alloc">
                <Donut segments={m.alloc.segments} />
                <ul className="mkt-legend">
                  {m.alloc.segments.map((s, i) => (
                    <li key={i}><span className="dot" style={{ background: s.color }}></span>{s.n}<b className="tnum">{s.v}%</b></li>
                  ))}
                </ul>
              </div>
            </Reveal>
          </div>
        </div>

        {/* lower row: rates + RWA/NFT + events */}
        <div className="mkt-row">
          <Reveal scale className="mkt-mod card card-hi">
            <span className="tag">{m.modules.rates}</span>
            <ul className="rate-list">
              {m.rates.map((r, i) => (
                <li key={i}>
                  <span className="rate-n">{r.n}</span>
                  <span className="rate-spark"><Sparkline data={r.d} color={r.c >= 0 ? 'var(--up)' : 'var(--down)'} w={70} h={22} fill={false} strokeW={1.8} id={'rs' + i} /></span>
                  <span className="rate-v tnum">{r.v}</span>
                  <span className={`rate-c tnum ${r.c >= 0 ? 'pos' : 'neg'}`}>{r.c >= 0 ? '+' : ''}{r.c}%</span>
                </li>
              ))}
            </ul>
          </Reveal>
          <Reveal scale delay={100} className="mkt-news card card-hi">
            <span className="tag">{m.modules.news}</span>
            <div className="news-track marquee-mask">
              <div className="marquee marquee-col" style={{ '--dur': '24s' }}>
                {news.map((n, i) => (
                  <div key={i} className="news-item">
                    <span className={`news-tag news-${n.tone}`}>{n.tag}</span>
                    <span className="news-text">{n.text}</span>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---- Marketplace ---- */
function marketKindFor(item) {
  const slot = (item.slot || '').toLowerCase();
  if (slot.includes('rwa')) return 'rwa';
  if (slot.includes('member')) return 'member';
  return 'nft';
}

function marketShotFor(item) {
  const kind = marketKindFor(item);
  if (kind === 'rwa') return 'assets/v3/metals-page-desktop.png';
  return '';
}

function MarketArt({ item, index }) {
  const kind = marketKindFor(item);
  const shot = marketShotFor(item);
  const positions = ['46% 74%', '50% 48%', '48% 38%', '50% 42%', '44% 70%'];
  const pos = positions[index % positions.length];
  return (
    <div className={`market-art ma-${kind}`} aria-hidden="true">
      {shot && <img src={shot} alt="" draggable="false" style={{ objectPosition: pos }} />}
      <div className="ma-sheen"></div>
      {kind === 'member' && (
        <div className="ma-member">
          <span className="ma-ring"></span>
          <div className="ma-member-lines"><i></i><i></i><i></i></div>
        </div>
      )}
      {kind === 'nft' && (
        <React.Fragment>
          <div className="ma-grid">{Array.from({ length: 12 }).map((_, i) => <i key={i}></i>)}</div>
          <span className="ma-orb"></span>
          <span className="ma-orb ma-orb-b"></span>
        </React.Fragment>
      )}
    </div>
  );
}

function Marketplace({ t }) {
  const mp = t.marketplace;
  const main = mp.items[0];
  const supporting = mp.items.slice(1, 4);
  return (
    <section className="section marketplace" id="marketplace">
      <div className="wrap">
        <div className="mp-stage">
          <div className="mp-copy">
            <Reveal className="eyebrow" delay={40}>{mp.eyebrow}</Reveal>
            <Reveal as="h2" className="h2" delay={70}>{mp.title[0]} <span className="brand-text">{mp.title[1]}</span></Reveal>
            <Reveal className="lead" delay={120}>{mp.sub}</Reveal>
            <Reveal delay={180} className="mp-cta">
              <MagneticButton className="btn btn-line btn-sm">{mp.cta}<ArrowIcon /></MagneticButton>
            </Reveal>
            <Reveal as="ul" className="mp-flow" delay={220}>
              {mp.steps.map((step, i) => (
                <li key={step}>
                  <span>{String(i + 1).padStart(2, '0')}</span>
                  <b>{step}</b>
                </li>
              ))}
            </Reveal>
          </div>

          <Reveal scale delay={120} className="mp-preview card card-hi">
            <div className="mp-draft">
              <div className="mp-draft-top">
                <span className="tag">{main.price}</span>
                <span>{mp.stepLabel}</span>
              </div>
              <b>{main.name}</b>
              <div className="mp-draft-fields">
                {mp.steps.map((step, i) => (
                  <div key={step} className={i === 0 ? 'on' : ''}>
                    <span>{String(i + 1).padStart(2, '0')}</span>
                    <em>{step}</em>
                  </div>
                ))}
              </div>
              <div className="mp-draft-foot">
                <span>{mp.cta}</span>
                <ArrowIcon />
              </div>
            </div>
          </Reveal>
        </div>

        <Reveal className="mp-gallery">
          {supporting.map((it) => (
            <article key={it.name} className="mp-card card card-hi">
              <span className="mp-card-type">{it.price}</span>
              <b className="mp-name">{it.name}</b>
              <span className="mp-card-line"></span>
              <span className="mp-card-meta">{mp.stepLabel}</span>
            </article>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { MarketIntel, MarketOrbit, MarketArt, marketKindFor, marketShotFor, Marketplace });
