// Top system-status bar — thin terminal strip with live ledger ticker.
// NETWORK: TESTNET (we are not on mainnet yet). Native token = XRMZ.

function SystemBar() {
  const [ledger, setLedger] = React.useState(94721337);
  const [peers, setPeers] = React.useState(36);
  const [xrp, setXrp] = React.useState({ price: null, change: null });

  React.useEffect(() => {
    // Ledger closes ~every 3.5s on XRPL. Bump it on that cadence.
    const lid = setInterval(() => setLedger(v => v + 1), 3500);
    // Testnet peer count drifts in a smaller, less-stable range than mainnet.
    const pid = setInterval(() => setPeers(v => {
      const next = v + (Math.random() > 0.5 ? 1 : -1);
      return Math.max(32, Math.min(42, next));
    }), 6000);

    // Live XRP price from CoinGecko (free, no auth, 30s cadence is safe).
    const fetchPrice = async () => {
      try {
        const r = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=ripple&vs_currencies=usd&include_24hr_change=true');
        if (!r.ok) return;
        const j = await r.json();
        if (j.ripple) setXrp({ price: j.ripple.usd, change: j.ripple.usd_24h_change });
      } catch (e) { /* network noise — leave last value */ }
    };
    fetchPrice();
    const xid = setInterval(fetchPrice, 30000);

    return () => { clearInterval(lid); clearInterval(pid); clearInterval(xid); };
  }, []);

  const Cell = ({ label, value, valueColor }) => (
    <span style={{
      display: 'inline-flex', alignItems: 'baseline', gap: 8,
      fontFamily: SP_MONO_W, fontSize: 10, letterSpacing: '0.3em',
      textTransform: 'uppercase', color: SP_COL.grayDark, whiteSpace: 'nowrap',
    }}>
      <span>{label}</span>
      <span style={{
        color: valueColor || SP_COL.grayLight, letterSpacing: '0.15em', fontWeight: 600,
      }}>{value}</span>
    </span>
  );

  const fmtPrice = p => p == null ? '——' : `$${p.toFixed(p < 1 ? 4 : 3)}`;
  const fmtChange = c => c == null ? '——' : `${c >= 0 ? '▲' : '▼'} ${Math.abs(c).toFixed(2)}%`;
  const changeColor = xrp.change == null
    ? SP_COL.grayLight
    : xrp.change >= 0 ? '#34D399' : '#F87171';

  return (
    <div style={{
      background: SP_COL.black,
      borderBottom: `1px solid ${SP_COL.grayDarker}`,
      position: 'relative', zIndex: 60,
    }}>
      <div className="sp-systembar-row" style={{
        maxWidth: 1152, margin: '0 auto',
        padding: '7px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 18,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 22, overflow: 'hidden' }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontFamily: SP_MONO_W, fontSize: 10, letterSpacing: '0.3em',
            textTransform: 'uppercase', color: SP_COL.accent, fontWeight: 600,
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%',
              background: SP_COL.accent,
            }} />
            TESTNET
          </span>
          <Cell label="Peers" value={peers} />
          <Cell label="Ledger" value={`#${ledger.toLocaleString()}`} />
          <span className="sp-systembar-hide-md">
            <a href="https://coinmarketcap.com/currencies/xrp/" target="_blank" rel="noopener noreferrer"
               style={{
                 display: 'inline-flex', alignItems: 'baseline', gap: 8,
                 fontFamily: SP_MONO_W, fontSize: 10, letterSpacing: '0.3em',
                 textTransform: 'uppercase', color: SP_COL.grayDark,
                 whiteSpace: 'nowrap', textDecoration: 'none',
               }}>
              <span>XRP</span>
              <span style={{ color: SP_COL.grayLight, letterSpacing: '0.15em', fontWeight: 600 }}>
                {fmtPrice(xrp.price)}
              </span>
              <span style={{ color: changeColor, letterSpacing: '0.15em', fontWeight: 600 }}>
                {fmtChange(xrp.change)}
              </span>
            </a>
          </span>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}
             className="sp-systembar-right">
          <a href={SP_LINKS.xrmzToken} target="_blank" rel="noopener noreferrer" style={{
            display: 'inline-flex', alignItems: 'baseline', gap: 8,
            fontFamily: SP_MONO_W, fontSize: 10, letterSpacing: '0.3em',
            textTransform: 'uppercase', color: SP_COL.grayLight,
            textDecoration: 'none', fontWeight: 600,
          }}>
            <span style={{ color: SP_COL.grayDark }}>Token</span>
            <span>$XRMZ ↗</span>
          </a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SystemBar });
