import type { Metadata } from 'next';
import Link from 'next/link';

export const metadata: Metadata = {
  title: 'How Resolution Works — Vaultfire',
  description:
    'Honest, technical breakdown of how Vaultfire actually resolves disputes and distributes accountability bonds. No hand-waving, no slashing theater — the real contract mechanism, with live on-chain numbers.',
};

// Always serve fresh on-chain numbers.
export const dynamic = 'force-dynamic';
export const revalidate = 0;

interface DistributionsApi {
  totalDisputesFiled: number;
  totalDisputesResolved: number;
  mechanismUsed: boolean;
  perChain: Record<
    string,
    {
      disputesFiled: number;
      disputesResolved: number;
      totalDisputeStake: string;
      totalActiveBondValue: string;
      totalPendingDistributions: string;
    }
  >;
  contracts: {
    accountability: Record<string, string>;
    disputes: Record<string, string>;
  };
  timestamp: number;
}

async function fetchDistributions(): Promise<DistributionsApi | null> {
  try {
    const r = await fetch(
      'https://theloopbreaker.com/api/protocol/distributions',
      { cache: 'no-store' },
    );
    if (!r.ok) return null;
    return r.json();
  } catch {
    return null;
  }
}

const EXPLORERS: Record<string, string> = {
  base:      'https://basescan.org/address/',
  avalanche: 'https://snowtrace.io/address/',
  arbitrum:  'https://arbiscan.io/address/',
  polygon:   'https://polygonscan.com/address/',
};

export default async function HowResolutionWorksPage() {
  const data = await fetchDistributions();

  return (
    <main style={{
      minHeight: '100vh',
      background: '#0a0a0a',
      color: '#F4F4F5',
      fontFamily: 'system-ui, -apple-system, "SF Pro Text", sans-serif',
      padding: '24px 16px 96px',
    }}>
      <div style={{ maxWidth: 680, margin: '0 auto' }}>

        {/* Top nav */}
        <div style={{ marginBottom: 16 }}>
          <Link href="/demo" style={{
            color: '#71717a', fontSize: 13, textDecoration: 'none',
          }}>← Back to demo</Link>
        </div>

        {/* Persistent alpha + collateral disclaimer strip */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          padding: '8px 12px',
          marginBottom: 24,
          borderRadius: 8,
          border: '1px solid rgba(234,179,8,0.25)',
          backgroundColor: 'rgba(234,179,8,0.05)',
          fontSize: 11,
          color: '#a1a1aa',
          flexWrap: 'wrap',
          lineHeight: 1.5,
        }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            color: '#EAB308', fontWeight: 600, letterSpacing: '0.04em',
          }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: '#EAB308' }} />
            ALPHA
          </span>
          <span>·</span>
          <span>Bonds are performance collateral, not investments.</span>
          <span>·</span>
          <Link href="/disclaimer" style={{ color: '#FF8C5A', textDecoration: 'underline' }}>
            Disclaimer
          </Link>
        </div>

        {/* Hero */}
        <header style={{ marginBottom: 48 }}>
          <div style={{
            display: 'inline-block',
            padding: '5px 12px',
            background: 'rgba(255,107,53,0.1)',
            color: '#FF6B35',
            borderRadius: 999,
            fontSize: 11,
            fontWeight: 600,
            letterSpacing: 0.6,
            textTransform: 'uppercase',
            marginBottom: 18,
          }}>The Honest Version</div>
          <h1 style={{
            fontSize: 30,
            fontWeight: 700,
            lineHeight: 1.18,
            margin: '0 0 14px',
            letterSpacing: -0.5,
          }}>
            How resolution actually works
          </h1>
          <p style={{
            fontSize: 15.5,
            color: '#a1a1aa',
            lineHeight: 1.6,
            margin: 0,
          }}>
            The /demo tells the story in plain English. This page tells you
            exactly what the contracts do — function names, events, the real
            mechanism. No simplification, no &ldquo;slashing&rdquo; metaphor.
            If you&apos;re evaluating Vaultfire technically, start here.
          </p>
        </header>

        {/* Honest framing */}
        <section style={CARD_WARN}>
          <div style={CARD_LABEL}>What this page corrects</div>
          <p style={{ ...P, marginTop: 8 }}>
            People talking about agent accountability default to the word{' '}
            <em>slashing</em> — borrowed from staking systems where misbehavior
            burns collateral. Vaultfire&apos;s mechanism is different and, we
            think, better. The bond doesn&apos;t get burned. It gets{' '}
            <strong style={STRONG}>distributed</strong> based on what actually
            happened, weighted toward the harmed human. That&apos;s what the
            contract does. That&apos;s what this page documents.
          </p>
        </section>

        {/* The two contracts */}
        <h2 style={H2}>The two contracts involved</h2>

        <div style={{ ...CARD, marginBottom: 14 }}>
          <div style={CARD_LABEL}>1 · AccountabilityBondV2</div>
          <p style={{ ...P, marginTop: 8, marginBottom: 10 }}>
            Holds the agent&apos;s collateral. Tracks bond outcomes via signed
            metrics submissions. When a bond is ready to resolve, it computes
            an <em>appreciation</em> score (positive = the agent flourished,
            negative = the human was harmed) and splits the bond accordingly.
          </p>
          <CodeBlock>
            <strong>Key events:</strong><br />
            BondCreated — bond is posted<br />
            MetricsSubmitted — agent submits signed outcome data<br />
            MetricsChallenged — anyone can challenge the metrics with stake<br />
            ChallengeResolved — challenge is upheld or rejected<br />
            BondDistributed — bond pays out (humanShare, aiCompanyShare, appreciation)<br />
            ProfitsLocked — yield pool can&apos;t cover full payout
          </CodeBlock>
          <p style={{ ...P_SMALL, marginTop: 12, marginBottom: 0 }}>
            <strong style={STRONG}>There is no <code style={CODE}>Slashed</code> event.</strong>{' '}
            The contract does not burn collateral. It distributes it.
          </p>
        </div>

        <div style={{ ...CARD, marginBottom: 14 }}>
          <div style={CARD_LABEL}>2 · VaultfireDisputeResolution</div>
          <p style={{ ...P, marginTop: 8, marginBottom: 10 }}>
            Separate contract that handles disputes when parties disagree about
            an outcome. Disputes are resolved by an arbitrator panel — not by
            the contract auto-evaluating rules, and not by a single judge.
          </p>
          <CodeBlock>
            <strong>The flow:</strong><br />
            1. Plaintiff calls fileDispute() with a stake and evidence pointer<br />
            2. Owner assigns a panel of 3-7 arbitrators (selected by reputation)<br />
            3. Arbitrators vote: for claimant or for respondent<br />
            4. Majority resolves the dispute on-chain<br />
            5. Arbitrators earn a 5% fee split among the panel<br />
            6. Parties cannot vote on their own dispute (enforced in contract)
          </CodeBlock>
        </div>

        {/* Oracle layer */}
        <h2 style={H2}>How metrics get into the system</h2>
        <p style={{ ...P_SMALL, marginTop: -8, marginBottom: 14 }}>
          Disputes resolve human-vs-human outcomes. But the bond&apos;s
          appreciation also depends on <em>flourishing metrics</em> — numbers
          like &ldquo;was the booking confirmed,&rdquo; &ldquo;did the user mark
          it acceptable.&rdquo; Those numbers come from oracles. Here&apos;s the
          honest design.
        </p>

        <div style={{ ...CARD, marginBottom: 14 }}>
          <div style={CARD_LABEL}>FlourishingMetricsOracle</div>
          <p style={{ ...P, marginTop: 8, marginBottom: 10 }}>
            Multi-oracle consensus. A minimum of <strong style={STRONG}>3 independent oracles</strong>{' '}
            must submit a value during a submission window. The reported metric
            is the <strong style={STRONG}>median</strong> of all submissions —
            outlier-resistant by construction. Submissions outside an
            acceptable deviation band are flagged.
          </p>
          <CodeBlock>
            <strong>Design constraints (enforced in contract):</strong><br />
            • Minimum quorum: 3 oracles<br />
            • Aggregation: median (not mean) — resistant to extreme submissions<br />
            • Owner can register/remove oracles but <em>cannot</em> submit data<br />
            • Each oracle can only submit once per round<br />
            • Rounds have explicit deadlines; late submissions rejected
          </CodeBlock>
        </div>

        <div style={{ ...CARD, marginBottom: 14 }}>
          <div style={CARD_LABEL}>MultiOracleConsensus</div>
          <p style={{ ...P, marginTop: 8, marginBottom: 10 }}>
            Hardened consensus layer for high-stakes data. Oracles register
            with a stake. Status transitions are explicit:{' '}
            <code style={CODE}>Inactive</code> →{' '}
            <code style={CODE}>Active</code> → (on misbehavior){' '}
            <code style={CODE}>Suspended</code> or{' '}
            <code style={CODE}>Slashed</code>. The word &ldquo;slashed&rdquo;
            applies to <em>oracle stake</em>, not bond collateral — a separate
            mechanism from the bonds themselves.
          </p>
          <CodeBlock>
            <strong>Per-submission lifecycle:</strong><br />
            Pending  → awaiting consensus<br />
            Confirmed → quorum reached, value accepted<br />
            Disputed → oracles disagree significantly<br />
            Expired  → consensus window closed without quorum
          </CodeBlock>
        </div>

        <div style={{ ...CARD_WARN, marginBottom: 14 }}>
          <div style={CARD_LABEL}>Honest limitations</div>
          <p style={{ ...P, marginTop: 8, marginBottom: 8 }}>
            The oracle infrastructure is <strong style={STRONG}>deployed but lightly populated</strong>.
            The contract enforces a 3-oracle minimum, but in practice the
            oracle set is small and the owner has the power to register or
            remove oracles (disclosed on{' '}
            <Link href="/security" style={A}>/security</Link>). This is
            appropriate for the bootstrap stage and inappropriate for
            high-value enterprise use — we say so in both places.
          </p>
          <p style={{ ...P, marginBottom: 0 }}>
            Read the source:{' '}
            <a
              href="https://github.com/Ghostkey316/theloopbreaker.com/blob/main/contracts/FlourishingMetricsOracle.sol"
              target="_blank"
              rel="noopener noreferrer"
              style={A}
            >
              FlourishingMetricsOracle.sol ↗
            </a>
            {' · '}
            <a
              href="https://github.com/Ghostkey316/theloopbreaker.com/blob/main/contracts/MultiOracleConsensus.sol"
              target="_blank"
              rel="noopener noreferrer"
              style={A}
            >
              MultiOracleConsensus.sol ↗
            </a>
          </p>
        </div>

        {/* Distribution math */}
        <h2 style={H2}>How the distribution math works</h2>

        <div style={{ ...CARD, marginBottom: 14 }}>
          <p style={{ ...P, marginTop: 0, marginBottom: 12 }}>
            When <code style={CODE}>distributeBond(bondId)</code> is called,
            the contract reads the snapshotted appreciation and splits as
            follows:
          </p>
          <CodeBlock>
            if (appreciation &gt; 0)  // the agent earned a positive outcome<br />
            &nbsp;&nbsp;if (yieldPool covers it)  →  human gets full share<br />
            &nbsp;&nbsp;else                     →  50/50 split (ProfitsLocked event)<br />
            <br />
            if (appreciation &lt; 0)  // the human was harmed<br />
            &nbsp;&nbsp;humanShare = abs(appreciation)<br />
            &nbsp;&nbsp;aiCompanyShare = 0  →  the human is made whole first
          </CodeBlock>
          <p style={{ ...P_SMALL, marginTop: 12, marginBottom: 0 }}>
            Read it directly:{' '}
            <a
              href="https://github.com/Ghostkey316/theloopbreaker.com/blob/main/contracts/AIAccountabilityBondsV2.sol"
              target="_blank"
              rel="noopener noreferrer"
              style={A}
            >
              AIAccountabilityBondsV2.sol on GitHub ↗
            </a>
          </p>
        </div>

        {/* Live numbers */}
        <h2 style={H2}>Live numbers, right now</h2>
        <p style={{ ...P_SMALL, marginTop: -8, marginBottom: 14 }}>
          Fetched from each chain at page load. If a number is zero,
          it&apos;s zero — we don&apos;t pad.
        </p>

        {data ? (
          <>
            <div style={STATS_ROW}>
              <BigStat
                value={String(data.totalDisputesFiled)}
                label="Disputes filed"
              />
              <BigStat
                value={String(data.totalDisputesResolved)}
                label="Disputes resolved"
              />
              <BigStat
                value={data.mechanismUsed ? 'Yes' : 'Not yet'}
                label="Mechanism used in production"
              />
            </div>

            {!data.mechanismUsed && (
              <p style={{
                fontSize: 12.5, color: '#a1a1aa', lineHeight: 1.6,
                marginTop: 14, padding: 12,
                background: 'rgba(255,255,255,0.02)',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 10,
              }}>
                <strong style={STRONG}>Honest status:</strong> the resolution
                mechanism is deployed and live on all four chains, but no
                dispute has ever been filed in production. The infrastructure
                exists; it has not yet been tested in anger. We&apos;ll show
                you the first one when it happens.
              </p>
            )}

            <h3 style={H3}>Per-chain breakdown</h3>
            <div style={{
              border: '1px solid rgba(255,255,255,0.08)',
              borderRadius: 12,
              overflow: 'hidden',
            }}>
              {Object.entries(data.perChain).map(([chain, c], i, arr) => (
                <div key={chain} style={{
                  display: 'grid',
                  gridTemplateColumns: '1fr auto auto',
                  gap: 10,
                  padding: '12px 14px',
                  borderBottom: i < arr.length - 1
                    ? '1px solid rgba(255,255,255,0.06)'
                    : 'none',
                  background: i % 2 === 0
                    ? 'rgba(255,255,255,0.02)'
                    : 'transparent',
                  alignItems: 'center',
                }}>
                  <div>
                    <div style={{
                      fontSize: 13, fontWeight: 600,
                      color: '#F4F4F5', textTransform: 'capitalize',
                    }}>{chain}</div>
                    <div style={{ fontSize: 10.5, color: '#71717a', marginTop: 2 }}>
                      <a
                        href={`${EXPLORERS[chain] ?? ''}${data.contracts.disputes[chain]}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={A_DIM}
                      >
                        Disputes contract ↗
                      </a>
                      {' · '}
                      <a
                        href={`${EXPLORERS[chain] ?? ''}${data.contracts.accountability[chain]}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={A_DIM}
                      >
                        Bond contract ↗
                      </a>
                    </div>
                  </div>
                  <div style={MICRO_STAT}>
                    <div style={MICRO_VAL}>{c.disputesFiled}</div>
                    <div style={MICRO_LABEL}>filed</div>
                  </div>
                  <div style={MICRO_STAT}>
                    <div style={MICRO_VAL}>{c.disputesResolved}</div>
                    <div style={MICRO_LABEL}>resolved</div>
                  </div>
                </div>
              ))}
            </div>

            <p style={{
              fontSize: 11, color: '#52525b',
              marginTop: 10, textAlign: 'right',
            }}>
              Snapshot at {new Date(data.timestamp).toISOString()}
            </p>
          </>
        ) : (
          <p style={{ ...P_SMALL, color: '#a1a1aa' }}>
            Live data unavailable right now. Try refreshing — we never serve
            stale numbers, so an empty result means the RPC fan-out failed,
            not that the data is hidden.
          </p>
        )}

        {/* Why this framing */}
        <h2 style={H2}>Why we don&apos;t use the word &ldquo;slashing&rdquo;</h2>
        <div style={{ ...CARD, marginBottom: 14 }}>
          <p style={{ ...P, marginTop: 0 }}>
            Slashing is a punishment frame: the bond is the penalty, the
            misbehavior triggers the burn. That model leaks value out of the
            system every time something goes wrong, and it treats the harmed
            human as a beneficiary of the punishment rather than the priority.
          </p>
          <p style={{ ...P, marginBottom: 0 }}>
            Distribution by appreciation is a different shape. The bond is
            still real, the agent still has skin in the game, but when the
            outcome is bad the harmed human is{' '}
            <strong style={STRONG}>made whole first</strong>. When the outcome
            is good, the human shares in the upside. The mechanism mirrors the
            principle: <em>making human thriving more profitable than extraction</em>.
          </p>
        </div>

        {/* Audit transparency note */}
        <h2 style={H2}>Has this been audited?</h2>
        <div style={{ ...CARD, marginBottom: 14 }}>
          <p style={{ ...P, marginTop: 0, marginBottom: 10 }}>
            <strong style={STRONG}>Honestly: not by a third-party firm.</strong>{' '}
            The contracts have gone through local review and AI-assisted audit
            passes (most recently the V3.3-R3 review). They are{' '}
            <strong style={STRONG}>open-source</strong> and deployed at the
            addresses linked above — anyone with the skill is welcome to read
            them, fork them, or break them.
          </p>
          <p style={{ ...P, marginBottom: 0 }}>
            A paid third-party audit costs more than this project currently
            earns. We&apos;d rather tell you that than fake it. If you want to
            audit the code yourself or fund an external review, the contact is{' '}
            <a href="mailto:ghostkey316@proton.me" style={A}>ghostkey316@proton.me</a>.
          </p>
        </div>

        {/* CTA */}
        <section style={{
          marginTop: 32,
          padding: 22,
          background: 'linear-gradient(135deg, rgba(255,107,53,0.10), rgba(255,107,53,0.02))',
          border: '1px solid rgba(255,107,53,0.25)',
          borderRadius: 16,
          textAlign: 'center',
        }}>
          <h3 style={{
            fontSize: 17, fontWeight: 700, margin: '0 0 6px', color: '#F4F4F5',
          }}>Want the plain-English version?</h3>
          <p style={{
            fontSize: 13, color: '#a1a1aa', margin: '0 0 16px',
          }}>
            The 60-second story walks through Alice and a real on-chain agent.
          </p>
          <Link href="/demo" style={CTA_PRIMARY}>Read the demo →</Link>
        </section>

        {/* Mission statement */}
        <p style={{
          fontSize: 14,
          fontStyle: 'italic',
          color: '#FF6B35',
          opacity: 0.85,
          textAlign: 'center',
          marginTop: 32,
          marginBottom: 0,
          lineHeight: 1.5,
          letterSpacing: '0.005em',
        }}>
          Making human thriving more profitable than extraction.
        </p>

      </div>
    </main>
  );
}

/* ─────────────────────────  COMPONENTS  ───────────────────── */

function BigStat({ value, label }: { value: string; label: string }) {
  return (
    <div style={{
      background: 'rgba(255,255,255,0.03)',
      border: '1px solid rgba(255,255,255,0.06)',
      borderRadius: 10,
      padding: '14px 8px',
      textAlign: 'center',
    }}>
      <div style={{
        fontSize: 22, fontWeight: 700, color: '#FF6B35',
        fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      <div style={{ fontSize: 10.5, color: '#71717a', marginTop: 4 }}>{label}</div>
    </div>
  );
}

function CodeBlock({ children }: { children: React.ReactNode }) {
  return (
    <pre style={{
      fontSize: 12,
      lineHeight: 1.7,
      color: '#d4d4d8',
      background: 'rgba(0,0,0,0.35)',
      border: '1px solid rgba(255,255,255,0.06)',
      borderRadius: 8,
      padding: '12px 14px',
      margin: 0,
      whiteSpace: 'pre-wrap',
      wordBreak: 'break-word',
      fontFamily: '"SF Mono", Menlo, Consolas, monospace',
    }}>
      {children}
    </pre>
  );
}

/* ─────────────────────────  STYLES  ───────────────────────── */

const P: React.CSSProperties = {
  fontSize: 14.5, lineHeight: 1.65, color: '#d4d4d8', margin: '0 0 10px',
};
const P_SMALL: React.CSSProperties = {
  fontSize: 13, lineHeight: 1.6, color: '#a1a1aa', margin: '0 0 6px',
};
const STRONG: React.CSSProperties = {
  color: '#F4F4F5', fontWeight: 600,
};
const H2: React.CSSProperties = {
  fontSize: 18, fontWeight: 700, color: '#F4F4F5',
  margin: '36px 0 14px', letterSpacing: -0.2,
};
const H3: React.CSSProperties = {
  fontSize: 14, fontWeight: 600, color: '#F4F4F5',
  margin: '20px 0 10px', letterSpacing: -0.1,
};
const CARD: React.CSSProperties = {
  background: 'rgba(255,255,255,0.03)',
  border: '1px solid rgba(255,255,255,0.08)',
  borderRadius: 14,
  padding: 18,
};
const CARD_WARN: React.CSSProperties = {
  background: 'rgba(255,107,53,0.05)',
  border: '1px solid rgba(255,107,53,0.18)',
  borderRadius: 14,
  padding: 18,
  marginBottom: 14,
};
const CARD_LABEL: React.CSSProperties = {
  fontSize: 11, fontWeight: 600, letterSpacing: 0.7,
  textTransform: 'uppercase', color: '#FF6B35',
};
const CODE: React.CSSProperties = {
  fontFamily: '"SF Mono", Menlo, Consolas, monospace',
  fontSize: 12,
  background: 'rgba(255,255,255,0.05)',
  padding: '1px 6px',
  borderRadius: 4,
  color: '#F4F4F5',
};
const A: React.CSSProperties = {
  color: '#FF6B35', textDecoration: 'underline',
};
const A_DIM: React.CSSProperties = {
  color: '#a1a1aa', textDecoration: 'underline',
};
const STATS_ROW: React.CSSProperties = {
  display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
};
const MICRO_STAT: React.CSSProperties = {
  textAlign: 'right', minWidth: 56,
};
const MICRO_VAL: React.CSSProperties = {
  fontSize: 16, fontWeight: 700, color: '#F4F4F5',
  fontVariantNumeric: 'tabular-nums',
};
const MICRO_LABEL: React.CSSProperties = {
  fontSize: 10, color: '#71717a', marginTop: 2,
};
const CTA_PRIMARY: React.CSSProperties = {
  display: 'inline-block',
  fontSize: 14, fontWeight: 700, padding: '11px 18px',
  background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
  color: '#fff', borderRadius: 10, textDecoration: 'none',
};
