// page-detail.jsx — Token Detail page
const { useState: useStateT, useMemo: useMemoT, useEffect: useEffectT } = React;

function KLine({ candles, w = 720, h = 280 }) {
  const padL = 8, padR = 56, padT = 12, padB = 24;
  const innerW = w - padL - padR, innerH = h - padT - padB;
  const max = Math.max(...candles.map((c) => c.h));
  const min = Math.min(...candles.map((c) => c.l));
  const range = max - min || 1;
  const cw = innerW / candles.length;
  const yOf = (p) => padT + (1 - (p - min) / range) * innerH;
  const gridY = [0, 0.25, 0.5, 0.75, 1].map((f) => min + range * f);
  const lastClose = candles[candles.length - 1].c;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 'auto', display: 'block', fontFamily: 'var(--font-mono)' }}>
      {gridY.map((g, i) => (
        <g key={i}>
          <line x1={padL} x2={w - padR} y1={yOf(g)} y2={yOf(g)} stroke="rgba(255,255,255,0.04)" />
          <text x={w - padR + 6} y={yOf(g) + 3} fill="var(--text-faint)" fontSize="9">{g.toExponential(2)}</text>
        </g>
      ))}
      <line x1={padL} x2={w - padR} y1={yOf(lastClose)} y2={yOf(lastClose)} stroke="var(--accent)" strokeDasharray="2 3" opacity="0.6" />
      <rect x={w - padR + 2} y={yOf(lastClose) - 8} width={padR - 6} height={16} fill="var(--accent)" rx="3" />
      <text x={w - padR + 6} y={yOf(lastClose) + 3} fill="#000" fontSize="9" fontWeight="700">{lastClose.toExponential(2)}</text>
      {candles.map((c, i) => {
        const x = padL + i * cw + cw * 0.5;
        const up = c.c >= c.o;
        const color = up ? 'var(--up)' : 'var(--down)';
        return (
          <g key={i}>
            <line x1={x} x2={x} y1={yOf(c.h)} y2={yOf(c.l)} stroke={color} strokeWidth="1" />
            <rect x={x - cw * 0.36} y={yOf(Math.max(c.o, c.c))} width={cw * 0.72} height={Math.max(1, Math.abs(yOf(c.o) - yOf(c.c)))} fill={color} />
          </g>
        );
      })}
    </svg>
  );
}

function HoldersDonut({ tok }) {
  const r = mulberry32(strSeed(tok.id) + 13);
  const segs = useMemoT(() => {
    const arr = [
      { addr: 'Holder #0 (dev)', pct: 12 + r() * 8 },
      { addr: FAKE_ADDRS[0], pct: 8 + r() * 5 },
      { addr: FAKE_ADDRS[1], pct: 6 + r() * 4 },
      { addr: FAKE_ADDRS[2], pct: 5 + r() * 3 },
      { addr: FAKE_ADDRS[3], pct: 4 + r() * 3 },
      { addr: FAKE_ADDRS[4], pct: 3 + r() * 2 },
    ];
    const sum = arr.reduce((s, a) => s + a.pct, 0);
    arr.push({ addr: 'others', pct: 100 - sum });
    return arr;
  }, [tok.id]);
  const colors = ['#00d4ff', '#7a5af7', '#00ff9d', '#ff4d6d', '#ffb547', '#ff7ab8', '#4a5469'];
  // draw donut
  let cum = 0;
  const cx = 100, cy = 100, R = 70, r0 = 44;
  return (
    <div className="donut-row">
      <svg className="donut" viewBox="0 0 200 200">
        {segs.map((s, i) => {
          const a0 = (cum / 100) * Math.PI * 2 - Math.PI / 2;
          cum += s.pct;
          const a1 = (cum / 100) * Math.PI * 2 - Math.PI / 2;
          const big = s.pct > 50 ? 1 : 0;
          const x0 = cx + R * Math.cos(a0), y0 = cy + R * Math.sin(a0);
          const x1 = cx + R * Math.cos(a1), y1 = cy + R * Math.sin(a1);
          const xi0 = cx + r0 * Math.cos(a0), yi0 = cy + r0 * Math.sin(a0);
          const xi1 = cx + r0 * Math.cos(a1), yi1 = cy + r0 * Math.sin(a1);
          return <path key={i} d={`M${x0},${y0} A${R},${R} 0 ${big} 1 ${x1},${y1} L${xi1},${yi1} A${r0},${r0} 0 ${big} 0 ${xi0},${yi0} Z`} fill={colors[i]} opacity="0.85" />;
        })}
        <text x="100" y="96" textAnchor="middle" fill="var(--text-dim)" fontSize="9" fontFamily="var(--font-mono)" letterSpacing="2">HOLDERS</text>
        <text x="100" y="116" textAnchor="middle" fill="var(--text)" fontSize="22" fontFamily="var(--font-display)" fontWeight="700">{tok.holders}</text>
      </svg>
      <div style={{ flex: 1 }}>
        {segs.map((s, i) => (
          <div key={i} className="legend-row">
            <span className="legend-dot" style={{ background: colors[i] }}></span>
            <span style={{ minWidth: 140 }}>{s.addr}</span>
            <span className="pct">{s.pct.toFixed(1)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TokenDetail({ id, lang, wallet, onBack, onSign, onToast }) {
  const t = I18N[lang];
  const tok = TOKEN_BY_ID[id] || TOKENS[0];
  const [tf, setTf] = useStateT('15m');
  const [side, setSide] = useStateT('buy');
  const [amount, setAmount] = useStateT('');
  const [bottomTab, setBottomTab] = useStateT('trades');

  const candles = useMemoT(() => makeOHLC(strSeed(tok.id), 64, tok.price), [tok.id, tf]);
  const amtNum = parseFloat(amount) || 0;
  const fee = amtNum * 0.01;
  const estTokens = (amtNum * 0.012 * 1_000_000_000).toFixed(0);

  const trades = useMemoT(() => {
    return Array.from({ length: 14 }, (_, i) => {
      const r = mulberry32(strSeed(tok.id) + i * 31);
      return {
        side: r() > 0.45 ? 'b' : 's',
        amount: (r() * 8 + 0.05),
        addr: FAKE_ADDRS[Math.floor(r() * FAKE_ADDRS.length)],
        when: i * 18 + Math.floor(r() * 12),
        tokens: Math.floor(r() * 50_000_000),
      };
    });
  }, [tok.id]);

  const submit = () => {
    if (!wallet.connected || !amtNum) return;
    onSign(() => onToast(`${side === 'buy' ? t.buy : t.sell} ${amtNum} TON · $${tok.sym} ✓`));
  };

  return (
    <div className="page" data-screen-label="05 Token Detail">
      <button className="btn btn-ghost" onClick={onBack} style={{ marginBottom: 16 }}>
        <Icon.back /> {t.detail_back}
      </button>

      <div className="detail-head" style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
        <div className="tok-avatar" style={{ width: 72, height: 72, fontSize: 38, borderRadius: 16, flex: 'none' }}>{tok.glyph}</div>
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, lineHeight: 1.1 }}>{tok.name[lang]}</h2>
            <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>${tok.sym}</span>
            <span className="tag live">{t.live}</span>
          </div>
          <div style={{ display: 'flex', gap: 22, fontFamily: 'var(--font-mono)', fontSize: 12, flexWrap: 'wrap', alignItems: 'center' }}>
            <div><span style={{ color:'var(--text-faint)' }}>{t.current_price} </span><b style={{ color: 'var(--accent)' }}>{fmtPrice(tok.price)}</b> <ChangeArrow v={tok.ch24} /></div>
            <div><span style={{ color:'var(--text-faint)' }}>{t.mcap} </span>{fmtMcap(tok.mcap)} TON</div>
            <div><span style={{ color:'var(--text-faint)' }}>{t.vol_24h} </span>{fmtMcap(tok.vol24)} TON</div>
          </div>
          <div style={{ display: 'flex', gap: 8, fontFamily: 'var(--font-mono)', fontSize: 11, flexWrap: 'wrap' }}>
            <button className="chip" onClick={() => { navigator.clipboard?.writeText(tok.contract); onToast(t.copied); }}>
              <Icon.copy /> {tok.contract.slice(0, 6)}…{tok.contract.slice(-6)}
            </button>
            <a className="chip" href={tok.tg} target="_blank" rel="noopener"><Icon.tg /> Telegram</a>
            <a className="chip" href={tok.tw} target="_blank" rel="noopener"><Icon.x /> X</a>
            <a className="chip" href={tok.web} target="_blank" rel="noopener"><Icon.web /> Web</a>
          </div>
        </div>
      </div>

      <div className="detail-grid">
        <div>
          <div className="kline-wrap">
            <div className="kline-tabs">
              {['1m','5m','15m','1h','4h','1d'].map((tf2) => (
                <button key={tf2} className={'kline-tab ' + (tf === tf2 ? 'active' : '')} onClick={() => setTf(tf2)}>{tf2}</button>
              ))}
              <div style={{ flex:1 }}></div>
              <span style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-faint)', alignSelf:'center', letterSpacing: '0.1em' }}>OHLC · TON</span>
            </div>
            <KLine candles={candles} />
          </div>

          <div className="card" style={{ marginTop: 18 }}>
            <div className="sub-tabs">
              <button className={'sub-tab ' + (bottomTab === 'trades' ? 'active' : '')} onClick={() => setBottomTab('trades')}>{t.tab_trades}</button>
              <button className={'sub-tab ' + (bottomTab === 'holders' ? 'active' : '')} onClick={() => setBottomTab('holders')}>{t.tab_holders}</button>
            </div>
            <div style={{ padding: 18 }}>
              {bottomTab === 'trades' ? (
                <table className="tbl">
                  <thead><tr>
                    <th>{t.direction}</th><th>{t.tx_amount}</th><th>{t.holder}</th>
                    <th style={{ textAlign:'right' }}>{t.total}</th><th style={{ textAlign:'right' }}>{t.price}</th><th style={{ textAlign:'right' }}>{t.tx_time}</th>
                  </tr></thead>
                  <tbody>
                    {trades.map((tr, i) => (
                      <tr key={i}>
                        <td><span className={'ticker-side ' + tr.side}>{tr.side === 'b' ? t.buy : t.sell}</span></td>
                        <td>{fmtAmt(tr.tokens)}</td>
                        <td style={{ color:'var(--text-dim)' }}>{tr.addr}</td>
                        <td style={{ textAlign:'right' }}>{tr.amount.toFixed(3)} TON</td>
                        <td style={{ textAlign:'right', color:'var(--accent)' }}>{fmtPrice(tok.price * (0.98 + (i % 5) * 0.01))}</td>
                        <td style={{ textAlign:'right', color:'var(--text-faint)' }}>{tr.when}s</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <HoldersDonut tok={tok} />
              )}
            </div>
          </div>
        </div>

        <div className="trade-panel">
          <div className="grad-bar">
            <div className="grad-bar-row"><span>{t.grad_progress}</span><b>{tok.progress.toFixed(1)}%</b></div>
            <div className="grad-bar-track"><div className="grad-bar-fill" style={{ width: tok.progress + '%' }}></div></div>
            <div style={{ marginTop: 8, fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-faint)', letterSpacing:'0.05em' }}>
              {fmtMcap(100000 - tok.mcap)} TON {t.grad_to_dex}
            </div>
          </div>
          <div className="trade-toggle">
            <button className={'btn-up ' + (side === 'buy' ? 'active' : '')} style={{ borderRadius: 8 }} onClick={() => setSide('buy')}>{t.buy}</button>
            <button className={'btn-down ' + (side === 'sell' ? 'active' : '')} style={{ borderRadius: 8 }} onClick={() => setSide('sell')}>{t.sell}</button>
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <div className="field-label">
              <span>{t.pay} (TON)</span>
              <span className="opt">{t.balance} {wallet.bal.toFixed(2)}</span>
            </div>
            <input className="input" type="number" placeholder="0.0" value={amount} onChange={(e) => setAmount(e.target.value)} />
          </div>
          <div className="chips" style={{ marginBottom: 14 }}>
            {['0.1', '1', '5', '10'].map((v) => (
              <button key={v} className="chip" onClick={() => setAmount(v)}>{v} TON</button>
            ))}
          </div>
          <div style={{ background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 8, padding: 12, fontFamily: 'var(--font-mono)', fontSize: 11, marginBottom: 14 }}>
            <div style={{ display:'flex', justifyContent:'space-between', padding:'4px 0' }}>
              <span style={{ color:'var(--text-dim)' }}>{t.est_recv}</span>
              <span><b style={{ color:'var(--accent)' }}>{amtNum ? fmtAmt(parseInt(estTokens)) : '—'}</b> ${tok.sym}</span>
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', padding:'4px 0' }}>
              <span style={{ color:'var(--text-dim)' }}>{t.current_price}</span>
              <span>{fmtPrice(tok.price)} TON</span>
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', padding:'4px 0' }}>
              <span style={{ color:'var(--text-dim)' }}>{t.fee} (1%)</span>
              <span>{fee.toFixed(4)} TON</span>
            </div>
          </div>
          <button
            className="btn btn-block"
            disabled={!wallet.connected || !amtNum}
            onClick={submit}
            style={{
              background: side === 'buy' ? 'var(--up)' : 'var(--down)',
              color: '#000', borderColor: 'transparent', fontWeight: 700, letterSpacing:'0.04em',
              boxShadow: `0 0 24px ${side === 'buy' ? 'var(--up-glow)' : 'var(--down-glow)'}`,
            }}
          >
            {side === 'buy' ? t.confirm_buy : t.confirm_sell}
          </button>
        </div>
      </div>
    </div>
  );
}

window.TokenDetail = TokenDetail;
