const {
  Brand,
  StatusDot,
  Pill,
  Metric,
  Glyph,
  HashText,
  MiniLogo,
  ProgressBar,
  CopyButton,
} = window;

const {
  AppSidebar,
  MobileBottomNav,
  ExplorerSidebar,
  MarketChart,
  formatMoney,
} = window;

const fairxMarketingNav = [
  ["产品", "fair28-intro"],
  ["公平机制", "fairness"],
  ["FAIRX 公链", "chain"],
  ["Oracle", "oracle"],
  ["官方桥", "bridge"],
  ["区块浏览器", "explorer-home"],
  ["开发者", "developer"],
];

function MarketingHeader({ currentView, onNavigate }) {
  return (
    <header className="site-nav marketing-nav">
      <Brand onClick={() => onNavigate("website")} />
      <nav className="site-links" aria-label="官网主导航">
        {fairxMarketingNav.map(([label, target]) => (
          <button key={target} className={currentView === target ? "is-current" : ""} aria-current={currentView === target ? "page" : undefined} onClick={() => onNavigate(target)}>{label}</button>
        ))}
      </nav>
      <div className="site-actions">
        <button className="network-button"><StatusDot tone="green" pulse /> FAIRX Testnet</button>
        <button className="primary-button primary-compact" onClick={() => onNavigate("app-dashboard")}>进入应用 <span>↗</span></button>
      </div>
    </header>
  );
}

function MarketingMobileNav({ currentView, onNavigate }) {
  return (
    <nav className="marketing-mobile-nav" aria-label="官网移动端导航">
      <button className={currentView === "website" ? "active" : ""} onClick={() => onNavigate("website")}><Glyph active={currentView === "website"}>F</Glyph><span>首页</span></button>
      <button className={["stock-intro", "fair28-intro"].includes(currentView) ? "active" : ""} onClick={() => onNavigate("fair28-intro")}><Glyph active={["stock-intro", "fair28-intro"].includes(currentView)}>28</Glyph><span>产品</span></button>
      <button className={currentView === "fairness" ? "active" : ""} onClick={() => onNavigate("fairness")}><Glyph active={currentView === "fairness"}>◇</Glyph><span>公平</span></button>
      <button className={currentView === "explorer-home" ? "active" : ""} onClick={() => onNavigate("explorer-home")}><Glyph active={currentView === "explorer-home"}>⌁</Glyph><span>浏览器</span></button>
    </nav>
  );
}

function MarketingPage({ currentView, onNavigate, label, title, description, children, visual, primaryAction = ["进入应用", "app-dashboard"], secondaryAction }) {
  return (
    <main className="screen marketing-screen" data-screen-label={`FAIRX ${title}`}>
      <MarketingHeader currentView={currentView} onNavigate={onNavigate} />
      <section className="marketing-hero">
        <div className="marketing-hero-copy">
          <div className="eyebrow"><span className="eyebrow-line"></span>{label}</div>
          <h1>{title}</h1>
          <p>{description}</p>
          <div className="hero-actions">
            <button className="primary-button" onClick={() => onNavigate(primaryAction[1])}>{primaryAction[0]} <span>↗</span></button>
            {secondaryAction && <button className="ghost-button" onClick={() => onNavigate(secondaryAction[1])}>{secondaryAction[0]}</button>}
          </div>
        </div>
        <div className="marketing-visual">{visual}</div>
      </section>
      <div className="marketing-sections">{children}</div>
      <footer className="marketing-footer">
        <div><Brand onClick={() => onNavigate("website")} /><p>规则上链，资金锁定，结果验证，自动结算。</p></div>
        <button onClick={() => onNavigate("explorer-home")}>验证 FAIRX 网络 <span>↗</span></button>
      </footer>
      <MarketingMobileNav currentView={currentView} onNavigate={onNavigate} />
    </main>
  );
}

function SectionHeading({ index, eyebrow, title, copy }) {
  return (
    <div className="section-heading">
      <span>{index}</span>
      <div><small>{eyebrow}</small><h2>{title}</h2>{copy && <p>{copy}</p>}</div>
    </div>
  );
}

function PrincipleGrid({ items, columns = 4 }) {
  return (
    <div className={`principle-grid columns-${columns}`}>
      {items.map(([index, title, copy, meta]) => (
        <article key={title} className="principle-card">
          <span>{index}</span><h3>{title}</h3><p>{copy}</p>{meta && <strong>{meta}</strong>}
        </article>
      ))}
    </div>
  );
}

function ProcessRail({ steps }) {
  return (
    <div className="process-rail">
      {steps.map(([index, title, copy], itemIndex) => (
        <React.Fragment key={title}>
          <article><span>{index}</span><h3>{title}</h3><p>{copy}</p></article>
          {itemIndex < steps.length - 1 && <i>→</i>}
        </React.Fragment>
      ))}
    </div>
  );
}

function FairnessPage({ currentView, onNavigate }) {
  const rights = [
    ["01", "出题权", "市场创建者定义标的、时间与结算条件。", "规则哈希"],
    ["02", "定赔率权", "庄家设定赔率和最大承接额度。", "报价透明"],
    ["03", "判结果权", "独立预言机根据公开数据提交结果。", "3 / 5 门槛"],
    ["04", "管资金权", "保险库合约保管所有已锁定资金。", "非托管"],
  ];
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="FAIRNESS BY DESIGN" title="公平如何被写进规则" description="公平不是平台的承诺，而是链上的执行结果。任何角色都不能同时控制规则、结果与资金。" primaryAction={["查看公平证明", "explorer"]} secondaryAction={["进入 FAIR28", "dapp"]} visual={
      <div className="fairness-core-card">
        <span className="proof-diamond">◇</span><small>ORDER PROOF</small><h2>规则与资金已原子化锁定</h2>
        <div><span>用户本金</span><strong>10,000 USDC</strong></div><div><span>庄家赔付</span><strong>8,500 USDC</strong></div>
        <ProgressBar value={100} tone="green" /><p><StatusDot tone="green" /> Coverage verified · 100%</p>
      </div>
    }>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="SEPARATION OF POWER" title="四权分离" copy="让任何单一角色都无法改变一场已经成交的博弈。" /><PrincipleGrid items={rights} /></section>
      <section className="marketing-section split-section">
        <div><SectionHeading index="02" eyebrow="CAPITAL FIRST" title="先锁赔付，再允许下注" /><p className="section-copy">用户下注 10,000 USDC、赔率 1.85 时，订单成交必须同时锁定用户本金 10,000 与庄家赔付 8,500。结算前不可撤出或重复使用。</p></div>
        <div className="formula-card"><small>ATOMIC COLLATERAL</small><span>用户总返还</span><strong>下注金额 × 赔率</strong><i></i><span>庄家最大赔付</span><strong>下注金额 ×（赔率 − 1）</strong></div>
      </section>
      <section className="marketing-section"><SectionHeading index="03" eyebrow="AUTOMATED RISK" title="风险达到上限，系统自动停单" /><div className="risk-ladder">{[["0—60%","正常接受订单",60,"green"],["60—75%","降低单笔上限",75,"cyan"],["75—85%","限制高风险方向",85,"amber"],["100%","停止全部新订单",100,"red"]].map(([range,label,value,tone]) => <div key={range}><span><b>{range}</b><small>{label}</small></span><ProgressBar value={value} tone={tone} /></div>)}</div></section>
      <section className="marketing-section"><SectionHeading index="04" eyebrow="AUDITABLE EVIDENCE" title="所有内容都能直接审计" /><div className="audit-strip">{["市场规则","赔率历史","资金锁定","风险使用率","Oracle 提交","结算交易"].map((item,index) => <span key={item}><i>0{index + 1}</i>{item}<b>✓</b></span>)}</div></section>
    </MarketingPage>
  );
}

function StockIntroPage({ currentView, onNavigate }) {
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="EQUITY DIRECTION MARKET" title="股票价格方向市场" description="以公开股票价格为参考，在固定时间窗口判断上涨或下跌。价格源、赔率、结算时刻和无效市场规则全部提前写入链上。" primaryAction={["进入股票交易", "stock-trade"]} secondaryAction={["查看 FAIR28", "fair28-intro"]} visual={
      <div className="stock-quote-visual"><div><MiniLogo label="TS" /><span><small>NASDAQ · TSLA</small><h2>$182.73</h2></span><Pill tone="success" dot>数据正常</Pill></div><MarketChart /><p><span>参考价格 $182.73</span><span>结算 16:00 UTC−4</span></p></div>
    }>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="TWO-SIDED MARKET" title="方向清楚，边界清楚" /><PrincipleGrid columns={2} items={[["LONG","做多／看涨","结算价格高于参考价格，做多获胜。","1.85"],["SHORT","做空／看跌","结算价格低于参考价格，做空获胜。","1.87"]]} /></section>
      <section className="marketing-section split-section"><div><SectionHeading index="02" eyebrow="ORDER PREVIEW" title="每笔订单都先展示最坏情况" /><p className="section-copy">下注前明确展示本金、赔率、总返还、庄家需锁赔付、结算时间、数据来源和市场合约。价格刚好等于参考价时，初版规则为全额退款。</p></div><div className="order-preview-card"><small>ORDER PREVIEW</small><div><span>投入</span><b>1,000 USDC</b></div><div><span>赔率</span><b>1.85</b></div><div><span>可能返还</span><b>1,850 USDC</b></div><div><span>庄家锁定</span><strong>850 USDC</strong></div></div></section>
      <section className="marketing-section"><SectionHeading index="03" eyebrow="PUBLIC RISK POOL" title="风险池公开可见" /><div className="metric-showcase"><Metric label="庄家池总额" value="200,000" meta="USDC" /><Metric label="已锁资金" value="108,000" meta="USDC" tone="cyan" /><Metric label="自由资金" value="92,000" meta="USDC" /><Metric label="风险使用率" value="67.5%" meta="85% 自动限向" tone="green" /></div></section>
    </MarketingPage>
  );
}

function Fair28IntroPage({ currentView, onNavigate }) {
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="VERIFIABLE NUMBER MARKET" title="FAIR28 数字结果市场" description="结果空间固定为 0—27，支持大小、单双、精确和值与组合玩法。每个可能结果的总赔付都会在接单前计算。" primaryAction={["进入 FAIR28", "dapp"]} secondaryAction={["股票市场", "stock-intro"]} visual={
      <div className="fair28-visual"><div><span><small>CURRENT ROUND</small><h2>202607212104</h2></span><Pill tone="success" dot>投注中</Pill></div><div className="fair28-number-row">{[10,11,12,13,14,15,16].map((number) => <span className={number === 14 ? "active" : ""} key={number}>{number}</span>)}</div><p><span>距离封盘</span><strong>00 : 42</strong></p></div>
    }>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="BET TYPES" title="所有玩法在下注前写清楚" /><PrincipleGrid items={[["01","大小","0—13 为小，14—27 为大。","1.96"],["02","单双","奇数为单，偶数为双。","1.94"],["03","精确和值","直接选择 0—27 中的结果。","9.90"],["04","组合玩法","大单、大双、小单、小双。","3.74"]]} /></section>
      <section className="marketing-section"><SectionHeading index="02" eyebrow="OUTCOME RISK ENGINE" title="不是计算一类玩法，而是计算 28 种结果" copy="同一个结果可能让多个玩法同时中奖，风险引擎逐一模拟结果 0—27，并取最高总赔付责任。" /><div className="outcome-risk-grid">{fairxNumbers.map(({value}) => <span key={value} className={value === 14 ? "worst" : ""}><b>{value}</b><small>{value === 14 ? "31.8K" : `${(12 + ((value * 7) % 16)).toFixed(1)}K`}</small></span>)}</div></section>
      <section className="marketing-section"><SectionHeading index="03" eyebrow="SETTLEMENT FLOW" title="从封盘到赔付全部自动执行" /><ProcessRail steps={[["01","自动封盘","停止新下注，保留已成交订单。"],["02","结果提交","多节点分别提交结果与签名。"],["03","门槛确认","至少 3 / 5 节点达成一致。"],["04","自动赔付","识别所有中奖玩法并完成结算。"]]} /></section>
    </MarketingPage>
  );
}

function ChainPage({ currentView, onNavigate }) {
  const modules = [["01","实时行情","接入股票、商品、汇率等连续报价"],["02","事件结果","接入体育、开奖、选举与商业事件"],["03","多源聚合","检查报价差异、数据新鲜度与确认门槛"],["04","签名上链","记录原始值、时间戳、来源与节点签名"],["05","市场执行","用可信报价触发风控、封盘与自动结算"],["06","数据开放","通过 RPC、API 与浏览器向所有应用开放"]];
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="REAL-WORLD DATA CHAIN" title="连接真实世界与链上市场" description="FAIRX 通过分布式预言机持续接入股票、商品、体育、开奖和事件数据。报价、时间戳与签名上链后，市场据此锁定规则、计算风险并自动结算。" primaryAction={["查看预言机网络", "oracle"]} secondaryAction={["验证链上记录", "explorer-home"]} visual={<div className="chain-stack">{[["REAL WORLD","股票 · 商品 · 体育 · 事件"],["ORACLE","报价 · 时间戳 · 多节点签名"],["FAIRX","规则 · 风险 · 资金 · 结算"],["APPLICATIONS","预测市场 · 保险 · 金融产品"]].map(([label,value],index) => <React.Fragment key={label}><div><small>{label}</small><strong>{value}</strong></div>{index < 3 && <span>↓</span>}</React.Fragment>)}</div>}>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="REAL-WORLD CONNECTIVITY" title="真实世界的数据，成为链上可执行的事实" /><div className="module-grid">{modules.map(([index,title,copy]) => <article key={title}><span>{index}</span><div><h3>{title}</h3><p>{copy}</p></div><b>↗</b></article>)}</div></section>
      <section className="marketing-section split-section"><div><SectionHeading index="02" eyebrow="DATA TRUST BOUNDARY" title="报价可以被验证，异常不能直接进入结算" /><p className="section-copy">FAIRX 不接受单一来源直接决定结果。每次报价都会检查来源数量、时间戳、数据差异和签名门槛；数据过期或节点分歧过大时，市场自动暂停等待确认。</p></div><div className="boundary-card"><small>VERIFIED BY</small>{["多源报价","节点签名","新鲜度检查","异常熔断"].map((item) => <span key={item}><i>✓</i>{item}</span>)}</div></section>
    </MarketingPage>
  );
}

function OraclePage({ currentView, onNavigate }) {
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="FAIRX ORACLE" title="让现实世界的结果被链上验证" description="多个独立节点读取股票、开奖、体育与事件数据，分别提交原始值、时间与数字签名，再由合约执行确认规则。" primaryAction={["查看市场证明", "explorer"]} secondaryAction={["公链架构", "chain"]} visual={<div className="oracle-network-visual"><div className="oracle-center"><span>14</span><small>FINAL</small></div>{fairxOracleVotes.map((vote,index) => <div className={`oracle-satellite satellite-${index + 1} ${vote.state}`} key={vote.node}><MiniLogo label={vote.node.slice(0,1)} /><span><b>{vote.node}</b><small>{vote.value === "—" ? "等待" : `提交 ${vote.value}`}</small></span></div>)}</div>}>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="CONSENSUS" title="每次结果都保留完整证据" /><div className="oracle-ledger"><div className="oracle-ledger-head"><span>节点</span><span>原始结果</span><span>提交时间</span><span>签名</span><span>状态</span></div>{fairxOracleVotes.map((vote) => <div key={vote.node}><span><StatusDot tone={vote.state === "confirmed" ? "green" : "amber"} />{vote.node}</span><strong>{vote.value}</strong><span>{vote.time}</span><HashText>{vote.state === "confirmed" ? "0x8fa2…91bc" : "—"}</HashText><b>{vote.state === "confirmed" ? "已确认" : "等待"}</b></div>)}</div></section>
      <section className="marketing-section"><SectionHeading index="02" eyebrow="DATA SAFETY" title="数据新鲜度、差异与异常都进入规则" /><PrincipleGrid items={[["01","多数据源","多个行情或结果提供方。","SOURCE"],["02","中位数结果","降低单点异常价格影响。","MEDIAN"],["03","新鲜度检查","拒绝超过时间窗口的数据。","FRESH"],["04","异常熔断","差异过大时进入待确认。","PAUSE"]]} /></section>
    </MarketingPage>
  );
}

function BridgePage({ currentView, onNavigate }) {
  const [amount, setAmount] = React.useState("5000");
  const [submitted, setSubmitted] = React.useState(false);
  const bridge = () => { if (Number(amount) > 0) { setSubmitted(true); window.setTimeout(() => setSubmitted(false), 2600); } };
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="FAIRX BRIDGE" title="安全进入公平博弈网络" description="将稳定币从其他网络转入 FAIRX。桥接资金与市场保险库严格隔离，每笔跨链记录都能在浏览器核验。" primaryAction={["查看跨链记录", "explorer-home"]} secondaryAction={["进入应用", "app-dashboard"]} visual={<div className="bridge-card"><div className="bridge-card-head"><span><small>TRANSFER TO FAIRX</small><h2>跨链转入</h2></span><Pill tone="success" dot>通道正常</Pill></div><label><span>来源网络</span><button>Ethereum <b>⌄</b></button></label><div className="bridge-arrow">↓</div><label><span>转入资产</span><button>USDC <b>FAIRX</b></button></label><label><span>金额</span><div className="bridge-amount"><input aria-label="桥接金额" value={amount} onChange={(event) => setAmount(event.target.value)} /><span>USDC</span></div></label><div className="bridge-summary"><span>预计到账 <b>{formatMoney(Number(amount) || 0)} USDC</b></span><span>预计时间 <b>≈ 4 分钟</b></span></div><button className="primary-button" disabled={Number(amount) <= 0} onClick={bridge}>确认跨链 <span>→</span></button></div>}>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="TRANSFER LIFECYCLE" title="每一步都可追踪" /><ProcessRail steps={[["01","连接钱包","选择来源链与稳定币资产。"],["02","来源链确认","等待交易达到安全确认数。"],["03","FAIRX 铸入","验证消息后在 FAIRX 到账。"],["04","浏览器核验","查看来源与目标链完整记录。"]]} /></section>
      <section className="marketing-section"><SectionHeading index="02" eyebrow="ISOLATED SECURITY" title="桥接资金与市场保险库相互隔离" /><div className="isolation-diagram"><article><small>BRIDGE VAULT</small><h3>跨链资产托管</h3><p>只处理来源链确认与 FAIRX 铸入。</p></article><span>严格隔离</span><article><small>MARKET VAULT</small><h3>市场赔付保险库</h3><p>只处理订单本金、赔付与结算。</p></article></div></section>
      {submitted && <div className="success-toast" role="status" aria-live="polite"><span>✓</span><div><b>跨链请求已提交</b><small>来源链确认后将在 FAIRX 到账</small></div><HashText>0xBRG8…21FA</HashText></div>}
    </MarketingPage>
  );
}

function DeveloperPage({ currentView, onNavigate }) {
  const code = `const market = await fairx.market("FX28-212104");\nconst proof = await market.getFairnessProof();\nconsole.log(proof.coverageRatio); // 100%`;
  return (
    <MarketingPage currentView={currentView} onNavigate={onNavigate} label="BUILD ON FAIRX" title="把可验证的公平接入任何产品" description="通过 EVM 合约、JSON-RPC、索引 API 与 Oracle 接口构建新的预测市场、风险产品和数据服务。" primaryAction={["查看网络数据", "explorer-home"]} secondaryAction={["了解公链", "chain"]} visual={<div className="developer-console"><div><i></i><i></i><i></i><span>fairx-sdk.ts</span></div><pre>{code}</pre><footer><span><StatusDot tone="green" /> RPC connected</span><b>42 ms</b></footer></div>}>
      <section className="marketing-section"><SectionHeading index="01" eyebrow="DEVELOPER SURFACES" title="从合约到数据索引" /><PrincipleGrid items={[["01","智能合约","创建市场、锁定资金、执行结算。","EVM"],["02","FAIRX SDK","读取市场与公平证明。","TS / JS"],["03","索引 API","查询订单、事件与风险快照。","REST"],["04","Oracle 接口","提交带签名的标准化结果。","SIGNED"]]} /></section>
      <section className="marketing-section split-section"><div><SectionHeading index="02" eyebrow="NETWORK ACCESS" title="测试网接入信息" /><p className="section-copy">当前原型展示测试网接入面板，具体正式 RPC、Chain ID 与合约地址应在网络部署后替换。</p></div><div className="endpoint-card">{[["Network","FAIRX Testnet"],["Chain ID","202607"],["RPC","https://rpc.testnet.fairx.network"],["Explorer","https://scan.testnet.fairx.network"]].map(([label,value]) => <div key={label}><span>{label}</span><HashText>{value}</HashText><CopyButton value={value} /></div>)}</div></section>
    </MarketingPage>
  );
}

function WorkspaceShell({ currentView, onNavigate, eyebrow, title, description, actions, children, mobileActive = "market" }) {
  return (
    <main className="screen dapp-screen workspace-page-screen" data-screen-label={`FAIRX 应用 · ${title}`}>
      <AppSidebar currentView={currentView} onNavigate={onNavigate} />
      <section className="app-workspace">
        <header className="workspace-page-topbar">
          <div className="mobile-app-brand"><Brand compact onClick={() => onNavigate("website")} /></div>
          <div><small>{eyebrow}</small><h1>{title}</h1><p>{description}</p></div>
          <div className="workspace-page-actions">{actions}<button className="icon-button" aria-label="通知">○</button><button className="wallet-compact"><span>0x</span>0x7A31…91F4</button></div>
        </header>
        <div className="workspace-page-content">{children}</div>
      </section>
      <MobileBottomNav active={mobileActive} onNavigate={onNavigate} />
    </main>
  );
}

function AppDashboardPage({ currentView, onNavigate }) {
  const orders = [["FAIR28 · 212104","大","1,000","1.96","进行中"],["TSLA · 30M","做多","2,500","1.85","进行中"],["FAIR28 · 212103","和值 14","250","9.90","可领取"]];
  return (
    <WorkspaceShell currentView={currentView} onNavigate={onNavigate} eyebrow="NETWORK OVERVIEW" title="总览" description="市场、资金、风险与网络状态汇总。" actions={<button className="proof-shortcut" onClick={() => onNavigate("explorer-home")}>区块浏览器 ↗</button>}>
      <section className="dashboard-metrics"><Metric label="全网锁仓量" value="$18.42M" meta="+4.8% 7D" tone="cyan" /><Metric label="庄家池总资金" value="$12.08M" meta="65.6% 可用" /><Metric label="今日成交额" value="$2.84M" meta="8,420 笔订单" /><Metric label="网络区块高度" value="12,984,201" meta="2 秒前" tone="green" /></section>
      <section className="dashboard-main-grid"><div className="dashboard-market-stack"><div className="workspace-section-head"><span><small>LIVE MARKETS</small><h2>核心市场</h2></span><button onClick={() => onNavigate("dapp")}>查看全部 ↗</button></div><div className="market-launch-grid"><button onClick={() => onNavigate("dapp")}><MiniLogo label="28" /><span><small>数字结果市场</small><h3>FAIR28</h3><p>48,920 USDC 成交 · 00:42 封盘</p></span><strong>进入市场 ↗</strong></button><button onClick={() => onNavigate("stock-trade")}><MiniLogo label="TS" /><span><small>股票方向市场</small><h3>TSLA / USD</h3><p>$182.73 参考价 · 28:10 封盘</p></span><strong>进入市场 ↗</strong></button></div><div className="workspace-section-head"><span><small>YOUR POSITIONS</small><h2>我的进行中订单</h2></span><button onClick={() => onNavigate("portfolio")}>全部订单 ↗</button></div><div className="workspace-table"><div className="workspace-table-head"><span>市场</span><span>方向</span><span>投入</span><span>赔率</span><span>状态</span></div>{orders.map((row) => <div key={row[0]}>{row.map((cell,index) => <span key={`${cell}-${index}`} className={index === 4 ? "state-cell" : ""}>{cell}{index === 2 && " USDC"}</span>)}</div>)}</div></div><aside className="dashboard-side-stack"><article className="network-health-card"><div className="workspace-section-head"><span><small>NETWORK</small><h2>运行状态</h2></span><Pill tone="success" dot>正常</Pill></div>{[["Oracle 节点","4 / 5 在线"],["活跃市场","128"],["平均出块","1.8 秒"],["待确认争议","0"]].map(([label,value]) => <div key={label}><span>{label}</span><strong>{value}</strong></div>)}</article><article className="claim-card"><span className="proof-diamond">◇</span><small>CLAIMABLE</small><h2>1,742.80 USDC</h2><p>2 笔已结算订单可领取</p><button onClick={() => onNavigate("portfolio")}>查看收益 <span>→</span></button></article><article className="contracts-card"><small>CORE CONTRACTS</small>{[["Market","0x8f2b…ca71"],["Vault","0x72de…18a4"],["Oracle","0x4bc1…d902"]].map(([label,value]) => <div key={label}><span>{label}</span><HashText>{value}</HashText></div>)}</article></aside></section>
    </WorkspaceShell>
  );
}

function StockTradePage({ currentView, onNavigate }) {
  const [side, setSide] = React.useState("long");
  const [amount, setAmount] = React.useState("1000");
  const [placed, setPlaced] = React.useState(false);
  const odds = side === "long" ? 1.85 : 1.87;
  const numericAmount = Math.max(0, Number(amount) || 0);
  const submit = () => { if (numericAmount > 0) { setPlaced(true); window.setTimeout(() => setPlaced(false), 2600); } };
  return (
    <WorkspaceShell currentView={currentView} onNavigate={onNavigate} eyebrow="EQUITY DIRECTION MARKET" title="TSLA · 30 分钟方向市场" description="高于参考价做多获胜，低于参考价做空获胜；价格相等全额退款。" actions={<button className="proof-shortcut" onClick={() => onNavigate("explorer")}>验证规则 ↗</button>}>
      <section className="stock-trade-metrics"><article className="stock-price-card"><div><MiniLogo label="TS" /><span><small>NASDAQ · TSLA</small><h2>$182.73</h2></span></div><span className="price-positive">+1.84%</span><MarketChart /></article><div className="stock-market-facts"><Metric label="参考价格" value="$182.73" meta="15:30:00 UTC−4" /><Metric label="当前价格" value="$183.09" meta="2 秒前" tone="green" /><Metric label="距离封盘" value="28:10" meta="结算 16:00" /><Metric label="Oracle" value="5 / 5" meta="数据正常" tone="cyan" /></div></section>
      <section className="stock-order-layout"><div className="direction-panel panel"><div className="workspace-section-head"><span><small>CHOOSE DIRECTION</small><h2>选择方向</h2></span><Pill tone="success" dot>投注中</Pill></div><div className="direction-grid"><button className={side === "long" ? "selected long" : "long"} aria-pressed={side === "long"} onClick={() => setSide("long")}><span>↗</span><small>做多／看涨</small><h3>结算价高于 $182.73</h3><strong>1.85</strong><p>剩余可承接 38,420 USDC</p></button><button className={side === "short" ? "selected short" : "short"} aria-pressed={side === "short"} onClick={() => setSide("short")}><span>↘</span><small>做空／看跌</small><h3>结算价低于 $182.73</h3><strong>1.87</strong><p>剩余可承接 42,780 USDC</p></button></div><div className="stock-proof-strip"><span><i>✓</i>规则已固定 <HashText>0x7ae1…d902</HashText></span><span><i>✓</i>价格数据 2 秒前</span><span><i>✓</i>最坏结果已覆盖</span></div></div><aside className="stock-order-panel panel"><div className="workspace-section-head"><span><small>PLACE ORDER</small><h2>订单确认</h2></span><strong>{odds.toFixed(2)}</strong></div><label><span>投入金额</span><small>余额 12,480.60 USDC</small></label><div className="amount-input"><input aria-label="股票市场投入金额" value={amount} onChange={(event) => setAmount(event.target.value)} /><span>USDC</span><button onClick={() => setAmount("12480.60")}>MAX</button></div><div className="quick-amounts">{["100","500","1000","5000"].map((value) => <button key={value} className={amount === value ? "active" : ""} onClick={() => setAmount(value)}>{Number(value).toLocaleString()}</button>)}</div><div className="order-summary"><div><span>方向</span><strong>{side === "long" ? "做多" : "做空"}</strong></div><div><span>可能获得总金额</span><strong>{formatMoney(numericAmount * odds)} USDC</strong></div><div><span>庄家新增锁定</span><strong>{formatMoney(numericAmount * (odds - 1))} USDC</strong></div><div><span>结算时间</span><strong>16:00 UTC−4</strong></div></div><button className="order-button" disabled={numericAmount <= 0} onClick={submit}>确认订单并锁定资金 <span>→</span></button></aside></section>
      <section className="stock-risk-footer"><div><span><small>庄家池总额</small><b>200,000 USDC</b></span><span><small>已锁资金</small><b>108,000 USDC</b></span><span><small>自由资金</small><b>92,000 USDC</b></span><span><small>风险使用率</small><b>67.5%</b></span></div><ProgressBar value={67.5} /></section>
      {placed && <div className="success-toast" role="status" aria-live="polite"><span>✓</span><div><b>股票方向订单已提交</b><small>本金与最大赔付正在同笔交易中锁定</small></div><HashText>0xTSLA…8F21</HashText></div>}
    </WorkspaceShell>
  );
}

function VaultPage({ currentView, onNavigate }) {
  const [action, setAction] = React.useState("deposit");
  const [amount, setAmount] = React.useState("10000");
  const [submitted, setSubmitted] = React.useState(false);
  const submit = () => { if (Number(amount) > 0) { setSubmitted(true); window.setTimeout(() => setSubmitted(false), 2400); } };
  return (
    <WorkspaceShell currentView={currentView} onNavigate={onNavigate} eyebrow="CREATOR VAULT" title="庄家池" description="谁定赔率，谁提前锁定对应赔付。" mobileActive="vault" actions={<Pill tone="success" dot>保险库正常</Pill>}>
      <section className="dashboard-metrics"><Metric label="保险库总额" value="200,000" meta="USDC" tone="cyan" /><Metric label="已锁赔付" value="108,000" meta="54.0%" /><Metric label="自由资金" value="92,000" meta="可撤出" tone="green" /><Metric label="历史净盈亏" value="+18,420" meta="USDC" tone="green" /></section>
      <section className="vault-layout"><div className="vault-control-card panel"><div className="workspace-section-head"><span><small>VAULT CONTROL</small><h2>资金操作</h2></span><Pill tone="success">可操作</Pill></div><div className="segmented-control">{[["deposit","存入"],["withdraw","撤出自由资金"],["exit","申请退出"]].map(([value,label]) => <button key={value} className={action === value ? "active" : ""} onClick={() => setAction(value)}>{label}</button>)}</div><label><span>{action === "deposit" ? "存入金额" : action === "withdraw" ? "撤出金额" : "退出后停止承接"}</span><small>{action === "deposit" ? "钱包余额 54,880 USDC" : "可用 92,000 USDC"}</small></label><div className="amount-input"><input aria-label="庄家池操作金额" value={amount} onChange={(event) => setAmount(event.target.value)} /><span>USDC</span><button onClick={() => setAmount(action === "deposit" ? "54880" : "92000")}>MAX</button></div><div className="vault-action-note"><span>◇</span><p>{action === "exit" ? "申请退出会立即停止新订单；已有订单继续锁仓，全部结算后才可提取剩余资金。" : "只有未被订单占用的自由资金可以撤出，已锁赔付不会受到影响。"}</p></div><button className="order-button" disabled={Number(amount) <= 0} onClick={submit}>{action === "deposit" ? "确认存入" : action === "withdraw" ? "确认撤出" : "确认申请退出"} <span>→</span></button></div><div className="vault-settings-card panel"><div className="workspace-section-head"><span><small>RISK POLICY</small><h2>风险参数</h2></span><button onClick={() => onNavigate("risk")}>风控详情 ↗</button></div>{[["最大风险比例","80%"],["自动限向阈值","85%"],["单笔最大承接","25,000 USDC"],["单市场最大敞口","60,000 USDC"]].map(([label,value]) => <div key={label}><span>{label}</span><strong>{value}</strong><button>修改</button></div>)}<div className="vault-utilization"><span><small>当前风险使用率</small><b>67.5%</b></span><ProgressBar value={67.5} /></div></div></section>
      <section className="workspace-history-card"><div className="workspace-section-head"><span><small>VAULT HISTORY</small><h2>最近资金记录</h2></span><button>导出记录 ↓</button></div><div className="workspace-table"><div className="workspace-table-head"><span>操作</span><span>金额</span><span>交易哈希</span><span>时间</span><span>状态</span></div>{[["锁定赔付","−960 USDC","0x9a21…8cd0","12 秒前","已确认"],["市场结算","+2,840 USDC","0x71de…3a20","18 分钟前","已确认"],["存入资金","+50,000 USDC","0x4bc1…d902","2 小时前","已确认"]].map((row) => <div key={row[2]}>{row.map((cell,index) => <span key={index} className={index === 4 ? "state-cell" : ""}>{cell}</span>)}</div>)}</div></section>
      {submitted && <div className="success-toast" role="status" aria-live="polite"><span>✓</span><div><b>保险库操作已提交</b><small>等待 FAIRX Testnet 确认</small></div><HashText>0xVLT8…13A2</HashText></div>}
    </WorkspaceShell>
  );
}

function RiskPage({ currentView, onNavigate }) {
  const results = Array.from({length: 28}, (_, index) => ({ result: index, exposure: 12000 + ((index * 7103) % 22000) }));
  const maxExposure = Math.max(...results.map((item) => item.exposure));
  return (
    <WorkspaceShell currentView={currentView} onNavigate={onNavigate} eyebrow="RISK ENGINE" title="风控中心" description="每笔订单成交前模拟所有可能结果，并限制最高总赔付责任。" actions={<Pill tone="success" dot>风险引擎正常</Pill>}>
      <section className="dashboard-metrics"><Metric label="保险库风险额度" value="160,000" meta="80% of vault" /><Metric label="当前最大结果负债" value="108,000" meta="结果 14" tone="cyan" /><Metric label="风险使用率" value="67.5%" meta="低于 85% 限向线" tone="green" /><Metric label="剩余可承接" value="52,000" meta="USDC" /></section>
      <section className="risk-page-grid"><article className="risk-map-card panel"><div className="workspace-section-head"><span><small>OUTCOME EXPOSURE</small><h2>FAIR28 · 0—27 结果风险</h2></span><span className="risk-legend"><i></i>赔付责任</span></div><div className="risk-result-chart">{results.map((item) => <div key={item.result} className={item.result === 14 ? "worst" : ""}><span style={{height:`${Math.max(18, item.exposure / maxExposure * 100)}%`}}></span><b>{item.result}</b><small>{(item.exposure / 1000).toFixed(0)}K</small></div>)}</div><p>系统按每个可能结果合并大小、单双、组合、和值和尾数玩法的全部赔付。</p></article><aside className="threshold-card panel"><div className="workspace-section-head"><span><small>AUTO CONTROLS</small><h2>自动风控阈值</h2></span></div>{[["0—60%","正常接受订单",60,"green"],["60—75%","降低单笔上限",75,"cyan"],["75—85%","限制高风险方向",85,"amber"],["85—100%","关闭风险过高方向",100,"red"]].map(([range,label,value,tone]) => <div className="threshold-row" key={range}><span><b>{range}</b><small>{label}</small></span><ProgressBar value={value} tone={tone} /></div>)}<div className="threshold-current"><span>当前</span><strong>67.5%</strong><small>降低单笔上限</small></div></aside></section>
      <section className="workspace-history-card"><div className="workspace-section-head"><span><small>RISK EVENTS</small><h2>最近风控事件</h2></span><button>查看链上记录 ↗</button></div><div className="risk-event-list">{[["订单风险检查通过","FAIR28 · 大 · 1,000 USDC","12 秒前","pass"],["单笔上限自动调整","FAIR28 · 结果 14 敞口上升","4 分钟前","warn"],["Oracle 数据新鲜度通过","TSLA · 2 秒","7 分钟前","pass"],["高风险方向自动关闭","FAIR28 · 和值 22","1 小时前","stop"]].map(([title,copy,time,state]) => <div key={`${title}-${time}`} className={state}><span>{state === "pass" ? "✓" : state === "warn" ? "!" : "×"}</span><div><b>{title}</b><small>{copy}</small></div><time>{time}</time></div>)}</div></section>
    </WorkspaceShell>
  );
}

function PortfolioPage({ currentView, onNavigate }) {
  const [tab, setTab] = React.useState("进行中");
  const [claimed, setClaimed] = React.useState(false);
  const rows = {
    "进行中": [["FAIR28 · 212104","大","1,000","1.96","1,960.00","等待开奖"],["TSLA · 30M","做多","2,500","1.85","4,625.00","28:10 封盘"]],
    "已结算": [["FAIR28 · 212102","双","800","1.94","0.00","未中奖"],["TSLA · 30M","做空","1,200","1.87","2,244.00","已领取"]],
    "可领取": [["FAIR28 · 212103","和值 14","250","9.90","2,475.00","可领取"],["AAPL · 30M","做多","900","1.82","1,638.00","可领取"]],
  };
  const claim = () => { setClaimed(true); window.setTimeout(() => setClaimed(false), 2400); };
  return (
    <WorkspaceShell currentView={currentView} onNavigate={onNavigate} eyebrow="POSITIONS & EARNINGS" title="我的下注与收益" description="查看进行中订单、结算结果和可领取资金。" mobileActive="portfolio" actions={<button className="primary-button primary-compact" disabled={tab !== "可领取"} onClick={claim}>领取全部</button>}>
      <section className="portfolio-summary"><article><small>总投入</small><h2>12,480.00 USDC</h2><span>过去 30 天</span></article><article><small>已结算收益</small><h2 className="positive">+2,842.80 USDC</h2><span>净收益率 +22.8%</span></article><article><small>进行中订单</small><h2>2</h2><span>最大可能返还 6,585 USDC</span></article><article><small>可领取</small><h2 className="cyan-text">4,113.00 USDC</h2><button onClick={() => { setTab("可领取"); }}>查看</button></article></section>
      <section className="portfolio-card panel"><div className="portfolio-tabs">{Object.keys(rows).map((item) => <button key={item} className={tab === item ? "active" : ""} aria-pressed={tab === item} onClick={() => setTab(item)}>{item}<span>{rows[item].length}</span></button>)}</div><div className="portfolio-table"><div className="portfolio-table-head"><span>市场</span><span>选择</span><span>投入 USDC</span><span>赔率</span><span>返还 USDC</span><span>状态</span><span></span></div>{rows[tab].map((row) => <div key={row[0]}>{row.map((cell,index) => <span key={index} className={index === 5 ? "state-cell" : ""}>{cell}</span>)}<button onClick={() => tab === "可领取" ? claim() : onNavigate("explorer")}>{tab === "可领取" ? "领取" : "证明 ↗"}</button></div>)}</div></section>
      <section className="earnings-proof panel"><span className="proof-diamond">◇</span><div><small>ONCHAIN EARNINGS</small><h2>所有收益都来自已完成的链上结算</h2><p>可领取余额由结算合约记录，平台无法冻结或改写。</p></div><button onClick={() => onNavigate("explorer")}>查看结算证明 ↗</button></section>
      {claimed && <div className="success-toast" role="status" aria-live="polite"><span>✓</span><div><b>领取交易已提交</b><small>4,113.00 USDC 将发送至当前钱包</small></div><HashText>0xCLM4…91A7</HashText></div>}
    </WorkspaceShell>
  );
}

function ExplorerHomePage({ currentView, onNavigate }) {
  const [search, setSearch] = React.useState("");
  const [found, setFound] = React.useState(false);
  const submit = (event) => { event.preventDefault(); if (search.trim()) { setFound(true); window.setTimeout(() => setFound(false), 2200); } };
  return (
    <main className="screen explorer-screen explorer-home-screen" data-screen-label="FAIRX 区块浏览器首页">
      <ExplorerSidebar currentView={currentView} onNavigate={onNavigate} />
      <section className="explorer-workspace"><header className="explorer-topbar"><div className="mobile-explorer-brand"><Brand compact onClick={() => onNavigate("website")} /></div><form className="explorer-search" onSubmit={submit}><button type="submit" aria-label="执行搜索">⌕</button><input aria-label="浏览器搜索" value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索交易哈希、地址、市场、区块…" /><kbd>⌘ K</kbd></form><div className="explorer-actions"><button onClick={() => onNavigate("developer")}>开发者 API</button><button className="network-button"><StatusDot tone="green" pulse /> FAIRX Testnet</button><button className="primary-button primary-compact" onClick={() => onNavigate("app-dashboard")}>进入应用 ↗</button></div></header><div className="explorer-home-content"><section className="explorer-home-hero"><div><div className="eyebrow"><span className="eyebrow-line"></span>FAIRX BLOCK EXPLORER</div><h1>不只是查交易，<br /><span>更是公平证明中心。</span></h1><p>直接验证市场规则、锁定资金、风险快照、Oracle 提交与自动结算。</p></div><div className="latest-block"><small>LATEST BLOCK</small><h2>#12,984,201</h2><span><StatusDot tone="green" /> 2 秒前确认</span><div><span>交易 <b>184</b></span><span>Gas <b>0.002 Gwei</b></span></div></div></section><section className="explorer-home-metrics"><Metric label="网络交易总数" value="28.42M" meta="+18,420 今日" /><Metric label="活跃市场" value="128" meta="14 个即将封盘" tone="cyan" /><Metric label="全网锁仓量" value="$18.42M" meta="100% 可验证" /><Metric label="Oracle 提交" value="4,820" meta="99.98% 成功" tone="green" /></section><section className="explorer-home-grid"><article className="explorer-list-card"><div className="workspace-section-head"><span><small>LATEST BLOCKS</small><h2>最新区块</h2></span><button>全部区块 ↗</button></div>{[["#12,984,201","2 秒前","184","0xA72F…19B4"],["#12,984,200","4 秒前","162","0x91C0…A221"],["#12,984,199","6 秒前","208","0x4BD8…72F1"],["#12,984,198","8 秒前","191","0xE2A1…08C4"]].map((row) => <div key={row[0]}><span className="block-cube">▦</span><span><b>{row[0]}</b><small>{row[1]}</small></span><span><small>交易</small><b>{row[2]}</b></span><HashText>{row[3]}</HashText></div>)}</article><article className="explorer-list-card"><div className="workspace-section-head"><span><small>LATEST TRANSACTIONS</small><h2>最新交易</h2></span><button>全部交易 ↗</button></div>{[["0x8F21…B902","OrderLocked","1,000 USDC","3 秒前"],["0x71DE…3A20","Settlement","48,920 USDC","6 秒前"],["0x4BC1…D902","OracleSubmit","结果 14","7 秒前"],["0x92A1…08C4","VaultDeposit","50,000 USDC","9 秒前"]].map((row) => <div key={row[0]}><span className="tx-glyph">↗</span><span><HashText>{row[0]}</HashText><small>{row[3]}</small></span><span><small>事件</small><b>{row[1]}</b></span><strong>{row[2]}</strong></div>)}</article></section><section className="verified-markets"><div className="workspace-section-head"><span><small>VERIFIED MARKETS</small><h2>最近公平证明</h2></span><button onClick={() => onNavigate("explorer")}>查看全部市场 ↗</button></div>{[["28","FAIR28 · 第 202607212104 期","规则、资金、结果、结算全部通过","已结算"],["TS","TSLA · 30 分钟方向市场","准备金覆盖 100% · Oracle 5/5","投注中"],["AP","AAPL · 30 分钟方向市场","规则哈希已固定 · 28:40 封盘","投注中"]].map(([logo,title,copy,status]) => <button key={title} onClick={() => onNavigate("explorer")}><MiniLogo label={logo} /><span><b>{title}</b><small>{copy}</small></span><Pill tone="success" dot={status === "投注中"}>{status}</Pill><strong>查看证明 ↗</strong></button>)}</section></div></section>
      <MobileBottomNav active="proof" onNavigate={onNavigate} />
      {found && <div className="search-toast" role="status" aria-live="polite"><span>✓</span><div><b>已找到链上记录</b><small>跳转到最匹配的市场证明</small></div></div>}
    </main>
  );
}

Object.assign(window, {
  FairnessPage,
  StockIntroPage,
  Fair28IntroPage,
  ChainPage,
  OraclePage,
  BridgePage,
  DeveloperPage,
  AppDashboardPage,
  StockTradePage,
  VaultPage,
  RiskPage,
  PortfolioPage,
  ExplorerHomePage,
});
