// ═════════════════════════════════════════════════════════════
//  0G Compute provider — Router / Advanced two modes
// ═════════════════════════════════════════════════════════════
//
//  Router mode (simple, OpenAI-style):
//    user pastes app-sk-… key, router routes inference + bills 0G
//
//  Advanced mode (decentralized, ghast trapezohe today):
//    user holds wallet → funds Ledger (≥3 0G) → transferFund to provider
//    sub-account → acknowledge TEE signer → generate API Secret → use
//

const ZG_ROUTER_MODELS = [
  { name: 'llama-3.3-70b-instruct',     in: '0.0009', out: '0.0018', tag: 'Default' },
  { name: 'deepseek-r1-distill-70b',    in: '0.0008', out: '0.0016', tag: '' },
  { name: 'qwen2.5-72b-instruct',       in: '0.0007', out: '0.0014', tag: '' },
  { name: 'mixtral-8x22b-instruct',     in: '0.0011', out: '0.0022', tag: '' },
];

const ZG_PROVIDERS = [
  {
    id: 'p-llama',
    addr: '0x1f4a…f8c2',
    model: 'llama-3.3-70b-instruct',
    tee: true, ack: true,
    balance: '0.847',
    locked24h: '0.521',
    refundable: '0.326',
    inPrice: '0.0008', outPrice: '0.0016',
    rps: 30,
  },
  {
    id: 'p-deepseek',
    addr: '0xa0bd…2c91',
    model: 'deepseek-r1-distill-70b',
    tee: true, ack: false,
    balance: '0',
    locked24h: '0',
    refundable: '0',
    inPrice: '0.0007', outPrice: '0.0014',
    rps: 30,
  },
  {
    id: 'p-qwen',
    addr: '0x9d2e…71ab',
    model: 'qwen2.5-72b-instruct',
    tee: true, ack: true,
    balance: '0.124',
    locked24h: '0',
    refundable: '0.124',
    inPrice: '0.0006', outPrice: '0.0012',
    rps: 30,
  },
];

// Ledger / wallet snapshot defaults (per artboard variant we override)
const ZG_DEFAULT_STATE = {
  walletConnected: true,
  walletAddr: '0x71c4…ae93',
  walletBal: '12.408',
  ledgerExists: true,
  ledgerBal: '4.281',
  minInitial: '3',
  minTopUp: '1',
};

// ────────── small atoms (reused inside this file) ──────────

function ZGStat({ t, label, value, mono = true, sub, accent }) {
  return (
    <div style={{
      flex: 1, padding: '12px 14px',
      background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12,
      minWidth: 0,
    }}>
      <div style={{ fontSize: 10, fontWeight: 600, color: t.fg3, letterSpacing: 0.6, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ marginTop: 6, fontSize: 18, fontWeight: 600, color: accent || t.fg, fontFamily: mono ? G.mono : G.sans, letterSpacing: -0.2 }}>
        {value}
      </div>
      {sub && <div style={{ fontSize: 11, color: t.fg3, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

function ZGSeg({ t, value, options }) {
  return (
    <div style={{
      display: 'inline-flex', padding: 3, gap: 2,
      background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10,
    }}>
      {options.map((o) => {
        const active = o.id === value;
        return (
          <div key={o.id} style={{
            padding: '6px 14px', borderRadius: 7, cursor: 'pointer',
            fontSize: 12, fontWeight: 500,
            background: active ? t.bg : 'transparent',
            color: active ? t.fg : t.fg2,
            boxShadow: active ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            {o.icon && <Icon name={o.icon} size={12} />}
            {o.label}
          </div>
        );
      })}
    </div>
  );
}

function ZGBadge({ t, kind = 'ok', children }) {
  const palette = {
    ok:    { fg: '#0e7c39', bg: 'rgba(34,197,94,.10)' },
    warn:  { fg: '#a16207', bg: 'rgba(234,179,8,.12)' },
    bad:   { fg: '#b91c1c', bg: 'rgba(239,68,68,.10)' },
    info:  { fg: '#1d4ed8', bg: 'rgba(59,130,246,.10)' },
    muted: { fg: t.fg3,     bg: t.surface },
  }[kind];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 8px', borderRadius: 999,
      fontSize: 10.5, fontWeight: 600, letterSpacing: 0.2,
      color: palette.fg, background: palette.bg,
    }}>{children}</span>
  );
}

// Tiny key-value row used across detail tables.
function ZGKV({ t, k, v, mono = true, hint }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, padding: '8px 0', borderBottom: `1px solid ${t.border2}` }}>
      <div style={{ width: 138, fontSize: 12, color: t.fg3 }}>{k}</div>
      <div style={{ flex: 1, fontSize: 13, color: t.fg, fontFamily: mono ? G.mono : G.sans }}>{v}</div>
      {hint && <div style={{ fontSize: 11, color: t.fg3 }}>{hint}</div>}
    </div>
  );
}

// ════════════════════════════════════════════════════════════
//  Top-level — the new entry rendered when ProvidersSettings sees
//  type === '0g'. Mirrors the right-panel layout of the existing
//  ProvidersSettings detail (header → segmented → body).
// ════════════════════════════════════════════════════════════

function ZeroGDetail({ dark, mode = 'router', sub = {} }) {
  const t = dark ? G.d : G.l;
  const state = { ...ZG_DEFAULT_STATE, ...(sub.state || {}) };
  return (
    <div className="gh-scroll" style={{ flex: 1, overflow: 'auto', padding: '28px 32px', maxWidth: 760 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 14,
          background: 'linear-gradient(135deg, #0a0a0a 0%, #2a2a2a 100%)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 700, fontFamily: G.mono, letterSpacing: -0.5,
        }}>0G</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.3, display: 'flex', alignItems: 'center', gap: 8 }}>
            0G Compute
            <Tag variant="solid">Configured</Tag>
            <ZGBadge t={t} kind="info">Decentralized</ZGBadge>
          </div>
          <div style={{ fontSize: 12, color: t.fg3, marginTop: 2 }}>
            Route via 0G API gateway, or fund providers directly on-chain.
          </div>
        </div>
        <Toggle on={true} dark={dark} />
      </div>

      {/* Mode segmented */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
        <ZGSeg t={t} value={mode} options={[
          { id: 'router',   label: 'Router',   icon: 'sparkle' },
          { id: 'advanced', label: 'Advanced', icon: 'plug' },
        ]} />
        <span style={{ fontSize: 11.5, color: t.fg3 }}>
          {mode === 'router'
            ? 'Single API key → OpenAI-compatible. Easy setup.'
            : 'Wallet + ledger + per-provider sub-accounts. Maximum control.'}
        </span>
      </div>

      <Divider style={{ margin: '4px 0 20px' }} />

      {mode === 'router' ? <ZeroGRouter t={t} dark={dark} sub={sub} /> : <ZeroGAdvanced t={t} dark={dark} state={state} sub={sub} />}
    </div>
  );
}

// ════════════════════════════════════════════════════════════
//  ROUTER MODE — variants: empty | typing | connected | invalid
// ════════════════════════════════════════════════════════════

function ZeroGRouter({ t, dark, sub = {} }) {
  const state = sub.routerState || 'connected'; // empty | typing | connected | invalid
  const keyByState = {
    empty:     '',
    typing:    'app-sk-',
    connected: 'app-sk-eyJhZGRyZXNzIj·············4Yz',
    invalid:   'app-sk-eyJhZGRyZxxxYY-malformed',
  };
  const showSecret = state === 'connected';

  return (
    <>
      {/* Mode comparison summary card */}
      <Card style={{ padding: 14, marginBottom: 18, display: 'flex', gap: 14 }}>
        <div style={{ flexShrink: 0, width: 32, height: 32, borderRadius: 9, background: t.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="zap" size={15} color={t.fg2} />
        </div>
        <div style={{ flex: 1, fontSize: 12.5, color: t.fg2, lineHeight: 1.55 }}>
          The 0G Router exposes an OpenAI-compatible endpoint. Top up at the web UI;
          balance is unified across all models and providers. No wallet signing per request.
        </div>
        <Button variant="secondary" size="sm" icon={<Icon name="external-link" size={11} />}>Open router UI</Button>
      </Card>

      {/* Endpoint */}
      <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Base URL</div>
      <div style={{
        height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10, marginBottom: 14,
      }}>
        <Icon name="globe" size={14} color={t.fg3} />
        <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg }}>https://router-api.0g.ai/v1</span>
        <ZGBadge t={t} kind="muted">Mainnet</ZGBadge>
      </div>

      {/* API key field */}
      <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>API Key</div>
      <div style={{
        height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
        background: t.surface,
        border: `1px solid ${state === 'invalid' ? '#dc2626' : (state === 'typing' ? t.fg2 : t.border)}`,
        borderRadius: 10, marginBottom: 6,
      }}>
        <Icon name="lock" size={14} color={t.fg3} />
        <span style={{
          flex: 1, fontFamily: G.mono, fontSize: 13,
          color: state === 'empty' ? t.fg3 : t.fg,
        }}>
          {state === 'empty' ? 'app-sk-…' : keyByState[state]}
          {state === 'typing' && <span style={{ marginLeft: 1, animation: 'blink 1s infinite', color: t.fg2 }}>|</span>}
        </span>
        {showSecret && (
          <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer' }}>
            <Icon name="eye" size={14} />
          </button>
        )}
      </div>
      <div style={{ fontSize: 11, color: state === 'invalid' ? '#dc2626' : t.fg3, marginBottom: 16 }}>
        {state === 'empty'    && 'Generate one at router-ui.0g.ai after connecting your wallet.'}
        {state === 'typing'   && 'Paste your full app-sk-… token; we’ll verify on save.'}
        {state === 'connected'&& 'Stored in your OS keychain. Linked to 0x71c4…ae93.'}
        {state === 'invalid'  && 'Could not verify this API key — make sure it’s the full app-sk-… token.'}
      </div>

      {/* Balance + status (only when connected) */}
      {state === 'connected' && (
        <>
          <SectionHeader title="Account" sub="On-chain unified balance" dark={dark} small />
          <div style={{ display: 'flex', gap: 10, marginBottom: 18 }}>
            <ZGStat t={t} label="Router balance" value="2.418 0G" sub="≈ $4.83 USD" />
            <ZGStat t={t} label="Spend · 7d"    value="0.412 0G" sub="0.0588 0G/day avg" />
            <ZGStat t={t} label="Requests · 24h" value="1,284" sub="98.6% success" accent={t.fg} />
          </div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 22 }}>
            <Button variant="primary" size="sm" icon={<Icon name="plus" size={12} />}>Top up at router UI</Button>
            <Button variant="secondary" size="sm" icon={<Icon name="refresh" size={12} />}>Refresh balance</Button>
          </div>
        </>
      )}

      {/* Models */}
      <SectionHeader title="Models" sub={`${ZG_ROUTER_MODELS.length} live · auto-failover`} dark={dark} small />
      <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, overflow: 'hidden', marginBottom: 18 }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 110px 110px 70px',
          gap: 10, padding: '10px 14px',
          fontSize: 10.5, fontWeight: 600, color: t.fg3, letterSpacing: 0.6, textTransform: 'uppercase',
          borderBottom: `1px solid ${t.border2}`, background: t.surface,
        }}>
          <div>Model</div>
          <div style={{ textAlign: 'right' }}>$ / 1k in</div>
          <div style={{ textAlign: 'right' }}>$ / 1k out</div>
          <div></div>
        </div>
        {ZG_ROUTER_MODELS.map((m, i) => (
          <div key={m.name} style={{
            display: 'grid', gridTemplateColumns: '1fr 110px 110px 70px',
            gap: 10, padding: '10px 14px', alignItems: 'center',
            borderTop: i === 0 ? 'none' : `1px solid ${t.border2}`,
            opacity: state === 'connected' ? 1 : 0.55,
          }}>
            <div style={{ fontFamily: G.mono, fontSize: 13 }}>{m.name}</div>
            <div style={{ fontFamily: G.mono, fontSize: 12, color: t.fg2, textAlign: 'right' }}>${m.in}</div>
            <div style={{ fontFamily: G.mono, fontSize: 12, color: t.fg2, textAlign: 'right' }}>${m.out}</div>
            <div style={{ textAlign: 'right' }}>{m.tag && <Tag variant="solid">{m.tag}</Tag>}</div>
          </div>
        ))}
      </div>

      <SettingRow dark={dark} label="Set as default provider" toggle={state === 'connected'} />
      <SettingRow dark={dark} label="Verify TEE attestation per request" value="Confirms inference came from attested provider." toggle={state === 'connected'} />
      {state === 'connected' && <SettingRow dark={dark} label="Remove API key" value="Disconnect 0G Router. Wallet & ledger unaffected." action="Remove" />}
    </>
  );
}

// ════════════════════════════════════════════════════════════
//  ADVANCED MODE — variants:
//    no-wallet | no-ledger | ledger-create | overview |
//    topup | refund-request | refund-locked | api-secret | ack | activity
// ════════════════════════════════════════════════════════════

function ZeroGAdvanced({ t, dark, state, sub = {} }) {
  const variant = sub.advancedVariant || 'overview';

  // Some variants render dialogs over the overview baseline
  const showDialog =
    variant === 'ledger-create' ||
    variant === 'topup' ||
    variant === 'refund-request' ||
    variant === 'refund-locked' ||
    variant === 'api-secret' ||
    variant === 'ack';

  if (variant === 'no-wallet') {
    return <ZGAdvNoWallet t={t} dark={dark} />;
  }
  if (variant === 'no-ledger') {
    return <ZGAdvWalletReady t={t} dark={dark} state={state} />;
  }
  if (variant === 'activity') {
    return <ZGAdvActivity t={t} dark={dark} state={state} />;
  }

  return (
    <div style={{ position: 'relative' }}>
      <ZGAdvOverview t={t} dark={dark} state={state} highlightProviderId={sub.providerId || 'p-llama'} />
      {showDialog && (
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          background: dark ? 'rgba(0,0,0,0.55)' : 'rgba(15,15,15,0.32)',
          backdropFilter: 'blur(2px)', borderRadius: 16,
        }}>
          {variant === 'ledger-create'  && <ZGDlgLedgerCreate t={t} state={state} />}
          {variant === 'topup'          && <ZGDlgTopup t={t} state={state} sub={sub} />}
          {variant === 'refund-request' && <ZGDlgRefund t={t} state={state} sub={sub} stage="request" />}
          {variant === 'refund-locked'  && <ZGDlgRefund t={t} state={state} sub={sub} stage="locked" />}
          {variant === 'api-secret'     && <ZGDlgApiSecret t={t} state={state} sub={sub} />}
          {variant === 'ack'            && <ZGDlgAcknowledge t={t} state={state} sub={sub} />}
        </div>
      )}
    </div>
  );
}

// ── Advanced · no wallet ─────────────────────────────────────
function ZGAdvNoWallet({ t, dark }) {
  return (
    <Card style={{ padding: 28, textAlign: 'center', maxWidth: 500, margin: '24px auto' }}>
      <div style={{
        width: 64, height: 64, borderRadius: 18, margin: '0 auto 18px',
        background: t.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name="wallet" size={26} color={t.fg2} />
      </div>
      <div style={{ fontSize: 17, fontWeight: 600, marginBottom: 6 }}>Connect a wallet to begin</div>
      <div style={{ fontSize: 13, color: t.fg3, marginBottom: 18, lineHeight: 1.6 }}>
        Advanced mode runs entirely on-chain. You hold the keys; Ghast signs requests on your behalf with a per-provider API secret.
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
        <Button variant="primary" size="md" icon={<Icon name="wallet" size={13} />}>Connect Ghast wallet</Button>
        <Button variant="secondary" size="md" icon={<Icon name="external-link" size={11} />}>Use external wallet</Button>
      </div>
      <div style={{ fontSize: 11, color: t.fg3, marginTop: 14 }}>You’ll need ≥ 3.001 0G to create the ledger account.</div>
    </Card>
  );
}

// ── Advanced · wallet ready, no ledger ───────────────────────
function ZGAdvWalletReady({ t, dark, state }) {
  return (
    <>
      <SectionHeader title="Wallet" sub="Holds your 0G token" dark={dark} small />
      <Card style={{ padding: 16, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: t.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="wallet" size={17} color={t.fg2} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontFamily: G.mono }}>{state.walletAddr}</div>
          <div style={{ fontSize: 11, color: t.fg3 }}>0G mainnet · chain id 16601</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 15, fontWeight: 600, fontFamily: G.mono }}>{state.walletBal} 0G</div>
          <div style={{ fontSize: 10.5, color: t.fg3 }}>≈ $24.81 USD</div>
        </div>
      </Card>

      <SectionHeader title="Ledger" sub="Main on-chain balance · funds are pulled from here" dark={dark} small />
      <Card style={{ padding: 22, marginBottom: 18, textAlign: 'center', borderStyle: 'dashed' }}>
        <Icon name="layers" size={22} color={t.fg3} />
        <div style={{ fontSize: 14, fontWeight: 500, marginTop: 8 }}>Ledger account not created yet</div>
        <div style={{ fontSize: 12, color: t.fg3, marginTop: 4, marginBottom: 14 }}>
          Minimum initial deposit is <span style={{ fontFamily: G.mono }}>{state.minInitial} 0G</span>. Top-ups can be {state.minTopUp} 0G or more.
        </div>
        <Button variant="primary" size="md" icon={<Icon name="plus" size={13} />}>Create ledger</Button>
      </Card>
    </>
  );
}

// ── Advanced · overview (wallet + ledger + provider list) ────
function ZGAdvOverview({ t, dark, state, highlightProviderId }) {
  return (
    <>
      {/* Wallet + ledger summary row — no "In providers" stat (table covers it) */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 18 }}>
        <ZGStat t={t} label="Wallet" value={`${state.walletBal} 0G`} sub={state.walletAddr} mono={false} />
        <ZGStat t={t} label="Ledger balance" value={`${state.ledgerBal} 0G`} sub="Available for transfer" />
        <ZGStat t={t} label="24h spend"      value="0.286 0G" sub="≈ 1.7M tokens" />
      </div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
        <Button variant="primary"   size="sm" icon={<Icon name="plus" size={12} />}>Add funds to ledger</Button>
        <Button variant="secondary" size="sm" icon={<Icon name="download" size={12} />}>Withdraw to wallet</Button>
        <Button variant="secondary" size="sm" icon={<Icon name="clock" size={12} />}>Activity</Button>
      </div>

      {/* Providers — selected row inline-expands an action bar; no separate detail card */}
      <SectionHeader title="Providers" sub={`${ZG_PROVIDERS.length} on-chain · click a row to act on its sub-account`} dark={dark} small />
      <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, overflow: 'hidden', marginBottom: 18 }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '20px 1.4fr 1fr 100px 130px 20px',
          gap: 10, padding: '10px 14px',
          fontSize: 10.5, fontWeight: 600, color: t.fg3, letterSpacing: 0.6, textTransform: 'uppercase',
          borderBottom: `1px solid ${t.border2}`,
        }}>
          <div></div>
          <div>Model · address</div>
          <div>Status</div>
          <div style={{ textAlign: 'right' }}>$ / 1k in · out</div>
          <div style={{ textAlign: 'right' }}>Sub · refundable</div>
          <div></div>
        </div>
        {ZG_PROVIDERS.map((p, i) => {
          const active = p.id === highlightProviderId;
          return (
            <React.Fragment key={p.id}>
              <div style={{
                display: 'grid', gridTemplateColumns: '20px 1.4fr 1fr 100px 130px 20px',
                gap: 10, padding: '12px 14px', alignItems: 'center',
                borderTop: i === 0 ? 'none' : `1px solid ${t.border2}`,
                background: active ? t.surface2 : 'transparent',
              }}>
                <Icon name="cpu" size={14} color={t.fg2} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: G.mono, fontSize: 13, color: t.fg, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.model}</div>
                  <div style={{ fontFamily: G.mono, fontSize: 10.5, color: t.fg3 }}>{p.addr}</div>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {p.tee && <ZGBadge t={t} kind="info">TEE</ZGBadge>}
                  {p.ack ? <ZGBadge t={t} kind="ok">Acknowledged</ZGBadge> : <ZGBadge t={t} kind="warn">Needs ack</ZGBadge>}
                </div>
                <div style={{ fontFamily: G.mono, fontSize: 11.5, color: t.fg2, textAlign: 'right' }}>
                  ${p.inPrice}<br/><span style={{ color: t.fg3 }}>${p.outPrice}</span>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: G.mono, fontSize: 13, fontWeight: 600 }}>{p.balance} 0G</div>
                  <div style={{ fontFamily: G.mono, fontSize: 10.5, color: t.fg3 }}>
                    refund {p.refundable}{parseFloat(p.locked24h) > 0 ? ` · locked ${p.locked24h}` : ''}
                  </div>
                </div>
                <Icon name={active ? 'chevron-down' : 'chevron-right'} size={14} color={t.fg3} />
              </div>
              {active && (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
                  padding: '10px 14px', borderTop: `1px solid ${t.border2}`,
                  background: t.surface2,
                }}>
                  <Button variant="primary"   size="sm" icon={<Icon name="plus" size={12} />}>Top up</Button>
                  <Button variant="secondary" size="sm" icon={<Icon name="reverse" size={12} />}>Refund</Button>
                  <Button variant="secondary" size="sm" icon={<Icon name="key" size={12} />}>Get API secret</Button>
                  {!p.ack && <Button variant="secondary" size="sm" icon={<Icon name="shield" size={12} />}>Acknowledge TEE</Button>}
                  <span style={{ flex: 1 }} />
                  <span style={{ fontSize: 11, color: t.fg3 }}>Rate limit {p.rps}/min</span>
                  <Button variant="ghost" size="sm" icon={<Icon name="external-link" size={11} />}>Explorer</Button>
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </>
  );
}

// ── Dialog: create ledger ────────────────────────────────────
function ZGDlgLedgerCreate({ t, state }) {
  return (
    <Card style={{ width: 420, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Icon name="layers" size={16} color={t.fg2} />
        <div style={{ fontSize: 15, fontWeight: 600 }}>Create ledger account</div>
      </div>
      <div style={{ fontSize: 12, color: t.fg3, marginBottom: 16, lineHeight: 1.55 }}>
        First-time deposit must be at least <span style={{ fontFamily: G.mono }}>{state.minInitial} 0G</span>. Funds stay in your control and can be withdrawn anytime (subject to a 24h refund lock).
      </div>
      <div style={{ fontSize: 11, fontWeight: 600, color: t.fg3, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>Amount</div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px', background: t.surface, border: `1px solid ${t.fg2}`, borderRadius: 10, marginBottom: 8,
      }}>
        <span style={{ flex: 1, fontFamily: G.mono, fontSize: 18, fontWeight: 600 }}>3.001</span>
        <span style={{ fontSize: 13, color: t.fg3, fontFamily: G.mono }}>0G</span>
      </div>
      <div style={{ fontSize: 11, color: t.fg3, marginBottom: 16 }}>
        Includes ~0.001 0G for gas. Wallet balance after: <span style={{ fontFamily: G.mono }}>9.407 0G</span>.
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <Button variant="ghost" size="sm">Cancel</Button>
        <Button variant="primary" size="sm" icon={<Icon name="check" size={12} />}>Sign &amp; create</Button>
      </div>
    </Card>
  );
}

// ── Dialog: topup provider sub-account ───────────────────────
function ZGDlgTopup({ t, state, sub }) {
  const p = ZG_PROVIDERS.find((x) => x.id === (sub.providerId || 'p-llama'));
  return (
    <Card style={{ width: 440, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Icon name="plus" size={16} color={t.fg2} />
        <div style={{ fontSize: 15, fontWeight: 600 }}>Top up sub-account</div>
      </div>
      <div style={{ fontSize: 12, color: t.fg3, marginBottom: 16, lineHeight: 1.55, fontFamily: G.mono }}>
        {p.model}<br/>
        <span style={{ color: t.fg3, fontFamily: G.mono }}>{p.addr}</span>
      </div>

      <div style={{ fontSize: 11, fontWeight: 600, color: t.fg3, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>Amount</div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px', background: t.surface, border: `1px solid ${t.fg2}`, borderRadius: 10, marginBottom: 6,
      }}>
        <span style={{ flex: 1, fontFamily: G.mono, fontSize: 18, fontWeight: 600 }}>1.000</span>
        <span style={{ fontSize: 13, color: t.fg3, fontFamily: G.mono }}>0G</span>
      </div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
        {['1', '2', '5', '10'].map((v) => (
          <span key={v} style={{
            padding: '4px 10px', borderRadius: 7,
            background: v === '1' ? t.surface2 : t.surface,
            border: `1px solid ${t.border}`, fontSize: 11, fontFamily: G.mono, cursor: 'pointer',
          }}>{v} 0G</span>
        ))}
      </div>

      <div style={{ background: t.surface2, border: `1px solid ${t.border2}`, borderRadius: 10, padding: 12, marginBottom: 14 }}>
        <ZGKV t={t} k="From ledger"        v={`${state.ledgerBal} → ${(parseFloat(state.ledgerBal) - 1).toFixed(3)} 0G`} mono />
        <ZGKV t={t} k="To sub-account"     v={`${p.balance} → ${(parseFloat(p.balance) + 1).toFixed(3)} 0G`} mono />
        <ZGKV t={t} k="Refund lock"        v="24h after each transfer" mono />
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, padding: '8px 0' }}>
          <div style={{ width: 138, fontSize: 12, color: t.fg3 }}>TEE acknowledge</div>
          <div style={{ flex: 1, fontSize: 13, color: t.fg }}>
            {p.ack ? <ZGBadge t={t} kind="ok">Already done</ZGBadge> : <ZGBadge t={t} kind="warn">Will sign automatically</ZGBadge>}
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <Button variant="ghost" size="sm">Cancel</Button>
        <Button variant="primary" size="sm" icon={<Icon name="check" size={12} />}>Sign &amp; transfer</Button>
      </div>
    </Card>
  );
}

// ── Dialog: refund (request / locked claim) ──────────────────
function ZGDlgRefund({ t, state, sub, stage }) {
  const p = ZG_PROVIDERS.find((x) => x.id === (sub.providerId || 'p-llama'));
  return (
    <Card style={{ width: 460, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Icon name="reverse" size={16} color={t.fg2} />
        <div style={{ fontSize: 15, fontWeight: 600 }}>Refund from sub-account</div>
      </div>
      <div style={{ fontSize: 12, color: t.fg3, marginBottom: 16, lineHeight: 1.55 }}>
        Two-step on-chain flow. Step 1 puts funds into a 24h lock; step 2 sweeps them back to the ledger once the lock matures.
      </div>

      {/* Stepper */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        {[
          { id: 'request', label: '1 · Request' },
          { id: 'locked',  label: '2 · Claim'   },
        ].map((s, i) => {
          const done   = (stage === 'locked' && s.id === 'request');
          const active = stage === s.id;
          return (
            <React.Fragment key={s.id}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 6,
                padding: '4px 10px', borderRadius: 999,
                background: active ? t.fg : (done ? t.surface2 : 'transparent'),
                color:      active ? t.bg : (done ? t.fg : t.fg3),
                border: `1px solid ${active ? t.fg : t.border}`,
                fontSize: 11, fontWeight: 600,
              }}>
                {done ? <Icon name="check" size={11} /> : <span>{i + 1}</span>}
                <span>{s.label}</span>
              </div>
              {i === 0 && <span style={{ flex: 1, height: 1, background: t.border }} />}
            </React.Fragment>
          );
        })}
      </div>

      <div style={{ background: t.surface2, border: `1px solid ${t.border2}`, borderRadius: 10, padding: 12, marginBottom: 14 }}>
        <ZGKV t={t} k="Provider" v={p.model} mono />
        <ZGKV t={t} k="Sub-balance" v={`${p.balance} 0G`} />
        <ZGKV t={t} k="Locked · 24h" v={`${p.locked24h} 0G`} hint="Recently funded — cannot refund yet" />
        {stage === 'request' && <ZGKV t={t} k="Refundable now" v={`${p.refundable} 0G`} />}
        {stage === 'locked'  && <ZGKV t={t} k="Pending claim"  v={`${p.refundable} 0G`} hint="Lock matured · ready to sweep" />}
      </div>

      {stage === 'request' && (
        <>
          <div style={{ fontSize: 11, fontWeight: 600, color: t.fg3, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>Refund amount</div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 14px', background: t.surface, border: `1px solid ${t.fg2}`, borderRadius: 10, marginBottom: 6,
          }}>
            <span style={{ flex: 1, fontFamily: G.mono, fontSize: 18, fontWeight: 600 }}>{p.refundable}</span>
            <span style={{ fontSize: 13, color: t.fg3, fontFamily: G.mono }}>0G</span>
          </div>
          <SettingRow dark={false} label="Re-fund remainder back to provider" toggle />
        </>
      )}

      {stage === 'locked' && (
        <SettingRow dark={false} label="Forward to wallet after claim" value="Skips a follow-up `ledger.refund` tx." toggle />
      )}

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
        <Button variant="ghost" size="sm">Cancel</Button>
        {stage === 'request' && <Button variant="primary" size="sm" icon={<Icon name="check" size={12} />}>Sign &amp; request</Button>}
        {stage === 'locked'  && <Button variant="primary" size="sm" icon={<Icon name="download" size={12} />}>Sign &amp; claim</Button>}
      </div>
    </Card>
  );
}

// ── Dialog: API secret generated ─────────────────────────────
function ZGDlgApiSecret({ t, state, sub }) {
  const p = ZG_PROVIDERS.find((x) => x.id === (sub.providerId || 'p-llama'));
  return (
    <Card style={{ width: 480, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Icon name="key" size={16} color={t.fg2} />
        <div style={{ fontSize: 15, fontWeight: 600 }}>API secret generated</div>
      </div>
      <div style={{ fontSize: 12, color: t.fg3, marginBottom: 14, lineHeight: 1.55 }}>
        Copy now — Ghast does not store the secret. It is signed with your wallet and bound to <span style={{ fontFamily: G.mono }}>{p.model}</span>.
      </div>
      <div style={{
        background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 10,
        padding: '12px 14px', marginBottom: 12,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <Icon name="lock" size={13} color={t.fg3} />
        <div style={{ flex: 1, fontFamily: G.mono, fontSize: 12.5, color: t.fg, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          app-sk-eyJhZGRyZXNzIjoiMHg3MWM0...|0xMjE0YmZj...
        </div>
        <Button variant="secondary" size="sm" icon={<Icon name="copy" size={11} />}>Copy</Button>
      </div>

      <div style={{ background: t.surface, border: `1px solid ${t.border2}`, borderRadius: 10, padding: 12, marginBottom: 14 }}>
        <ZGKV t={t} k="Token id"        v="0" />
        <ZGKV t={t} k="Generation"      v="3" hint="Increments on revoke-all" />
        <ZGKV t={t} k="Bound provider"  v={p.addr} />
        <ZGKV t={t} k="Wallet signer"   v={state.walletAddr} />
        <ZGKV t={t} k="Expires"         v="never" hint="Revoke any time on-chain" />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: t.fg3, marginBottom: 12 }}>
        <Icon name="info" size={11} />
        Up to 255 secrets per provider account. Revoking individual tokens uses 1 transaction each.
      </div>

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <Button variant="ghost" size="sm" icon={<Icon name="x" size={11} />}>Revoke this token</Button>
        <Button variant="primary" size="sm" icon={<Icon name="check" size={12} />}>Done</Button>
      </div>
    </Card>
  );
}

// ── Dialog: TEE acknowledge (first time funding) ─────────────
function ZGDlgAcknowledge({ t, state, sub }) {
  const p = ZG_PROVIDERS.find((x) => x.id === (sub.providerId || 'p-deepseek'));
  return (
    <Card style={{ width: 440, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Icon name="shield" size={16} color={t.fg2} />
        <div style={{ fontSize: 15, fontWeight: 600 }}>Acknowledge TEE signer</div>
      </div>
      <div style={{ fontSize: 12, color: t.fg3, marginBottom: 16, lineHeight: 1.55 }}>
        First-time use of a provider requires acknowledging its TEE attestation key. Ghast does this automatically during top-up; you can also confirm here.
      </div>

      <div style={{ background: t.surface2, border: `1px solid ${t.border2}`, borderRadius: 10, padding: 12, marginBottom: 14 }}>
        <ZGKV t={t} k="Provider"            v={p.model} mono />
        <ZGKV t={t} k="Provider address"    v={p.addr} />
        <ZGKV t={t} k="TEE signer"          v="0x4f1c…29ad" />
        <ZGKV t={t} k="Attestation"         v={<ZGBadge t={t} kind="ok">Verified · Phala TEE</ZGBadge>} mono={false} />
      </div>

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <Button variant="ghost" size="sm">Cancel</Button>
        <Button variant="primary" size="sm" icon={<Icon name="check" size={12} />}>Sign &amp; acknowledge</Button>
      </div>
    </Card>
  );
}

// ── Advanced · activity / settlement timeline ────────────────
function ZGAdvActivity({ t, dark, state }) {
  const events = [
    { kind: 'settle',  time: '12:04',   amount: '−0.0184 0G', who: 'llama-3.3-70b', note: 'Batch settlement · 1.4M tok' },
    { kind: 'refund',  time: '11:42',   amount: '+0.300 0G',  who: 'qwen2.5-72b',  note: 'Lock matured · swept to ledger' },
    { kind: 'topup',   time: '10:18',   amount: '−1.000 0G',  who: 'llama-3.3-70b', note: 'transferFund · sub-account' },
    { kind: 'ack',     time: '10:18',   amount: '',           who: 'deepseek-r1',   note: 'TEE signer acknowledged' },
    { kind: 'deposit', time: 'Yesterday', amount: '−4.000 0G', who: 'ledger',       note: 'depositFund · from wallet' },
    { kind: 'create',  time: '3 days ago', amount: '−3.000 0G', who: 'ledger',     note: 'addLedger · initial' },
  ];
  const palette = {
    settle:  { i: 'activity',  c: '#6366f1' },
    refund:  { i: 'reverse',   c: '#0e7c39' },
    topup:   { i: 'plus',      c: '#1d4ed8' },
    ack:     { i: 'shield',    c: '#a16207' },
    deposit: { i: 'download',  c: t.fg2 },
    create:  { i: 'layers',    c: t.fg2 },
  };
  return (
    <>
      <SectionHeader title="On-chain activity" sub="All operations are signed by your wallet" dark={dark} small />
      <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, overflow: 'hidden', marginBottom: 18 }}>
        {events.map((e, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '20px 78px 1fr 110px 28px',
            gap: 10, padding: '12px 14px', alignItems: 'center',
            borderTop: i === 0 ? 'none' : `1px solid ${t.border2}`,
          }}>
            <div style={{ width: 20, height: 20, borderRadius: 6, background: t.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={palette[e.kind].i} size={11} color={palette[e.kind].c} />
            </div>
            <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono }}>{e.time}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontFamily: G.mono }}>{e.who}</div>
              <div style={{ fontSize: 11, color: t.fg3 }}>{e.note}</div>
            </div>
            <div style={{ fontSize: 13, fontFamily: G.mono, textAlign: 'right', color: e.amount.startsWith('+') ? '#0e7c39' : (e.amount.startsWith('−') ? t.fg : t.fg3) }}>
              {e.amount || '—'}
            </div>
            <Icon name="external-link" size={11} color={t.fg3} />
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: t.fg3 }}>
        <Icon name="info" size={11} />
        Settlements are batched on the provider side — fees may take seconds to minutes to appear here.
      </div>
    </>
  );
}

// Export
Object.assign(window, {
  ZeroGDetail, ZG_PROVIDERS, ZG_ROUTER_MODELS, ZG_DEFAULT_STATE,
});
