// Metrics page entry, sciphr.io/metrics.html. Fetches the two published
// JSON files (spec §8 contract) and renders everything client-side. The
// only live network calls are the posture lookups against public XRPL
// JSON-RPC endpoints; aggregate numbers come from the static JSON.

function MetricsPage() {
  const [latest, setLatest] = React.useState(null);
  const [history, setHistory] = React.useState(null);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    // Crawler output from the public bucket first; the local data/ fixtures
    // are the fallback so the page still renders if the bucket is unreachable.
    const get = (url) => fetch(url).then(r => {
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.json();
    });
    const load = (base) => Promise.all([
      get(base + 'metrics-latest.json'),
      get(base + 'metrics-history.json'),
    ]);
    const remote = (window.SP_LINKS && SP_LINKS.metricsData) || '';
    (remote ? load(remote).catch(() => load('data/')) : load('data/'))
      .then(([l, h]) => { setLatest(l); setHistory(h); })
      .catch(e => setErr(String(e)));
  }, []);

  const isSample = !!(latest && latest.source && latest.source.indexOf('MOCK') !== -1);

  return (
    <SiteShell current="metrics">
      {err ? (
        <p style={{ fontFamily: SP_MONO_W, fontSize: 13, color: SP_COL.error }}>&gt; failed to load metrics JSON: {err}</p>
      ) : !latest || !history ? (
        <p style={{ fontFamily: SP_MONO_W, fontSize: 13, color: SP_COL.grayLight }}>&gt; loading metrics-latest.json <Caret /></p>
      ) : (
        <>
          <MetricsHero latest={latest} isSample={isSample} />
          <HeadlineStats m={latest.metrics} />
          <TrendCharts rows={history.slice(-365)} />
          <ValueAndDormancy m={latest.metrics} />
          <QuorumAndIdentity m={latest.metrics} />
          <Methodology />
          <PostureLookup />
          <MetricsProvenance latest={latest} isSample={isSample} />
        </>
      )}
    </SiteShell>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MetricsPage />);
