// pesito — Apply form sheet (8 real steps, real inputs, real submission)

const ApplySheet = ({ lang, open, onClose, principal, term, quincenal, total }) => {
  const [step, setStep] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [result, setResult] = React.useState(null);
  // OTP state — phone is verified by SMS code via /apply/{id}/otp/{send,verify}
  const [appId, setAppId] = React.useState(null);
  const [otpSending, setOtpSending] = React.useState(false);
  const [otpVerifying, setOtpVerifying] = React.useState(false);
  const [otpSent, setOtpSent] = React.useState(false);
  const [otpCode, setOtpCode] = React.useState('');
  const [otpError, setOtpError] = React.useState('');
  const [otpCooldown, setOtpCooldown] = React.useState(0);
  React.useEffect(() => {
    if (otpCooldown > 0) {
      const id = setTimeout(() => setOtpCooldown(otpCooldown - 1), 1000);
      return () => clearTimeout(id);
    }
  }, [otpCooldown]);
  const [form, setForm] = React.useState({
    // step 1 — Tú
    firstName: '', lastName: '', secondLastName: '',
    gender: '', dob: '', maritalStatus: '', nationality: 'MX',
    // step 2 — Contacto
    phone: '+52 ', phoneVerified: false, email: '', secondaryPhone: '',
    // step 2.5 — Address (lives with contact in MX flow)
    addrStreet: '', addrExterior: '', addrInterior: '',
    addrColonia: '', addrCity: '', addrState: '', addrCp: '',
    addrYears: '',
    // step 3 — Trabajo
    employmentStatus: '', employer: '', jobTitle: '',
    monthlyIncome: '', yearsAtJob: '', incomeType: '',
    // step 4 — Banco
    clabe: '',
    // step 5 — Documentos
    idDocType: 'INE', idDocNumber: '', idDocExpiry: '',
    curp: '', rfc: '',
    // step 6 — Referencias
    refs: [
      { name: '', phone: '', relation: '' },
      { name: '', phone: '', relation: '' },
    ],
    // step 7 — Confirmar (consent)
    contractAccepted: true, privacyAccepted: true, buroAccepted: true,
  });

  React.useEffect(() => {
    if (open) {
      setStep(0); setDone(false); setSubmitting(false); setResult(null);
      setAppId(null); setOtpSent(false); setOtpCode(''); setOtpError(''); setOtpCooldown(0);
    }
  }, [open]);

  // Lazy-create the Application so we have an id for OTP send/verify.
  // Idempotent within a single sheet open: first call creates, subsequent return cached id.
  async function ensureApp() {
    if (appId) return appId;
    const r = await fetch('/api/v1/apply/start', {
      method: 'POST', headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ amount: principal, termCount: term, termUnit: 'quincena' }),
    });
    if (!r.ok) throw new Error('start failed: ' + r.status);
    const j = await r.json();
    setAppId(j.applicationId);
    return j.applicationId;
  }

  async function sendOtp() {
    setOtpError(''); setOtpSending(true);
    try {
      const id = await ensureApp();
      const phone = (form.phone || '').replace(/\s+/g, '');
      const r = await fetch('/api/v1/apply/' + id + '/otp/send', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ phone }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok || j.ok === false) {
        if (j.reason === 'cooldown' && j.cooldown) {
          setOtpCooldown(j.cooldown);
          setOtpError(lang === 'es'
            ? `Espera ${j.cooldown}s para reenviar`
            : `Подождите ${j.cooldown} с до повторной отправки`);
        } else {
          setOtpError(lang === 'es' ? 'No se pudo enviar el código' : 'Не удалось отправить код');
        }
        return;
      }
      setOtpSent(true);
      setOtpCooldown(30);
    } catch (e) {
      setOtpError(String(e.message || e));
    } finally {
      setOtpSending(false);
    }
  }

  async function verifyOtp() {
    setOtpError(''); setOtpVerifying(true);
    try {
      const id = await ensureApp();
      const phone = (form.phone || '').replace(/\s+/g, '');
      const r = await fetch('/api/v1/apply/' + id + '/otp/verify', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ phone, code: otpCode }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok || j.ok === false) {
        setOtpError(lang === 'es' ? 'Código incorrecto' : 'Неверный код');
        return;
      }
      set('phoneVerified', true);
    } catch (e) {
      setOtpError(String(e.message || e));
    } finally {
      setOtpVerifying(false);
    }
  }

  const set = (k, v) => setForm(prev => ({ ...prev, [k]: v }));
  const setRef = (i, k, v) => setForm(prev => ({
    ...prev,
    refs: prev.refs.map((r, idx) => idx === i ? { ...r, [k]: v } : r),
  }));

  // Sandbox demo: phones in +52 55 0000 0001..0999 auto-mark verified
  // and prefill identity to keep the path runnable end-to-end.
  function fillDemoIfSandboxPhone(phoneValue) {
    // React state is async — callers must pass the current phone string
    // directly (e.g. from the input event) rather than relying on form.phone closure.
    const norm = (phoneValue || form.phone || '').replace(/\s+/g, '');
    if (/^\+?525500000\d{3}$/.test(norm)) {  // matches +52 55 0000 0001..0999
      // NB: phoneVerified is no longer set here — user still has to send and
      // verify the OTP. Demo phones get TEST_MAGIC_CODE 000000 from the backend
      // so it stays trivial to verify, but the verification flow still runs.
      setForm(prev => ({
        ...prev,
        firstName: prev.firstName || 'Demo',
        lastName: prev.lastName || 'Borrower',
        secondLastName: prev.secondLastName || 'Test',
        gender: prev.gender || 'F',
        dob: prev.dob || '1990-01-15',
        maritalStatus: prev.maritalStatus || 'single',
        email: prev.email || 'demo-' + Date.now() + '@test.mx',
        addrStreet: prev.addrStreet || 'Av Reforma',
        addrExterior: prev.addrExterior || '100',
        addrColonia: prev.addrColonia || 'Centro',
        addrCity: prev.addrCity || 'CDMX',
        addrState: prev.addrState || 'CDMX',
        addrCp: prev.addrCp || '06600',
        addrYears: prev.addrYears || '5',
        employmentStatus: prev.employmentStatus || 'employed',
        employer: prev.employer || 'Test Co',
        jobTitle: prev.jobTitle || 'Engineer',
        monthlyIncome: prev.monthlyIncome || '25000',
        yearsAtJob: prev.yearsAtJob || '3',
        incomeType: prev.incomeType || 'salary',
        clabe: prev.clabe || '012180001234567899',
        idDocNumber: prev.idDocNumber || '0000000000',
        idDocExpiry: prev.idDocExpiry || '2030-01-01',
        curp: prev.curp || 'HEGJ850315HDFLNSA9',
        rfc: prev.rfc || 'XAXX010101000',
        refs: prev.refs[0].name ? prev.refs : [
          { name: 'Carlos Reyes', phone: '+525500000088', relation: 'family' },
          { name: 'Lucía Méndez', phone: '+525500000077', relation: 'friend' },
        ],
      }));
    }
  }

  // Per-step gate: which fields are required before "Siguiente" enables.
  function canProceed() {
    if (step === 0) return true;  // monto/plazo come from calculator
    if (step === 1) return form.firstName && form.lastName && form.dob && form.gender;
    if (step === 2) return /\d{10,}/.test(form.phone) && /\S+@\S+\.\S+/.test(form.email)
                       && form.addrStreet && form.addrCity && form.addrCp
                       && form.phoneVerified;
    if (step === 3) return form.employmentStatus &&
                       (form.employmentStatus === 'unemployed' || form.monthlyIncome);
    if (step === 4) return /^\d{18}$/.test((form.clabe || '').replace(/\s+/g, ''));
    if (step === 5) return form.idDocNumber && form.curp && form.rfc;
    if (step === 6) return form.refs[0].name && form.refs[0].phone &&
                       form.refs[1].name && form.refs[1].phone;
    if (step === 7) return form.contractAccepted && form.privacyAccepted && form.buroAccepted;
    return true;
  }

  async function submitApplication() {
    setSubmitting(true);
    try {
      const applicationId = await ensureApp();

      const data = {
        firstName: form.firstName, lastName: form.lastName, secondLastName: form.secondLastName,
        gender: form.gender, maritalStatus: form.maritalStatus, nationality: form.nationality,
        dob: form.dob,
        phone: form.phone.replace(/\s+/g, ''), phoneVerified: form.phoneVerified,
        email: form.email, secondaryPhone: form.secondaryPhone.replace(/\s+/g, '') || undefined,
        address: {
          street: form.addrStreet, exterior: form.addrExterior, interior: form.addrInterior,
          colonia: form.addrColonia, city: form.addrCity, state: form.addrState, cp: form.addrCp,
          yearsAtAddress: Number(form.addrYears) || 0,
        },
        employment: {
          status: form.employmentStatus, employer: form.employer, jobTitle: form.jobTitle,
          monthlyIncome: Number(form.monthlyIncome) || 0,
          yearsAtJob: Number(form.yearsAtJob) || 0,
          incomeType: form.incomeType,
        },
        clabe: form.clabe.replace(/\s+/g, ''),
        idDocType: form.idDocType, idDocNumber: form.idDocNumber, idDocExpiry: form.idDocExpiry,
        curp: form.curp.toUpperCase(), rfc: form.rfc.toUpperCase(),
        references: form.refs.filter(r => r.name && r.phone)
          .map(r => ({ ...r, phone: r.phone.replace(/\s+/g, '') })),
        consents: {
          contract: form.contractAccepted, privacy: form.privacyAccepted,
          buroDeCredito: form.buroAccepted,
        },
      };
      const dataRes = await fetch('/api/v1/apply/' + applicationId + '/data', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify(data),
      });
      if (!dataRes.ok) throw new Error('data failed: ' + dataRes.status);

      const submitRes = await fetch('/api/v1/apply/' + applicationId + '/submit', {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}',
      });
      const sb = await submitRes.json().catch(() => ({}));
      if (!submitRes.ok) throw new Error(sb.error || ('submit failed: ' + submitRes.status));

      setResult({ applicationId, status: sb.decision || 'SUBMITTED', offer: sb.offer });
      setDone(true);
    } catch (e) {
      setResult({ error: String(e.message || e) });
      setDone(true);
    } finally {
      setSubmitting(false);
    }
  }

  if (!open) return null;
  const stepsEs = ['Monto y plazo', 'Tú', 'Contacto', 'Trabajo', 'Banco', 'Documentos', 'Referencias', 'Confirmar'];
  const stepsRu = ['Сумма и срок', 'Вы', 'Контакт', 'Работа', 'Банк', 'Документы', 'Контакты', 'Подтвердить'];
  const steps = lang === 'es' ? stepsEs : stepsRu;

  const t = lang === 'es' ? {
    title: 'Solicitud express', sub: '8 pasos. La mayoría tarda 3 minutos.',
    summary: 'Tu préstamo',
    contract: 'He leído y acepto el contrato y el aviso de privacidad.',
    privacy: 'Acepto el tratamiento de datos personales.',
    buro: 'Autorizo consulta a Buró de Crédito.',
    sign: 'Firmar y solicitar', next: 'Siguiente', back: 'Volver',
    confirmTitle: '¿Todo en orden?',
    confirmSub: 'Esto es lo que vas a firmar. Léelo, dilo en voz alta si quieres. Nadie te apura.',
    successTitle: '¡Listo!',
    successSub: 'Tu solicitud está en revisión. Te avisamos por SMS y WhatsApp en menos de 2 minutos.',
  } : {
    title: 'Экспресс-заявка', sub: '8 шагов. У большинства уходит 3 минуты.',
    summary: 'Ваш заём',
    contract: 'Прочитал и принимаю договор и уведомление о приватности.',
    privacy: 'Согласен на обработку персональных данных.',
    buro: 'Разрешаю запрос в Бюро Кредитных Историй.',
    sign: 'Подписать и подать', next: 'Далее', back: 'Назад',
    confirmTitle: 'Всё в порядке?', confirmSub: 'Вот что вы подпишете. Читайте, не торопим.',
    successTitle: 'Готово!',
    successSub: 'Заявка на проверке. Сообщим по SMS и WhatsApp за 2 минуты.',
  };
  const cat = 518;

  // ─── Field primitives ─────────────────────────────────────────────
  const fieldStyle = {
    width: '100%', font: '500 16px var(--font-body)',
    background: 'var(--surface-2)', border: '1px solid var(--line)',
    borderRadius: 10, padding: '13px 14px', color: 'var(--ink)',
    transition: 'border-color 160ms ease, background 160ms ease',
    outline: 'none',
  };
  const labelStyle = {
    display: 'block',
    fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 11,
    letterSpacing: '0.12em', textTransform: 'uppercase',
    color: 'var(--ink-soft)', marginBottom: 6,
  };
  const Field = ({ label, children, hint }) => (
    <label style={{ display: 'block', marginBottom: 12 }}>
      <span style={labelStyle}>{label}</span>
      {children}
      {hint && <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 4 }}>{hint}</div>}
    </label>
  );
  const Input = (p) => <input {...p} style={{ ...fieldStyle, ...(p.style || {}) }} />;
  const Select = ({ children, ...p }) => <select {...p} style={{ ...fieldStyle, appearance: 'auto' }}>{children}</select>;
  const Row = ({ children, cols = 2 }) => (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 10, marginBottom: 12 }}>
      {children}
    </div>
  );

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 110,
      background: 'rgba(40, 25, 15, 0.55)',
      backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      animation: 'fadeIn 200ms ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--surface)', borderRadius: '24px 24px 0 0',
        width: '100%', maxWidth: 580, padding: 24, paddingBottom: 20,
        animation: 'sheetIn 360ms cubic-bezier(0.2, 0.8, 0.2, 1)',
        boxShadow: '0 -10px 40px rgba(63,38,24,0.2)',
        maxHeight: '94vh', overflow: 'auto',
      }}>
        <div style={{ width: 36, height: 5, borderRadius: 999, background: 'var(--line)', margin: '0 auto 16px' }} />

        {!done ? (
          <React.Fragment>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
              <div>
                <div className="eyebrow" style={{ marginBottom: 4 }}>{t.title}</div>
                <div style={{ fontSize: 13, color: 'var(--char-2)' }}>{t.sub}</div>
              </div>
              <button onClick={onClose} aria-label="close" style={{
                background: 'var(--surface-2)', border: 'none', width: 32, height: 32,
                borderRadius: 999, cursor: 'pointer', display: 'flex',
                alignItems: 'center', justifyContent: 'center',
              }}>
                <I.close />
              </button>
            </div>

            {/* Stepper bar */}
            <div style={{ display: 'flex', gap: 4, marginBottom: 16 }}>
              {steps.map((s, i) => (
                <div key={i} style={{
                  flex: 1, height: 3, borderRadius: 999,
                  background: i <= step ? 'var(--brand)' : 'var(--surface-3)',
                  transition: 'background 220ms ease',
                }} />
              ))}
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-soft)', fontFamily: 'var(--font-mono)', marginBottom: 16, letterSpacing: '0.04em' }}>
              {String(step + 1).padStart(2, '0')} / {String(steps.length).padStart(2, '0')} · {steps[step]}
            </div>

            {/* ─── STEP 0 — Monto y plazo (read-only summary; sliders live on landing) ─── */}
            {step === 0 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 16 }}>
                  {lang === 'es' ? '¿Cuánto y por cuánto?' : 'Сколько и насколько?'}
                </div>
                <div style={{ background: 'var(--surface-2)', borderRadius: 14, padding: 16, marginBottom: 10 }}>
                  <div style={labelStyle}>{lang === 'es' ? 'Monto' : 'Сумма'}</div>
                  <div className="display tabular" style={{ fontSize: 40, fontWeight: 600, lineHeight: 1 }}>
                    ${principal.toLocaleString('en-US')}
                    <span style={{ fontSize: 14, color: 'var(--ink-soft)', marginLeft: 6, fontWeight: 500 }}>MXN</span>
                  </div>
                </div>
                <div style={{ background: 'var(--surface-2)', borderRadius: 14, padding: 16 }}>
                  <div style={labelStyle}>{lang === 'es' ? 'Plazo' : 'Срок'}</div>
                  <div className="display tabular" style={{ fontSize: 40, fontWeight: 600, lineHeight: 1 }}>
                    {term}
                    <span style={{ fontSize: 14, color: 'var(--ink-soft)', marginLeft: 6, fontWeight: 500 }}>
                      {lang === 'es' ? 'quincenas' : 'двухнед.'}
                    </span>
                  </div>
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 10, lineHeight: 1.5 }}>
                  {lang === 'es'
                    ? 'Para cambiar, cierra y mueve los sliders en la calculadora.'
                    : 'Чтобы изменить, закрой и подвинь ползунки в калькуляторе.'}
                </div>
              </div>
            )}

            {/* ─── STEP 1 — Tú (identity) ─── */}
            {step === 1 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 14 }}>
                  {lang === 'es' ? 'Cuéntanos de ti' : 'Расскажите о себе'}
                </div>
                <Row>
                  <Field label={lang === 'es' ? 'Nombre' : 'Имя'}>
                    <Input value={form.firstName} onChange={e => set('firstName', e.target.value)} />
                  </Field>
                  <Field label={lang === 'es' ? 'Apellido paterno' : 'Фамилия'}>
                    <Input value={form.lastName} onChange={e => set('lastName', e.target.value)} />
                  </Field>
                </Row>
                <Field label={lang === 'es' ? 'Apellido materno' : 'Отчество'}>
                  <Input value={form.secondLastName} onChange={e => set('secondLastName', e.target.value)} />
                </Field>
                <Row>
                  <Field label={lang === 'es' ? 'Fecha de nacimiento' : 'Дата рождения'}>
                    <Input type="date" value={form.dob} onChange={e => set('dob', e.target.value)} />
                  </Field>
                  <Field label={lang === 'es' ? 'Sexo' : 'Пол'}>
                    <Select value={form.gender} onChange={e => set('gender', e.target.value)}>
                      <option value="">—</option>
                      <option value="F">{lang === 'es' ? 'Femenino' : 'Женский'}</option>
                      <option value="M">{lang === 'es' ? 'Masculino' : 'Мужской'}</option>
                      <option value="X">{lang === 'es' ? 'No binario' : 'Другой'}</option>
                    </Select>
                  </Field>
                </Row>
                <Field label={lang === 'es' ? 'Estado civil' : 'Семейное положение'}>
                  <Select value={form.maritalStatus} onChange={e => set('maritalStatus', e.target.value)}>
                    <option value="">—</option>
                    <option value="single">{lang === 'es' ? 'Soltero/a' : 'Холост/незамужем'}</option>
                    <option value="married">{lang === 'es' ? 'Casado/a' : 'В браке'}</option>
                    <option value="divorced">{lang === 'es' ? 'Divorciado/a' : 'В разводе'}</option>
                    <option value="widowed">{lang === 'es' ? 'Viudo/a' : 'Вдовец/Вдова'}</option>
                    <option value="other">{lang === 'es' ? 'Otro' : 'Другое'}</option>
                  </Select>
                </Field>
              </div>
            )}

            {/* ─── STEP 2 — Contacto + dirección ─── */}
            {step === 2 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 14 }}>
                  {lang === 'es' ? '¿Cómo te contactamos?' : 'Как с вами связаться?'}
                </div>
                <Field label={lang === 'es' ? 'Teléfono móvil' : 'Мобильный'} hint={lang === 'es' ? 'Para SMS y WhatsApp.' : 'Для SMS и WhatsApp.'}>
                  <Input
                    type="tel" value={form.phone}
                    onChange={e => {
                      set('phone', e.target.value);
                      // changing the phone invalidates any prior verification
                      if (form.phoneVerified) set('phoneVerified', false);
                      if (otpSent) { setOtpSent(false); setOtpCode(''); setOtpError(''); }
                      fillDemoIfSandboxPhone(e.target.value);
                    }}
                    placeholder="+52 55 1234 5678"
                  />
                </Field>

                {/* OTP verification — phone must be confirmed by SMS code */}
                {form.phoneVerified ? (
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    background: 'oklch(0.95 0.04 155)', color: 'oklch(0.40 0.13 155)',
                    padding: '8px 14px', borderRadius: 999,
                    fontSize: 13, fontWeight: 600, letterSpacing: '0.04em',
                    marginBottom: 16,
                  }}>
                    <I.check />
                    {lang === 'es' ? 'Teléfono verificado' : 'Телефон подтверждён'}
                  </div>
                ) : !otpSent ? (
                  <div style={{ marginBottom: 16 }}>
                    <button
                      className="btn btn-ghost"
                      type="button"
                      onClick={sendOtp}
                      disabled={otpSending || !/\d{10,}/.test(form.phone)}
                      style={{ padding: '12px 18px', fontSize: 14, opacity: otpSending ? 0.6 : 1 }}
                    >
                      {otpSending
                        ? (lang === 'es' ? 'Enviando…' : 'Отправка…')
                        : (lang === 'es' ? 'Verificar teléfono por SMS' : 'Подтвердить телефон по SMS')}
                    </button>
                    {otpError && (
                      <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 6 }}>{otpError}</div>
                    )}
                  </div>
                ) : (
                  <div style={{
                    background: 'var(--brand-wash)', border: '1px solid oklch(0.88 0.04 28)',
                    borderRadius: 12, padding: 14, marginBottom: 16,
                  }}>
                    <div style={{ ...labelStyle, color: 'var(--brand-deep)' }}>
                      {lang === 'es' ? 'Código SMS' : 'Код из SMS'}
                    </div>
                    <p style={{ fontSize: 12, color: 'var(--char)', margin: '0 0 10px', lineHeight: 1.4 }}>
                      {lang === 'es'
                        ? `Enviamos un código de 6 dígitos al ${form.phone}.`
                        : `Отправили 6-значный код на ${form.phone}.`}
                    </p>
                    <div style={{ display: 'flex', gap: 8 }}>
                      <Input
                        inputMode="numeric" pattern="\d{6}" maxLength={6}
                        value={otpCode}
                        onChange={e => { setOtpCode(e.target.value.replace(/\D/g, '')); setOtpError(''); }}
                        style={{ flex: 1, fontFamily: 'var(--font-mono)', fontSize: 18, letterSpacing: '0.4em', textAlign: 'center' }}
                        placeholder="000000"
                      />
                      <button
                        className="btn btn-primary"
                        type="button"
                        onClick={verifyOtp}
                        disabled={otpVerifying || otpCode.length !== 6}
                        style={{ padding: '12px 18px', fontSize: 14 }}
                      >
                        {otpVerifying ? '…' : (lang === 'es' ? 'Confirmar' : 'Подтвердить')}
                      </button>
                    </div>
                    {otpError && (
                      <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 8 }}>{otpError}</div>
                    )}
                    <button
                      type="button"
                      onClick={sendOtp}
                      disabled={otpCooldown > 0 || otpSending}
                      style={{
                        background: 'transparent', border: 'none',
                        fontSize: 12, color: 'var(--brand-deep)', fontWeight: 600,
                        cursor: otpCooldown > 0 ? 'not-allowed' : 'pointer',
                        marginTop: 8, padding: 0,
                        opacity: otpCooldown > 0 ? 0.5 : 1,
                      }}
                    >
                      {otpCooldown > 0
                        ? (lang === 'es' ? `Reenviar en ${otpCooldown}s` : `Повторить через ${otpCooldown} с`)
                        : (lang === 'es' ? 'Reenviar código' : 'Отправить заново')}
                    </button>
                  </div>
                )}

                <Field label={lang === 'es' ? 'Email' : 'Email'}>
                  <Input type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="tu@correo.com" />
                </Field>
                <Field label={lang === 'es' ? 'Teléfono secundario (opcional)' : 'Доп. телефон (необязательно)'}>
                  <Input type="tel" value={form.secondaryPhone} onChange={e => set('secondaryPhone', e.target.value)} />
                </Field>

                <div style={{ ...labelStyle, marginTop: 18 }}>
                  {lang === 'es' ? 'Dirección actual' : 'Текущий адрес'}
                </div>
                <Field label={lang === 'es' ? 'Calle' : 'Улица'}>
                  <Input value={form.addrStreet} onChange={e => set('addrStreet', e.target.value)} />
                </Field>
                <Row cols={2}>
                  <Field label={lang === 'es' ? 'Núm. ext.' : 'Дом'}>
                    <Input value={form.addrExterior} onChange={e => set('addrExterior', e.target.value)} />
                  </Field>
                  <Field label={lang === 'es' ? 'Núm. int.' : 'Кв./офис'}>
                    <Input value={form.addrInterior} onChange={e => set('addrInterior', e.target.value)} />
                  </Field>
                </Row>
                <Row cols={2}>
                  <Field label={lang === 'es' ? 'Colonia' : 'Район'}>
                    <Input value={form.addrColonia} onChange={e => set('addrColonia', e.target.value)} />
                  </Field>
                  <Field label={lang === 'es' ? 'CP' : 'Индекс'}>
                    <Input value={form.addrCp} onChange={e => set('addrCp', e.target.value)} placeholder="06600" />
                  </Field>
                </Row>
                <Row cols={2}>
                  <Field label={lang === 'es' ? 'Ciudad' : 'Город'}>
                    <Input value={form.addrCity} onChange={e => set('addrCity', e.target.value)} />
                  </Field>
                  <Field label={lang === 'es' ? 'Estado' : 'Регион'}>
                    <Input value={form.addrState} onChange={e => set('addrState', e.target.value)} />
                  </Field>
                </Row>
                <Field label={lang === 'es' ? 'Años en domicilio' : 'Лет по адресу'}>
                  <Input type="number" min="0" max="100" value={form.addrYears} onChange={e => set('addrYears', e.target.value)} />
                </Field>
              </div>
            )}

            {/* ─── STEP 3 — Trabajo ─── */}
            {step === 3 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 14 }}>
                  {lang === 'es' ? '¿De qué vives?' : 'Где работаете?'}
                </div>
                <Field label={lang === 'es' ? 'Situación laboral' : 'Тип занятости'}>
                  <Select value={form.employmentStatus} onChange={e => set('employmentStatus', e.target.value)}>
                    <option value="">—</option>
                    <option value="employed">{lang === 'es' ? 'Empleado' : 'Наёмный работник'}</option>
                    <option value="self-employed">{lang === 'es' ? 'Independiente / freelancer' : 'Самозанятый/фрилансер'}</option>
                    <option value="business-owner">{lang === 'es' ? 'Dueño de negocio' : 'Владелец бизнеса'}</option>
                    <option value="unemployed">{lang === 'es' ? 'Sin empleo' : 'Без работы'}</option>
                    <option value="retired">{lang === 'es' ? 'Jubilado' : 'Пенсионер'}</option>
                    <option value="student">{lang === 'es' ? 'Estudiante' : 'Студент'}</option>
                  </Select>
                </Field>
                {form.employmentStatus && form.employmentStatus !== 'unemployed' && (
                  <React.Fragment>
                    <Row cols={2}>
                      <Field label={lang === 'es' ? 'Empresa / cliente principal' : 'Компания/основной клиент'}>
                        <Input value={form.employer} onChange={e => set('employer', e.target.value)} />
                      </Field>
                      <Field label={lang === 'es' ? 'Puesto' : 'Должность'}>
                        <Input value={form.jobTitle} onChange={e => set('jobTitle', e.target.value)} />
                      </Field>
                    </Row>
                    <Row cols={2}>
                      <Field label={lang === 'es' ? 'Ingreso mensual (MXN)' : 'Доход в месяц (MXN)'}>
                        <Input type="number" min="0" value={form.monthlyIncome} onChange={e => set('monthlyIncome', e.target.value)} />
                      </Field>
                      <Field label={lang === 'es' ? 'Años en empleo' : 'Лет на этой работе'}>
                        <Input type="number" min="0" max="60" value={form.yearsAtJob} onChange={e => set('yearsAtJob', e.target.value)} />
                      </Field>
                    </Row>
                    <Field label={lang === 'es' ? 'Tipo de ingreso' : 'Тип дохода'}>
                      <Select value={form.incomeType} onChange={e => set('incomeType', e.target.value)}>
                        <option value="">—</option>
                        <option value="salary">{lang === 'es' ? 'Salario' : 'Зарплата'}</option>
                        <option value="commission">{lang === 'es' ? 'Comisiones' : 'Комиссии'}</option>
                        <option value="invoices">{lang === 'es' ? 'Facturación' : 'По счетам'}</option>
                        <option value="cash">{lang === 'es' ? 'Efectivo' : 'Наличные'}</option>
                        <option value="mixed">{lang === 'es' ? 'Mixto' : 'Смешанный'}</option>
                      </Select>
                    </Field>
                  </React.Fragment>
                )}
              </div>
            )}

            {/* ─── STEP 4 — Banco ─── */}
            {step === 4 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 8 }}>
                  {lang === 'es' ? '¿A dónde te depositamos?' : 'Куда переводить?'}
                </div>
                <p style={{ fontSize: 14, color: 'var(--char-2)', margin: '0 0 18px', lineHeight: 1.5 }}>
                  {lang === 'es'
                    ? 'CLABE de 18 dígitos — número que identifica tu cuenta. Lo encuentras en la app de tu banco.'
                    : 'CLABE из 18 цифр — номер вашего банковского счёта в Мексике. Найдёте в приложении банка.'}
                </p>
                <Field label="CLABE" hint={lang === 'es' ? 'Sólo números, sin espacios.' : 'Только цифры, без пробелов.'}>
                  <Input
                    inputMode="numeric" pattern="\d{18}" maxLength={20}
                    value={form.clabe} onChange={e => set('clabe', e.target.value.replace(/\D/g, ''))}
                    style={{ fontFamily: 'var(--font-mono)', letterSpacing: '0.05em' }}
                    placeholder="012180001234567899"
                  />
                </Field>
                <div style={{
                  background: 'var(--brand-wash)', border: '1px solid oklch(0.88 0.04 28)',
                  borderRadius: 10, padding: '12px 14px', marginTop: 12,
                  fontSize: 13, color: 'var(--brand-deep)', lineHeight: 1.5,
                }}>
                  {lang === 'es'
                    ? 'La cuenta debe estar a tu nombre. No aceptamos transferencias a terceros.'
                    : 'Счёт должен быть на ваше имя. Переводы на третьих лиц не принимаем.'}
                </div>
              </div>
            )}

            {/* ─── STEP 5 — Documentos ─── */}
            {step === 5 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 14 }}>
                  {lang === 'es' ? 'Documentos oficiales' : 'Документы'}
                </div>
                <Row cols={2}>
                  <Field label={lang === 'es' ? 'Tipo de ID' : 'Тип документа'}>
                    <Select value={form.idDocType} onChange={e => set('idDocType', e.target.value)}>
                      <option value="INE">INE</option>
                      <option value="PASSPORT">{lang === 'es' ? 'Pasaporte' : 'Паспорт'}</option>
                      <option value="CEDULA">Cédula prof.</option>
                    </Select>
                  </Field>
                  <Field label={lang === 'es' ? 'Vence' : 'Действителен до'}>
                    <Input type="date" value={form.idDocExpiry} onChange={e => set('idDocExpiry', e.target.value)} />
                  </Field>
                </Row>
                <Field label={lang === 'es' ? 'Número de documento' : 'Номер документа'}>
                  <Input value={form.idDocNumber} onChange={e => set('idDocNumber', e.target.value)} style={{ fontFamily: 'var(--font-mono)' }} />
                </Field>
                <Field label="CURP" hint={lang === 'es' ? '18 caracteres. Si no la sabes, RENAPO la genera en gob.mx/curp.' : '18 символов. Уникальный мексиканский ID.'}>
                  <Input
                    value={form.curp} onChange={e => set('curp', e.target.value.toUpperCase())}
                    maxLength={18}
                    style={{ fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.05em' }}
                    placeholder="HEGJ850315HDFLNSA9"
                  />
                </Field>
                <Field label="RFC" hint={lang === 'es' ? '13 caracteres con homoclave (10 si es genérico).' : 'Налоговый ID, 13 символов.'}>
                  <Input
                    value={form.rfc} onChange={e => set('rfc', e.target.value.toUpperCase())}
                    maxLength={13}
                    style={{ fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.05em' }}
                    placeholder="XAXX010101000"
                  />
                </Field>
              </div>
            )}

            {/* ─── STEP 6 — Referencias ─── */}
            {step === 6 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 8 }}>
                  {lang === 'es' ? 'Dos contactos' : 'Два контакта'}
                </div>
                <p style={{ fontSize: 14, color: 'var(--char-2)', margin: '0 0 16px', lineHeight: 1.5 }}>
                  {lang === 'es'
                    ? 'Personas que te conocen — un familiar y otra persona. No las llamamos a menos que no podamos contactarte a ti.'
                    : 'Люди которые вас знают — один родственник и ещё кто-то. Звоним им только если не можем дозвониться до вас.'}
                </p>
                {form.refs.map((r, i) => (
                  <div key={i} style={{
                    background: 'var(--surface-2)', borderRadius: 12, padding: 14, marginBottom: 10,
                    border: '1px solid var(--line)',
                  }}>
                    <div style={{ ...labelStyle, marginBottom: 10 }}>
                      {lang === 'es' ? `Contacto ${i + 1}` : `Контакт ${i + 1}`}
                    </div>
                    <Field label={lang === 'es' ? 'Nombre completo' : 'Имя и фамилия'}>
                      <Input value={r.name} onChange={e => setRef(i, 'name', e.target.value)} />
                    </Field>
                    <Row cols={2}>
                      <Field label={lang === 'es' ? 'Teléfono' : 'Телефон'}>
                        <Input type="tel" value={r.phone} onChange={e => setRef(i, 'phone', e.target.value)} />
                      </Field>
                      <Field label={lang === 'es' ? 'Relación' : 'Кем приходится'}>
                        <Select value={r.relation} onChange={e => setRef(i, 'relation', e.target.value)}>
                          <option value="">—</option>
                          <option value="family">{lang === 'es' ? 'Familiar' : 'Родственник'}</option>
                          <option value="friend">{lang === 'es' ? 'Amigo/a' : 'Друг'}</option>
                          <option value="coworker">{lang === 'es' ? 'Compañero de trabajo' : 'Коллега'}</option>
                          <option value="neighbor">{lang === 'es' ? 'Vecino/a' : 'Сосед'}</option>
                        </Select>
                      </Field>
                    </Row>
                  </div>
                ))}
              </div>
            )}

            {/* ─── STEP 7 — Confirmar ─── */}
            {step === 7 && (
              <div>
                <div className="display" style={{ fontSize: 28, fontWeight: 600, marginBottom: 6 }}>{t.confirmTitle}</div>
                <div style={{ fontSize: 13, color: 'var(--char-2)', marginBottom: 16 }}>{t.confirmSub}</div>

                <div className="card-ink" style={{ padding: 18, marginBottom: 14 }}>
                  <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 600, marginBottom: 8 }}>{t.summary}</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <div>
                      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>{lang === 'es' ? 'Monto' : 'Сумма'}</div>
                      <div className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: '#fff' }}>${principal.toLocaleString('en-US')}</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>{lang === 'es' ? 'Pago quincenal' : 'Платёж'}</div>
                      <div className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: '#fff' }}>${quincenal.toLocaleString('en-US')}</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>CAT</div>
                      <div className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: 'var(--sun)' }}>{cat}%</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>{lang === 'es' ? 'Total' : 'Всего'}</div>
                      <div className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: '#fff' }}>${total.toLocaleString('en-US')}</div>
                    </div>
                  </div>
                </div>

                {[
                  ['contractAccepted', t.contract],
                  ['privacyAccepted', t.privacy],
                  ['buroAccepted', t.buro],
                ].map(([k, label]) => (
                  <label key={k} style={{
                    display: 'flex', gap: 10, alignItems: 'flex-start',
                    padding: 12, background: 'var(--surface-2)', borderRadius: 10,
                    cursor: 'pointer', fontSize: 13, color: 'var(--char)', marginBottom: 8,
                  }}>
                    <input
                      type="checkbox" checked={form[k]}
                      onChange={e => set(k, e.target.checked)}
                      style={{ marginTop: 2, accentColor: 'var(--brand)' }}
                    />
                    <span>{label}</span>
                  </label>
                ))}
              </div>
            )}

            <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
              {step > 0 && (
                <button className="btn btn-ghost" onClick={() => setStep(step - 1)} style={{ flex: '0 0 auto' }}>
                  {t.back}
                </button>
              )}
              <button
                className="btn btn-primary"
                onClick={() => step < 7 ? setStep(step + 1) : submitApplication()}
                style={{ flex: 1, opacity: (submitting || !canProceed()) ? 0.5 : 1 }}
                disabled={submitting || !canProceed()}
              >
                {submitting
                  ? (lang === 'es' ? 'Enviando…' : 'Отправка…')
                  : (step < 7 ? t.next : t.sign)}
                {!submitting && <I.arrow />}
              </button>
            </div>
          </React.Fragment>
        ) : (
          <div style={{ textAlign: 'center', padding: '32px 0 16px', animation: 'scaleIn 400ms cubic-bezier(0.34, 1.56, 0.64, 1)' }}>
            {result?.error ? (
              <React.Fragment>
                <div style={{
                  width: 72, height: 72, borderRadius: 999, background: 'var(--brand)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  margin: '0 auto 22px', color: '#fff',
                }}>
                  <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
                </div>
                <div className="display" style={{ fontSize: 30, fontWeight: 600 }}>
                  {lang === 'es' ? 'Algo salió mal' : 'Что-то пошло не так'}
                </div>
                <p style={{ fontSize: 14, color: 'var(--char-2)', maxWidth: 380, marginInline: 'auto', marginTop: 8, fontFamily: 'var(--font-mono)' }}>
                  {result.error}
                </p>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <div style={{
                  width: 72, height: 72, borderRadius: 999,
                  background: result?.status === 'REJECTED' ? 'var(--brand)' : 'var(--green)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  margin: '0 auto 22px', color: '#fff',
                  boxShadow: '0 8px 24px rgba(60, 140, 90, 0.3)',
                }}>
                  <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 7"/></svg>
                </div>
                <div className="display" style={{ fontSize: 32, fontWeight: 600 }}>{t.successTitle}</div>
                <p style={{ fontSize: 15, color: 'var(--char-2)', maxWidth: 360, marginInline: 'auto', marginTop: 8 }}>{t.successSub}</p>
                {result?.applicationId && (
                  <div style={{
                    marginTop: 18, padding: '12px 16px',
                    background: 'var(--surface-2)', borderRadius: 10,
                    fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-soft)',
                    display: 'inline-block',
                  }}>
                    <span style={{ textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>
                      {lang === 'es' ? 'Aplicación' : 'Заявка'}
                    </span>{' '}
                    <span style={{ color: 'var(--ink)' }}>#{String(result.applicationId).slice(-8)}</span>
                    {' · '}
                    <span style={{ color: 'var(--brand)', fontWeight: 600 }}>{result.status}</span>
                  </div>
                )}
              </React.Fragment>
            )}
            <div style={{ marginTop: 20 }}>
              <button className="btn btn-primary" onClick={onClose}>
                {lang === 'es' ? 'Cerrar' : 'Закрыть'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

/* Add field-focus styling globally for sheet inputs */
if (typeof document !== 'undefined' && !document.getElementById('apply-sheet-style')) {
  const s = document.createElement('style'); s.id = 'apply-sheet-style';
  s.textContent = `
    input:focus, select:focus { border-color: var(--brand) !important; background: var(--surface) !important; }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { ApplySheet });
