// council-slashing.jsx
// Public slashing log — proof of consequence.
//
// Each smart wallet stakes capital. Wrong votes get slashed publicly,
// on-chain. After enough time, slash histories diverge enough to be
// statistically impossible to fake. Anyone can audit any slash by
// pulling the linked transaction from Base.

const SLASH_REASONS = [
  { tag: 'CIRCUIT-BREAK',  pattern: 'Voted CLEARED on {sym}; price hit limit-down 90s after fill — slashed.' },
  { tag: 'STALE-QUOTE',    pattern: 'Voted CLEARED on {sym} against a quote >5s stale — slashed.' },
  { tag: 'WIDE-SPREAD',    pattern: 'Voted CLEARED on {sym} when bid-ask exceeded the slip cap — slashed.' },
  { tag: 'BAD-WICK',       pattern: 'Voted CLEARED on {sym} after a flash wick the pattern check should have caught — slashed.' },
  { tag: 'EVENT-MISS',     pattern: 'Voted CLEARED on {sym} 14m before earnings; halted within minutes — slashed.' },
  { tag: 'NEWS-MISS',      pattern: 'Voted CLEARED on {sym} 6m after an SEC filing the news check missed — slashed.' },
  { tag: 'CONC-MISS',      pattern: 'Voted CLEARED on a position that pushed sector concentration past the cap — slashed.' },
  { tag: 'CORR-MISS',      pattern: 'Voted CLEARED on {sym} despite a correlation cluster with two existing positions — slashed.' },
];

const SLASH_SYMBOLS = ['AAPL','TSLA','NVDA','META','AMZN','MSFT','GME','SPY','QQQ','PLTR','SOFI','UBER','AMD','BABA','HK.00700','HK.09988','SHOP','NIO','RIVN','COIN'];

// Deterministic — same per-agent slash history every render.
function slashesFor(agent) {
  const stats = statsFor(agent.id);
  if (stats.slashCount === 0) return [];
  const out = [];
  const r = (off) => {
    const x = ((agent.id * 1664525 + off * 1013904223) ^ 0xDEADBEEF) >>> 0;
    return ((x * 1103515245 + 12345) >>> 0) / 0xFFFFFFFF;
  };
  for (let i = 0; i < stats.slashCount; i++) {
    const reason = SLASH_REASONS[Math.floor(r(i * 7 + 1) * SLASH_REASONS.length)];
    const sym = SLASH_SYMBOLS[Math.floor(r(i * 7 + 2) * SLASH_SYMBOLS.length)];
    const amount = +(0.05 + r(i * 7 + 3) * 0.45).toFixed(3);
    const daysAgo = 5 + Math.floor(r(i * 7 + 4) * 320);
    const block = 46_000_000 - daysAgo * 43_200 + Math.floor(r(i * 7 + 5) * 5000);
    const date = new Date(Date.now() - daysAgo * 86_400_000);
    const dateLabel = date.toISOString().slice(0, 10);
    const tx = '0x' + (((agent.id * 17 + i * 31) * 2654435761) >>> 0).toString(16).padStart(8, '0').repeat(8).slice(0, 64);
    const orderId = 'ord_' + ((agent.id * 999 + i * 37) >>> 0).toString(16).padStart(8, '0').slice(0, 8);
    out.push({
      agent, amount, daysAgo, dateLabel, block, tx, orderId,
      reasonTag: reason.tag,
      reasonText: reason.pattern.replace('{sym}', sym),
      sym,
    });
  }
  return out;
}

// All slashes in the past, sorted newest-first.
function allSlashesNewestFirst() {
  const out = [];
  for (const a of AGENTS) out.push(...slashesFor(a));
  out.sort((x, y) => x.daysAgo - y.daysAgo);
  return out;
}

// ── Slashing Log section ──────────────────────────────────────
function SlashingLog() {
  const all = React.useMemo(allSlashesNewestFirst, []);
  const [filter, setFilter] = React.useState('all');     // 'all' | reasonTag

  // Aggregate stats
  const totalEthSlashed = +all.reduce((s, x) => s + x.amount, 0).toFixed(3);
  const agentsAffected = new Set(all.map(x => x.agent.id)).size;
  const cleanAgents = AGENTS.length - agentsAffected;

  // Slash counts per reason tag for filter chips
  const reasonCounts = {};
  for (const tag of SLASH_REASONS.map(r => r.tag)) reasonCounts[tag] = 0;
  for (const s of all) reasonCounts[s.reasonTag] = (reasonCounts[s.reasonTag] || 0) + 1;

  const filtered = filter === 'all' ? all : all.filter(s => s.reasonTag === filter);

  // "Top 5 most slashed agents" leaderboard
  const perAgent = {};
  for (const s of all) {
    perAgent[s.agent.id] = perAgent[s.agent.id] || { agent: s.agent, count: 0, eth: 0 };
    perAgent[s.agent.id].count += 1;
    perAgent[s.agent.id].eth += s.amount;
  }
  const top5 = Object.values(perAgent).sort((a, b) => b.eth - a.eth).slice(0, 5);

  return (
    <div>
      <div style={{ marginBottom: 22, maxWidth: 760 }}>
        <Mono color={T.allow} weight={500}>§ 06 · CONSEQUENCE</Mono>
        <h2 style={{
          fontFamily: GEIST, fontWeight: 600, fontSize: 36, letterSpacing: -1.2, lineHeight: 1.05,
          margin: '10px 0 6px', color: T.textInv,
        }}>Wrong votes cost money. Publicly.</h2>
        <p style={{
          margin: 0, fontSize: 15, lineHeight: 1.55,
          color: T.muteInv, letterSpacing: -0.1,
        }}>
          Every agent stakes ETH in its smart wallet. When a vote goes wrong — clearing an order the platform later flags as harmful — the stake is slashed on-chain. Different agents have different slash histories, which is itself a proof of independence. One entity controlling all 25 would have no reason to penalize itself.
        </p>
      </div>

      {/* Aggregate strip */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 0,
        border: `1px solid ${T.inkBorder}`, background: 'rgba(244,244,240,0.02)',
        marginBottom: 20,
      }}>
        <Agg k="TOTAL SLASHES"    v={`${all.length}`}             sub="all-time, on Base"/>
        <Agg k="ETH SLASHED"      v={`${totalEthSlashed} ETH`}     sub={`avg ${(totalEthSlashed/Math.max(1,all.length)).toFixed(3)}/event`}/>
        <Agg k="AGENTS AFFECTED"  v={`${agentsAffected} of 25`}    sub={`${cleanAgents} clean records`}/>
        <Agg k="MOST RECENT"      v={all[0] ? `${all[0].daysAgo}d ago` : '\u2014'}
                                  sub={all[0] ? all[0].agent.name : 'no slashes'}
                                  color={T.refuse}/>
        <Agg k="HEALTH"           v="HEALTHY"   color={T.allow}
                                  sub="below threshold by 73%"/>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20, alignItems: 'flex-start' }}>
        {/* LEFT — reason filter + event list */}
        <div>
          {/* Filter chips */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center', marginBottom: 14 }}>
            <Mono color={T.muteInv} size={10}>FILTER</Mono>
            <SlashChip label="ALL"     count={all.length}                  on={filter === 'all'} onClick={() => setFilter('all')}/>
            {SLASH_REASONS.map(r => reasonCounts[r.tag] > 0 && (
              <SlashChip key={r.tag} label={r.tag} count={reasonCounts[r.tag]}
                on={filter === r.tag} onClick={() => setFilter(r.tag)}/>
            ))}
          </div>

          {/* Event rows */}
          <div style={{
            border: `1px solid ${T.inkBorder}`, background: 'rgba(244,244,240,0.02)',
            maxHeight: 580, overflowY: 'auto',
            scrollbarWidth: 'thin', scrollbarColor: 'rgba(244,244,240,0.15) transparent',
          }}>
            {filtered.length === 0 && (
              <div style={{ padding: '40px 22px', textAlign: 'center', color: T.muteInv, fontSize: 13 }}>
                No slash events match the current filter.
              </div>
            )}
            {filtered.map((s, i) => <SlashRow key={s.tx} slash={s} idx={i} last={i === filtered.length - 1}/>)}
          </div>
        </div>

        {/* RIGHT — top-5 slashed agents leaderboard + footnote */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div style={{
            border: `1px solid ${T.inkBorder}`, background: 'rgba(244,244,240,0.02)',
            padding: '16px 18px',
          }}>
            <Mono color={T.allow} weight={500}>MOST SLASHED · TOP 5</Mono>
            <p style={{ margin: '6px 0 12px', fontSize: 11.5, color: T.muteInv, letterSpacing: -0.05, lineHeight: 1.5 }}>
              The leaderboard nobody wants to top. Persistent offenders bleed stake until they drop below the participation floor.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {top5.map((row, i) => {
                const spec = SPEC[row.agent.specialty];
                return (
                  <a key={row.agent.id}
                     href={basescanAddr(tbaFor(row.agent.id))} target="_blank" rel="noopener"
                     style={{
                       display: 'grid', gridTemplateColumns: '20px 28px 1fr auto', gap: 10, alignItems: 'center',
                       padding: '8px 10px',
                       background: 'rgba(244,244,240,0.02)', border: `1px solid ${T.inkBorder}`,
                       transition: 'transform .15s ease',
                     }}
                     onMouseEnter={e => e.currentTarget.style.transform = 'translateX(2px)'}
                     onMouseLeave={e => e.currentTarget.style.transform = 'translateX(0)'}
                  >
                    <Mono color={T.muteInv} size={10}>{i + 1}</Mono>
                    <Sigil id={row.agent.id} color={spec.color} size={22}/>
                    <div>
                      <div style={{
                        fontFamily: GMONO, fontSize: 12, fontWeight: 500,
                        color: T.textInv, letterSpacing: 0.4,
                      }}>{row.agent.name}</div>
                      <Mono color={T.muteInv} size={9}>{spec.label.toUpperCase()} · {row.count} EVENT{row.count > 1 ? 'S' : ''}</Mono>
                    </div>
                    <span style={{
                      fontFamily: GMONO, fontSize: 12, color: T.refuse, letterSpacing: 0.3,
                    }}>{row.eth.toFixed(3)} ETH</span>
                  </a>
                );
              })}
            </div>
          </div>

          <div style={{
            padding: '12px 14px', border: `1px dashed ${T.inkBorder}`,
            background: 'rgba(244,244,240,0.015)',
          }}>
            <Mono color={T.allow} size={9.5} weight={500}>WHAT THIS PROVES</Mono>
            <p style={{
              margin: '6px 0 0', fontSize: 11.5, lineHeight: 1.55,
              color: 'rgba(244,244,240,0.78)', letterSpacing: -0.05,
            }}>
              A single entity controlling 25 wallets has no rational reason to slash itself. Divergent slash histories — different counts, different totals, different reasons — are statistically impossible to fake without a real adversarial process. Each row above is independently verifiable on Base.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

function Agg({ k, v, sub, color }) {
  return (
    <div style={{ padding: '18px 22px', borderRight: `1px solid ${T.inkBorder}` }}>
      <Mono color={T.allow} weight={500} size={10}>{k}</Mono>
      <div style={{
        marginTop: 6, fontFamily: GMONO, fontSize: 18, fontWeight: 500,
        color: color || T.textInv, letterSpacing: 0.3,
      }}>{v}</div>
      <Mono color={T.muteInv} size={9.5} style={{ display: 'block', marginTop: 4 }}>{sub}</Mono>
    </div>
  );
}

function SlashChip({ label, count, on, onClick }) {
  return (
    <button onClick={onClick} style={{
      background: on ? T.refuse : 'transparent',
      color: on ? T.textInv : T.muteInv,
      border: `1px solid ${on ? T.refuse : T.inkBorder}`,
      padding: '5px 10px', cursor: 'pointer',
      fontFamily: GMONO, fontSize: 9.5, letterSpacing: 0.8, fontWeight: 500,
      textTransform: 'uppercase',
      display: 'inline-flex', alignItems: 'center', gap: 6,
      transition: 'all .12s ease',
    }}>
      {label}
      <span style={{
        fontSize: 9, opacity: 0.6,
        background: on ? 'rgba(10,11,14,0.28)' : 'rgba(244,244,240,0.06)',
        padding: '1px 5px',
      }}>{count}</span>
    </button>
  );
}

function SlashRow({ slash, idx, last }) {
  const spec = SPEC[slash.agent.specialty];
  const seed = (typeof slashSeed === 'function') ? slashSeed(slash.tx) : 0;
  return (
    <a href={basescanTx(slash.tx)} target="_blank" rel="noopener"
       style={{
         display: 'grid', gap: 14,
         gridTemplateColumns: '80px 30px 36px 1fr 90px 100px 90px',
         alignItems: 'center', padding: '14px 18px',
         borderBottom: last ? 'none' : `1px solid ${T.inkBorder}`,
         transition: 'background .12s ease',
       }}
       onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,86,117,0.05)'}
       onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <div>
        <Mono color={T.muteInv} size={10}>{slash.dateLabel}</Mono>
        <div style={{ fontFamily: GMONO, fontSize: 10, color: T.muteInv, marginTop: 2 }}>
          {slash.daysAgo}d ago
        </div>
      </div>

      <Sigil id={slash.agent.id} color={spec.color} size={26}/>

      {/* Per-slash generative mark — verifiable from the slash tx */}
      <div title={`Slash sigil · ${slash.tx.slice(0, 10)}…`}>
        {typeof SeedSigil === 'function' && (
          <SeedSigil seed={seed} size={30} variant="mark"
            colors={{ ring: '#e72020', field: '#b05222', core: '#e72020' }}/>
        )}
      </div>

      <div style={{ minWidth: 0 }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3,
        }}>
          <span style={{ fontFamily: GMONO, fontSize: 12, fontWeight: 500, color: T.textInv, letterSpacing: 0.4 }}>
            {slash.agent.name}
          </span>
          <Mono color={spec.color} size={9} weight={500}>{spec.label.toUpperCase()}</Mono>
        </div>
        <div style={{
          fontSize: 12.5, lineHeight: 1.45, color: 'rgba(244,244,240,0.75)',
          letterSpacing: -0.05, overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{slash.reasonText}</div>
        <Mono color={T.muteInv} size={9.5} style={{ display: 'block', marginTop: 4 }}>
          ORDER {slash.orderId} · BLOCK #{slash.block.toLocaleString()}
        </Mono>
      </div>

      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        padding: '4px 8px',
        background: 'rgba(255,86,117,0.10)', border: `1px solid ${T.refuse}`,
        fontFamily: GMONO, fontSize: 10, color: T.refuse, letterSpacing: 0.6,
        fontWeight: 500,
      }}>{slash.reasonTag}</span>

      <span style={{
        fontFamily: GMONO, fontSize: 14, color: T.refuse, fontWeight: 500,
        letterSpacing: 0.3, textAlign: 'right',
      }}>−{slash.amount} ETH</span>

      <span style={{
        fontFamily: GMONO, fontSize: 10, color: T.muteInv, letterSpacing: 0.4,
        textAlign: 'right',
      }}>tx {slash.tx.slice(2, 8)}… ↗</span>
    </a>
  );
}

Object.assign(window, { SlashingLog, slashesFor, allSlashesNewestFirst });
