/* eslint-disable */
// DashboardFlow.jsx — Module 4 clickable flow.
// Wraps the console shell; renders one of: home, transactions, banks, wallets, apikeys, security.

const DASH_NAV_KEY = {
  home: 'dashboard', transactions: 'transactions', 'tx-detail': 'transactions',
  banks: 'banks', wallets: 'wallets', apikeys: 'apikeys', security: 'security',
};

const DashboardFlow = ({ screen }) => {
  const s = screen || 'home';
  const t = useT();
  const DASH_BREADCRUMBS = {
    home:         [t('Dashboard', 'Дашборд')],
    transactions: [t('Transactions', 'Транзакции')],
    'tx-detail':  [t('Transactions', 'Транзакции'), t('Request detail', 'Детали запроса')],
    banks:        [t('Account', 'Аккаунт'), t('Bank Accounts', 'Банковские счета')],
    wallets:      [t('Account', 'Аккаунт'), t('Wallet Addresses', 'Адреса кошельков')],
    apikeys:      [t('Account', 'Аккаунт'), t('API Keys', 'API-ключи')],
    security:     [t('Account', 'Аккаунт'), t('Security', 'Безопасность')],
  };
  return (
    <ProtoConsoleShell current={DASH_NAV_KEY[s]} breadcrumbs={DASH_BREADCRUMBS[s] || [t('Dashboard', 'Дашборд')]}>
      {s === 'home'         && <DashboardHomeScreen />}
      {s === 'transactions' && <TransactionsScreen />}
      {s === 'tx-detail'    && <TxDetailScreen />}
      {s === 'banks'        && <BanksScreen />}
      {s === 'wallets'      && <WalletsScreen />}
      {s === 'apikeys'      && <ApiKeysScreen />}
      {s === 'security'     && <SecurityScreen />}
    </ProtoConsoleShell>
  );
};

// =================================================================
// Dashboard home (S4.1 Variant A)
// =================================================================
const DashboardHomeScreen = () => {
  const { set } = usePrototype();
  const t = useT();
  const openTx = (r) => { set({ selectedTxId: r.id }); navigateTo('dashboard', 'tx-detail'); };
  return (
  <>
    <PageHeader
      title={t('Good morning, Lin', 'Доброе утро, Lin')}
      sub={t('Reserves are in attestation. No active alerts.', 'Резервы на аттестации. Активных уведомлений нет.')}
      actions={
        <>
          <Button variant="secondary" icon={<Icons.arrowDown size={13} />} onClick={() => navigateTo('burn', 'initiate')}>{t('Burn', 'Погасить')}</Button>
          <Button icon={<Icons.arrowUp size={13} />} onClick={() => navigateTo('mint', 'initiate')}>{t('Mint', 'Эмиссия')}</Button>
        </>
      }
    />

    {/* Hero balance row */}
    <div style={{
      display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr', gap: 16, marginBottom: 22,
    }}>
      <Card padding={26} style={{
        background: 'linear-gradient(135deg, rgba(82,0,4,0.20), rgba(20,18,16,0.4))',
        border: '1px solid var(--border-gold)', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', inset: 0, background: 'var(--grad-vignette)', opacity: 0.6, pointerEvents: 'none' }} />
        <span className="kgst-caption" style={{ color: 'var(--bone-3)', position: 'relative' }}>{t('Total KGST · all chains', 'Всего KGST · все сети')}</span>
        <div style={{ marginTop: 10, position: 'relative' }}>
          <Amount value="8,724,310.41" size={42} />
        </div>
        <div style={{ marginTop: 16, position: 'relative', display: 'flex', gap: 20 }}>
          {[['eth','Ethereum','5,224,310.41'],['tron','Tron','3,500,000.00'],['bnb','BNB','0.00']].map(([k,n,v]) => (
            <div key={k} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <ChainBadge chain={k} small /><span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{n}</span>
              </div>
              <span className="kgst-mono" style={{ fontSize: 13, color: 'var(--bone-5)' }}>{v}</span>
            </div>
          ))}
        </div>
      </Card>

      <Card padding={22}>
        <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Pending settlement', 'Ожидает расчета')}</span>
        <div style={{ marginTop: 10, fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 600, color: 'var(--amber-400)' }}>
          5,000,000.00 <span style={{ fontSize: 11, color: 'var(--fg-tertiary)', fontWeight: 500, marginLeft: 4 }}>KGS</span>
        </div>
        <div style={{ marginTop: 6, fontSize: 11.5, color: 'var(--fg-tertiary)' }}>{t('1 inbound mint · awaiting wire', '1 эмиссия · ожидает SWIFT')}</div>
        <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--border-subtle)', fontSize: 11.5, color: 'var(--fg-secondary)', display: 'flex', justifyContent: 'space-between' }}>
          <span>{t('Outbound burn', 'Исходящее погашение')}</span>
          <span className="kgst-mono">0.00 KGS</span>
        </div>
      </Card>

      <Card padding={22}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Month to date', 'С начала месяца')}</span>
          <span style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{t('Jan 2026', 'янв 2026')}</span>
        </div>
        <div style={{ marginTop: 10, display: 'flex', gap: 16 }}>
          <div>
            <div style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{t('Minted', 'Эмитировано')}</div>
            <div className="kgst-mono" style={{ fontSize: 17, color: 'var(--gold-300)', fontWeight: 600 }}>12.4M</div>
          </div>
          <div>
            <div style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{t('Burned', 'Погашено')}</div>
            <div className="kgst-mono" style={{ fontSize: 17, color: 'var(--bone-5)', fontWeight: 600 }}>4.2M</div>
          </div>
        </div>
        <div style={{ marginTop: 10, marginLeft: -6, marginRight: -6 }}>
          <Sparkline data={[2,3,5,4,7,9,8,10,7,12,11,14,10,16,18,15,21,19,22,18,24,20,27,25,28]} height={48} />
        </div>
      </Card>
    </div>

    {/* Activity + quick actions */}
    <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 22 }}>
      <Card padding={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '16px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid var(--border-subtle)' }}>
          <div className="kgst-h3" style={{ fontSize: 15 }}>{t('Recent transactions', 'Последние транзакции')}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <a style={{ fontSize: 12, color: 'var(--gold-300)', cursor: 'pointer' }} onClick={() => navigateTo('dashboard', 'transactions')}>{t('View all', 'Смотреть все')} →</a>
          </div>
        </div>
        <TxTable rows={RECENT_TX.slice(0, 5)} onRowClick={openTx} />
      </Card>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Card padding={20}>
          <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 12 }}>{t('Quick actions', 'Быстрые действия')}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <DashQuickRow icon="arrowUp"   title={t('Mint KGST', 'Эмитировать KGST')}             body={t('Wire KGS, receive on-chain', 'Перевести KGS, получить в сети')}     onClick={() => navigateTo('mint', 'initiate')} />
            <DashQuickRow icon="arrowDown" title={t('Redeem KGST', 'Погасить KGST')}           body={t('Burn KGST, receive KGS', 'Сжечь KGST, получить KGS')}         onClick={() => navigateTo('burn', 'initiate')} />
            <DashQuickRow icon="bank"      title={t('Manage bank accounts', 'Правила банковских счетов')}  body={t('2 accounts bound', 'Привязано: 2 счёта')}                onClick={() => navigateTo('dashboard', 'banks')} />
            <DashQuickRow icon="spark"     title={t('Generate API key', 'Создать API-ключ')}      body={t('For programmatic mint/burn', 'Для программной эмиссии и погашения')}      onClick={() => navigateTo('dashboard', 'apikeys')} />
          </div>
        </Card>
        <Card padding={18} style={{
          background: 'linear-gradient(135deg, rgba(82,0,4,0.25), rgba(20,18,16,0.4))',
          border: '1px solid var(--border-default)',
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
            <Icons.audit size={18} style={{ color: 'var(--gold-300)', marginTop: 2 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{t('December reserve attestation published', 'Аттестация резервов за декабрь опубликована')}</div>
              <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)', marginTop: 3 }}>{t('Independent auditor: BDO Kyrgyzstan · 99.98% coverage', 'Независимый аудитор: BDO Kyrgyzstan · покрытие 99,98%')}</div>
              <a style={{ fontSize: 11.5, color: 'var(--gold-300)', marginTop: 6, display: 'inline-block', cursor: 'pointer' }}>{t('Open report', 'Открыть отчет')} →</a>
            </div>
          </div>
        </Card>
      </div>
    </div>
  </>
);
};

const DashQuickRow = ({ icon, title, body, onClick }) => {
  const I = Icons[icon];
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 12px', borderRadius: 6, cursor: 'pointer',
      transition: 'background 120ms ease',
    }}
    onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,244,219,0.04)'; }}
    onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}>
      <span style={{
        width: 28, height: 28, borderRadius: 6,
        background: 'rgba(201,152,64,0.08)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--gold-300)', flexShrink: 0,
      }}><I size={14} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{title}</div>
        <div style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{body}</div>
      </div>
      <Icons.arrowRight size={13} style={{ color: 'var(--fg-tertiary)' }} />
    </div>
  );
};

// =================================================================
// Transactions
// =================================================================
const TransactionsScreen = () => {
  const { set } = usePrototype();
  const t = useT();
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const filteredRows = RECENT_TX.filter(r => {
    if (filter !== 'all' && r.dir !== filter && r.status !== filter) return false;
    if (query.trim()) {
      const q = query.toLowerCase();
      return r.id.toLowerCase().includes(q) || r.tx.toLowerCase().includes(q);
    }
    return true;
  });
  const openTx = (r) => { set({ selectedTxId: r.id }); navigateTo('dashboard', 'tx-detail'); };
  return (
    <>
      <PageHeader
        title={t('Transaction history', 'История транзакций')}
        sub={t('Every mint and burn issued under your institutional account. Exports include signed receipts and on-chain proofs.', 'Все эмиссии и погашения по вашему институциональному счету. Экспорт включает подписанные квитанции и блокчейн-доказательства.')}
        actions={
          <>
            <Button variant="ghost" icon={<Icons.download size={13} />}>{t('Export CSV', 'Экспорт CSV')}</Button>
            <Button variant="secondary">{t('Filters', 'Фильтры')} · 2</Button>
          </>
        }
      />

      <Card padding={14} style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          {[
            ['all',     t('All', 'Все')],
            ['mint',    t('Mint', 'Эмиссия')],
            ['burn',    t('Burn', 'Погашение')],
            ['failed',  t('Failed', 'Ошибка')],
            ['pending', t('Pending', 'В ожидании')],
          ].map(([k, l]) => (
            <span key={k} onClick={() => setFilter(k)} style={{
              padding: '5px 11px', borderRadius: 999, fontSize: 11, letterSpacing: '0.02em',
              color: filter === k ? 'var(--gold-200)' : 'var(--fg-secondary)',
              background: filter === k ? 'rgba(201,152,64,0.08)' : 'transparent',
              border: '1px solid ' + (filter === k ? 'var(--border-gold)' : 'var(--border-subtle)'),
              cursor: 'pointer',
            }}>{l}</span>
          ))}
          <div style={{ flex: 1 }} />
          <DashSearchField value={query} onChange={setQuery} placeholder={t('Search request ID, tx hash…', 'Поиск ID, хэша…')} />
        </div>
      </Card>

      <Card padding={0} style={{ overflow: 'hidden' }}>
        <TxTable rows={filteredRows.length ? filteredRows : []} onRowClick={openTx} />
        {filteredRows.length === 0 ? (
          <div style={{ padding: '40px 0', textAlign: 'center', fontSize: 12.5, color: 'var(--fg-tertiary)' }}>
            {t('No transactions match your filters.', 'Нет транзакций, соответствующих фильтрам.')}
          </div>
        ) : null}
        <div style={{ padding: '12px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid var(--border-subtle)', background: 'var(--ink-2)' }}>
          <span style={{ fontSize: 11.5, color: 'var(--fg-tertiary)' }}>{t(`Showing ${filteredRows.length} of ${RECENT_TX.length} requests`, `Показано ${filteredRows.length} из ${RECENT_TX.length}`)}</span>
          <div style={{ display: 'flex', gap: 4 }}>
            {[1,2,3,'…',21].map((p,i) => (
              <span key={i} style={{
                minWidth: 26, height: 26, padding: '0 8px',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                borderRadius: 5, fontSize: 11.5,
                color: p === 1 ? 'var(--gold-200)' : 'var(--fg-secondary)',
                background: p === 1 ? 'rgba(201,152,64,0.08)' : 'transparent',
                border: '1px solid ' + (p === 1 ? 'var(--border-gold)' : 'transparent'),
                cursor: 'pointer',
              }}>{p}</span>
            ))}
          </div>
        </div>
      </Card>
    </>
  );
};

// =================================================================
// Transaction detail (mock per row)
// =================================================================
const CHAIN_NAMES = { eth: 'Ethereum', tron: 'Tron', bnb: 'BNB Chain' };
const CHAIN_STDS  = { eth: 'ERC-20',   tron: 'TRC-20', bnb: 'BEP-20' };
const CHAIN_EXPLORERS = { eth: 'Etherscan', tron: 'Tronscan', bnb: 'BscScan' };

const TX_DETAIL_EXTRAS = {
  'KGST-MINT-2026000914': {
    fromAddr: 'KKB · Kyrgyzkommertsbank OJSC',
    toAddr:   'TKgQ9b2A4Fz81G7tHpY5sLwM2eC8DfN6Vx',
    addrLabel:'Treasury · Tron',
    wireRef:  'KGST-MINT-2026000914',
    block:    'pending',
    confirms: '7 / 12',
    fee:      '0.00 KGS',
    bank:     'KKB · KKBKKG22 · 1230 0050 4711 0008',
    submittedBy: 'Lin Zhao · treasury@binance.com',
  },
  'KGST-BURN-2026000418': {
    fromAddr: '0x9b21A8e7d1f5C4b8…2E4d8B',
    toAddr:   'Optima Bank OJSC · 1170 0702 4000 5611',
    addrLabel:'Treasury · Cold storage',
    burnTx:   '0xd4f9c8e1…48bca91a8',
    block:    '20,418,617',
    confirms: '12 / 12',
    fee:      '0.00 KGS',
    bank:     'Optima Bank OJSC · ENEJKG22 · 1170 0702 4000 5611',
    submittedBy: 'Lin Zhao · treasury@binance.com',
  },
};

const TxDetailScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const txId = data.selectedTxId || 'KGST-MINT-2026000914';
  const row = RECENT_TX.find(r => r.id === txId) || RECENT_TX[0];
  const extra = TX_DETAIL_EXTRAS[row.id] || {
    fromAddr: row.dir === 'mint' ? 'KKB · Kyrgyzkommertsbank OJSC' : '0x9b21A8e7d1f5C4b8…2E4d8B',
    toAddr:   row.dir === 'mint' ? 'Bound institutional wallet' : 'Optima Bank OJSC',
    addrLabel:'Treasury',
    wireRef:  row.id,
    block:    row.status === 'pending' ? 'pending' : '20,418,617',
    confirms: row.status === 'pending' ? '7 / 12' : '12 / 12',
    fee:      '0.00 KGS',
    bank:     'KKB · KKBKKG22 · 1230 0050 4711 0008',
    submittedBy: 'Lin Zhao · treasury@binance.com',
  };
  const isMint = row.dir === 'mint';
  const chainName = CHAIN_NAMES[row.chain] || row.chain;
  const chainStd  = CHAIN_STDS[row.chain]  || '';
  const explorer  = CHAIN_EXPLORERS[row.chain] || 'Explorer';

  // Status-driven timeline
  const mintSteps = [
    { label: t('Mint request created', 'Запрос эмиссии создан'),  sub: row.time, tone: 'gold' },
    { label: t('Wire received', 'SWIFT получен'),          sub: row.status === 'pending' ? t('pending', 'ожидает') : `${row.time} +25m`, tone: row.status === 'pending' ? 'amber' : 'gold' },
    { label: t('On-chain mint broadcast', 'Эмиссия в блокчейне'),sub: row.status === 'pending' ? t('pending', 'ожидает') : `${row.time} +26m`, tone: row.status === 'pending' ? 'neutral' : 'gold' },
    { label: t('KGST delivered', 'KGST доставлены'),         sub: row.status === 'settled' ? `${row.time} +28m` : t('pending', 'ожидает'), tone: row.status === 'settled' ? 'gold' : 'neutral' },
  ];
  const burnSteps = [
    { label: t('Burn request submitted', 'Запрос погашения'), sub: row.time, tone: 'gold' },
    { label: t('KGST received', 'KGST получены'),         sub: `${row.time} +3m`,  tone: row.status === 'failed' ? 'red' : 'gold' },
    { label: t('On-chain burn', 'Погашение в блокчейне'), sub: `${row.time} +4m`,  tone: row.status === 'failed' ? 'red' : 'gold' },
    { label: t('RTGS wire sent', 'SWIFT/RTGS отправлен'),  sub: `${row.time} +14m`, tone: row.status === 'settled' ? 'gold' : 'neutral' },
    { label: t('Settled at bank', 'Исполнено банком'), sub: row.status === 'settled' ? `${row.time} +18m` : t('pending', 'ожидает'), tone: row.status === 'settled' ? 'gold' : 'neutral' },
  ];
  const timeline = isMint ? mintSteps : burnSteps;

  const statusPill = row.status === 'settled'
    ? <Pill tone="success">{t('Settled', 'Исполнено')}</Pill>
    : row.status === 'pending'
    ? <Pill tone="warning">{t('Pending', 'В ожидании')}</Pill>
    : <Pill tone="danger">{t('Failed', 'Ошибка')}</Pill>;

  return (
    <>
      <PageHeader
        title={
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 14 }}>
            <span>{isMint ? t('Mint request', 'Запрос эмиссии') : t('Burn request', 'Запрос погашения')}</span>
            <span className="kgst-mono" style={{ fontSize: 14, color: 'var(--bone-3)', fontWeight: 500 }}>{row.id}</span>
            {statusPill}
          </span>
        }
        sub={`${chainName} (${chainStd}) · ${t('submitted', 'подан')} ${row.time}, 2026 · ${extra.submittedBy}`}
        actions={
          <>
            <Button variant="ghost" onClick={() => navigateTo('dashboard', 'transactions')}>{t('Back to list', 'Назад к списку')}</Button>
            <Button variant="ghost" icon={<Icons.download size={13} />}>{t('Receipt', 'Квитанция')}</Button>
            <Button variant="secondary" iconRight={<Icons.arrowUp size={13} />}>{t(`Open on ${explorer}`, `Открыть в ${explorer}`)}</Button>
          </>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 22 }}>
        {/* LEFT — primary details */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={26} style={{
            background: 'linear-gradient(135deg, rgba(82,0,4,0.20), rgba(20,18,16,0.4))',
            border: '1px solid var(--border-gold)', position: 'relative', overflow: 'hidden',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>
                {isMint ? t('KGST issued', 'KGST эмитированы') : t('KGST burned', 'KGST погашены')}
              </span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--fg-secondary)' }}>
                <ChainBadge chain={row.chain} small /> {chainName}
              </span>
            </div>
            <Amount value={row.amount} size={38} />
            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label={isMint ? t('KGS wired in', 'KGS входящий SWIFT') : t('KGS to be wired out', 'KGS исходящий SWIFT')} value={`${row.amount} KGS`} mono />
              <Field label={t('Issuance fee', 'Комиссия')} value={extra.fee} mono />
            </div>
          </Card>

          <Card padding={24}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 14 }}>{t('Details', 'Детали')}</div>
            <Field label={t('Request ID', 'ID запроса')} value={row.id} mono copyable />
            <Field label={t('Direction', 'Направление')} value={isMint ? t('Mint (issue KGST)', 'Эмиссия KGST') : t('Burn (redeem KGST)', 'Погашение KGST')} />
            <Field label={t('Chain', 'Сеть')} value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><ChainBadge chain={row.chain} small /> {chainName} ({chainStd})</span>} />
            <Field label={isMint ? t('Receive address', 'Адрес получения') : t('Source address', 'Адрес отправления')} value={extra.fromAddr.startsWith('0x') || extra.fromAddr.startsWith('T') ? extra.fromAddr : ''} sub={extra.addrLabel} mono={extra.fromAddr.startsWith('0x') || extra.fromAddr.startsWith('T')} copyable />
            <Field label={isMint ? t('From bank', 'Банк-отправитель') : t('To bank', 'Банк-получатель')} value={extra.bank} />
            <Field label={t('On-chain tx', 'Хэш в блокчейне')} value={<span style={{ color: 'var(--gold-300)' }}>{row.tx}</span>} mono copyable />
            <Field label={t('Block', 'Блок')} value={`${extra.block} · ${extra.confirms} ${t('confirmations', 'подтверждений')}`} mono />
            <Field label={t('Submitted', 'Подано')} value={`${row.time}, 2026 UTC`} />
            <Field label={t('Submitted by', 'Подал')} value={extra.submittedBy} />
            {isMint ? <Field label={t('Wire reference matched', 'SWIFT-референс совпал')} value={extra.wireRef || row.id} mono copyable /> : null}
          </Card>
        </div>

        {/* RIGHT — timeline + receipt */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={22}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 14 }}>{t('Timeline', 'Хронология')}</div>
            <TxDetailTimeline steps={timeline} />
          </Card>

          <Card padding={20}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 10 }}>{t('Receipt', 'Квитанция')}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, borderRadius: 8, background: 'var(--bg-inset)', border: '1px solid var(--border-default)' }}>
              <Icons.audit size={20} style={{ color: 'var(--gold-300)', flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500 }}>{row.id}.pdf</div>
                <div style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{t('Signed receipt with on-chain proof · 184 KB', 'Подписанная квитанция с блокчейн-доказательством · 184 КБ')}</div>
              </div>
              <Button size="sm" variant="secondary" icon={<Icons.download size={12} />}>{t('Download', 'Скачать')}</Button>
            </div>
          </Card>

          {row.status === 'failed' ? (
            <Card padding={16} style={{ background: 'rgba(196,69,69,0.06)', border: '1px solid rgba(196,69,69,0.25)' }}>
              <div style={{ display: 'flex', gap: 10, fontSize: 12, color: 'var(--bone-5)' }}>
                <Icons.shield size={14} style={{ color: 'var(--red-400)', marginTop: 1, flexShrink: 0 }} />
                <div>
                  <div style={{ color: 'var(--fg-primary)', fontWeight: 500, marginBottom: 4 }}>{t('Why did this fail?', 'Почему ошибка?')}</div>
                  {t('Source address was not bound at submission time. KGST was returned to the originating wallet; no fees were charged.', 'Адрес-отправитель не был привязан на момент отправки. KGST возвращены на исходный кошелёк; комиссия не взята.')}
                </div>
              </div>
            </Card>
          ) : null}

          <Card padding={16} style={{ background: 'rgba(93,139,217,0.06)', border: '1px solid rgba(93,139,217,0.20)' }}>
            <div style={{ display: 'flex', gap: 10, fontSize: 11.5, color: 'var(--bone-5)' }}>
              <Icons.shield size={13} style={{ color: 'var(--blue-400)', marginTop: 1, flexShrink: 0 }} />
              <span>{t('All settled requests carry an independent attestation hash that is published in the next monthly reserve report.', 'Все исполненные запросы имеют независимый хэш аттестации, публикуемый в следующем ежемесячном отчёте о резервах.')}</span>
            </div>
          </Card>
        </div>
      </div>
    </>
  );
};

const TxDetailTimeline = ({ steps }) => {
  const toneColor = (t) => {
    if (t === 'gold')  return 'var(--gold-300)';
    if (t === 'amber') return 'var(--amber-400)';
    if (t === 'red')   return 'var(--red-400)';
    return 'var(--bone-3)';
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0, position: 'relative' }}>
      {steps.map((s, i) => {
        const last = i === steps.length - 1;
        return (
          <div key={i} style={{ display: 'flex', gap: 12, position: 'relative', paddingBottom: last ? 0 : 18 }}>
            <div style={{ position: 'relative', width: 14, flexShrink: 0, display: 'flex', justifyContent: 'center' }}>
              <span style={{
                width: 10, height: 10, marginTop: 4, borderRadius: '50%',
                background: toneColor(s.tone),
                boxShadow: s.tone === 'amber' ? '0 0 0 3px rgba(225,165,58,0.12)' : 'none',
                animation: s.tone === 'amber' ? 'kgstPulse 1.4s ease-in-out infinite' : 'none',
              }} />
              {!last ? (
                <span style={{
                  position: 'absolute', top: 14, bottom: -4, width: 1,
                  background: 'var(--border-subtle)',
                }} />
              ) : null}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, color: 'var(--fg-primary)', fontWeight: 500 }}>{s.label}</div>
              <div style={{ fontSize: 11, color: 'var(--fg-tertiary)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>{s.sub}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

const DashSearchField = ({ value, onChange, placeholder }) => {
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '0 10px', height: 30, background: 'var(--ink-2)', borderRadius: 6,
      border: '1px solid ' + (focused ? 'var(--border-gold)' : 'var(--border-subtle)'),
      boxShadow: focused ? '0 0 0 2px rgba(201,152,64,0.10)' : 'none',
      color: 'var(--bone-3)', fontSize: 11.5, width: 280,
      transition: 'border-color 120ms ease, box-shadow 120ms ease',
    }}>
      <Icons.search size={12} />
      <input
        value={value}
        onChange={e => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder={placeholder}
        style={{
          flex: 1, background: 'transparent', border: 'none', outline: 'none',
          color: 'var(--fg-primary)', fontFamily: 'inherit', fontSize: 11.5,
          padding: 0,
        }}
      />
    </div>
  );
};

// =================================================================
// Settings layout — clickable sub-nav
// =================================================================
// Settings layout — the sidebar already exposes these sections, so the
// inner sub-nav was redundant. Now just a passthrough wrapper.
const ProtoSettingsLayout = ({ current, children }) => (
  <div>{children}</div>
);

// =================================================================
// Banks
// =================================================================
const BanksScreen = () => {
  const t = useT();
  return (
  <>
    <PageHeader
      title={t('Settlement bank accounts', 'Банковские счета для расчетов')}
      sub={t('Outgoing KGS wires (burn settlements) are sent to one of these accounts. The account holder must match your verified business name.', 'Исходящие платежи KGS (погашения) направляются на один из этих счетов. Имя владельца должно совпадать с верифицированным названием вашей организации.')}
      actions={<Button icon={<Icons.plus size={13} />}>{t('Add account', 'Добавить счет')}</Button>}
    />
    <ProtoSettingsLayout current="banks">
      <Card padding={0} style={{ overflow: 'hidden' }}>
        {[
          { bank: 'Optima Bank OJSC', swift: 'ENEJKG22', acct: '1170 0702 4000 5611', holder: 'Binance Asia Services Pte. Ltd.', country: 'Kyrgyzstan', isDefault: true, added: '14 Jan 2026' },
          { bank: 'DemirBank',         swift: 'DEMIKG22', acct: '1090 4001 0023 8842', holder: 'Binance Asia Services Pte. Ltd.', country: 'Kyrgyzstan', isDefault: false, added: '02 Feb 2026' },
        ].map((b, i, arr) => (
          <div key={i} style={{
            padding: '20px 24px',
            borderBottom: i < arr.length - 1 ? '1px solid var(--border-subtle)' : 'none',
            display: 'flex', alignItems: 'center', gap: 18,
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 8,
              background: 'linear-gradient(135deg, var(--wine-500), var(--ink-4))',
              border: '1px solid var(--border-gold)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold-200)',
            }}><Icons.bank size={18} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 14, fontWeight: 600 }}>{b.bank}</span>
                {b.isDefault ? <Pill tone="gold" dot>{t('Default', 'По умолчанию')}</Pill> : null}
              </div>
              <div style={{ marginTop: 4, fontSize: 12, color: 'var(--fg-secondary)' }}>
                <span className="kgst-mono">SWIFT {b.swift}</span> · <span className="kgst-mono">A/C {b.acct}</span>
              </div>
              <div style={{ marginTop: 2, fontSize: 11.5, color: 'var(--fg-tertiary)' }}>
                {b.holder} · {b.country} · added {b.added}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              {!b.isDefault ? <Button size="sm" variant="ghost">{t('Set as default', 'По умолчанию')}</Button> : null}
              <Button size="sm" variant="ghost">{t('Edit', 'Изменить')}</Button>
              <Button size="sm" variant="danger">{t('Remove', 'Удалить')}</Button>
            </div>
          </div>
        ))}
      </Card>

      <Card padding={16} style={{ marginTop: 14, background: 'rgba(93,139,217,0.06)', border: '1px solid rgba(93,139,217,0.20)' }}>
        <div style={{ display: 'flex', gap: 10, fontSize: 12, color: 'var(--bone-5)' }}>
          <Icons.shield size={14} style={{ color: 'var(--blue-400)', marginTop: 1, flexShrink: 0 }} />
          <span>{t('Adding or modifying a bank account requires 2FA confirmation and an emailed click-through.', 'Добавление или изменение банковского счета требует подтверждения 2FA и подтверждения по е-mail.')}</span>
        </div>
      </Card>
    </ProtoSettingsLayout>
  </>
  );
};

// =================================================================
// Wallets
// =================================================================
const WalletsScreen = () => {
  const { data, set } = usePrototype();
  const t = useT();
  const customAddrs = data.customAddresses || [];
  const [bindOpen, setBindOpen] = React.useState(false);
  const [defaultChain, setDefaultChain] = React.useState('tron');
  const openBind = (chain) => { setDefaultChain(chain); setBindOpen(true); };
  const onBound = (newAddr) => {
    set({ customAddresses: [...customAddrs, newAddr] });
    setBindOpen(false);
  };

  const baseGroups = [
    { chain: 'eth',  addrs: [
      { name: 'Treasury · Cold storage', addr: '0x9b21A8e7d1f5C4b8Ad3F8c2E9B7d3A1F6c2E4d8B', added: '12 Oct 2025', balance: '5,224,310.41' },
      { name: 'Operations · Hot wallet', addr: '0x4Ad7b2F9c1B8E6d2A5F3c8B1d9E2A6F4c7B3d1E5', added: '03 Dec 2025', balance: '0.00' },
    ]},
    { chain: 'tron', addrs: [
      { name: 'Treasury · Tron', addr: 'TKgQ9b2A4Fz81G7tHpY5sLwM2eC8DfN6Vx', added: '21 Nov 2025', balance: '3,500,000.00' },
    ]},
    { chain: 'bnb',  addrs: [] },
  ];
  // Merge in custom-bound addresses by chain
  const groups = baseGroups.map(g => {
    const custom = customAddrs.filter(a => a.chain === g.chain).map(a => ({
      name: a.label, addr: a.addr, added: a.added, balance: '0.00', isNew: true,
    }));
    return { ...g, addrs: [...g.addrs, ...custom], count: g.addrs.length + custom.length };
  });

  return (
  <>
    <PageHeader
      title={t('Wallet addresses', 'Адреса кошельков')}
      sub={t('Addresses bound to your institution. Mint deliveries can only go to these addresses, and burns can only originate from them.', 'Адреса, привязанные к вашей организации. Доставка эмиссии возможна только на эти адреса; погашение может исходить только с них.')}
      actions={<Button icon={<Icons.plus size={13} />} onClick={() => openBind('tron')}>{t('Bind new address', 'Привязать адрес')}</Button>}
    />
    <ProtoSettingsLayout current="wallets">
      {groups.map((g, i) => (
        <Card key={i} padding={0} style={{ marginBottom: 14, overflow: 'hidden' }}>
          <div style={{ padding: '14px 22px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--border-subtle)' }}>
            <ChainBadge chain={g.chain} />
            <span style={{ fontSize: 13.5, fontWeight: 600 }}>{CHAIN_MAP[g.chain].name}</span>
            <span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{t(`${g.count} address${g.count === 1 ? '' : 'es'}`, `${g.count} \u0430\u0434\u0440\u0435\u0441${g.count === 1 ? '' : '\u0430'}`)}</span>
            <span style={{ flex: 1 }} />
            <Button size="sm" variant="ghost" icon={<Icons.plus size={12} />} onClick={() => openBind(g.chain)}>{t('Add', 'Добавить')}</Button>
          </div>
          {g.addrs.length === 0 ? (
            <div style={{ padding: '24px 22px', textAlign: 'center', fontSize: 12.5, color: 'var(--fg-tertiary)' }}>
              {t('No addresses bound on this chain yet.', 'На этой сети пока нет привязанных адресов.')}
            </div>
          ) : g.addrs.map((a, j) => (
            <div key={j} style={{
              padding: '14px 22px', display: 'flex', alignItems: 'center', gap: 18,
              borderBottom: j < g.addrs.length - 1 ? '1px solid var(--border-subtle)' : 'none',
            }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  {a.name}
                  {a.isNew ? <Pill tone="gold" dot={false} style={{ fontSize: 9.5, padding: '1px 6px' }}>{t('New', 'Новый')}</Pill> : null}
                </div>
                <div className="kgst-mono" style={{ marginTop: 2, fontSize: 11.5, color: 'var(--fg-tertiary)' }}>{a.addr}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="kgst-mono kgst-num" style={{ fontSize: 13, color: 'var(--bone-5)' }}>{a.balance} <span style={{ fontSize: 10, color: 'var(--fg-tertiary)' }}>KGST</span></div>
                <div style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{t('Bound', 'Привязан')} {a.added}</div>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <Button size="sm" variant="ghost">{t('Rename', 'Переименовать')}</Button>
                <Button size="sm" variant="danger">{t('Remove', 'Удалить')}</Button>
              </div>
            </div>
          ))}
        </Card>
      ))}
    </ProtoSettingsLayout>
    <BindAddressModal
      open={bindOpen}
      defaultChain={defaultChain}
      onClose={() => setBindOpen(false)}
      onBound={onBound}
    />
  </>
  );
};

// =================================================================
// API keys
// =================================================================
const ApiKeysScreen = () => {
  const t = useT();
  return (
  <>
    <PageHeader
      title={t('API keys', 'API-ключи')}
      sub={t('Programmatic access for treasury automation. Keys are scoped per environment and never displayed twice — generate, copy, store.', 'Программный доступ для автоматизации казначейства. Ключи разделены по окружениям и видны только один раз — создайте, скопируйте и сохраните.')}
      actions={<Button icon={<Icons.plus size={13} />}>{t('Create key', 'Создать ключ')}</Button>}
    />
    <ProtoSettingsLayout current="apikeys">
      <Card padding={0} style={{ overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
          <thead>
            <tr style={{ background: 'var(--ink-2)', color: 'var(--fg-tertiary)', textAlign: 'left' }}>
              {[t('Name','Имя'), t('Key','Ключ'), t('Scopes','Права'), t('Created','Создан'), t('Last used','Посл. исп.'), t('Status','Статус'), ''].map((h, i) => (
                <th key={i} style={{ padding: '12px 18px', fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 500, borderBottom: '1px solid var(--border-subtle)' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {[
              { name: 'binance-prod',      key: 'kgst_live_a4F…7Q2', scopes: 'mint, burn, read', created: '14 Jan 2026', used: '2 min ago',   status: 'active' },
              { name: 'binance-staging',   key: 'kgst_test_xZ1…r9C', scopes: 'mint, burn, read', created: '14 Jan 2026', used: '3 days ago',  status: 'active' },
              { name: 'treasury-readonly', key: 'kgst_live_p9Y…m1V', scopes: 'read',             created: '02 Feb 2026', used: '17 days ago', status: 'active' },
              { name: 'legacy-ops',        key: 'kgst_live_q8C…b3J', scopes: 'mint, burn, read', created: '03 Sep 2025', used: '120 days ago',status: 'revoked' },
            ].map((k, i, arr) => (
              <tr key={i} style={{ borderBottom: i < arr.length - 1 ? '1px solid var(--border-subtle)' : 'none' }}>
                <td style={{ padding: '14px 18px', fontWeight: 500 }}>{k.name}</td>
                <td style={{ padding: '14px 18px', fontFamily: 'var(--font-mono)', color: 'var(--gold-300)' }}>{k.key}</td>
                <td style={{ padding: '14px 18px' }}>
                  <div style={{ display: 'flex', gap: 4 }}>
                    {k.scopes.split(', ').map(s => <Pill key={s} tone="neutral" dot={false} style={{ fontSize: 10 }}>{s}</Pill>)}
                  </div>
                </td>
                <td style={{ padding: '14px 18px', color: 'var(--fg-tertiary)' }}>{k.created}</td>
                <td style={{ padding: '14px 18px', color: 'var(--fg-tertiary)' }}>{k.used}</td>
                <td style={{ padding: '14px 18px' }}>
                  <Pill tone={k.status === 'active' ? 'success' : 'danger'}>{k.status === 'active' ? t('Active', 'Активен') : t('Revoked', 'Отозван')}</Pill>
                </td>
                <td style={{ padding: '14px 18px', textAlign: 'right' }}>
                  {k.status === 'active' ? <Button size="sm" variant="danger">{t('Revoke', 'Отозвать')}</Button> : <Button size="sm" variant="ghost" disabled>{t('Removed', 'Удалён')}</Button>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <Card padding={18} style={{ marginTop: 14, background: 'rgba(225,165,58,0.06)', border: '1px solid rgba(225,165,58,0.20)' }}>
        <div style={{ display: 'flex', gap: 10, fontSize: 12, color: 'var(--bone-5)' }}>
          <Icons.shield size={14} style={{ color: 'var(--amber-400)', marginTop: 1, flexShrink: 0 }} />
          <span>{t('Keys with mint/burn scope can move funds. Treat them with the same care as wire-instruction passwords; rotate every 90 days.', 'Ключи с правами mint/burn могут перемещать средства. Относитесь к ним как к паролям банк-клиента; период ротации — 90 дней.')}</span>
        </div>
      </Card>
    </ProtoSettingsLayout>
  </>
  );
};

// =================================================================
// Security
// =================================================================
const SecurityScreen = () => {
  const t = useT();
  const [notifs, setNotifs] = React.useState({
    signIn: true, mintBurn: true, attest: true, weekly: false,
  });
  const toggleN = (k) => setNotifs(s => ({ ...s, [k]: !s[k] }));
  return (
    <>
      <PageHeader
        title={t('Security', 'Безопасность')}
        sub={t('Two-factor authentication, password, devices, and notifications.', 'Двухфакторная аутентификация, пароль, устройства и уведомления.')}
      />
      <ProtoSettingsLayout current="security">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={22}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
              <div style={{
                width: 40, height: 40, borderRadius: 8, background: 'rgba(201,152,64,0.08)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--gold-300)', flexShrink: 0,
                border: '1px solid var(--border-gold)',
              }}><Icons.shield size={18} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 14, fontWeight: 600 }}>{t('Two-factor authentication', 'Двухфакторная аутентификация')}</span>
                  <Pill tone="gold" dot>{t('TOTP active', 'TOTP активен')}</Pill>
                </div>
                <div style={{ marginTop: 4, fontSize: 12, color: 'var(--fg-secondary)' }}>
                  {t('Authenticator app is your primary 2FA. Email is kept as a fallback.', 'Приложение-аутентификатор — основной способ 2FA. Резервный — код по е-mail.')}
                </div>
                <div style={{
                  marginTop: 14, padding: 12, borderRadius: 8,
                  background: 'var(--ink-2)', border: '1px solid var(--border-subtle)',
                  display: 'flex', alignItems: 'center', gap: 14,
                }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--gold-300)' }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{t('Authenticator (TOTP) · primary', 'Аутентификатор (TOTP) · основной')}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{t('Bound 14 Jan 2026 · Last used 2 min ago', 'Привязан 14.01.2026 · посл. исп. 2 мин. назад')}</div>
                  </div>
                  <Button size="sm" variant="ghost">{t('Reset', 'Сброс')}</Button>
                </div>
                <div style={{
                  marginTop: 8, padding: 12, borderRadius: 8,
                  background: 'var(--ink-2)', border: '1px solid var(--border-subtle)',
                  display: 'flex', alignItems: 'center', gap: 14,
                }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--bone-3)' }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{t('Email codes · fallback', 'Коды по e-mail · резерв')}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>treasury@binance.com · {t('used if TOTP unavailable', 'используется, если TOTP недоступен')}</div>
                  </div>
                </div>
              </div>
            </div>
          </Card>

          <Card padding={22}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{t('Password', 'Пароль')}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-tertiary)', marginTop: 4 }}>{t('Last changed 03 Dec 2025 · 42 days ago', 'Изменён 03.12.2025 · 42 дн. назад')}</div>
              </div>
              <Button size="sm" variant="secondary">{t('Change password', 'Сменить пароль')}</Button>
            </div>
          </Card>

          <Card padding={0} style={{ overflow: 'hidden' }}>
            <div style={{ padding: '16px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid var(--border-subtle)' }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{t('Active sessions', 'Активные сессии')}</div>
                <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)', marginTop: 3 }}>{t('3 devices currently signed in.', 'Сейчас в системе 3 устройства.')}</div>
              </div>
              <Button size="sm" variant="danger">{t('Sign out all', 'Выйти со всех')}</Button>
            </div>
            {[
              { dev: 'MacBook Pro · Chrome 132', loc: 'Singapore, SG · 13 Jan 14:24 UTC', current: true },
              { dev: 'iPhone 15 Pro · KGST iOS', loc: 'Singapore, SG · 13 Jan 11:48 UTC', current: false },
              { dev: 'Windows 11 · Edge 121',    loc: 'Hong Kong, HK · 11 Jan 09:02 UTC', current: false },
            ].map((d, i, arr) => (
              <div key={i} style={{
                padding: '14px 22px', display: 'flex', alignItems: 'center', gap: 16,
                borderBottom: i < arr.length - 1 ? '1px solid var(--border-subtle)' : 'none',
              }}>
                <Icons.user size={16} style={{ color: 'var(--bone-3)' }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                    {d.dev}
                    {d.current ? <Pill tone="success" style={{ fontSize: 10 }}>{t('This device', 'Это устройство')}</Pill> : null}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)', marginTop: 2 }}>{d.loc}</div>
                </div>
                {!d.current ? <Button size="sm" variant="ghost">{t('Sign out', 'Выход')}</Button> : null}
              </div>
            ))}
          </Card>

          <Card padding={22}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>{t('Notifications', 'Уведомления')}</div>
            {[
              ['signIn',   t('New sign-in', 'Новый вход'),                 t('Email me when a new device signs into this account.', 'Писать на e-mail, когда в аккаунт заходит новое устройство.')],
              ['mintBurn', t('Mint / burn completion', 'Завершение эмиссии / погашения'), t('Email a signed receipt on every settlement.', 'Присылать подписанную квитанцию на каждый расчёт.')],
              ['attest',   t('Reserve attestations', 'Аттестации резервов'),     t('Notify when the monthly attestation is published.', 'Сообщать, когда публикуется ежемесячная аттестация.')],
              ['weekly',   t('Weekly summary', 'Еженедельная сводка'),         t('A digest of last week\'s activity.', 'Дайджест активности за неделю.')],
            ].map(([k, T, body]) => (
              <div key={k} style={{
                padding: '14px 0', display: 'flex', alignItems: 'center', gap: 16,
                borderTop: '1px solid var(--border-subtle)',
              }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{T}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)', marginTop: 2 }}>{body}</div>
                </div>
                <ProtoToggle on={notifs[k]} onClick={() => toggleN(k)} />
              </div>
            ))}
          </Card>
        </div>
      </ProtoSettingsLayout>
    </>
  );
};

const ProtoToggle = ({ on, onClick }) => (
  <span onClick={onClick} style={{
    width: 38, height: 22, borderRadius: 999,
    background: on ? 'var(--gold-400)' : 'var(--ink-4)',
    position: 'relative', cursor: 'pointer',
    border: '1px solid ' + (on ? 'var(--gold-500)' : 'var(--border-default)'),
    transition: 'all 150ms var(--ease-standard)',
    display: 'inline-block', flexShrink: 0,
  }}>
    <span style={{
      position: 'absolute', top: 2, left: on ? 18 : 2,
      width: 16, height: 16, borderRadius: '50%', background: '#fff',
      transition: 'left 150ms var(--ease-standard)',
      boxShadow: '0 1px 2px rgba(0,0,0,0.4)',
    }} />
  </span>
);

window.DashboardFlow = DashboardFlow;
