// page-portfolio.jsx
function Portfolio({ lang, wallet, onOpenToken }) {
  const t = I18N[lang];

  const enriched = HOLDINGS.map((h) => {
    const tk = TOKEN_BY_ID[h.id];
    if (!tk) return null;
    const value = h.amount * tk.price;
    const cost = h.amount * h.costBasis;
    const pnl = value - cost;
    const pnlPct = (pnl / cost) * 100;
    return { ...h, tk, value, cost, pnl, pnlPct };
  }).filter(Boolean);

  const totalValue = enriched.reduce((s, h) => s + h.value, 0);
  const totalCost = enriched.reduce((s, h) => s + h.cost, 0);
  const totalPnl = totalValue - totalCost;
  const totalPnlPct = totalCost ? (totalPnl / totalCost) * 100 : 0;
  const gradOwned = 2;

  if (!wallet.connected) {
    return (
      <div className="page" data-screen-label="03 Portfolio">
        <div className="page-head">
          <div>
            <h1 className="page-title">/ {t.nav_portfolio.toLowerCase()}</h1>
            <div className="page-sub">&gt; wallet not connected</div>
          </div>
        </div>
        <div className="card" style={{ padding: 60, textAlign: 'center' }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-dim)', marginBottom: 18 }}>
            ▽ no wallet connected — connect one to see your bags
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="03 Portfolio">
      <div className="page-head">
        <div>
          <h1 className="page-title">/ {t.nav_portfolio.toLowerCase()}</h1>
          <div className="page-sub">&gt; {wallet.addr} · {fmtMcap(totalValue)} TON in bags</div>
        </div>
      </div>

      <div className="stats4" style={{ gridTemplateColumns: '2fr 1fr 1fr' }}>
        <div className="stat">
          <label>{t.total_assets}</label>
          <b className="glitch" data-text={fmtMcap(totalValue)}>{fmtMcap(totalValue)} <small>TON</small></b>
        </div>
        <div className="stat">
          <label>{t.total_pnl}</label>
          <b className={totalPnl >= 0 ? 'up' : 'down'}>
            {totalPnl >= 0 ? '+' : ''}{fmtMcap(totalPnl)} <small>TON</small>
          </b>
          <small className={totalPnl >= 0 ? 'up' : 'down'} style={{ fontSize: 12, marginLeft: 0 }}>{totalPnl >= 0 ? '▲' : '▼'} {Math.abs(totalPnlPct).toFixed(1)}%</small>
        </div>
        <div className="stat">
          <label>{t.graduated_owned}</label>
          <b>{gradOwned} <small>{t.achievement}</small></b>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-head"><h3>{t.holdings}</h3></div>
        <table className="tbl">
          <thead>
            <tr>
              <th>{t.token}</th>
              <th style={{ textAlign: 'right' }}>{t.amount}</th>
              <th style={{ textAlign: 'right' }}>{t.value}</th>
              <th style={{ textAlign: 'right' }}>{t.pnl}</th>
            </tr>
          </thead>
          <tbody>
            {enriched.map((h) => (
              <tr key={h.id} onClick={() => onOpenToken(h.id)}>
                <td>
                  <div className="tbl-token">
                    <div className="tbl-avatar">{h.tk.glyph}</div>
                    <div>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 14 }}>{h.tk.name[lang]}</div>
                      <div style={{ color: 'var(--text-dim)', fontSize: 11 }}>${h.tk.sym}</div>
                    </div>
                  </div>
                </td>
                <td style={{ textAlign: 'right' }}>{fmtAmt(h.amount)}</td>
                <td style={{ textAlign: 'right' }}><b style={{ color: 'var(--accent)' }}>{h.value.toFixed(2)}</b> TON</td>
                <td style={{ textAlign: 'right' }} className={h.pnl >= 0 ? 'up' : 'down'}>
                  {h.pnl >= 0 ? '+' : ''}{h.pnl.toFixed(2)} TON
                  <div style={{ fontSize: 10, opacity: 0.7 }}>{h.pnl >= 0 ? '▲' : '▼'} {Math.abs(h.pnlPct).toFixed(1)}%</div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="card">
        <div className="card-head"><h3>{t.tx_history}</h3></div>
        <table className="tbl">
          <thead>
            <tr>
              <th>{t.tx_type}</th><th>{t.token}</th>
              <th style={{ textAlign: 'right' }}>{t.tx_amount}</th>
              <th style={{ textAlign: 'right' }}>{t.tx_price}</th>
              <th>{t.tx_hash}</th>
              <th style={{ textAlign: 'right' }}>{t.tx_time}</th>
            </tr>
          </thead>
          <tbody>
            {TX_HISTORY.map((x, i) => (
              <tr key={i}>
                <td>
                  <span className={'ticker-side ' + (x.type === 'buy' ? 'b' : x.type === 'sell' ? 's' : '')} style={{ background: x.type === 'create' ? 'color-mix(in oklab, var(--accent) 18%, transparent)' : undefined, color: x.type === 'create' ? 'var(--accent)' : undefined }}>
                    {x.type === 'buy' ? t.buy : x.type === 'sell' ? t.sell : t.create}
                  </span>
                </td>
                <td style={{ fontFamily: 'var(--font-mono)' }}>${x.sym}</td>
                <td style={{ textAlign: 'right' }}>{x.amount == null ? '—' : fmtAmt(x.amount)}</td>
                <td style={{ textAlign: 'right' }}>{x.price == null ? '—' : fmtPrice(x.price)}</td>
                <td>
                  <a style={{ color: 'var(--accent)', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 4 }} onClick={(e) => e.stopPropagation()}>
                    {x.hash} <Icon.ext />
                  </a>
                </td>
                <td style={{ textAlign: 'right', color: 'var(--text-faint)' }}>{fmtTime(x.minAgo, lang)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
window.Portfolio = Portfolio;
