/* eslint-disable */
// BurnFlow.jsx — Module 3 clickable flow.
// Screens: initiate → twofa (modal) → redeem (address info) → status → complete

// const BURN_BREADCRUMBS = (moved inside BurnFlow)

const BURN_BANKS = [
  { id: 'optima', bank: 'Optima Bank OJSC', swift: 'ENEJKG22', acct: '1170 0702 4000 5611', isDefault: true },
  { id: 'demir',  bank: 'DemirBank',         swift: 'DEMIKG22', acct: '1090 4001 0023 8842', isDefault: false },
];
const BURN_CHAINS = [
  { id: 'eth',  name: 'Ethereum',  std: 'ERC-20', bal: '5,224,310 KGST' },
  { id: 'tron', name: 'Tron',      std: 'TRC-20', bal: '3,500,000 KGST' },
  { id: 'bnb',  name: 'BNB Chain', std: 'BEP-20', bal: '—' },
];

const BurnFlow = ({ screen }) => {
  const t = useT();
  const BURN_BREADCRUMBS = {
    initiate: [t('Burn', 'Погашение'), t('New request', 'Новый запрос')],
    twofa:    [t('Burn', 'Погашение'), t('New request', 'Новый запрос')],
    redeem:   [t('Burn', 'Погашение'), t('Request KGST-BURN-2026000418', 'Запрос KGST-BURN-2026000418')],
    status:   [t('Burn', 'Погашение'), 'KGST-BURN-2026000418'],
    complete: [t('Burn', 'Погашение'), 'KGST-BURN-2026000418'],
  };
  return (
  <ProtoConsoleShell current="burn" breadcrumbs={BURN_BREADCRUMBS[screen] || [t('Burn', 'Погашение')]}>
    {screen === 'initiate' && <BurnInitiateScreen />}
    {screen === 'twofa'    && <BurnInitiateScreen modal="twofa" />}
    {screen === 'redeem'   && <BurnRedeemScreen />}
    {screen === 'status'   && <BurnStatusScreen />}
    {screen === 'complete' && <BurnCompleteScreen />}
  </ProtoConsoleShell>
  );
};

// =================================================================
// Burn initiate
// =================================================================
const BurnInitiateScreen = ({ modal }) => {
  const { data, set } = usePrototype();
  const t = useT();
  const amount = data.burnAmount || '';
  const chain = data.burnChain || 'tron';
  const bankId = data.burnBankId || 'optima';

  const parsed = parseAmount(amount);
  const chainObj = BURN_CHAINS.find(c => c.id === chain);
  const bankObj = BURN_BANKS.find(b => b.id === bankId);
  const available = 8724310.41;
  const overBalance = parsed > available;
  const canContinue = parsed > 0 && !overBalance && chainObj.bal !== '—';

  return (
    <>
      <PageHeader
        title={t('Redeem KGST for Kyrgyz som', 'Погасить KGST в кыргызские сомы')}
        sub={t("Send KGST from a bound wallet to the redemption address. Once we confirm receipt, we'll wire KGS via RTGS to your chosen settlement account.", 'Отправьте KGST с привязанного кошелька на адрес погашения. После подтверждения мы отправим KGS через RTGS на выбранный счёт.')}
        actions={<Button variant="ghost" onClick={() => navigateTo('dashboard', 'transactions')}>{t('View past redemptions', 'Прошлые погашения')}</Button>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'flex-start' }}>
        <Card padding={28} style={{ background: 'var(--ink-2)' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            {/* Amount */}
            <div>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Amount to redeem', 'Сумма к погашению')}</span>
              <AmountInput
                value={amount}
                onChange={v => set({ burnAmount: v })}
                unit="KGST"
                placeholder="0.00"
                autoFocus
              />
              <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: 'var(--fg-tertiary)' }}>
                <span>
                  {t('You receive', 'Вы получите')}{' '}
                  <span style={{ color: 'var(--gold-300)', fontFamily: 'var(--font-mono)' }}>
                    {amount ? formatAmount(amount) : '0.00'} KGS
                  </span>{' '}· {t('pegged 1:1', 'привязка 1:1')}
                </span>
                <span style={{ color: overBalance ? 'var(--red-400)' : 'var(--fg-tertiary)' }}>
                  {t('Available', 'Доступно')}:{' '}
                  <span style={{ color: 'var(--bone-5)', fontFamily: 'var(--font-mono)' }}>
                    8,724,310.41 KGST
                  </span>
                </span>
              </div>
            </div>

            {/* Source chain */}
            <div>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Send from', 'Отправить из')}</span>
              <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                {BURN_CHAINS.map(c => {
                  const sel = chain === c.id;
                  const disabled = c.bal === '—';
                  return (
                    <div key={c.id}
                      onClick={() => !disabled && set({ burnChain: c.id })}
                      style={{
                        padding: 14, borderRadius: 10,
                        background: sel ? 'rgba(201,152,64,0.06)' : 'var(--bg-inset)',
                        border: `1px solid ${sel ? 'var(--border-gold)' : 'var(--border-default)'}`,
                        display: 'flex', flexDirection: 'column', gap: 6,
                        cursor: disabled ? 'not-allowed' : 'pointer',
                        opacity: disabled ? 0.45 : 1,
                        transition: 'border-color 120ms ease, background 120ms ease',
                      }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <ChainBadge chain={c.id} />
                        <span style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</span>
                        {sel ? <span style={{ marginLeft: 'auto', color: 'var(--gold-300)', display: 'inline-flex' }}>
                          <Icons.check size={14} /></span> : null}
                      </div>
                      <div style={{ fontSize: 10.5, color: 'var(--fg-tertiary)', fontFamily: 'var(--font-mono)' }}>{c.bal}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Settlement account */}
            <div>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Settlement bank account', 'Банковский счёт для расчёта')}</span>
              <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {BURN_BANKS.map(b => (
                  <Selector
                    key={b.id}
                    selected={bankId === b.id}
                    onClick={() => set({ burnBankId: b.id })}
                    leading={
                      <div style={{
                        width: 30, height: 30, borderRadius: 6,
                        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={14} /></div>
                    }
                    value={b.bank}
                    hint={<span className="kgst-mono">SWIFT {b.swift} · A/C {b.acct}</span>}
                    trailing={b.isDefault
                      ? <Pill tone="gold" dot={false} style={{ fontSize: 10 }}>{t('Default', 'По умолчанию')}</Pill>
                      : null}
                  />
                ))}
                <button onClick={() => navigateTo('dashboard', 'banks')} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  padding: 12, borderRadius: 8,
                  background: 'transparent', border: '1px dashed var(--border-default)',
                  color: 'var(--gold-300)', fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit',
                }}>
                  <Icons.plus size={13} /> {t('Add a new bank account', 'Добавить счёт')}
                </button>
              </div>
            </div>
          </div>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={20} style={{ background: 'var(--ink-2)' }}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 12 }}>{t('Summary', 'Сводка')}</div>
            <Field label={t('You burn', 'Вы сжигаете')}     value={`${amount ? formatAmount(amount) : '0.00'} KGST`} mono />
            <Field label={t('You receive', 'Вы получаете')}  value={<span style={{ color: 'var(--gold-300)' }}>{amount ? formatAmount(amount) : '0.00'} KGS</span>} mono />
            <Field label={t('From chain', 'Из сети')}   value={`${chainObj.name} (${chainObj.std})`} />
            <Field label={t('Settlement', 'Расчёт')}   value={`${bankObj.bank} · ${bankObj.swift}`} mono />
            <Field label={t('Fee', 'Комиссия')}          value="0.00 KGS" mono />
            <Field label={t('Wire arrives', 'Поступление SWIFT')} value={t('Same business day via RTGS', 'В течение рабочего дня через RTGS')} />
          </Card>

          <Button size="lg" iconRight={<Icons.arrowRight size={14} />}
            disabled={!canContinue}
            onClick={() => navigateTo('burn', 'twofa')}>
            {t('Continue · 2FA required', 'Продолжить · требуется 2FA')}
          </Button>

          <div style={{
            padding: 12, borderRadius: 8, background: 'rgba(82,0,4,0.18)',
            border: '1px solid rgba(184,80,68,0.20)', fontSize: 11.5, color: 'var(--bone-5)',
            display: 'flex', gap: 10,
          }}>
            <Icons.shield size={13} style={{ color: 'var(--wine-200)', marginTop: 1, flexShrink: 0 }} />
            <span>{t('KGST must be sent from one of your bound addresses. Transfers from unbound addresses trigger manual review and delay your wire.', 'KGST нужно отправлять с одного из привязанных адресов. Переводы с непривязанных адресов требуют ручной проверки и задерживают SWIFT.')}</span>
          </div>
        </div>
      </div>

      {modal === 'twofa' && (
        <BurnTwoFAModal
          amount={amount}
          chainName={chainObj.name}
          bankName={bankObj.bank}
        />
      )}
    </>
  );
};

// =================================================================
// 2FA modal
// =================================================================
const BurnTwoFAModal = ({ amount, chainName, bankName }) => {
  const t = useT();
  const [code, setCode] = React.useState('');
  const timer = useCountdown(30);
  const onConfirm = () => { if (code.length === 6) navigateTo('burn', 'redeem'); };
  return (
    <ModalScrim width={440}>
      <ModalHeader
        title={t('Confirm with 2FA', 'Подтвердить через 2FA')}
        sub={t('Enter the 6-digit code from your authenticator app to sign this redemption.', 'Введите 6-значный код из приложения-аутентификатора, чтобы подписать запрос погашения.')}
      />
      <div style={{ padding: '24px 24px 20px', display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{
          padding: 14, borderRadius: 8,
          background: 'var(--ink-2)', border: '1px solid var(--border-default)',
        }}>
          <div className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('You are about to burn', 'Вы собираетесь сжечь')}</div>
          <div style={{ marginTop: 6 }}>
            <Amount value={amount || '0.00'} size={22} />
          </div>
          <div style={{ marginTop: 6, fontSize: 11.5, color: 'var(--fg-tertiary)' }}>
            {t('from', 'из сети')} {chainName} · {t('settling to', 'расчёт на')} {bankName}
          </div>
        </div>

        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Authenticator code', 'Код аутентификатора')}</span>
            <span style={{ fontSize: 11, color: 'var(--fg-tertiary)', fontFamily: 'var(--font-mono)' }}>
              {t('Refreshes in', 'Обновление через')} {timer.sec > 0 ? timer.sec : 30}s
            </span>
          </div>
          <OTPField value={code} onChange={setCode} autoFocus onComplete={onConfirm} />
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <a style={{ fontSize: 12, color: 'var(--gold-300)', cursor: 'pointer' }}>{t('Use email code instead', 'Использовать код по e-mail')}</a>
          <a style={{ fontSize: 12, color: 'var(--fg-tertiary)', cursor: 'pointer' }}>{t('Lost your device?', 'Потеряли устройство?')}</a>
        </div>
      </div>
      <div style={{
        padding: '16px 24px', borderTop: '1px solid var(--border-subtle)',
        background: 'var(--ink-2)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <Button variant="ghost"
          icon={<Icons.chevronRight size={13} style={{ transform: 'rotate(180deg)' }} />}
          onClick={() => navigateTo('burn', 'initiate')}>
          {t('Back', 'Назад')}
        </Button>
        <Button onClick={onConfirm} disabled={code.length < 6}>{t('Confirm and sign', 'Подтвердить и подписать')}</Button>
      </div>
    </ModalScrim>
  );
};

// =================================================================
// Redemption address (S3.2)
// =================================================================
const BurnRedeemScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const amount = data.burnAmount || '2,500,000.00';
  const fullAddr = '0xRedEemKGST5Eth00000000000a18c9F4b231D7e5';
  const [copied, setCopied] = React.useState(false);
  const copyAddr = () => {
    try { navigator.clipboard && navigator.clipboard.writeText(fullAddr); } catch (e) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <>
      <PageHeader
        title={t(`Send ${formatAmount(amount)} KGST to the redemption address`, `Отправьте ${formatAmount(amount)} KGST на адрес погашения`)}
        sub={t("Transfer KGST from a bound wallet to the on-chain redemption address. We'll detect the inbound transfer and broadcast the burn on your behalf.", 'Переведите KGST с привязанного кошелька на адрес погашения. Мы сами обнаружим входящий перевод и отправим burn-транзакцию.')}
        actions={
          <>
            <Button variant="ghost" onClick={() => navigateTo('burn', 'initiate')}>{t('Cancel request', 'Отменить запрос')}</Button>
            <Button variant="secondary">{t('Download as PDF', 'Скачать PDF')}</Button>
          </>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
        <Card padding={0} style={{ overflow: 'hidden' }}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('KGST redemption address', 'Адрес погашения KGST')}</span>
              <div style={{ marginTop: 4, fontSize: 15, fontWeight: 600 }}>{t('On-chain burn pool — KGSToken JSC', 'On-chain burn-пул — KGSToken АО')}</div>
            </div>
            <Pill tone="wine" dot>{t('Operator-controlled', 'Под управлением оператора')}</Pill>
          </div>
          <div style={{ padding: 24 }}>
            <Field label={t('Network', 'Сеть')} value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><ChainBadge chain="eth" /> Ethereum (ERC-20)</span>} />
            <Field label={t('Token', 'Токен')} value="KGST · KGS Token" />
            <Field label={t('Redemption address', 'Адрес погашения')} value="0xRedE…D7e5" mono copyable />
            <Field label={t('Authorised source addresses', 'Разрешённые адреса-отправители')} value={t('2 bound · cold + ops', '2 привязаны · cold + ops')} sub={t('Transfers from unbound addresses are paused for review.', 'Переводы с непривязанных адресов временно приостановлены.')} />
            <Field label={t('Memo / tag', 'Примечание / tag')} value={<span style={{ color: 'var(--fg-tertiary)' }}>{t('Not required', 'Не требуется')}</span>} />
            <Field label={t('Token contract', 'Контракт токена')} value="0xA0b8…48eB" mono copyable />
            <Field label={t('Amount to send', 'Сумма к отправке')} value={<span style={{ color: 'var(--gold-300)' }}>{formatAmount(amount)} KGST</span>} mono />
          </div>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={20} style={{
            background: 'linear-gradient(180deg, var(--ink-3), var(--ink-2))',
            border: '1px solid var(--border-gold)',
            boxShadow: 'var(--shadow-gold-glow)',
          }}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 10 }}>{t('Redemption address · scan or copy', 'Адрес погашения · скан или копия')}</div>
            <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
              <div style={{ padding: 8, borderRadius: 8, background: 'var(--bg-inset)', border: '1px solid var(--border-default)', flexShrink: 0 }}>
                <QRPlaceholder size={112} data="kgst-burn-eth-2026000418" />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="kgst-mono" style={{
                  fontSize: 13, fontWeight: 600, letterSpacing: '0.01em',
                  color: 'var(--gold-300)', wordBreak: 'break-all', lineHeight: 1.5,
                }}>
                  0xRedEemKGST5Eth0000<br />0000000a18c9F4b231D7e5
                </div>
                <div style={{ marginTop: 10, display: 'flex', gap: 6 }}>
                  <Button size="sm" variant="secondary"
                    icon={copied ? <Icons.check size={11} /> : <Icons.spark size={11} />}
                    onClick={copyAddr}>
                    {copied ? t('Copied', 'Скопировано') : t('Copy', 'Копия')}
                  </Button>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 14, fontSize: 11.5, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
              {t('Send', 'Отправьте')} <span style={{ color: 'var(--fg-primary)' }}>{t('exactly', 'ровно')} {formatAmount(amount)} KGST</span> {t('from a bound address. Other amounts pause for human review.', 'с привязанного адреса. Другие суммы будут приостановлены для ручной проверки.')}
            </div>
          </Card>

          <Card padding={18}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 10 }}>{t('Authorised source addresses', 'Разрешённые адреса-отправители')}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[
                [t('Treasury · Cold', 'Казначейство · Cold'), '0x9b21A8e7d1f5C4b8…2E4d8B'],
                [t('Ops · Hot',       'Операции · Hot'),     '0x4Ad7b2F9c1B8E6d2…7B3d1E5'],
              ].map(([n, a], i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '7px 10px',
                  background: 'var(--bg-inset)', borderRadius: 6,
                  border: '1px solid var(--border-subtle)',
                }}>
                  <Icons.check size={11} style={{ color: 'var(--gold-300)' }} />
                  <span className="kgst-mono" style={{ flex: 1, fontSize: 11, color: 'var(--bone-5)' }}>{a}</span>
                  <span style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{n}</span>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>

      <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: 16, borderRadius: 10, background: 'var(--ink-2)', border: '1px solid var(--border-default)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{
            width: 8, height: 8, borderRadius: '50%', background: 'var(--amber-400)',
            boxShadow: '0 0 0 4px rgba(225,165,58,0.12)',
            animation: 'kgstPulse 1.6s ease-in-out infinite',
          }} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{t('Waiting for KGST', 'Ожидаю перевод KGST')}</div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)' }}>{t("We'll auto-advance this request when the redemption address receives the transfer.", 'Как только адрес погашения получит перевод, мы продвинем запрос.')}</div>
          </div>
        </div>
        <Button iconRight={<Icons.arrowRight size={13} />} onClick={() => navigateTo('burn', 'status')}>
          {t('Track this request', 'Отслеживать запрос')}
        </Button>
      </div>
    </>
  );
};

// =================================================================
// Status tracking
// =================================================================
const BurnStatusScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const amount = data.burnAmount || '2,500,000.00';
  const steps = [
    { label: t('Request submitted', 'Запрос подан'), sub: t('You', 'Вы') },
    { label: t('KGST received', 'KGST получены'),     sub: 'Ethereum' },
    { label: t('On-chain burn', 'Погашение в блокчейне'),     sub: 'Ethereum' },
    { label: t('RTGS wire sent', 'SWIFT/RTGS отправлен'),    sub: 'KGS' },
    { label: t('Settled', 'Исполнено'),           sub: t('Bank', 'Банк') },
  ];

  const [stage, setStage] = React.useState(1);
  React.useEffect(() => {
    if (stage >= steps.length) {
      const t = setTimeout(() => navigateTo('burn', 'complete'), 1500);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStage(s => s + 1), 2000);
    return () => clearTimeout(t);
  }, [stage]);  // eslint-disable-line

  const baseLog = [
    { t: '09:02:11', s: t(`Redemption request created · ${formatAmount(amount)} KGST`, `Запрос погашения создан · ${formatAmount(amount)} KGST`), tone: 'gold' },
    { t: '09:14:48', s: t('KGST received from 0x9b21…d8B · 12 / 12 confirmed', 'KGST получены от 0x9b21…d8B · 12 / 12 подтверждено'), tone: 'gold' },
    { t: '09:15:02', s: t('On-chain burn broadcast · 0xd4f9…91a8', 'Погашение в блокчейне · 0xd4f9…91a8'), tone: 'gold' },
    { t: '09:15:46', s: t('Burn confirmed · KGS reserve unlocked', 'Погашение подтверждено · резерв KGS разблокирован'), tone: 'gold' },
    { t: t('pending', 'ожидает'), s: t('Preparing RTGS wire to Optima Bank ENEJKG22', 'Готовим SWIFT/RTGS в Optima Bank ENEJKG22'), tone: 'amber' },
  ];
  const log = baseLog.slice(0, Math.max(1, stage + 1));

  return (
    <>
      <PageHeader
        title={t(`Burn in progress · ${formatAmount(amount)} KGST`, `Погашение в процессе · ${formatAmount(amount)} KGST`)}
        sub={t("KGST has been received and the on-chain burn transaction is confirmed. We're preparing the KGS wire.", 'KGST получены, burn-транзакция подтверждена. Готовим отправку SWIFT.')}
        actions={<Button variant="ghost" iconRight={<Icons.arrowUp size={13} />}>{t('Open block explorer', 'Открыть блок-эксплорер')}</Button>}
      />

      <Card padding={28}>
        <Stepper steps={steps} current={stage} />
      </Card>

      <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
        <Card padding={24}>
          <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 14 }}>{t('Request details', 'Детали запроса')}</div>
          <Field label={t('Request ID', 'ID запроса')} value="KGST-BURN-2026000418" mono copyable />
          <Field label={t('Amount burned', 'Погашено')} value={<span style={{ color: 'var(--gold-300)' }}>{formatAmount(amount)} KGST</span>} mono />
          <Field label={t('Source address', 'Адрес-отправитель')} value="0x9b21A8e7…2E4d8B" mono copyable />
          <Field label={t('Inbound tx', 'Входящая tx')} value={t('0xa12b…48cf · confirmed (12 / 12)', '0xa12b…48cf · подтверждена (12 / 12)')} mono />
          <Field label={t('Burn tx', 'Burn tx')} value={<span style={{ color: 'var(--gold-300)' }}>{t('0xd4f9…91a8 · confirmed', '0xd4f9…91a8 · подтверждена')}</span>} mono copyable />
          <Field label={t('RTGS wire', 'SWIFT/RTGS')} value={t('MT103 dispatched · NBKR booking pending', 'MT103 отправлен · книга NBKR ожидает')} sub={t('Booking expected within 2 hours', 'Проводка ожидается в течение 2 часов')} />
        </Card>

        <Card padding={24}>
          <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 14 }}>{t('Activity', 'Активность')}</div>
          <MintTimeline items={log} />
        </Card>
      </div>
    </>
  );
};

// =================================================================
// Complete
// =================================================================
const BurnCompleteScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const amount = data.burnAmount || '2,500,000.00';
  return (
    <>
      <PageHeader
        title={t('Redemption complete', 'Погашение выполнено')}
        sub={t('KGS has been settled to your Optima Bank account. The on-chain burn and bank confirmation are recorded below.', 'KGS зачислены на ваш счёт в Optima Bank. burn-транзакция и подтверждение банка записаны ниже.')}
        actions={
          <>
            <Button variant="ghost">{t('Receipt', 'Квитанция')}</Button>
            <Button onClick={() => navigateTo('burn', 'initiate')}>{t('Redeem again', 'Погасить ещё')}</Button>
          </>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 24, alignItems: 'flex-start' }}>
        <Card padding={32} style={{
          background: 'linear-gradient(135deg, rgba(82,0,4,0.30), rgba(20,18,16,0.5))',
          border: '1px solid var(--border-gold)', position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 22 }}>
            <SealDot size={44} />
            <div>
              <Pill tone="gold" dot>{t('Settled', 'Исполнено')}</Pill>
              <div style={{ marginTop: 8, fontSize: 13, color: 'var(--fg-secondary)' }}>{t('RTGS booked at', 'RTGS проведён')} 11:02:33 UTC · {t('13 Jan 2026', '13 янв 2026')}</div>
            </div>
          </div>
          <Amount value={formatAmount(amount)} unit="KGS" size={48} />
          <div style={{ marginTop: 24 }}>
            <Field label={t('Request ID', 'ID запроса')} value="KGST-BURN-2026000418" mono />
            <Field label={t('KGST burned', 'KGST погашено')} value={`${formatAmount(amount)} KGST`} mono />
            <Field label={t('Source chain', 'Исходная сеть')} value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><ChainBadge chain="eth" /> Ethereum</span>} />
            <Field label={t('Burn tx', 'Burn tx')} value={<span style={{ color: 'var(--gold-300)' }}>0xd4f9c8e1…48bca91a8</span>} mono copyable />
            <Field label={t('Settlement bank', 'Банк расчёта')} value="Optima Bank OJSC · ENEJKG22" />
            <Field label={t('RTGS reference', 'RTGS референс')} value="NBKR-RTGS-20260113-7714" mono copyable />
          </div>
          <span style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: 2,
            background: 'linear-gradient(90deg, transparent, var(--gold-300), transparent)',
            animation: 'kgstShimmer 2.6s ease-in-out infinite',
          }} />
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={22}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 10 }}>{t('Documents', 'Документы')}</div>
            <BurnDocRow name={t('Bank settlement advice (MT103)', 'Банковское уведомление (MT103)')} sub={t('From NBKR · received 11:08 UTC · 92 KB', 'От NBKR · получено 11:08 UTC · 92 КБ')} />
            <BurnDocRow name={t('On-chain burn proof', 'Доказательство погашения')}             sub={t('Etherscan PDF export · 110 KB', 'PDF-экспорт Etherscan · 110 КБ')} />
            <BurnDocRow name={t('Internal redemption receipt', 'Внутренняя квитанция погашения')}     sub={t('Signed by KGST operator · 184 KB', 'Подписана оператором KGST · 184 КБ')} />
          </Card>
          <Card padding={22}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 8 }}>{t('Reserve impact', 'Влияние на резерв')}</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
              {t(`Total outstanding KGST decreased by ${formatAmount(amount)}. Reserve attestation will reflect this in the next monthly cycle.`, `Общий объём KGST в обращении уменьшился на ${formatAmount(amount)}. Аттестация резервов отразит это в следующем ежемесячном отчёте.`)}
            </div>
          </Card>
          <Button variant="secondary" onClick={() => navigateTo('dashboard', 'home')}>{t('Return to dashboard', 'Вернуться на дашборд')}</Button>
        </div>
      </div>
    </>
  );
};

const BurnDocRow = ({ name, sub }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0',
    borderTop: '1px solid var(--border-subtle)',
  }}>
    <span style={{ color: 'var(--gold-300)', display: 'inline-flex' }}><Icons.audit size={15} /></span>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 12.5, fontWeight: 500 }}>{name}</div>
      <div style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{sub}</div>
    </div>
    <Icons.download size={14} style={{ color: 'var(--bone-3)', cursor: 'pointer' }} />
  </div>
);

window.BurnFlow = BurnFlow;
