// council.jsx — The Council page.
// Hero · Proof layers · Roster · Matrix · Live feed · Verify yourself · Footer.

// ── Sticky top bar ────────────────────────────────────────────
function CouncilNav() {
  const items = [
    { n: '02', label: 'Roster',       href: '#roster' },
    { n: '03', label: 'Proof',        href: '#proof' },
    { n: '04', label: 'Independence', href: '#matrix' },
    { n: '05', label: 'Heartbeat',    href: '#heartbeat' },
    { n: '06', label: 'Slashing',     href: '#slashing' },
    { n: '07', label: 'Family',       href: '#family' },
    { n: '08', label: 'Lineage',      href: '#lineage' },
    { n: '09', label: 'Live',         href: '#live' },
    { n: '10', label: 'Verify',       href: '#verify' },
  ];
  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(10,11,14,0.86)',
      backdropFilter: 'saturate(180%) blur(16px)',
      WebkitBackdropFilter: 'saturate(180%) blur(16px)',
      borderBottom: `1px solid ${T.inkBorder}`,
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto', padding: '0 32px',
        height: 64, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="https://www.tradexchange.cc/" style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
          <BrandMark size={24} withWord/>
          <span style={{ width: 1, height: 14, background: T.inkBorder }}/>
          <Mono color={T.muteInv}>· THE COUNCIL</Mono>
        </a>
        <div style={{ display: 'flex', gap: 28 }}>
          {items.map(it => (
            <a key={it.n} href={it.href} style={{
              color: T.muteInv,
              fontFamily: GMONO, fontSize: 11, letterSpacing: 1, textTransform: 'uppercase',
              display: 'inline-flex', gap: 8, alignItems: 'center',
              transition: 'color .15s',
            }}
              onMouseEnter={e => e.currentTarget.style.color = T.textInv}
              onMouseLeave={e => e.currentTarget.style.color = T.muteInv}
            >
              <span style={{ color: T.allow }}>{it.n}</span>
              <span>{it.label}</span>
            </a>
          ))}
        </div>
        <TXButton variant="allow" size="md" href="https://www.tradexchange.cc/">← Back to platform</TXButton>
      </div>
    </nav>
  );
}

// ── Hero ──────────────────────────────────────────────────────
function CouncilHero() {
  const agg = aggregateStats();
  return (
    <section id="top" style={{
      padding: '72px 0 64px', position: 'relative',
    }}>
      <div style={{ maxWidth: 1320, margin: '0 auto', padding: '0 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 64, alignItems: 'flex-start' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 26 }}>
              <Bracket color={T.allow}>§ 01 · THE COUNCIL</Bracket>
              <Mono color={T.muteInv}>BASE · MAINNET · ERC-721</Mono>
            </div>

            <h1 style={{
              fontFamily: GEIST, fontWeight: 600,
              fontSize: 'clamp(48px, 6.6vw, 86px)',
              lineHeight: 0.97, letterSpacing: -3,
              margin: 0, color: T.textInv,
            }}>
              25 agents.<br/>
              Each one a{' '}
              <span style={{ color: T.allow }}>name</span>.<br/>
              Each one an{' '}
              <span style={{ color: T.allow }}>NFT</span>.<br/>
              Each one a{' '}
              <span style={{ color: T.allow }}>wallet</span>.
            </h1>

            <p style={{
              marginTop: 26, fontSize: 18, lineHeight: 1.55,
              color: T.muteInv, letterSpacing: -0.2, maxWidth: 540,
            }}>
              The Council is 25 named, on-chain verifiers — published as a finite NFT collection on Base. Every order routes through all 25 before it reaches your broker. Every vote is signed by a token-bound smart wallet. Every receipt anchors to a block you can read yourself.
            </p>

            <div style={{ display: 'flex', gap: 12, marginTop: 32, flexWrap: 'wrap' }}>
              <TXButton variant="allow" size="lg" href="#roster">See the roster</TXButton>
              <TXButton variant="ghost" size="lg" href={basescanContract()}
                style={{ color: T.textInv, border: `1px solid ${T.inkBorder}` }}>
                Open contract on Basescan ↗
              </TXButton>
            </div>

            {/* contract block */}
            <div style={{
              marginTop: 28, padding: '14px 18px',
              border: `1px solid ${T.inkBorder}`, background: 'rgba(244,244,240,0.02)',
              display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 14, alignItems: 'center',
            }}>
              <Mono color={T.allow} weight={500}>CONTRACT</Mono>
              <span style={{
                fontFamily: GMONO, fontSize: 13, color: T.textInv,
                letterSpacing: 0.3, wordBreak: 'break-all',
              }}>{NFT_CONTRACT}</span>
              <a href={basescanContract()} target="_blank" rel="noopener"
                 style={{ fontFamily: GMONO, fontSize: 11, color: T.allow, letterSpacing: 0.8 }}>
                BASESCAN ↗
              </a>
            </div>
          </div>

          {/* Right side: aggregate stat tiles */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1,
            background: T.inkBorder, border: `1px solid ${T.inkBorder}`,
          }}>
            <HeroTile k="AGENTS"          v={`${agg.totalAgents}`}         sub="finite collection" big/>
            <HeroTile k="ETH STAKED"      v={`${agg.totalStake}`}          sub="across all wallets" big/>
            <HeroTile k="AVG ACCURACY"    v={`${(agg.avgAccuracy*100).toFixed(1)}%`} sub="last 30 days"/>
            <HeroTile k="VOTES CAST"      v={agg.totalVotes.toLocaleString()} sub="lifetime"/>
            <HeroTile k="ORDERS CLEARED"  v={agg.totalCleared.toLocaleString()} sub="receipts on Base"/>
            <HeroTile k="SLASHES ON FILE" v={`${agg.totalSlashes}`}        sub="public, on-chain"/>
          </div>
        </div>
      </div>
    </section>
  );
}

function HeroTile({ k, v, sub, big = false }) {
  return (
    <div style={{
      background: T.ink, padding: '20px 22px',
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      minHeight: big ? 130 : 100,
    }}>
      <Mono color={T.allow} weight={500} size={10}>{k}</Mono>
      <div>
        <div style={{
          fontFamily: GMONO, fontWeight: 500,
          fontSize: big ? 36 : 22,
          color: T.textInv, letterSpacing: 0.3, lineHeight: 1,
        }}>{v}</div>
        <Mono color={T.muteInv} size={10} style={{ marginTop: 6, display: 'block' }}>{sub}</Mono>
      </div>
    </div>
  );
}

// ── How the proof works (4 layers) ────────────────────────────
function CouncilProof() {
  const layers = [
    {
      n: '01', t: 'Identity', sub: 'NFT contract',
      d: 'The contract on Base holds exactly 25 tokens. Call totalSupply() and you get 25 — no API key, no permission needed. The contract IS the registry.',
      proof: 'totalSupply() = 25',
    },
    {
      n: '02', t: 'Signature', sub: 'Token-bound accounts',
      d: 'Each NFT has its own ERC-6551 smart wallet. Every vote is signed by that wallet\u2019s private key. The signature, the wallet, and the NFT are all linkable on-chain.',
      proof: '25 distinct signers, 1 receipt',
    },
    {
      n: '03', t: 'Independence', sub: 'Divergent voting',
      d: 'The 25 do not vote in lockstep — same-specialty pairs cluster, cross-specialty pairs diverge. If one entity controlled all 25, the agreement matrix would flatten to a uniform field.',
      proof: 'see the matrix below',
    },
    {
      n: '04', t: 'Consequence', sub: 'Stake + slashing',
      d: 'Each smart wallet stakes capital. Wrong votes get slashed publicly. After enough time, stakes and slashing histories diverge enough to be statistically impossible to fake.',
      proof: 'each card shows its own slash count',
    },
  ];
  return (
    <Section id="proof" num="03" eyebrow="How the proof works" dark
      title="Four layers, none of which require trusting us."
      intro="If the only proof was \u201cwe say there are 25 agents,\u201d a skeptic could fairly say it might be one. The roster, signatures, divergence, and stake history are each independently verifiable.">
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0,
        border: `1px solid ${T.inkBorder}`,
      }}>
        {layers.map((l, i) => (
          <div key={l.n} style={{
            padding: '26px 24px 28px',
            borderRight: i < layers.length - 1 ? `1px solid ${T.inkBorder}` : 'none',
            background: 'rgba(244,244,240,0.02)',
          }}>
            <Mono color={T.allow} weight={500}>§ 03.{l.n} · {l.sub}</Mono>
            <h3 style={{
              fontFamily: GEIST, fontWeight: 600, fontSize: 22,
              letterSpacing: -0.6, margin: '14px 0 10px', color: T.textInv,
            }}>{l.t}</h3>
            <p style={{
              margin: 0, fontSize: 14, lineHeight: 1.55,
              color: 'rgba(244,244,240,0.7)', letterSpacing: -0.05,
            }}>{l.d}</p>
            <div style={{
              marginTop: 14, padding: '8px 10px',
              border: `1px dashed ${T.inkBorder}`, background: T.ink,
              fontFamily: GMONO, fontSize: 11, color: T.allow, letterSpacing: 0.3,
            }}>{l.proof}</div>
          </div>
        ))}
      </div>
    </Section>
  );
}

// ── Verify yourself ───────────────────────────────────────────
function VerifyYourself() {
  const steps = [
    {
      n: '01', t: 'Read the contract',
      code: `// Call this on the contract — anyone can.\nERC721(${NFT_CONTRACT}).totalSupply()\n→ 25`,
      d: 'The collection has 25 tokens. There will never be a 26th. Verifiable in any block explorer.',
    },
    {
      n: '02', t: 'Compute any agent\u2019s wallet',
      code: `// ERC-6551 deterministic wallet address\ntokenBoundAccount(\n  chainId: 8453, // Base\n  contract: ${NFT_CONTRACT.slice(0, 10)}\u2026,\n  tokenId:  17,\n)`,
      d: 'Same inputs always produce the same address. Each agent\u2019s wallet is open to view.',
    },
    {
      n: '03', t: 'Inspect any receipt',
      code: `// Receipt anchors to a Base block\nreceipt.merkle_root \u2192 0xMR\u2026ab\nreceipt.block        \u2192 #46,270,762\nreceipt.signers      \u2192 [0xA1\u202624, \u2026 \u00d725]`,
      d: 'Every receipt anchors to a Base block. Pull the block, recompute the Merkle root, match it byte-for-byte.',
    },
    {
      n: '04', t: 'Verify the compute',
      code: `// GPU dispatcher every quantum\n// score routes through:\nPOST cuquantum.epochcoreqcs.com/v1/run\nauthorization: Bearer <token>\n{ "circuit": "<OpenQASM>",\n  "shots":   1024,\n  "backend": "auto" }\n\n// Source, pinned to a commit:\ngithub.com/QuantumSwarms/\n  epochcore-cusv-dispatcher\n  @ 5e504bfd`,
      d: 'Real GPU statevector simulation. Every receipt cites the commit it ran against. Replay the same circuit on your own GPU — same counts, \u00b1 statevector noise.',
    },
    {
      n: '05', t: 'Check liveness',
      code: `// 28-endpoint canary, public:\nGET status.epochcoreqcs.com\n\n// Returns green/red for every\n// surface in the platform.\n// Refreshes every 5 minutes.`,
      d: 'The platform monitors itself in the open. If anything goes red, you see it before we do.',
    },
    {
      n: '06', t: 'Audit the seal',
      code: `// Cryptographic seal of the\n// whole platform's source tree:\nGET chain.epochcoreqcs.com/v1/verify\n  ?hash=<tree_root>\n  &full=1\n\n// Returns the manifest of every\n// tracked file, signed.`,
      d: 'A signed tree-root hash over every line of code running the platform. If the source changes, the seal changes. Public verifier — no key required.',
    },
    {
      n: '07', t: 'Verify a sealed PDF',
      code: `// Same chain, different artifact.\n// Watermarked PDFs from\n// proof.epochpay.today carry an\n// XMP-embedded seal_full_hash.\nHASH = xmp.seal_full_hash\nGET chain.epochcoreqcs.com/v1/verify\n  ?hash=<HASH>&full=1\n\n// found: true,\n// signatures.post_quantum_dual_sign: true\n// = procurement-grade evidence`,
      d: 'Watermarked PDFs from proof.epochpay.today anchor to the same chain as Council orders and EpochPay receipts. One verifier, three artifact types.',
    },
  ];
  return (
    <Section id="verify" num="08" eyebrow="Verify yourself"
      title="You don\u2019t have to trust us. The proof is public."
      intro="Three reads from a free Base RPC endpoint and you have proven, end-to-end, that the Council is exactly what we claim it is.">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        {steps.map(s => (
          <div key={s.n} style={{
            background: T.ink, color: T.textInv,
            border: `1px solid ${T.inkBorder}`,
            padding: '24px 22px', display: 'flex', flexDirection: 'column', gap: 14,
          }}>
            <div>
              <Mono color={T.allow} weight={500}>§ 08.{s.n}</Mono>
              <h3 style={{
                fontFamily: GEIST, fontWeight: 600, fontSize: 20,
                letterSpacing: -0.5, margin: '8px 0 0', color: T.textInv,
              }}>{s.t}</h3>
            </div>
            <pre style={{
              margin: 0, padding: '12px 14px', background: 'rgba(244,244,240,0.04)',
              border: `1px solid ${T.inkBorder}`, overflow: 'auto',
              fontFamily: GMONO, fontSize: 11.5, lineHeight: 1.55,
              color: '#9FE7BD', letterSpacing: 0.2, whiteSpace: 'pre-wrap',
            }}>{s.code}</pre>
            <p style={{
              margin: 0, fontSize: 13.5, lineHeight: 1.55,
              color: 'rgba(244,244,240,0.7)', letterSpacing: -0.05,
            }}>{s.d}</p>
          </div>
        ))}
      </div>

      <div style={{
        marginTop: 24, padding: '16px 20px',
        border: `1px solid ${T.allow}`, background: 'rgba(45,216,129,0.06)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18,
      }}>
        <div>
          <Mono color={T.allow} weight={500}>WANT TO POKE IT YOURSELF?</Mono>
          <p style={{ margin: '6px 0 0', fontSize: 13.5, color: T.textInv, letterSpacing: -0.05, lineHeight: 1.5 }}>
            Open the contract on Basescan, read totalSupply, then click any token to see its current holder. The address you land on holds the entire Council.
          </p>
        </div>
        <TXButton variant="allow" href={basescanContract()} size="md">Open Basescan ↗</TXButton>
      </div>
    </Section>
  );
}

// ── Footer ────────────────────────────────────────────────────
function CouncilFooter() {
  return (
    <footer style={{ background: T.ink, color: T.textInv, padding: '64px 0 32px', borderTop: `1px solid ${T.inkBorder}` }}>
      <div style={{ maxWidth: 1320, margin: '0 auto', padding: '0 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 48, marginBottom: 48 }}>
          <div>
            <BrandMark size={28} withWord label="EpochCore"/>
            <p style={{
              marginTop: 18, fontSize: 14, lineHeight: 1.55,
              color: 'rgba(244,244,240,0.6)', maxWidth: 360, letterSpacing: -0.05,
            }}>
              The Council is a finite NFT collection of 25 on-chain trading verifiers. Each one is a smart wallet, each one a public vote, each one a public stake. By EpochCore.
            </p>
            <div style={{
              marginTop: 14, padding: '6px 10px',
              border: `1px dashed ${T.inkBorder}`, display: 'inline-block',
            }}>
              <Mono color={T.muteInv} size={9}>
                BRAND SEED · {String(BRAND_SEEDS.colorSeed).slice(0, 13)} · OSCILLIAN STUDIO
              </Mono>
            </div>
          </div>
          <FootCol title="Council" links={[
            { l: 'Roster',          href: '#roster' },
            { l: 'Proof',           href: '#proof' },
            { l: 'Independence',    href: '#matrix' },
            { l: 'Heartbeat',       href: '#heartbeat' },
            { l: 'Slashing log',    href: '#slashing' },
            { l: 'Live votes',      href: '#live' },
            { l: 'Verify yourself', href: '#verify' },
          ]}/>
          <FootCol title="On-chain" links={[
            { l: 'Contract',         href: basescanContract() },
            { l: 'Collection owner', href: basescanAddr(COUNCIL_OWNER) },
            { l: 'OpenSea',          href: '#' },
            { l: 'Base block index', href: 'https://basescan.org' },
          ]}/>
          <FootCol title="Platform" links={[
            { l: 'Back to landing',  href: 'https://www.tradexchange.cc/' },
            { l: 'Open terminal',    href: '/' },
            { l: 'Pricing',          href: 'https://www.tradexchange.cc/#pricing' },
            { l: 'Customer onboarding →', href: 'onboarding.html' },
          ]}/>
        </div>
        <div style={{
          paddingTop: 24, borderTop: `1px solid ${T.inkBorder}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap',
        }}>
          <Mono color={T.muteInv}>© 2026 EPOCHCORE LLC · COUNCIL v1 · NOT INVESTMENT ADVICE</Mono>
          <Mono color={T.muteInv}>BASE CHAIN ID 8453 · ERC-721 · ERC-6551</Mono>
        </div>
      </div>
    </footer>
  );
}

function FootCol({ title, links }) {
  return (
    <div>
      <Mono color={T.allow} weight={500}>{title}</Mono>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
        {links.map(l => (
          <a key={l.l} href={l.href} target={l.href && l.href.startsWith('http') ? '_blank' : undefined} rel="noopener" style={{
            color: 'rgba(244,244,240,0.75)',
            fontFamily: GEIST, fontSize: 14, letterSpacing: -0.05,
          }}>{l.l}</a>
        ))}
      </div>
    </div>
  );
}

// ── App ───────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);

  // Apply aesthetic by toggling a class on <body>.
  React.useEffect(() => {
    const body = document.body;
    ['aes-terminal','aes-singularity','aes-velocity','aes-runtime','aes-protocol','aes-crown'].forEach(c => body.classList.remove(c));
    body.classList.add(`aes-${t.aesthetic || 'singularity'}`);
    return () => body.classList.remove(`aes-${t.aesthetic || 'singularity'}`);
  }, [t.aesthetic]);

  // The Roster / Matrix / Live components each bring their own H2 header.
  // Wrap them in plain dark sections so the brand Section doesn't double up.
  const wrap = (id, padTop = 80, padBot = 80, dark = true) => ({
    id,
    style: {
      background: dark ? T.ink : T.paper,
      color: dark ? T.textInv : T.text,
      padding: `${padTop}px 0 ${padBot}px`,
    },
  });
  const inner = { maxWidth: 1320, margin: '0 auto', padding: '0 32px' };

  return (
    <div style={{ color: T.textInv, minHeight: '100vh' }}>
      <CouncilNav/>
      <CouncilHero/>

      <section {...wrap('roster', 64, 96)}>
        <div style={inner}><Roster layout={t.rosterLayout}/></div>
      </section>

      <CouncilProof/>

      <section {...wrap('matrix', 88, 96)}>
        <div style={inner}><AgreementMatrix/></div>
      </section>

      <section {...wrap('heartbeat', 88, 96)}>
        <div style={inner}><Heartbeat/></div>
      </section>

      <section {...wrap('slashing', 88, 96)}>
        <div style={inner}><SlashingLog/></div>
      </section>

      <section {...wrap('family', 88, 96)}>
        <div style={inner}><FamilyTree/></div>
      </section>

      <section {...wrap('lineage', 88, 96)}>
        <div style={inner}><LineageStrip/></div>
      </section>

      <section {...wrap('live', 88, 96)}>
        <div style={inner}><LiveCouncilFeed/></div>
      </section>

      <VerifyYourself/>

      <CouncilFooter/>

      <TweaksPanel title="Council tweaks">
        <TweakSection label="Aesthetic"/>
        <TweakSelect label="Atmosphere" value={t.aesthetic}
                     options={['terminal', 'singularity', 'velocity', 'runtime', 'protocol', 'crown']}
                     onChange={(v) => setTweak('aesthetic', v)}/>

        <TweakSection label="Roster"/>
        <TweakRadio label="Layout" value={t.rosterLayout}
                    options={['compact', 'comfort', 'showcase']}
                    onChange={(v) => setTweak('rosterLayout', v)}/>
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
