/* eslint-disable */
// OnboardingFlow.jsx — Module 1 clickable flow.
// Screens: signup → email-verify → twofa-recommend → totp-bind →
//          kyb-intro → sumsub → bank → status-review → status-approved
// All input fields are controllable and typable.

const ONBOARDING_STEPS = {
  'signup':           { step: 1, label: 'Create account' },
  'email-verify':     { step: 2, label: 'Verify email' },
  'twofa-recommend':  { step: 3, label: 'Strengthen 2FA' },
  'totp-bind':        { step: 3, label: 'Bind authenticator' },
  'kyb-intro':        { step: 4, label: 'Verify business' },
  'sumsub':           { step: 4, label: 'Verify business · Sumsub' },
  'bank':             { step: 5, label: 'Bind settlement account' },
  'status-review':    { step: 6, label: 'Verification status' },
  'status-approved':  { step: 6, label: 'Verification status' },
};

const OnboardingFlow = ({ screen }) => {
  const { data, set } = usePrototype();
  const t = useT();
  const STEP_LABELS = {
    'signup':           t('Create account', 'Создать аккаунт'),
    'email-verify':     t('Verify email', 'Подтвердить e-mail'),
    'twofa-recommend':  t('Strengthen 2FA', 'Усилить 2FA'),
    'totp-bind':        t('Bind authenticator', 'Привязать аутентификатор'),
    'kyb-intro':        t('Verify business', 'Верификация бизнеса'),
    'sumsub':           t('Verify business · Sumsub', 'Верификация · Sumsub'),
    'bank':             t('Bind settlement account', 'Привязать расчётный счёт'),
    'status-review':    t('Verification status', 'Статус верификации'),
    'status-approved':  t('Verification status', 'Статус верификации'),
  };
  const cur = ONBOARDING_STEPS[screen] || ONBOARDING_STEPS.signup;
  const stepLabel = STEP_LABELS[screen] || cur.label;

  return (
    <AuthShell step={cur.step} stepLabel={stepLabel}>
      {screen === 'signup'          && <SignupScreen data={data} set={set} />}
      {screen === 'email-verify'    && <EmailVerifyScreen data={data} set={set} />}
      {screen === 'twofa-recommend' && <TwoFARecommendScreen />}
      {screen === 'totp-bind'       && <TOTPBindScreen data={data} set={set} />}
      {screen === 'kyb-intro'       && <KYBIntroScreen />}
      {screen === 'sumsub'          && <SumsubScreen />}
      {screen === 'bank'            && <BankBindScreen data={data} set={set} />}
      {screen === 'status-review'   && <KYBStatusReviewScreen />}
      {screen === 'status-approved' && <KYBStatusApprovedScreen />}
    </AuthShell>
  );
};

// =================================================================
// S1.1 — Sign up
// =================================================================
const SignupScreen = ({ data, set }) => {
  const t = useT();
  const [agreed, setAgreed] = React.useState(!!data.agreed);
  const email = data.email || '';
  const pwd = data.pwd || '';
  const pwd2 = data.pwd2 || '';
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const pwdValid = pwd.length >= 8 && /[A-Za-z]/.test(pwd) && /\d/.test(pwd);
  const matches = pwd === pwd2 && pwd.length > 0;
  const canContinue = emailValid && pwdValid && matches && agreed;

  const onContinue = () => {
    set({ agreed });
    navigateTo('onboarding', 'email-verify');
  };

  return (
    <div style={{ width: 480, display: 'flex', flexDirection: 'column', gap: 24 }}>
      <div>
        <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 26 }}>{t('Create your institutional account', 'Создалте институциональный аккаунт')}</h1>
        <p style={{ margin: 0, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55 }}>
          {t("KGST is issued to vetted institutional partners only. We'll verify your organisation in the next steps.", 'KGST выпускается только верифицированным институциональным партнёрам. На следующих этапах мы проведём проверку вашей организации.')}
        </p>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <TextField
          label={t('Work email', 'Рабочая эл. почта')}
          value={email}
          onChange={v => set({ email: v })}
          placeholder="you@institution.com"
          autoFocus
          type="email"
        />
        <TextField
          label={t('Password', 'Пароль')}
          value={pwd}
          onChange={v => set({ pwd: v })}
          placeholder={t('At least 8 characters', 'Не менее 8 символов')}
          type="password"
          helper={t('Minimum 8 characters · at least one letter and one number.', 'Минимум 8 символов · хотя бы одна буква и одна цифра.')}
        />
        <TextField
          label={t('Confirm password', 'Повторите пароль')}
          value={pwd2}
          onChange={v => set({ pwd2: v })}
          placeholder={t('Re-enter password', 'Введите пароль повторно')}
          type="password"
          error={pwd2.length > 0 && !matches ? t('Passwords do not match.', 'Пароли не совпадают.') : null}
          onEnter={() => canContinue && onContinue()}
        />

        <Checkbox checked={agreed} onChange={setAgreed}>
          {t('I agree to the ', 'Я согласен с ')}<span style={{ color: 'var(--gold-300)' }}>{t('Master Services Agreement', 'Основным соглашением об услугах')}</span>{t(', ', ', ')}
          <span style={{ color: 'var(--gold-300)' }}>{t('Privacy Notice', 'Политикой конфиденциальности')}</span>{t(', and confirm I am authorised to bind my organisation.', ' и подтверждаю полномочия действовать от имени организации.')}
        </Checkbox>
      </div>

      <Button size="lg" style={{ width: '100%' }} disabled={!canContinue} onClick={onContinue}>
        {t('Create account', 'Создать аккаунт')}
      </Button>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontSize: 12.5, color: 'var(--fg-tertiary)' }}>
        {t('Already have an account?', 'Уже есть аккаунт?')}
        <a style={{ color: 'var(--gold-300)', textDecoration: 'none', cursor: 'pointer' }}>{t('Sign in', 'Войти')}</a>
      </div>
    </div>
  );
};

// =================================================================
// S1.2 — Email verify
// =================================================================
const EmailVerifyScreen = ({ data, set }) => {
  const t = useT();
  const [code, setCode] = React.useState('');
  const timer = useCountdown(5 * 60);
  const onSubmit = () => {
    if (code.length === 6) navigateTo('onboarding', 'twofa-recommend');
  };
  return (
    <div style={{ width: 460, display: 'flex', flexDirection: 'column', gap: 24, alignItems: 'flex-start' }}>
      <div>
        <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 26 }}>{t('Check your inbox', 'Проверьте почту')}</h1>
        <p style={{ margin: 0, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55 }}>
          {t('We sent a 6-digit code to ', 'Мы отправили 6-значный код на ')}
          <span style={{ color: 'var(--fg-primary)', fontWeight: 500 }}>{data.email || t('your inbox', 'вашу почту')}</span>.
          {' '}{t('Enter it below within 5 minutes.', 'Введите код в течение 5 минут.')} <span style={{ color: 'var(--fg-tertiary)' }}>{t('(Type any 6 digits.)', '(Введите любые 6 цифр.)')}</span>
        </p>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Verification code', 'Код подтверждения')}</span>
        <OTPField value={code} onChange={setCode} autoFocus onComplete={onSubmit} />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 12 }}>
        <span style={{ color: 'var(--fg-tertiary)' }}>{t("Didn't get it?", 'Не пришёл код?')}</span>
        <a style={{ color: 'var(--gold-300)', cursor: 'pointer' }} onClick={() => timer.reset()}>{t('Resend code', 'Отправить снова')}</a>
        <span style={{ color: 'var(--fg-disabled)', fontFamily: 'var(--font-mono)' }}>· {timer.label}</span>
      </div>

      <div style={{
        marginTop: 4, padding: 14, borderRadius: 10,
        background: 'rgba(82,0,4,0.18)', border: '1px solid rgba(184,80,68,0.20)',
        display: 'flex', gap: 12, alignItems: 'flex-start', width: '100%',
      }}>
        <Icons.shield size={16} style={{ color: 'var(--wine-200)', marginTop: 1, flexShrink: 0 }} />
        <div style={{ fontSize: 12, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
          {t('Once verified, ', 'После подтверждения ')}<span style={{ color: 'var(--fg-primary)' }}>{t('email-based 2FA', '2FA по e-mail')}</span>{t(" is enabled by default. We'll prompt you for a code on every sensitive action — mint, burn, account changes.", ' включается по умолчанию. Код будет запрашиваться перед каждым критическим действием — эмиссия, погашение, изменения в аккаунте.')}
        </div>
      </div>

      <Button size="lg" style={{ width: '100%' }} disabled={code.length < 6} onClick={onSubmit}>
        {t('Verify and continue', 'Подтвердить и продолжить')}
      </Button>
    </div>
  );
};

// =================================================================
// S1.2a — Recommend stronger 2FA
// =================================================================
const TwoFARecommendScreen = () => {
  const t = useT();
  return (
  <div style={{ width: 540, display: 'flex', flexDirection: 'column', gap: 22 }}>
    <div>
      <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 26 }}>{t('Email 2FA is now active', '2FA по e-mail включена')}</h1>
      <p style={{ margin: 0, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55 }}>
        {t('Authenticator apps (TOTP) are stronger and faster than email codes. We strongly recommend upgrading before signing transactions.', 'Приложения-аутентификаторы (TOTP) надёжнее и быстрее кодов по e-mail. Рекомендуем перейти перед подписанием транзакций.')}
      </p>
    </div>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <OnbCompareRow recommended
        title={t('Authenticator app (TOTP)', 'Приложение-аутентификатор (TOTP)')}
        body={t('Google Authenticator, Authy, 1Password. Generates a fresh 6-digit code every 30 seconds, offline.', 'Google Authenticator, Authy, 1Password. Оффлайн каждые 30 сек генерирует 6-значный код.')}
        badges={[[t('Strongest', 'Надёжнее всех'), 'gold'], [t('Recommended', 'Рекомендуется'), 'wine']]}
      />
      <OnbCompareRow
        title={t('Email code', 'Код по e-mail')}
        body={t('Currently active. Vulnerable to inbox compromise and slower to deliver.', 'Активно сейчас. Уязвимо к компрометации почты, медленнее доставка.')}
        badges={[[t('Active fallback', 'Активный резерв'), 'neutral']]}
      />
    </div>

    <div style={{ display: 'flex', gap: 10 }}>
      <Button size="lg" style={{ flex: 1 }} onClick={() => navigateTo('onboarding', 'totp-bind')}>
        {t('Upgrade to authenticator', 'Перейти к аутентификатору')}
      </Button>
      <Button size="lg" variant="ghost" onClick={() => navigateTo('onboarding', 'kyb-intro')}>
        {t('Skip for now', 'Пропустить')}
      </Button>
    </div>
    <span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>
      {t('You can upgrade later in Account → Security.', 'Обновить можно позже в Аккаунт → Безопасность.')}
    </span>
  </div>
  );
};

const OnbCompareRow = ({ title, body, badges, recommended }) => (
  <div style={{
    padding: 16, borderRadius: 12,
    background: 'var(--ink-2)',
    border: `1px solid ${recommended ? 'var(--border-gold)' : 'var(--border-default)'}`,
    boxShadow: recommended ? '0 0 0 2px rgba(201,152,64,0.08)' : 'none',
    display: 'flex', flexDirection: 'column', gap: 8,
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
      <span style={{ fontWeight: 600, fontSize: 14 }}>{title}</span>
      {badges.map(([l, t], i) => <Pill key={i} tone={t} dot={t === 'gold'}>{l}</Pill>)}
    </div>
    <p style={{ margin: 0, fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>{body}</p>
  </div>
);

// =================================================================
// S1.2b — Bind authenticator (TOTP)
// =================================================================
const TOTPBindScreen = () => {
  const t = useT();
  const [code, setCode] = React.useState('');
  const onConfirm = () => {
    if (code.length === 6) navigateTo('onboarding', 'kyb-intro');
  };
  return (
    <div style={{ width: 620, display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 26 }}>{t('Scan to bind your authenticator', 'Привяжите аутентификатор')}</h1>
        <p style={{ margin: 0, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55 }}>
          {t('Scan the QR code with Google Authenticator, Authy, or 1Password. After scanning, enter the current 6-digit code to confirm.', 'Отсканируйте QR в Google Authenticator, Authy или 1Password. После сканирования введите текущий 6-значный код.')}
        </p>
      </div>

      <div style={{
        display: 'flex', gap: 24, padding: 20, borderRadius: 12,
        background: 'var(--ink-2)', border: '1px solid var(--border-default)',
      }}>
        <div style={{ flexShrink: 0 }}><QRPlaceholder size={180} data="kgst-totp-binance-asia" /></div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
          <div>
            <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Or enter this key manually', 'Или введите ключ вручную')}</span>
            <div className="kgst-mono" style={{
              marginTop: 6, padding: '10px 12px', background: 'var(--bg-inset)',
              borderRadius: 6, border: '1px solid var(--border-subtle)',
              fontSize: 12.5, color: 'var(--gold-300)', letterSpacing: '0.05em',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span>K6XQ&nbsp;7L9N&nbsp;FJ4S&nbsp;2T8R&nbsp;HB3V&nbsp;P5MC</span>
              <Icons.spark size={13} style={{ color: 'var(--bone-3)' }} />
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-tertiary)', marginTop: 6 }}>
              {t('Issuer', 'Эмитент')}: KGST · {t('30-second TOTP', '30-секундный TOTP')}
            </div>
          </div>

          <div style={{ marginTop: 4 }}>
            <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Confirmation code', 'Код подтверждения')}</span>
            <div style={{ marginTop: 8 }}>
              <OTPField value={code} onChange={setCode} autoFocus onComplete={onConfirm} />
            </div>
          </div>
        </div>
      </div>

      <div style={{
        padding: 12, borderRadius: 8,
        background: 'rgba(225,165,58,0.06)',
        border: '1px solid rgba(225,165,58,0.18)',
        fontSize: 12, color: 'var(--bone-5)',
        display: 'flex', gap: 10,
      }}>
        <Icons.shield size={14} style={{ color: 'var(--amber-400)', marginTop: 1, flexShrink: 0 }} />
        <span>{t('Email 2FA will be kept as a recovery fallback. You can reset it from Account → Security anytime.', '2FA по e-mail сохранится как резерв. Сбросить можно в Аккаунт → Безопасность.')}</span>
      </div>

      <div style={{ display: 'flex', gap: 10 }}>
        <Button size="lg" disabled={code.length < 6} style={{ flex: 1 }} onClick={onConfirm}>
          {t('Confirm and continue', 'Подтвердить и продолжить')}
        </Button>
        <Button size="lg" variant="ghost" onClick={() => navigateTo('onboarding', 'kyb-intro')}>{t('Skip', 'Пропустить')}</Button>
      </div>
    </div>
  );
};

// =================================================================
// S1.3 — KYB intro
// =================================================================
const KYBIntroScreen = () => {
  const t = useT();
  return (
  <div style={{ width: 620, display: 'flex', flexDirection: 'column', gap: 22 }}>
    <div>
      <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 26 }}>{t('Verify your business', 'Проверьте ваш бизнес')}</h1>
      <p style={{ margin: 0, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55, maxWidth: 540 }}>
        {t('KGST follows national regulations of the Kyrgyz Republic with strong KYC/AML protection. Verification is handled by our partner Sumsub. Have these ready before you start:', 'KGST соответствует национальным требованиям КР с проверками KYC/AML. Верификация проводится партнёром Sumsub. Подготовьте заранее:')}
      </p>
    </div>

    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <OnbChecklist icon="audit"  title={t('Certificate of incorporation', 'Свидетельство о регистрации')} body={t('PDF or JPG, max 10 MB.', 'PDF или JPG, до 10 МБ.')} />
      <OnbChecklist icon="audit"  title={t('Articles of association', 'Устав')} body={t('PDF or JPG, max 10 MB.', 'PDF или JPG, до 10 МБ.')} />
      <OnbChecklist icon="user"   title={t('Ultimate beneficial owners', 'Конечные бенефициары')} body={t('Anyone holding ≥ 25% — full name, share, passport.', 'Любой с долей ≥ 25 % — ФИО, доля, паспорт.')} />
      <OnbChecklist icon="shield" title={t('Authorised signer ID + liveness', 'Представитель: паспорт и liveness')} body={t('Passport scan and a short liveness check on camera.', 'Скан паспорта и короткая liveness-проверка.')} />
    </div>

    <div style={{
      padding: 14, borderRadius: 10,
      background: 'var(--ink-2)', border: '1px solid var(--border-default)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Icons.clock size={16} style={{ color: 'var(--gold-300)' }} />
        <div>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{t('Typical turnaround: under 2 business days', 'Срок рассмотрения: менее 2 раб. дней')}</div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)' }}>{t('We notify you by email and in-console once a decision is made.', 'Об итоге сообщим на e-mail и в консоли.')}</div>
        </div>
      </div>
    </div>

    <div style={{ display: 'flex', gap: 10 }}>
      <Button size="lg" style={{ flex: 1 }} iconRight={<Icons.arrowRight size={14} />}
        onClick={() => navigateTo('onboarding', 'sumsub')}>
        {t('Start verification', 'Начать верификацию')}
      </Button>
      <Button size="lg" variant="ghost" onClick={() => navigateTo('menu')}>{t('Save and exit', 'Сохранить и выйти')}</Button>
    </div>
  </div>
  );
};

const OnbChecklist = ({ icon, title, body }) => {
  const I = Icons[icon];
  return (
    <div style={{
      padding: 14, borderRadius: 10,
      background: 'var(--ink-2)', border: '1px solid var(--border-default)',
      display: 'flex', gap: 12,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: '50%',
        background: 'rgba(201,152,64,0.08)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--gold-300)', flexShrink: 0,
      }}><I size={15} /></div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{title}</div>
        <div style={{ fontSize: 11.5, color: 'var(--fg-tertiary)', marginTop: 2 }}>{body}</div>
      </div>
    </div>
  );
};

// =================================================================
// S1.4 — Sumsub (mocked iframe). "Continue (simulated)" → bank
// =================================================================
const SumsubScreen = () => {
  const t = useT();
  const [steps, setSteps] = React.useState(0);
  const total = 4;
  const stepLabels = [t('Company details', 'Данные компании'), t('Beneficial owners', 'Бенефициары'), t('Signer ID', 'Представитель'), t('Liveness check', 'Liveness-проверка')];

  return (
    <div style={{ width: 740, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 24 }}>{t('Business verification', 'Верификация бизнеса')}</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--fg-tertiary)' }}>
          <Icons.shield size={12} />
          <span>{t('Secured by our partner Sumsub · You are on', 'Защищено партнёром Sumsub · вы на')} <span style={{ color: 'var(--gold-300)' }}>kgst.kg</span></span>
        </div>
      </div>

      <div style={{
        position: 'relative', minHeight: 420, borderRadius: 12, overflow: 'hidden',
        border: '1.5px dashed rgba(201,152,64,0.35)',
        background:
          'repeating-linear-gradient(135deg, rgba(201,152,64,0.025) 0 12px, transparent 12px 24px), var(--ink-2)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 28,
      }}>
        <div style={{ textAlign: 'center', maxWidth: 420, width: '100%' }}>
          <div style={{
            width: 56, height: 56, margin: '0 auto 16px', borderRadius: 12,
            background: 'rgba(201,152,64,0.08)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: '1px solid var(--border-gold)',
          }}>
            <Icons.shield size={24} style={{ color: 'var(--gold-300)' }} />
          </div>
          <div className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t('Sumsub WebSDK iframe · simulated', 'Sumsub WebSDK · эмуляция')}</div>
          <div style={{ marginTop: 8, fontSize: 14, fontWeight: 500 }}>
            {steps < total ? stepLabels[steps] : t('All steps captured', 'Все шаги выполнены')}
          </div>
          <div style={{ marginTop: 6, fontSize: 12, color: 'var(--fg-tertiary)', lineHeight: 1.55, marginBottom: 22 }}>
            {t("In production, this region hosts Sumsub's embedded flow. Click below to simulate completing each step.", 'В продакшене здесь Sumsub’овский iframe. Ниже имитируем прохождение шагов.')}
          </div>

          {/* progress dots */}
          <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 22 }}>
            {stepLabels.map((_, i) => (
              <span key={i} style={{
                width: i < steps ? 22 : 8, height: 8, borderRadius: 999,
                background: i < steps ? 'var(--gold-400)' : i === steps ? 'rgba(201,152,64,0.30)' : 'var(--ink-4)',
                transition: 'width 200ms ease, background 200ms ease',
              }} />
            ))}
          </div>

          {steps < total ? (
            <Button onClick={() => setSteps(s => s + 1)} size="md" iconRight={<Icons.arrowRight size={13} />}>
              {t('Complete', 'Завершить')} “{stepLabels[steps]}”
            </Button>
          ) : (
            <Button size="md" iconRight={<Icons.arrowRight size={13} />}
              onClick={() => navigateTo('onboarding', 'bank')}>
              {t('Continue to bank binding', 'Перейти к привязке банка')}
            </Button>
          )}
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: 'var(--fg-tertiary)' }}>
        <span>{t('Auto-saved · Your progress is preserved if you leave this page.', 'Автосохранение · ваш прогресс сохранится, если вы уйдёте.')}</span>
        <a style={{ color: 'var(--gold-300)', cursor: 'pointer' }}>{t('Need help with KYB?', 'Нужна помощь с KYB?')}</a>
      </div>
    </div>
  );
};

// =================================================================
// S1.5 — Bind settlement bank account (OPTIONAL during onboarding;
// can be added later from Account → Bank Accounts).
// =================================================================
const BankBindScreen = ({ data, set }) => {
  const t = useT();
  const fields = [
    ['bankName',   t('Bank name', 'Название банка'),               t('e.g. Optima Bank OJSC', 'напр. Optima Bank OJSC'),          false],
    ['swift',      'SWIFT / BIC',                                                                                  t('e.g. ENEJKG22', 'напр. ENEJKG22'),                  true],
    ['acctNum',    t('Account number', 'Номер счёта'),               t('e.g. 1170070240005611', 'напр. 1170070240005611'),          true],
    ['acctHolder', t('Account holder name', 'Имя владельца'), t('Must match your verified business', 'Должно совпадать с верифицированным бизнесом'), false],
    ['country',    t('Bank country', 'Страна банка'),               t('e.g. Kyrgyzstan', 'напр. Кыргызстан'),                false],
  ];
  const anyFilled = fields.some(([k]) => (data[k] || '').trim().length > 0);
  const allFilled = fields.every(([k]) => (data[k] || '').trim().length > 0);

  const onSubmit = () => {
    if (allFilled) navigateTo('onboarding', 'status-review');
  };
  const onSkip = () => navigateTo('onboarding', 'status-review');

  return (
    <div style={{ width: 560, display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 className="kgst-h2" style={{ margin: '0 0 6px', fontSize: 26 }}>
          {t('Bind a settlement bank account', 'Привяжите банковский счет для расчетов')}
          <span style={{ marginLeft: 10, fontSize: 11, color: 'var(--fg-tertiary)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase', verticalAlign: 'middle' }}>{t('Optional', 'Необязательно')}</span>
        </h1>
        <p style={{ margin: 0, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55 }}>
          {t('When you redeem (burn) KGST, Kyrgyz som is wired out via RTGS to this account.', 'При погашении (burn) KGST сомы отправляются через RTGS на этот счёт.')}
          {' '}{t('You can do this later from', 'Привязать можно позже в')} <span style={{ color: 'var(--fg-primary)' }}>{t('Account → Bank Accounts', 'Аккаунт → Банковские счета')}</span> {t('— mint will still work without one bound.', '— эмиссия работает и без привязки.')}
        </p>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {fields.map(([k, label, placeholder, mono], i) => (
          <TextField
            key={k}
            label={label}
            value={data[k] || ''}
            onChange={v => set({ [k]: v })}
            placeholder={placeholder}
            mono={mono}
            autoFocus={i === 0}
          />
        ))}
      </div>

      <div style={{
        padding: 12, borderRadius: 8,
        background: 'rgba(93,139,217,0.06)',
        border: '1px solid rgba(93,139,217,0.20)',
        fontSize: 12, color: 'var(--bone-5)',
        display: 'flex', gap: 10,
      }}>
        <Icons.shield size={14} style={{ color: 'var(--blue-400)', marginTop: 1, flexShrink: 0 }} />
        <span>{t('Account holder must match the verified business name on KYB. Mismatches will block redemptions and require human review.', 'Имя владельца счета должно совпадать с названием бизнеса в KYB. Несовпадения блокируют погашения и потребуют ручной проверки.')}</span>
      </div>

      <div style={{ display: 'flex', gap: 10 }}>
        <Button size="lg" style={{ flex: 1 }} disabled={!allFilled}
          iconRight={<Icons.arrowRight size={14} />} onClick={onSubmit}>
          {t('Save and submit for review', 'Сохранить и отправить')}
        </Button>
        <Button size="lg" variant="ghost" onClick={onSkip}>
          {anyFilled ? t('Skip for now', 'Пропустить') : t('Skip — I\'ll add this later', 'Пропустить — добавлю позже')}
        </Button>
      </div>
      <div style={{ marginTop: -10, fontSize: 11, color: 'var(--fg-tertiary)' }}>
        {t('Burns are paused until a settlement bank is bound — you can still mint, hold, and transfer KGST.', 'Погашения приостановлены, пока не привязан банковский счёт — но эмитировать, хранить и переводить KGST можно.')}
      </div>
    </div>
  );
};

// =================================================================
// S1.6 — KYB status (review then auto-advances to approved)
// =================================================================
const KYBStatusReviewScreen = () => {
  const { data } = usePrototype();
  const t = useT();
  const bankFilled = !!(data.bankName || '').trim();
  useDelayedAdvance(5000, () => navigateTo('onboarding', 'status-approved'));
  const T_RECEIVED = t('Received', 'Получено');
  const T_INREVIEW = t('In review', 'На рассмотрении');
  const T_SKIPPED  = t('Skipped — add later', 'Пропущено — позже');
  return (
    <div style={{ width: 640, display: 'flex', flexDirection: 'column', gap: 22 }}>
      <h1 className="kgst-h2" style={{ margin: 0, fontSize: 26 }}>{t('Verification status', 'Статус верификации')}</h1>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
        {[[t('Under review', 'На рассмотрении'), true], [t('Approved', 'Одобрено'), false], [t('Action required', 'Требуется действие'), false]].map(([l, active], i) => (
          <div key={i} style={{
            padding: '8px 12px', borderRadius: 8,
            border: '1px solid ' + (active ? 'var(--border-gold)' : 'var(--border-default)'),
            background: active ? 'rgba(201,152,64,0.06)' : 'var(--ink-2)',
            fontSize: 11, color: 'var(--fg-tertiary)', textAlign: 'center',
          }}>{l}</div>
        ))}
      </div>

      <div style={{
        padding: 24, borderRadius: 14,
        background: 'var(--ink-2)', border: '1px solid var(--border-default)',
        display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Pill tone="warning">{t('Under review', 'На рассмотрении')}</Pill>
          <span style={{ fontSize: 12, color: 'var(--fg-tertiary)' }}>{t('Submitted just now · auto-advancing in 5s', 'Отправлено только что · автопереход через 5 сек')}</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            [t('Company documents', 'Документы компании'), T_RECEIVED, 'ok'],
            [t('Beneficial owners', 'Бенефициары'), T_RECEIVED, 'ok'],
            [t('Authorised signer ID + liveness', 'Представитель: паспорт и liveness'), T_INREVIEW, 'review'],
            [t('Settlement bank account', 'Банковский счёт'), bankFilled ? T_RECEIVED : T_SKIPPED, bankFilled ? 'ok' : 'skip'],
          ].map(([k, v, tone], i) => (
            <div key={i} style={{
              display: 'flex', justifyContent: 'space-between', padding: '8px 0',
              borderTop: i === 0 ? 'none' : '1px solid var(--border-subtle)', fontSize: 13,
            }}>
              <span style={{ color: 'var(--fg-secondary)' }}>{k}</span>
              <span style={{ color: tone === 'review' ? 'var(--amber-400)' : tone === 'skip' ? 'var(--fg-tertiary)' : 'var(--bone-5)' }}>{v}</span>
            </div>
          ))}
        </div>
        <Button size="md" variant="ghost">{t('Refresh status', 'Обновить статус')}</Button>
      </div>
    </div>
  );
};

const KYBStatusApprovedScreen = () => {
  const { set } = usePrototype();
  const t = useT();
  React.useEffect(() => { set({ kybApproved: true }); }, []); // eslint-disable-line
  return (
    <div style={{ width: 640, display: 'flex', flexDirection: 'column', gap: 22 }}>
      <h1 className="kgst-h2" style={{ margin: 0, fontSize: 26 }}>{t('Verification status', 'Статус верификации')}</h1>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
        {[[t('Under review', 'На рассмотрении'), false], [t('Approved', 'Одобрено'), true], [t('Action required', 'Требуется действие'), false]].map(([l, active], i) => (
          <div key={i} style={{
            padding: '8px 12px', borderRadius: 8,
            border: '1px solid ' + (active ? 'var(--border-gold)' : 'var(--border-default)'),
            background: active ? 'rgba(201,152,64,0.06)' : 'var(--ink-2)',
            fontSize: 11, color: 'var(--fg-tertiary)', textAlign: 'center',
          }}>{l}</div>
        ))}
      </div>

      <div style={{
        padding: 24, borderRadius: 14,
        background: 'var(--ink-2)', border: '1px solid var(--border-default)',
        display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Pill tone="success">{t('Approved', 'Одобрено')}</Pill>
          <span style={{ fontSize: 12, color: 'var(--fg-tertiary)' }}>{t('Approved just now · Mint and burn unlocked.', 'Одобрено только что · эмиссия и погашение разблокированы.')}</span>
        </div>
        <div style={{
          padding: 16, borderRadius: 10, position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(135deg, rgba(82,0,4,0.35), rgba(201,152,64,0.08))',
          border: '1px solid var(--border-gold)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <SealDot size={36} />
            <div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{t('Welcome to KGST.', 'Добро пожаловать в KGST.')}</div>
              <div style={{ fontSize: 12, color: 'var(--bone-4)', marginTop: 4 }}>
                {t('Your account ID is', 'Ваш ID аккаунта:')} <span className="kgst-mono" style={{ color: 'var(--gold-300)' }}>KGST-INST-00214</span>.
              </div>
            </div>
          </div>
          <span style={{
            position: 'absolute', inset: 0, background: 'linear-gradient(90deg, transparent, rgba(255,244,219,0.10), transparent)',
            animation: 'kgstShimmer 2.4s ease-in-out infinite',
          }} />
        </div>
        <Button size="md" iconRight={<Icons.arrowRight size={14} />}
          onClick={() => navigateTo('dashboard', 'home')}>
          {t('Enter console', 'Открыть консоль')}
        </Button>
      </div>
    </div>
  );
};

window.OnboardingFlow = OnboardingFlow;
