/* eslint-disable */
// BindAddressModal.jsx — shared 3-step modal for binding a new wallet address.
// Steps: 1) verify ownership (connect wallet → sign) → 2) 2FA → 3) email confirm.
// Used from Mint initiate, Burn initiate, and Wallets settings page.

const BindAddressModal = ({ open, onClose, onBound, defaultChain = 'tron' }) => {
  const t = useT();
  const [step, setStep] = React.useState(0);
  const [connected, setConnected] = React.useState(false);
  const [label, setLabel] = React.useState('');
  const [code, setCode] = React.useState('');
  const [chain, setChain] = React.useState(defaultChain);

  // Reset internal state when modal closes
  React.useEffect(() => {
    if (!open) {
      const t = setTimeout(() => {
        setStep(0); setConnected(false); setLabel(''); setCode(''); setChain(defaultChain);
      }, 200);
      return () => clearTimeout(t);
    }
  }, [open, defaultChain]);

  if (!open) return null;

  const STEPS = [t('Verify ownership', 'Подтвердить владение'), t('Confirm with 2FA', 'Подтвердить через 2FA'), t('Confirm by email', 'Подтвердить по e-mail')];

  const finalize = () => {
    // Generate a realistic-looking address for the chosen chain
    let addr;
    if (chain === 'tron') {
      addr = 'T' + Array.from({ length: 33 }, () => 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789'[Math.floor(Math.random() * 58)]).join('');
    } else {
      // eth / bnb — 40-char hex
      addr = '0x' + Array.from({ length: 40 }, () => '0123456789abcdef'[Math.floor(Math.random() * 16)]).join('');
    }
    if (onBound) {
      onBound({
        id: 'custom-' + Date.now(),
        chain,
        addr,
        label: label.trim() || t(`New ${CHAIN_MAP[chain].name} wallet`, `Новый кошелёк · ${CHAIN_MAP[chain].name}`),
        added: t('Just now', 'Только что'),
      });
    }
    onClose();
  };

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 150,
        background: 'rgba(0,0,0,0.55)',
        backdropFilter: 'blur(3px)', WebkitBackdropFilter: 'blur(3px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        animation: 'kgstFadeIn 200ms ease',
      }}
    >
      <div style={{
        width: 580, maxWidth: '100%', maxHeight: '90vh',
        background: 'var(--bg-raised)',
        border: '1px solid var(--border-default)',
        boxShadow: 'var(--shadow-lg)',
        borderRadius: 14,
        overflow: 'hidden', display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{
          padding: '20px 24px 16px',
          borderBottom: '1px solid var(--border-subtle)',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16,
        }}>
          <div>
            <div className="kgst-h3" style={{ margin: 0, fontSize: 17 }}>{t('Bind a new wallet address', 'Привязать новый адрес кошелька')}</div>
            <div style={{ marginTop: 4, fontSize: 12.5, color: 'var(--fg-secondary)' }}>
              {t('Prove control of this address, confirm with 2FA, and finalise via email.', 'Подтвердите владение адресом, подтвердите через 2FA, завершите по e-mail.')}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            color: 'var(--bone-3)', padding: 4, display: 'inline-flex',
          }}><Icons.x size={16} /></button>
        </div>

        {/* Progress bar */}
        <div style={{ padding: '16px 24px 14px', borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {STEPS.map((l, i) => (
              <React.Fragment key={i}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: '50%',
                    background: i < step ? 'var(--gold-400)' : i === step ? 'rgba(201,152,64,0.18)' : 'var(--ink-2)',
                    color: i < step ? 'var(--ink-1)' : i === step ? 'var(--gold-300)' : 'var(--fg-tertiary)',
                    border: '1px solid ' + (i <= step ? 'var(--border-gold)' : 'var(--border-default)'),
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 700,
                    boxShadow: i === step ? '0 0 0 3px rgba(201,152,64,0.10)' : 'none',
                    transition: 'background 200ms ease, color 200ms ease',
                  }}>
                    {i < step ? <Icons.check size={11} /> : i + 1}
                  </span>
                  <span style={{
                    fontSize: 12.5, fontWeight: i === step ? 600 : 400,
                    color: i < step ? 'var(--bone-5)' : i === step ? 'var(--fg-primary)' : 'var(--fg-tertiary)',
                  }}>{l}</span>
                </div>
                {i < STEPS.length - 1 ? (
                  <div style={{ flex: 1, height: 1.5, background: i < step ? 'var(--gold-400)' : 'var(--border-default)', minWidth: 12, transition: 'background 200ms ease' }} />
                ) : null}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflow: 'auto' }}>
          {step === 0 && (
            <BindStep1Verify
              connected={connected}
              setConnected={setConnected}
              label={label}
              setLabel={setLabel}
              chain={chain}
              setChain={setChain}
            />
          )}
          {step === 1 && <BindStep2TwoFA code={code} setCode={setCode} chain={chain} />}
          {step === 2 && <BindStep3Email chain={chain} />}
        </div>

        {/* Footer */}
        <div style={{
          padding: '14px 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={() => step === 0 ? onClose() : setStep(s => s - 1)}>
            {step === 0 ? t('Cancel', 'Отмена') : t('Back', 'Назад')}
          </Button>
          {step === 0 && (
            <Button disabled={!connected}
              iconRight={<Icons.arrowRight size={13} />}
              onClick={() => setStep(1)}>
              {t('Continue', 'Продолжить')}
            </Button>
          )}
          {step === 1 && (
            <Button disabled={code.length < 6}
              iconRight={<Icons.arrowRight size={13} />}
              onClick={() => setStep(2)}>
              {t('Continue', 'Продолжить')}
            </Button>
          )}
          {step === 2 && (
            <Button onClick={finalize}>{t("I've confirmed", 'Я подтвердил')}</Button>
          )}
        </div>
      </div>
    </div>
  );
};

// =================================================================
// Step 1 — connect wallet + sign
// =================================================================
const BindStep1Verify = ({ connected, setConnected, label, setLabel, chain, setChain }) => {
  const t = useT();
  return (
  <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18 }}>
    <p style={{ margin: 0, fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.55 }}>
      {t("Connect the wallet that holds the address you want to bind. We'll request a one-tap signature from your browser extension to prove ownership — no private keys ever leave your device.", 'Подключите кошелёк, к которому относится этот адрес. Мы запросим однократную подпись из вашего расширения-кошелька для подтверждения владения — приватные ключи не покидают ваше устройство.')}
    </p>

    {/* Chain picker */}
    <div>
      <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Chain', 'Сеть')}</span>
      <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
        {CHAIN_OPTS_BIND.map(c => (
          <div key={c.id}
            onClick={() => !connected && setChain(c.id)}
            style={{
              padding: 12, borderRadius: 10,
              background: chain === c.id ? 'rgba(201,152,64,0.06)' : 'var(--bg-inset)',
              border: `1px solid ${chain === c.id ? 'var(--border-gold)' : 'var(--border-default)'}`,
              display: 'flex', alignItems: 'center', gap: 8,
              cursor: connected ? 'not-allowed' : 'pointer',
              opacity: connected ? 0.6 : 1,
              transition: 'border-color 120ms ease, background 120ms ease',
            }}>
            <ChainBadge chain={c.id} />
            <span style={{ fontSize: 12.5, fontWeight: 500 }}>{c.name}</span>
            {chain === c.id ? <span style={{ marginLeft: 'auto', color: 'var(--gold-300)', display: 'inline-flex' }}><Icons.check size={13} /></span> : null}
          </div>
        ))}
      </div>
    </div>

    {connected ? (
      <>
        {/* Connected wallet card */}
        <div style={{
          padding: 14, borderRadius: 12,
          background: 'var(--ink-2)',
          border: '1px solid var(--border-gold)',
          boxShadow: '0 0 0 2px rgba(201,152,64,0.06)',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 8,
            background: 'linear-gradient(135deg, #F6851B, #E2761B)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontWeight: 700, fontSize: 15, flexShrink: 0,
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.18)',
          }}>M</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>MetaMask</span>
              <Pill tone="success" dot>{t('Connected', 'Подключён')}</Pill>
            </div>
            <div className="kgst-mono" style={{ marginTop: 4, fontSize: 11.5, color: 'var(--bone-5)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <ChainBadge chain={chain} small />
              <span>0x4Ad7b2F9c1B8E6d2A5F3c8B1d9E2A6F4c7B3d1E5</span>
            </div>
          </div>
          <a style={{ fontSize: 11.5, color: 'var(--gold-300)', cursor: 'pointer' }}
            onClick={() => setConnected(false)}>{t('Disconnect', 'Отключить')}</a>
        </div>

        {/* Signature confirmation */}
        <div style={{
          padding: '12px 14px', borderRadius: 8,
          background: 'rgba(79,168,106,0.06)',
          border: '1px solid rgba(79,168,106,0.25)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: '50%',
            background: 'rgba(79,168,106,0.18)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--green-400)', flexShrink: 0,
          }}>
            <Icons.check size={14} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 500 }}>{t('Ownership signature received', 'Подпись владения получена')}</div>
            <div style={{ marginTop: 2, fontSize: 11, color: 'var(--fg-tertiary)' }}>
              {t('Signed in MetaMask · recovered address matches the connected wallet.', 'Подписано в MetaMask · восстановленный адрес совпадает с подключенным кошельком.')}
            </div>
          </div>
        </div>

        {/* Label */}
        <TextField
          label={t('Label (optional)', 'Метка (необязательно)')}
          value={label}
          onChange={setLabel}
          placeholder={t('e.g. Operations · Hot wallet', 'напр. Операции · hot wallet')}
          helper={t('Shown next to the address everywhere in the console.', 'Отображается рядом с адресом по всей консоли.')}
        />
      </>
    ) : (
      <>
        <div style={{
          padding: '22px 20px', borderRadius: 12,
          background: 'var(--ink-2)',
          border: '1px dashed var(--border-default)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, textAlign: 'center',
        }}>
          <div style={{
            width: 48, height: 48, borderRadius: 10,
            background: 'rgba(201,152,64,0.08)',
            border: '1px solid var(--border-gold)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold-300)',
          }}>
            <Icons.link size={20} />
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{t('No wallet connected', 'Кошельк не подключён')}</div>
            <div style={{ marginTop: 4, fontSize: 12, color: 'var(--fg-tertiary)' }}>
              {t('Connect to detect the address and sign the ownership proof.', 'Подключите кошелёк, чтобы определить адрес и подписать доказательство владения.')}
            </div>
          </div>
          <Button size="lg" icon={<Icons.link size={14} />} onClick={() => setConnected(true)}>
            {t('Connect wallet', 'Подключить кошелёк')}
          </Button>
          <div style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>
            {t('Supports MetaMask, Rabby, Coinbase Wallet, WalletConnect', 'Поддерживаются MetaMask, Rabby, Coinbase Wallet, WalletConnect')}
          </div>
        </div>

        <div style={{
          padding: '10px 12px', borderRadius: 8,
          background: 'rgba(82,0,4,0.18)', border: '1px solid rgba(184,80,68,0.20)',
          display: 'flex', gap: 10, fontSize: 11.5, color: 'var(--bone-5)',
        }}>
          <Icons.shield size={13} style={{ color: 'var(--wine-200)', marginTop: 1, flexShrink: 0 }} />
          <span>{t('Gas-free · the signature is off-chain and only used to prove control of the address.', 'Без комиссии · подпись оффчейн, используется только для подтверждения владения адресом.')}</span>
        </div>
      </>
    )}
  </div>
  );
};

const CHAIN_OPTS_BIND = [
  { id: 'eth',  name: 'Ethereum' },
  { id: 'tron', name: 'Tron' },
  { id: 'bnb',  name: 'BNB Chain' },
];

// =================================================================
// Step 2 — 2FA
// =================================================================
const BindStep2TwoFA = ({ code, setCode, chain }) => {
  const t = useT();
  const timer = useCountdown(22);
  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18 }}>
      <p style={{ margin: 0, fontSize: 12.5, color: 'var(--fg-secondary)' }}>
        {t('Enter the 6-digit code from your authenticator app to sign the address-binding request.', 'Введите 6-значный код из приложения-аутентификатора, чтобы подписать запрос на привязку адреса.')}
      </p>

      <div style={{
        padding: 14, borderRadius: 8,
        background: 'var(--ink-2)', border: '1px solid var(--border-subtle)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <Icons.check size={14} style={{ color: 'var(--green-400)' }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 500 }}>{t('Address ownership verified', 'Владение адресом подтверждено')}</div>
          <div className="kgst-mono" style={{ fontSize: 11, color: 'var(--fg-tertiary)', marginTop: 2 }}>
            0x4Ad7b2F9…c7B3d1E5 · {CHAIN_MAP[chain].name}
          </div>
        </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 />
        <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', fontSize: 11.5 }}>
          <a style={{ color: 'var(--gold-300)', cursor: 'pointer' }}>{t('Use email code instead', 'Использовать код по e-mail')}</a>
          <a style={{ color: 'var(--fg-tertiary)', cursor: 'pointer' }}>{t('Lost your device?', 'Потеряли устройство?')}</a>
        </div>
      </div>
    </div>
  );
};

// =================================================================
// Step 3 — waiting for email confirmation
// =================================================================
const BindStep3Email = ({ chain }) => {
  const t = useT();
  return (
  <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18, alignItems: 'center', textAlign: 'center' }}>
    <div style={{
      width: 64, height: 64, borderRadius: '50%',
      background: 'rgba(201,152,64,0.08)', border: '1px solid var(--border-gold)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      color: 'var(--gold-300)', position: 'relative',
    }}>
      <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="4" width="20" height="16" rx="2" /><path d="M22 7l-10 7L2 7" />
      </svg>
      <span style={{
        position: 'absolute', inset: -3, borderRadius: '50%',
        border: '1.5px solid var(--gold-300)', opacity: 0.5,
        animation: 'kgstPulse 1.8s ease-in-out infinite',
      }} />
    </div>

    <div>
      <div className="kgst-h3" style={{ fontSize: 16 }}>{t('Check your inbox', 'Проверьте почту')}</div>
      <p style={{ margin: '6px 0 0', fontSize: 12.5, color: 'var(--fg-secondary)', maxWidth: 380, lineHeight: 1.55 }}>
        {t("We've sent a confirmation link to ", 'Мы отправили ссылку подтверждения на ')}
        <span style={{ color: 'var(--fg-primary)' }}>treasury@binance.com</span>.
        {' '}{t('Click the link from the same device to finish binding this address. The link expires in 15 minutes.', 'Перейдите по ссылке с этого же устройства, чтобы завершить привязку. Ссылка действительна 15 минут.')}
      </p>
    </div>

    <div style={{
      width: '100%', padding: 12, borderRadius: 8,
      background: 'var(--ink-2)', border: '1px solid var(--border-subtle)',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <ChainBadge chain={chain} />
      <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
        <div style={{ fontSize: 12.5, fontWeight: 500 }}>{t(`Binding to ${CHAIN_MAP[chain].name}`, `Привязка к сети ${CHAIN_MAP[chain].name}`)}</div>
        <div className="kgst-mono" style={{ fontSize: 11, color: 'var(--fg-tertiary)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis' }}>
          0x4Ad7b2F9c1B8E6d2A5F3c8B1d9E2A6F4c7B3d1E5
        </div>
      </div>
      <Pill tone="warning" dot>{t('Awaiting', 'Ожидаем')}</Pill>
    </div>

    <div style={{
      width: '100%', padding: '10px 14px', borderRadius: 8,
      background: 'var(--bg-inset)', border: '1px solid var(--border-default)',
      display: 'flex', alignItems: 'center', gap: 12, fontSize: 12,
    }}>
      <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',
      }} />
      <span style={{ flex: 1, textAlign: 'left', color: 'var(--fg-secondary)' }}>
        {t("Listening for confirmation… click below once you've clicked the email link.", 'Ожидаем подтверждения… нажмите кнопку ниже после перехода по ссылке из письма.')}
      </span>
    </div>

    <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontSize: 11.5 }}>
      <a style={{ color: 'var(--gold-300)', cursor: 'pointer' }}>{t('Resend email', 'Отправить снова')}</a>
      <span style={{ color: 'var(--fg-disabled)' }}>·</span>
      <a style={{ color: 'var(--fg-tertiary)', cursor: 'pointer' }}>{t('Sent to wrong address?', 'Ошиблись в адресе?')}</a>
    </div>
  </div>
  );
};

window.BindAddressModal = BindAddressModal;
