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

export const metadata: Metadata = {
  title: 'How Vaultfire Works — A 60-Second Story',
  description:
    "Why Vaultfire matters, in plain English. Meet Alice, an AI agent, and a $500 bond that makes accountability automatic. Real agent, real bond, real on-chain proof.",
};

// Always serve fresh on-chain numbers — no stale demo data.
export const dynamic = 'force-dynamic';
export const revalidate = 0;

/* ─────────────────────────  TYPES  ───────────────────────── */

// Matches the actual /api/agent/status payload shape.
interface AgentStatus {
  registered: boolean;
  vnsName?: string;
  name?: string;
  description?: string;
  bondTier?: string | null;
  trustScore?: number | null;
  bondCount?: number;
  bondAmountEth?: number;
  explorerUrl?: string;
}

// Per-chain stake entry. Vaultfire bonds are denominated in the native gas
// token of each chain — ETH on Base/Arbitrum, AVAX on Avalanche, POL on
// Polygon. We never sum these into a single number because they are
// different assets with different prices.
interface ChainStake {
  chain: string;             // 'base' | 'avalanche' | 'arbitrum' | 'polygon'
  amount: number;            // Amount in that chain's native token
  token: string;             // 'ETH' | 'AVAX' | 'POL'
}

// Map each chain to its native gas token. Truthful units only — no fake ETH.
const CHAIN_NATIVE_TOKEN: Record<string, string> = {
  base: 'ETH',
  arbitrum: 'ETH',
  avalanche: 'AVAX',
  polygon: 'POL',
};

interface AggregatedAgent {
  vnsName: string;
  description: string;
  trustTier: string;         // Trust tier derived from bestScore — same
                             // ladder /agent/[address] uses, so demo → profile
                             // is consistent.
  bestScore: number;         // Best trustScore across chains.
  totalBonds: number;        // Sum across all chains.
  stakeByChain: ChainStake[];// Per-chain stake in native token (ETH/AVAX/POL).
                             // We do NOT sum across chains — different tokens.
  registeredChains: string[];// Chains where registered=true.
  explorerUrl: string;       // Explorer link.
}

// Mirror the tier ladder used in app/agent/[address]/page.tsx so both
// surfaces show the same tier for the same agent.
function trustTierFromScore(score: number): string {
  if (score >= 90) return 'Diamond';
  if (score >= 75) return 'Platinum';
  if (score >= 60) return 'Gold';
  if (score >= 40) return 'Silver';
  if (score >= 20) return 'Bronze';
  return 'Newcomer';
}

interface HubStats {
  totalIdentities: number;
  activeBonds: number;
  chainCounts: Record<string, number>;
  chainBonded: Record<string, { amount: number; token: string }>;
}

interface BondCounts {
  partnership: number;
  accountability: number;
  total: number;
}

interface Distributions {
  totalDisputesFiled: number;
  totalDisputesResolved: number;
  mechanismUsed: boolean;
}

/* ─────────────────────────  DATA  ─────────────────────────── */

// The featured agent — vaultfire-sentinel.vns, the founding agent.
const FEATURED_AGENT = '0xa054f831b562e729f8d268291ebde1b2edcfb84f';

// Pinned "story" artifact — the live Accountability contract on Base, linked
// from the receipt so every claim points to a real on-chain artifact.
const ACCOUNTABILITY_BASE = '0x6750D28865434344e04e1D0a6044394b726C3dfE';

const ALL_CHAINS = ['base', 'avalanche', 'arbitrum', 'polygon'] as const;

async function fetchAgentOnChain(chain: string): Promise<AgentStatus | null> {
  try {
    const r = await fetch(
      `https://theloopbreaker.com/api/agent/status?address=${FEATURED_AGENT}&chain=${chain}`,
      { cache: 'no-store' },
    );
    if (!r.ok) return null;
    return r.json();
  } catch {
    return null;
  }
}

/**
 * Fetch the featured agent across all 4 chains and aggregate honestly.
 * If a chain RPC fails, that chain is excluded — we never make up data.
 */
async function fetchAgentAggregated(): Promise<AggregatedAgent | null> {
  const results = await Promise.all(ALL_CHAINS.map(c => fetchAgentOnChain(c)));
  const registered = results
    .map((r, i) => ({ chain: ALL_CHAINS[i] as string, data: r }))
    .filter((x): x is { chain: string; data: AgentStatus } =>
      x.data !== null && x.data.registered === true,
    );

  if (registered.length === 0) return null;

  let bestScore = 0;
  let totalBonds = 0;
  const stakeByChain: ChainStake[] = [];
  let firstName = '';
  let firstDesc = '';
  let explorerUrl = '';

  for (const { chain, data } of registered) {
    if (data.vnsName && !firstName) firstName = data.vnsName;
    if (data.description && !firstDesc) firstDesc = data.description;
    if (chain === 'base' && data.explorerUrl) explorerUrl = data.explorerUrl;

    const score = data.trustScore ?? 0;
    if (score > bestScore) bestScore = score;

    totalBonds += data.bondCount ?? 0;

    // Capture this chain's stake in its OWN native token. The /api/agent/status
    // field is misnamed `bondAmountEth` for legacy reasons but the value is
    // already denominated in whatever native gas token the chain uses
    // (computed as `Number(stakeWei) / 1e18` from the contract).
    const amount = data.bondAmountEth ?? 0;
    if (amount > 0) {
      stakeByChain.push({
        chain,
        amount: Math.round(amount * 10000) / 10000,
        token: CHAIN_NATIVE_TOKEN[chain] || '?',
      });
    }
  }

  if (!explorerUrl && registered[0]?.data.explorerUrl) {
    explorerUrl = registered[0].data.explorerUrl;
  }

  return {
    vnsName: firstName || 'vaultfire-sentinel.vns',
    description: firstDesc,
    trustTier: trustTierFromScore(bestScore),
    bestScore,
    totalBonds,
    stakeByChain,
    registeredChains: registered.map(r => r.chain),
    explorerUrl,
  };
}

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

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

async function fetchDistributions(): Promise<Distributions | 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;
  }
}

/* ─────────────────────────  PAGE  ─────────────────────────── */

export default async function DemoPage() {
  const [agent, stats, bondCounts, distributions] = await Promise.all([
    fetchAgentAggregated(),
    fetchStats(),
    fetchBondCounts(),
    fetchDistributions(),
  ]);

  // Honest empty values when data isn't available — no invented numbers.
  const agentName = agent?.vnsName || 'vaultfire-sentinel.vns';
  const agentTier = agent?.trustTier || '—';
  const agentScore = agent && agent.bestScore > 0 ? String(agent.bestScore) : '—';
  const agentBonds = agent ? String(agent.totalBonds) : '—';
  const stakeByChain = agent?.stakeByChain || [];
  const chains = agent?.registeredChains || [];
  const explorerLink = agent?.explorerUrl
    || `https://basescan.org/address/${FEATURED_AGENT}`;

  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: 640, margin: '0 auto' }}>

        {/* Top nav back link */}
        <div style={{ marginBottom: 16 }}>
          <Link href="/" style={{
            color: '#71717a', fontSize: 13, textDecoration: 'none',
          }}>← Back to home</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={{ textAlign: 'center', marginBottom: 64 }}>
          <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,
          }}>60-Second Story</div>
          <h1 style={{
            fontSize: 32,
            fontWeight: 700,
            lineHeight: 1.15,
            margin: '0 0 14px',
            letterSpacing: -0.5,
          }}>
            Why does Vaultfire matter?
          </h1>
          <p style={{
            fontSize: 15.5,
            color: '#a1a1aa',
            lineHeight: 1.55,
            margin: 0,
            maxWidth: 480,
            marginInline: 'auto',
          }}>
            AI agents are about to spend your money for you. Right now, no one
            is liable when they screw up. Here&apos;s how Vaultfire fixes that —
            with a real story and real on-chain proof.
          </p>
        </header>

        {/* ══════ SCENE 1 ══════ */}
        <Scene number={1} title="Meet Alice">
          <p style={P}>
            Alice asks her AI agent to book a flight to Tokyo for{' '}
            <strong style={STRONG}>$1,200</strong>.
          </p>
          <p style={P_SMALL}>
            She doesn&apos;t want to compare 40 sites. She just wants the agent to handle it.
          </p>
          <Illustration emoji="✈️" caption="A normal Tuesday in 2026" />
        </Scene>

        {/* ══════ SCENE 2 — THE PROBLEM ══════ */}
        <Scene number={2} title="Without Vaultfire" tone="bad">
          <p style={P}>The agent books the wrong flight. Won&apos;t refund.</p>
          <ul style={UL}>
            <li>The vendor says <em>&ldquo;not our agent.&rdquo;</em></li>
            <li>The agent&apos;s developer says <em>&ldquo;sorry, the model hallucinated.&rdquo;</em></li>
            <li>Alice is out <strong style={STRONG}>$1,200</strong>.</li>
            <li>No one takes responsibility. Accountability becomes slow, messy, and expensive.</li>
          </ul>
          <p style={P_SMALL}>
            This isn&apos;t hypothetical. The first wave of AI agents is hitting production with{' '}
            <strong style={STRONG}>zero accountability infrastructure</strong>.
          </p>
        </Scene>

        {/* ══════ SCENE 3 — THE IDEA ══════ */}
        <Scene number={3} title="What if the agent had skin in the game?">
          <p style={P}>
            What if — before doing your job — the agent had to lock real money
            in a smart contract that pays <em>you</em> if it breaks the rules?
          </p>
          <p style={P_SMALL}>
            That&apos;s a <strong style={STRONG}>bond</strong>. Bail money for AI.
            That&apos;s Vaultfire.
          </p>
        </Scene>

        {/* ══════ SCENE 4 — REAL AGENT ══════ */}
        <Scene number={4} title="Here's a real Vaultfire agent" tone="good">
          <p style={P}>
            Not a mockup. This agent is registered on-chain right now, on four
            networks. Click the address to verify on a block explorer.
          </p>

          <div style={{
            background: 'rgba(255,255,255,0.03)',
            border: '1px solid rgba(255,255,255,0.08)',
            borderRadius: 14,
            padding: 18,
            marginTop: 14,
          }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
              gap: 12, flexWrap: 'wrap', marginBottom: 12,
            }}>
              <div style={{ fontSize: 17, fontWeight: 700, color: '#F4F4F5' }}>
                {agentName}
              </div>
              <span style={TIER_BADGE}>{agentTier} · {agentScore}</span>
            </div>

            <div style={STAT_ROW}>
              <Stat label="Bonds posted" value={String(agentBonds)} />
              <Stat label="Chains" value={String(chains.length)} />
            </div>

            {/* Per-chain stake breakdown — every chain's bond is in its own
                native gas token (ETH on Base/Arb, AVAX on Avalanche, POL on
                Polygon). We never sum across chains because they are different
                assets. Truthful unit reporting only. */}
            {stakeByChain.length > 0 && (
              <div style={{ marginTop: 14 }}>
                <div style={{
                  fontSize: 11, color: '#71717a', textTransform: 'uppercase',
                  letterSpacing: 0.5, marginBottom: 8,
                }}>
                  Stake by chain
                </div>
                <div style={{
                  display: 'flex', flexWrap: 'wrap', gap: 8,
                }}>
                  {stakeByChain.map((s) => (
                    <div key={s.chain} style={{
                      background: 'rgba(255,255,255,0.04)',
                      border: '1px solid rgba(255,255,255,0.06)',
                      borderRadius: 8,
                      padding: '6px 10px',
                      fontSize: 12,
                    }}>
                      <span style={{ color: '#a1a1aa', textTransform: 'capitalize' }}>
                        {s.chain}
                      </span>
                      <span style={{ color: '#52525b', margin: '0 6px' }}>·</span>
                      <span style={{ color: '#F4F4F5', fontVariantNumeric: 'tabular-nums' }}>
                        {s.amount} {s.token}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div style={{ marginTop: 14, fontSize: 12, color: '#71717a' }}>
              Verified on:{' '}
              {chains.map((c, i) => (
                <span key={c}>
                  <span style={{ color: '#22c55e' }}>✓</span>{' '}
                  <span style={{ textTransform: 'capitalize' }}>{c}</span>
                  {i < chains.length - 1 ? '  ·  ' : ''}
                </span>
              ))}
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap' }}>
              <Link
                href={`/agent/${FEATURED_AGENT}`}
                style={LINK_PRIMARY}
              >
                See full profile →
              </Link>
              <a
                href={explorerLink}
                target="_blank"
                rel="noopener noreferrer"
                style={LINK_SECONDARY}
              >
                View on Basescan ↗
              </a>
            </div>
          </div>
        </Scene>

        {/* ══════ SCENE 5 — HIRING ══════ */}
        <Scene number={5} title="Alice hires this agent">
          <p style={P}>
            Before starting the job, the agent locks{' '}
            <strong style={STRONG}>$500 of its own money</strong> in an{' '}
            <strong style={STRONG}>accountability bond</strong> on Base.
          </p>
          <p style={P_SMALL}>
            An accountability bond is the agent putting collateral behind its
            promise to Alice. If it does the job correctly, it gets the bond
            back. If something goes wrong, that money is on the line — and the
            contract decides where it goes based on what actually happened.
          </p>
        </Scene>

        {/* ══════ SCENE 6 — DISPUTE FILED ══════ */}
        <Scene number={6} title="Something goes wrong" tone="bad">
          <p style={P}>
            The agent books the wrong flight. Alice files a dispute on-chain.
          </p>
          <p style={P_SMALL}>
            A panel of independent arbitrators — selected by reputation score —
            reviews the evidence and votes. Majority wins. The whole record
            sits on-chain forever: no private inbox, no support queue, no
            single point of control.
          </p>
        </Scene>

        {/* ══════ SCENE 7 — DISTRIBUTION + RECEIPT ══════ */}
        <Scene number={7} title="The bond distributes" tone="good">
          <p style={P}>
            The contract distributes the bond automatically based on the
            resolution. Alice — the harmed human — gets her share. The
            agent&apos;s track record updates on-chain forever.
          </p>
          <p style={P_SMALL}>
            No lawyers. No support tickets. No phone calls. Every step is
            public, signed, and auditable. This isn&apos;t slashing theater —
            it&apos;s accountable distribution, weighted by what actually flourished.
          </p>

          <div style={{
            background: 'rgba(34,197,94,0.05)',
            border: '1px solid rgba(34,197,94,0.18)',
            borderRadius: 14,
            padding: 16,
            marginTop: 18,
          }}>
            <div style={{
              fontSize: 11, fontWeight: 600, letterSpacing: 0.7,
              textTransform: 'uppercase', color: '#22c55e', marginBottom: 12,
            }}>The receipt</div>

            <ReceiptRow
              n={1}
              label="Agent registered"
              detail={agentName}
              href={`/agent/${FEATURED_AGENT}`}
            />
            <ReceiptRow
              n={2}
              label="Accountability bond locked"
              detail="Accountability contract on Base"
              href={`https://basescan.org/address/${ACCOUNTABILITY_BASE}`}
              external
            />
            <ReceiptRow
              n={3}
              label="Dispute filed on-chain"
              detail="Recorded in VaultfireDisputeResolution"
              href="/how-resolution-works"
            />
            <ReceiptRow
              n={4}
              label="Proof verified"
              detail="ERC-8128 signature checked on-chain"
              href="/proof"
            />
            <ReceiptRow
              n={5}
              label="Bond distributed"
              detail="Harmed party receives their share"
              href={`https://basescan.org/address/${ACCOUNTABILITY_BASE}`}
              external
              last
            />
          </div>
        </Scene>

        {/* ══════ SCENE 8 — WHY IT MATTERS ══════ */}
        <Scene number={8} title="Why this matters">
          <p style={{ ...P, fontSize: 17, lineHeight: 1.55 }}>
            When agents have to put money on the line, they earn trust the
            same way humans do — <strong style={STRONG}>by being accountable</strong>.
          </p>
          <p style={P_SMALL}>
            That&apos;s Vaultfire. KYA — Know Your Agent — is the trust
            layer for the agent economy.
          </p>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, 1fr)',
            gap: 8,
            marginTop: 22,
          }}>
            <BigStat
              value={stats ? String(stats.totalIdentities) : '—'}
              label="Live agents"
            />
            <BigStat
              value={bondCounts ? String(bondCounts.accountability) : '—'}
              label="Accountability bonds"
            />
            <BigStat
              value={bondCounts ? String(bondCounts.partnership) : '—'}
              label="Partnership bonds"
            />
            <BigStat
              value={distributions ? String(distributions.totalDisputesFiled) : '—'}
              label="Disputes filed"
              href="/how-resolution-works"
              subtext={
                distributions && !distributions.mechanismUsed
                  ? 'Mechanism live, untested'
                  : undefined
              }
            />
          </div>
          <p style={{
            fontSize: 11, color: '#52525b', textAlign: 'center', marginTop: 10,
          }}>
            Live, across Base · Avalanche · Arbitrum · Polygon
          </p>
          <p style={{
            fontSize: 12.5, color: '#a1a1aa', lineHeight: 1.55,
            marginTop: 22, paddingTop: 18,
            borderTop: '1px solid rgba(255,255,255,0.05)',
          }}>
            <strong style={STRONG}>One more thing.</strong> Vaultfire also
            supports{' '}
            <strong style={STRONG}>partnership bonds</strong> — collateral
            posted between two agents collaborating on a task, so neither side
            can ghost the other. Different shape, same accountability
            principle. See it in the{' '}
            <Link href="/demo/live" style={{ color: '#FF6B35', textDecoration: 'underline' }}>technical demo</Link>.
          </p>
        </Scene>

        {/* ══════ SCENE 9 — CTA ══════ */}
        <section style={{
          marginTop: 48,
          padding: 24,
          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: 19, fontWeight: 700, margin: '0 0 8px', color: '#F4F4F5',
          }}>See it live</h3>
          <p style={{
            fontSize: 13, color: '#a1a1aa', margin: '0 0 20px',
          }}>
            Every claim on this page is backed by a real contract you can verify yourself.
          </p>
          <div style={{
            display: 'flex', gap: 10, justifyContent: 'center',
            flexWrap: 'wrap',
          }}>
            <Link href={`/agent/${FEATURED_AGENT}`} style={CTA_PRIMARY}>
              View the live agent
            </Link>
            <Link href="/proof" style={CTA_SECONDARY}>
              Browse all activity
            </Link>
            <Link href="/demo/live" style={CTA_SECONDARY}>
              Technical demo
            </Link>
          </div>
        </section>

        {/* Mission statement — the creed */}
        <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>

        {/* Footer note */}
        <p style={{
          fontSize: 11, color: '#52525b', textAlign: 'center',
          marginTop: 40, lineHeight: 1.55,
        }}>
          Featured agent: {agentName}<br />
          All numbers above are fetched live from Vaultfire&apos;s on-chain
          registries at page load. Nothing on this page is a mockup.<br />
          Resolution flow shown is the contract mechanism — see{' '}
          <Link href="/how-resolution-works" style={{ color: '#71717a', textDecoration: 'underline' }}>
            how resolution works
          </Link>{' '}
          for the full breakdown.
        </p>

      </div>
    </main>
  );
}

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

function Scene({
  number, title, tone, children,
}: {
  number: number;
  title: string;
  tone?: 'good' | 'bad';
  children: React.ReactNode;
}) {
  const accent =
    tone === 'good' ? '#22c55e' :
    tone === 'bad' ? '#ef4444' :
    '#FF6B35';
  return (
    <section style={{ marginBottom: 56 }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12,
      }}>
        <span style={{
          width: 24, height: 24, borderRadius: 999,
          background: `${accent}22`, color: accent,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 12, fontWeight: 700,
        }}>{number}</span>
        <h2 style={{
          fontSize: 13, fontWeight: 600, margin: 0, color: accent,
          letterSpacing: 0.4, textTransform: 'uppercase',
        }}>{title}</h2>
      </div>
      <div style={{
        paddingLeft: 34,
        borderLeft: `1px solid ${accent}22`,
        marginLeft: 11,
      }}>
        {children}
      </div>
    </section>
  );
}

function Illustration({ emoji, caption }: { emoji: string; caption: string }) {
  return (
    <div style={{
      marginTop: 14,
      padding: '20px 16px',
      background: 'rgba(255,255,255,0.02)',
      border: '1px solid rgba(255,255,255,0.05)',
      borderRadius: 12,
      textAlign: 'center',
    }}>
      <div style={{ fontSize: 36, lineHeight: 1, marginBottom: 8 }}>{emoji}</div>
      <div style={{ fontSize: 11, color: '#71717a' }}>{caption}</div>
    </div>
  );
}

function Stat({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <div style={{ fontSize: 18, fontWeight: 700, color: '#F4F4F5' }}>{value}</div>
      <div style={{ fontSize: 10.5, color: '#71717a', marginTop: 2 }}>{label}</div>
    </div>
  );
}

function BigStat({
  value, label, href, subtext,
}: {
  value: string;
  label: string;
  href?: string;
  subtext?: string;
}) {
  const inner = (
    <div style={{
      background: 'rgba(255,255,255,0.03)',
      border: '1px solid rgba(255,255,255,0.06)',
      borderRadius: 10,
      padding: '12px 8px',
      textAlign: 'center',
    }}>
      <div style={{
        fontSize: 22, fontWeight: 700, color: '#FF6B35',
        fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      <div style={{ fontSize: 10, color: '#71717a', marginTop: 2 }}>{label}</div>
      {subtext && (
        <div style={{ fontSize: 9.5, color: '#52525b', marginTop: 3, fontStyle: 'italic' }}>
          {subtext}
        </div>
      )}
    </div>
  );
  if (!href) return inner;
  return <Link href={href} style={{ textDecoration: 'none', display: 'block' }}>{inner}</Link>;
}

function ReceiptRow({
  n, label, detail, href, external, last,
}: {
  n: number;
  label: string;
  detail: string;
  href?: string;
  external?: boolean;
  last?: boolean;
}) {
  const content = (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 0',
      borderBottom: last ? 'none' : '1px solid rgba(34,197,94,0.10)',
    }}>
      <span style={{
        width: 20, height: 20, borderRadius: 999,
        background: 'rgba(34,197,94,0.20)',
        color: '#22c55e',
        fontSize: 10, fontWeight: 700,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{n}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: '#F4F4F5', fontWeight: 500 }}>{label}</div>
        <div style={{
          fontSize: 11, color: '#a1a1aa', marginTop: 1,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{detail}</div>
      </div>
      {href && (
        <span style={{ fontSize: 11, color: '#22c55e', flexShrink: 0 }}>
          {external ? '↗' : '→'}
        </span>
      )}
    </div>
  );
  if (!href) return content;
  if (external) {
    return (
      <a href={href} target="_blank" rel="noopener noreferrer" style={{
        textDecoration: 'none', display: 'block',
      }}>{content}</a>
    );
  }
  return <Link href={href} style={{ textDecoration: 'none', display: 'block' }}>{content}</Link>;
}

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

const P: React.CSSProperties = {
  fontSize: 15, lineHeight: 1.6, color: '#d4d4d8', margin: '0 0 10px',
};
const P_SMALL: React.CSSProperties = {
  fontSize: 13.5, lineHeight: 1.6, color: '#a1a1aa', margin: '0 0 6px',
};
const STRONG: React.CSSProperties = {
  color: '#F4F4F5', fontWeight: 600,
};
const UL: React.CSSProperties = {
  fontSize: 14, lineHeight: 1.65, color: '#a1a1aa',
  paddingLeft: 20, margin: '6px 0 10px',
};
const TIER_BADGE: React.CSSProperties = {
  fontSize: 11, fontWeight: 700, letterSpacing: 0.5,
  background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
  color: '#fff', padding: '4px 10px', borderRadius: 999,
};
const STAT_ROW: React.CSSProperties = {
  display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12,
};
const LINK_PRIMARY: React.CSSProperties = {
  fontSize: 13, fontWeight: 600, padding: '8px 14px',
  background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
  color: '#fff', borderRadius: 8, textDecoration: 'none',
};
const LINK_SECONDARY: React.CSSProperties = {
  fontSize: 13, fontWeight: 500, padding: '8px 14px',
  background: 'rgba(255,255,255,0.04)',
  border: '1px solid rgba(255,255,255,0.10)',
  color: '#d4d4d8', borderRadius: 8, textDecoration: 'none',
};
const CTA_PRIMARY: React.CSSProperties = {
  fontSize: 14, fontWeight: 700, padding: '11px 18px',
  background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
  color: '#fff', borderRadius: 10, textDecoration: 'none',
};
const CTA_SECONDARY: React.CSSProperties = {
  fontSize: 14, fontWeight: 600, padding: '11px 18px',
  background: 'rgba(255,255,255,0.04)',
  border: '1px solid rgba(255,255,255,0.10)',
  color: '#F4F4F5', borderRadius: 10, textDecoration: 'none',
};
