/* eslint-disable */
// MintFlow.jsx — Module 2 clickable flow.
// Screens: initiate → twofa (modal) → wire → status → complete

// const MINT_BREADCRUMBS = (moved inside MintFlow for translation)

const MINT_ADDRESSES = [
  { id: 'tron-treasury', label: 'Treasury · Tron',         name: 'Treasury · Tron',         addr: 'TKgQ9b2A4Fz81G7tHpY5sLwM2eC8DfN6Vx',          chain: 'tron', sub: 'Bound 21 Nov 2025' },
  { id: 'cold',          label: 'Treasury · Cold storage', name: 'Treasury · Cold storage', addr: '0x9b21A8e7d1f5C4b8Ad3F8c2E9B7d3A1F6c2E4d8B', chain: 'eth',  sub: 'Bound 12 Oct 2025' },
  { id: 'ops',           label: 'Operations · Hot wallet', name: 'Operations · Hot wallet', addr: '0x4Ad7b2F9c1B8E6d2A5F3c8B1d9E2A6F4c7B3d1E5', chain: 'eth',  sub: 'Bound 03 Dec 2025' },
];
const CHAIN_OPTIONS = [
  { id: 'tron', name: 'Tron',     std: 'TRC-20' },
  { id: 'eth',  name: 'Ethereum', std: 'ERC-20' },
  { id: 'bnb',  name: 'BNB Chain',std: 'BEP-20' },
];

const MintFlow = ({ screen }) => {
  const t = useT();
  const MINT_BREADCRUMBS = {
    initiate: [t('Mint', 'Эмиссия'), t('New request', 'Новый запрос')],
    twofa:    [t('Mint', 'Эмиссия'), t('New request', 'Новый запрос')],
    wire:     [t('Mint', 'Эмиссия'), t('Request KGST-MINT-2026000914', 'Запрос KGST-MINT-2026000914')],
    status:   [t('Mint', 'Эмиссия'), 'KGST-MINT-2026000914'],
    complete: [t('Mint', 'Эмиссия'), 'KGST-MINT-2026000914'],
  };
  return (
  <ProtoConsoleShell current="mint" breadcrumbs={MINT_BREADCRUMBS[screen] || [t('Mint', 'Эмиссия')]}>
    {screen === 'initiate' && <MintInitiateScreen />}
    {screen === 'twofa'    && <MintInitiateScreen modal="twofa" />}
    {screen === 'wire'     && <MintWireScreen />}
    {screen === 'status'   && <MintStatusScreen />}
    {screen === 'complete' && <MintCompleteScreen />}
  </ProtoConsoleShell>
  );
};

// =================================================================
// Mint initiate
// =================================================================
const MintInitiateScreen = ({ modal }) => {
  const { data, set } = usePrototype();
  const t = useT();
  const amount = data.mintAmount || '';
  const chain = data.mintChain || 'tron';
  const customAddrs = data.customAddresses || [];
  const allAddresses = [...MINT_ADDRESSES, ...customAddrs];
  const addrId = data.mintAddrId || (allAddresses[0] && allAddresses[0].id) || 'cold';
  const [bindOpen, setBindOpen] = React.useState(false);

  const parsed = parseAmount(amount);
  const hasAmount = parsed > 0;
  const minOK = parsed >= 1000000;
  const chainObj = CHAIN_OPTIONS.find(c => c.id === chain);
  const addrObj = allAddresses.find(a => a.id === addrId) || allAddresses[0];

  const onWalletBound = (newAddr) => {
    set({
      customAddresses: [...customAddrs, newAddr],
      mintAddrId: newAddr.id,         // auto-select
      mintChain: newAddr.chain,        // switch chain if needed
    });
    setBindOpen(false);
  };

  return (
    <>
      <PageHeader
        title={t('New mint request', 'Новый запрос эмиссии')}
        sub={t("Generate a wire reference, send Kyrgyz som to the KGST reserve account, and we'll issue KGST to your bound wallet on the chain you select.", 'Создайте референс SWIFT, отправьте кыргызские сомы на резервный счёт KGST — и мы выпустим KGST на ваш привязанный кошелёк в выбранной сети.')}
        actions={<Button variant="ghost" onClick={() => navigateTo('dashboard', 'transactions')}>{t('View past requests', 'Прошлые запросы')}</Button>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'flex-start' }}>
        {/* Form */}
        <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', 'Сумма')}</span>
              <AmountInput
                value={amount}
                onChange={v => set({ mintAmount: v })}
                unit="KGS"
                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'} KGST
                  </span>{' '}· {t('pegged 1:1', 'привязка 1:1')}
                </span>
                <span style={{ color: minOK ? 'var(--fg-tertiary)' : 'var(--amber-400)' }}>
                  {t('Minimum 1,000,000 KGS', 'Минимум 1 000 000 KGS')}
                </span>
              </div>
            </div>

            {/* Chain */}
            <div>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Receive on', 'Сеть получения')}</span>
              <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                {CHAIN_OPTIONS.map(c => (
                  <ChainPickerCard
                    key={c.id}
                    chain={c.id}
                    name={c.name}
                    std={c.std}
                    selected={chain === c.id}
                    onClick={() => set({ mintChain: c.id })}
                  />
                ))}
              </div>
            </div>

            {/* Address */}
            <div>
              <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Receive address', 'Адрес получения')}</span>
              <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {allAddresses.map(a => (
                  <Selector
                    key={a.id}
                    selected={addrId === a.id}
                    onClick={() => set({ mintAddrId: a.id })}
                    leading={
                      <span style={{
                        width: 26, height: 26, borderRadius: '50%',
                        background: addrId === a.id ? 'rgba(201,152,64,0.15)' : 'var(--ink-3)',
                        border: '1px solid var(--border-default)',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        {addrId === a.id ? <Icons.check size={12} style={{ color: 'var(--gold-300)' }} /> : null}
                      </span>
                    }
                    value={
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                        {a.label || a.name}
                        {a.id && a.id.startsWith('custom-') ? <Pill tone="gold" dot={false} style={{ fontSize: 9.5, padding: '1px 6px' }}>New</Pill> : null}
                      </span>
                    }
                    hint={
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                        <ChainBadge chain={a.chain || 'eth'} small />
                        <span className="kgst-mono">{a.addr.slice(0, 16)}…{a.addr.slice(-8)}</span>
                      </span>
                    }
                    trailing={<span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{a.sub || (a.added ? `Bound ${a.added}` : '')}</span>}
                  />
                ))}
                <button 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',
                }} onClick={() => setBindOpen(true)}>
                  <Icons.plus size={13} /> {t('Bind a new address', 'Привязать новый адрес')}
                </button>
              </div>
            </div>
          </div>
        </Card>

        {/* Summary */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, position: 'sticky', top: 0 }}>
          <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 wire', 'Вы отправляете')} value={`${amount ? formatAmount(amount) : '0.00'} KGS`} mono />
            <Field label={t('You receive', 'Вы получаете')} value={<span style={{ color: 'var(--gold-300)' }}>{amount ? formatAmount(amount) : '0.00'} KGST</span>} mono />
            <Field label={t('Chain', 'Сеть')} value={`${chainObj.name} (${chainObj.std})`} />
            <Field label={t('Address', 'Адрес')} value={`${addrObj.addr.slice(0, 6)}…${addrObj.addr.slice(-4)}`} mono />
            <Field label={t('Fee', 'Комиссия')} value="0.00 KGS" mono sub={t('Zero issuance fee for verified institutions.', 'Комиссия за эмиссию отсутствует для верифицированных институтов.')} />
            <Field label={t('Settles', 'Расчет')} value={t('Same business day', 'В течение одного рабочего дня')} />
          </Card>

          <Button size="lg" iconRight={<Icons.arrowRight size={14} />}
            disabled={!hasAmount}
            onClick={() => navigateTo('mint', 'twofa')}>
            {t('Continue · 2FA required', 'Продолжить · требуется 2FA')}
          </Button>
          {hasAmount && !minOK ? (
            <div style={{ fontSize: 11, color: 'var(--amber-400)', marginTop: -4, textAlign: 'center' }}>
              {t("Note · institutional minimum is 1,000,000 KGS. We'll proceed for the prototype.", 'Минимум для институтов — 1 000 000 KGS. Для прототипа продолжим.')}
            </div>
          ) : null}

          <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('Wires arriving without the reference number will be queued for manual matching.', 'SWIFT без номера референса будут переданы на ручное сопоставление.')}</span>
          </div>
        </div>
      </div>

      {modal === 'twofa' && <MintTwoFAModal amount={amount} addrShort={`${addrObj.addr.slice(0,6)}…${addrObj.addr.slice(-4)}`} chainName={chainObj.name} />}

      <BindAddressModal
        open={bindOpen}
        defaultChain={chain}
        onClose={() => setBindOpen(false)}
        onBound={onWalletBound}
      />
    </>
  );
};

// Amount input — typable, big, mono, with KGS suffix
const AmountInput = ({ value, onChange, unit = 'KGS', placeholder = '0.00', autoFocus }) => {
  const [focused, setFocused] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (autoFocus && ref.current) {
      const t = setTimeout(() => ref.current && ref.current.focus(), 80);
      return () => clearTimeout(t);
    }
  }, [autoFocus]);
  const handle = (e) => {
    const v = formatAmount(e.target.value);
    onChange(v);
  };
  return (
    <div style={{
      marginTop: 8, padding: '16px 18px', borderRadius: 10,
      background: 'var(--bg-inset)',
      border: `1px solid ${focused ? 'var(--border-gold)' : 'var(--border-default)'}`,
      boxShadow: focused ? '0 0 0 3px rgba(201,152,64,0.10)' : 'none',
      display: 'flex', alignItems: 'center', gap: 14,
      transition: 'border-color 120ms ease, box-shadow 120ms ease',
    }}>
      <input
        ref={ref}
        value={value}
        onChange={handle}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder={placeholder}
        inputMode="decimal"
        style={{
          flex: 1, background: 'transparent', border: 'none', outline: 'none',
          fontFamily: 'var(--font-mono)', fontSize: 32, fontWeight: 600,
          color: 'var(--fg-primary)', letterSpacing: '-0.01em',
          width: '100%', minWidth: 0,
        }}
      />
      <span style={{ color: 'var(--fg-tertiary)', fontSize: 14, fontWeight: 500 }}>{unit}</span>
    </div>
  );
};

const ChainPickerCard = ({ chain, name, std, selected, onClick }) => (
  <div onClick={onClick} style={{
    padding: 14, borderRadius: 10,
    background: selected ? 'rgba(201,152,64,0.06)' : 'var(--bg-inset)',
    border: `1px solid ${selected ? 'var(--border-gold)' : 'var(--border-default)'}`,
    display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
    transition: 'border-color 120ms ease, background 120ms ease',
  }}>
    <ChainBadge chain={chain} />
    <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
      <span style={{ fontSize: 13, fontWeight: 500 }}>{name}</span>
      <span style={{ fontSize: 10.5, color: 'var(--fg-tertiary)' }}>{std}</span>
    </div>
    {selected ? (
      <span style={{ marginLeft: 'auto', color: 'var(--gold-300)', display: 'inline-flex' }}>
        <Icons.check size={14} />
      </span>
    ) : null}
  </div>
);

// =================================================================
// 2FA modal
// =================================================================
const MintTwoFAModal = ({ amount, addrShort, chainName }) => {
  const t = useT();
  const [code, setCode] = React.useState('');
  const timer = useCountdown(30);
  const onConfirm = () => {
    if (code.length === 6) navigateTo('mint', 'wire');
  };
  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 mint request.', 'Введите 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 mint', 'Вы собираетесь эмитировать')}</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('to', 'на')} <span className="kgst-mono" style={{ color: 'var(--fg-secondary)' }}>{addrShort}</span> · {chainName}
          </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('mint', 'initiate')}>
          {t('Back', 'Назад')}
        </Button>
        <Button onClick={onConfirm} disabled={code.length < 6}>{t('Confirm and sign', 'Подтвердить и подписать')}</Button>
      </div>
    </ModalScrim>
  );
};

// =================================================================
// Wire instructions
// =================================================================
const MintWireScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const amount = data.mintAmount || '5,000,000.00';
  const reference = 'KGST-MINT-2026000914';
  const [copied, setCopied] = React.useState(false);
  const copyRef = () => {
    try { navigator.clipboard && navigator.clipboard.writeText(reference); } catch (e) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <>
      <PageHeader
        title={t(`Wire ${formatAmount(amount)} KGS to the KGST reserve account`, `Переведите ${formatAmount(amount)} KGS на резервный счёт KGST`)}
        sub={t('The reference number below is what links your wire to this mint. Bank operators must include it verbatim in the wire memo.', 'Номер референса ниже связывает SWIFT с данным запросом эмиссии. Банковский оператор должен указать его буквально в поле назначения.')}
        actions={
          <>
            <Button variant="ghost" onClick={() => navigateTo('mint', 'initiate')}>{t('Cancel request', 'Отменить запрос')}</Button>
            <Button variant="secondary">{t('Download as PDF', 'Скачать PDF')}</Button>
          </>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
        {/* Wire details */}
        <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 reserve account', 'Резервный счёт KGST')}</span>
              <div style={{ marginTop: 4, fontSize: 15, fontWeight: 600 }}>{t('Kyrgyzkommertsbank (KKB) — KGST reserve sub-account', 'Кыргызкоммерцбанк (KKB) — резервный субсчёт KGST')}</div>
            </div>
            <Pill tone="wine" dot>{t('State-backed reserve', 'Резерв под государственным обеспечением')}</Pill>
          </div>
          <div style={{ padding: 24 }}>
            <Field label={t('Bank name', 'Название банка')} value={t('KKB · Kyrgyzkommertsbank OJSC', 'KKB · Кыргызкоммерцбанк ОАО')} />
            <Field label={t('Beneficiary', 'Получатель')} value={t('KGST Reserve Pool — KGSToken JSC', 'Резервный пул KGST — KGSToken АО')} />
            <Field label="SWIFT / BIC" value="KKBKKG22" mono copyable />
            <Field label={t('Account number', 'Номер счёта')} value="1230 0050 4711 0008" mono copyable />
            <Field label={t('Bank address', 'Адрес банка')} value={t('21 Toktogul Str., Bishkek 720040, Kyrgyzstan', 'ул. Токтогула 21, Бишкек 720040, Кыргызстан')} />
            <Field label={t('Currency', 'Валюта')} value={t('KGS · Kyrgyz som', 'KGS · кыргызский сом')} />
            <Field label={t('Amount to wire', 'Сумма перевода')} value={<span style={{ color: 'var(--gold-300)' }}>{formatAmount(amount)} KGS</span>} mono />
          </div>
        </Card>

        {/* Reference */}
        <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: 8 }}>{t('Wire memo / reference', 'Назначение / референс SWIFT')}</div>
            <div className="kgst-mono" style={{
              fontSize: 22, fontWeight: 600, letterSpacing: '0.02em',
              color: 'var(--gold-300)',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <span style={{ flex: 1 }}>{reference}</span>
              <button onClick={copyRef} style={{
                background: 'transparent', border: 'none', cursor: 'pointer', color: copied ? 'var(--green-400)' : 'var(--bone-3)',
                display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontFamily: 'inherit',
              }}>
                {copied ? <><Icons.check size={12} />{t('Copied', 'Скопировано')}</> : <><Icons.spark size={12} />{t('Copy', 'Копия')}</>}
              </button>
            </div>
            <div style={{ marginTop: 12, fontSize: 11.5, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
              {t('Include this code verbatim in your wire memo / reference field.', 'Укажите этот код буквально в поле назначения платежа.')} <span style={{ color: 'var(--fg-primary)' }}>{t('Capitalisation and dashes matter.', 'Регистр и дефисы важны.')}</span>
            </div>
          </Card>

          <Card padding={18}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 8 }}>{t('Example memo', 'Пример назначения')}</div>
            <div className="kgst-mono" style={{
              fontSize: 11.5, color: 'var(--bone-5)', lineHeight: 1.6,
              padding: 10, background: 'var(--bg-inset)', borderRadius: 6,
              border: '1px solid var(--border-subtle)', whiteSpace: 'pre-line',
            }}>
              {`Payment for KGST issuance
Ref: ${reference}
Sender: ${data.acctHolder || 'Binance Asia Services Pte. Ltd.'}`}
            </div>
          </Card>

          <Card padding={14} style={{ 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.clock size={14} style={{ color: 'var(--amber-400)', marginTop: 1, flexShrink: 0 }} />
              <span>{t('Reference expires in', 'Срок референса:')} <span className="kgst-mono" style={{ color: 'var(--fg-primary)' }}>23h 48m</span>. {t('Wires arriving later will be queued for manual matching.', 'Позже SWIFT попадёт в ручную обработку.')}</span>
            </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.4s ease-in-out infinite',
          }} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{t('Waiting for your wire', 'Ожидание платежа')}</div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)' }}>{t("We'll auto-advance this request when the reserve account credits.", 'Как только резервный счёт пополнится, мы продвинем запрос.')}</div>
          </div>
        </div>
        <Button iconRight={<Icons.arrowRight size={13} />} onClick={() => navigateTo('mint', 'status')}>
          {t('Track this request', 'Отслеживать запрос')}
        </Button>
      </div>
    </>
  );
};

// =================================================================
// Status tracking — auto-progresses through steps
// =================================================================
const MintStatusScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const amount = data.mintAmount || '5,000,000.00';
  const chainId = data.mintChain || 'tron';
  const chainName = (CHAIN_OPTIONS.find(c => c.id === chainId) || CHAIN_OPTIONS[0]).name;
  const customAddrs = data.customAddresses || [];
  const allAddresses = [...MINT_ADDRESSES, ...customAddrs];
  const addrObj = allAddresses.find(a => a.id === data.mintAddrId) || allAddresses[0];
  const txHash = chainId === 'tron' ? '6FA2c8b1d9E2…12c3' : (chainId === 'bnb' ? '0xB9b2a4c1…f8e0' : '0x7c4a3f8b21…ba31');
  const stepDefs = [
    { label: t('Wire submitted', 'SWIFT отправлен'),         sub: t('You', 'Вы') },
    { label: t('Bank credit confirmed', 'Поступление в банк'), sub: t('Reserve', 'Резерв') },
    { label: t('On-chain mint broadcast', 'Эмиссия в блокчейне'),  sub: chainName },
    { label: t('KGST delivered', 'KGST доставлены'),       sub: t('Wallet', 'Кошелёк') },
  ];

  // Auto-advance step every 2.4s; jump to complete after final step
  const [stage, setStage] = React.useState(1);
  React.useEffect(() => {
    if (stage >= stepDefs.length) {
      const tm = setTimeout(() => navigateTo('mint', 'complete'), 1600);
      return () => clearTimeout(tm);
    }
    const tm = setTimeout(() => setStage(s => s + 1), 2400);
    return () => clearTimeout(tm);
  }, [stage]);  // eslint-disable-line

  const baseLog = [
    { t: '14:18:32', s: t(`Mint request created · reference KGST-MINT-2026000914`, `Запрос эмиссии создан · референс KGST-MINT-2026000914`), tone: 'gold' },
    { t: '14:43:11', s: t(`Wire received at reserve account · ${formatAmount(amount)} KGS · reference matched`, `SWIFT получен на резервный счёт · ${formatAmount(amount)} KGS · референс совпал`), tone: 'gold' },
    { t: '14:43:24', s: t(`On-chain mint broadcast · tx ${txHash}`, `Эмиссия в блокчейне · tx ${txHash}`), tone: 'gold' },
    { t: 'pending',  s: t(`Awaiting block confirmations on ${chainName} (${stage * 4} / 12)`, `Ожидание подтверждений в сети ${chainName} (${stage * 4} / 12)`), tone: 'amber' },
  ];
  const log = baseLog.slice(0, Math.max(1, stage + 1));

  return (
    <>
      <PageHeader
        title={t(`Mint in progress · ${formatAmount(amount)} KGST`, `Эмиссия в процессе · ${formatAmount(amount)} KGST`)}
        sub={t(`We've received your wire and broadcast the on-chain mint. Final confirmation typically takes 1–3 minutes on ${chainName}.`, `Мы получили SWIFT и отправили эмиссию в блокчейн. Окончательное подтверждение в ${chainName} обычно занимает 1–3 мин.`)}
        actions={<Button variant="ghost" iconRight={<Icons.arrowUp size={13} />}>{t('Open block explorer', 'Открыть эксплорер')}</Button>}
      />

      <Card padding={28}>
        <Stepper steps={stepDefs} 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-MINT-2026000914" mono copyable />
          <Field label={t('Amount', 'Сумма')} value={<span style={{ color: 'var(--gold-300)' }}>{formatAmount(amount)} KGST</span>} mono />
          <Field label={t('Chain', 'Сеть')} value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><ChainBadge chain={chainId} /> {chainName}</span>} />
          <Field label={t('Receive address', 'Адрес получения')} value={`${(addrObj.addr || '').slice(0, 10)}…${(addrObj.addr || '').slice(-6)}`} mono copyable />
          <Field label={t('On-chain tx', 'Хэш в блокчейне')} value={<span style={{ color: 'var(--gold-300)' }}>{txHash} · {t('pending', 'ожидает')}</span>} mono copyable />
          <Field label={t('Submitted', 'Подано')} value="13 Jan 2026 · 14:18:32 UTC" />
        </Card>

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

const MintTimeline = ({ items }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
    {items.map((it, i) => (
      <div key={i} style={{ display: 'flex', gap: 12, position: 'relative', animation: 'kgstFadeIn 320ms ease' }}>
        <div style={{ width: 56, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-tertiary)', flexShrink: 0, paddingTop: 1 }}>{it.t}</div>
        <span style={{
          position: 'relative', width: 8, height: 8, marginTop: 6, flexShrink: 0, borderRadius: '50%',
          background: it.tone === 'amber' ? 'var(--amber-400)' : 'var(--gold-300)',
          boxShadow: it.tone === 'amber' ? '0 0 0 4px rgba(225,165,58,0.10)' : 'none',
          animation: it.tone === 'amber' ? 'kgstPulse 1.4s ease-in-out infinite' : 'none',
        }} />
        <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.5, flex: 1 }}>{it.s}</div>
      </div>
    ))}
  </div>
);

// =================================================================
// Complete
// =================================================================
const MintCompleteScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const amount = data.mintAmount || '5,000,000.00';
  const chainId = data.mintChain || 'tron';
  const chainObj = CHAIN_OPTIONS.find(c => c.id === chainId) || CHAIN_OPTIONS[0];
  const customAddrs = data.customAddresses || [];
  const allAddresses = [...MINT_ADDRESSES, ...customAddrs];
  const addrObj = allAddresses.find(a => a.id === data.mintAddrId) || allAddresses[0];
  const txHash = chainId === 'tron' ? '6FA2c8b1d9E2a8f7…12c3' : (chainId === 'bnb' ? '0xB9b2a4c1d8e7…f8e0' : '0x7c4a3f8b21…ba31');
  const explorer = chainId === 'tron' ? 'Tronscan' : (chainId === 'bnb' ? 'BscScan' : 'Etherscan');
  return (
    <>
      <PageHeader
        title={t('Mint complete', 'Эмиссия выполнена')}
        sub={t(`${formatAmount(amount)} KGST has been issued to your bound ${chainObj.name} address. A signed receipt is available below.`, `${formatAmount(amount)} KGST выпущены на ваш привязанный адрес в сети ${chainObj.name}. Подписанная квитанция доступна ниже.`)}
        actions={
          <>
            <Button variant="ghost">{t(`View on ${explorer}`, `Открыть в ${explorer}`)}</Button>
            <Button onClick={() => navigateTo('mint', 'initiate')}>{t('Mint 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('Minted', 'Эмитировано')}</Pill>
              <div style={{ marginTop: 8, fontSize: 13, color: 'var(--fg-secondary)' }}>{t('Signed and finalised at 14:46:18 UTC', 'Подписано и завершено в 14:46:18 UTC')}</div>
            </div>
          </div>
          <Amount value={formatAmount(amount)} size={48} />
          <div style={{ marginTop: 24 }}>
            <Field label={t('Request ID', 'ID запроса')} value="KGST-MINT-2026000914" mono />
            <Field label={t('Wire reference matched', 'SWIFT-референс совпал')} value="KGST-MINT-2026000914" mono />
            <Field label={t('Chain', 'Сеть')} value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><ChainBadge chain={chainId} /> {chainObj.name} ({chainObj.std})</span>} />
            <Field label={t('Receive address', 'Адрес получения')} value={`${(addrObj.addr || '').slice(0, 10)}…${(addrObj.addr || '').slice(-6)}`} mono copyable />
            <Field label={t('On-chain tx', 'Хэш в блокчейне')} value={<span style={{ color: 'var(--gold-300)' }}>{txHash}</span>} mono copyable />
            <Field label={t('Block', 'Блок')} value={t('20,418,772 · 12 / 12 confirmed', '20 418 772 · 12 / 12 подтверждений')} mono />
          </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('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={22} style={{ color: 'var(--gold-300)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>KGST-MINT-2026000914.pdf</div>
                <div style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{t('Signed receipt with wire copy and on-chain proof · 184 KB', 'Подписанная квитанция с копией SWIFT и блокчейн-доказательством · 184 КБ')}</div>
              </div>
              <Button size="sm" variant="secondary" icon={<Icons.download size={13} />}>{t('Download', 'Скачать')}</Button>
            </div>
          </Card>

          <Card padding={22}>
            <div className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 8 }}>{t("What's next?", 'Что дальше?')}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <MintNextRow icon="arrowUp"   label={t('Mint another tranche', 'Эмитировать ещё один транш')} onClick={() => navigateTo('mint', 'initiate')} />
              <MintNextRow icon="arrowDown" label={t('Redeem (burn) KGST back to KGS', 'Погасить (burn) KGST обратно в KGS')} onClick={() => navigateTo('burn', 'initiate')} />
              <MintNextRow icon="dashboard" label={t('Return to dashboard', 'Вернуться на дашборд')} onClick={() => navigateTo('dashboard', 'home')} />
            </div>
          </Card>
        </div>
      </div>
    </>
  );
};

const MintNextRow = ({ icon, label, onClick }) => {
  const I = Icons[icon];
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 10px', 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={{ color: 'var(--gold-300)', display: 'inline-flex' }}><I size={14} /></span>
      <span style={{ flex: 1, fontSize: 13 }}>{label}</span>
      <Icons.arrowRight size={13} style={{ color: 'var(--fg-tertiary)' }} />
    </div>
  );
};

window.MintFlow = MintFlow;
