/* global React */
// Live on-chain stats from Alchemy BSC RPC — proves the page is wired to real chain data.
// Endpoint comes from window.GB_CONFIG so it can be swapped without code changes.
const { useState: useS_RPC, useEffect: useFX_RPC } = React;

function BlockTicker() {
  const RPC = window.GB_CONFIG && window.GB_CONFIG.bscRpc;
  const [block, setBlock] = useS_RPC(null);
  const [gasGwei, setGasGwei] = useS_RPC(null);
  const [err, setErr] = useS_RPC(false);
  const [tick, setTick] = useS_RPC(0);

  useFX_RPC(() => {
    if (!RPC) return;
    let alive = true;
    const fetchOne = async () => {
      try {
        const [bn, gp] = await Promise.all([
          fetch(RPC, {
            method: "POST",
            headers: { "content-type": "application/json", "accept": "application/json" },
            body: JSON.stringify({ id: 1, jsonrpc: "2.0", method: "eth_blockNumber" })
          }).then(r => r.json()),
          fetch(RPC, {
            method: "POST",
            headers: { "content-type": "application/json", "accept": "application/json" },
            body: JSON.stringify({ id: 2, jsonrpc: "2.0", method: "eth_gasPrice" })
          }).then(r => r.json()),
        ]);
        if (!alive) return;
        if (bn && bn.result) setBlock(parseInt(bn.result, 16));
        if (gp && gp.result) setGasGwei(parseInt(gp.result, 16) / 1e9);
        setErr(false);
        setTick(t => t + 1);
      } catch (e) {
        if (alive) setErr(true);
      }
    };
    fetchOne();
    const id = setInterval(fetchOne, 6000);
    return () => { alive = false; clearInterval(id); };
  }, []);

  if (!RPC) return null;
  if (err) return <div className="b-block" title="RPC unreachable"><span className="b-block-dot down"></span><span className="dim">RPC offline</span></div>;
  if (block == null) return <div className="b-block"><span className="b-block-dot warm"></span><span className="dim">Connecting…</span></div>;

  return (
    <div className="b-block" title={`Alchemy BSC RPC · refreshed ${tick} times`}>
      <span className="b-block-dot live"></span>
      <span className="mono">BSC #{block.toLocaleString()}</span>
      {gasGwei != null && <span className="mono dim" style={{marginLeft: 8}}>{gasGwei.toFixed(2)} gwei</span>}
    </div>
  );
}

window.BlockTicker = BlockTicker;
