// Application multi-step screen – visa-style flow
function ApplicationFlow({ lang, setRoute, initialProgramId, openCallback }) {
  const all = [...window.MIGRONIS_DATA.citizenship, ...window.MIGRONIS_DATA.residency];
  const [step, setStep] = React.useState(0);
  // contactMode: 'email' = send a written plan, 'call' = book a callback (calendly)
  const [contactMode, setContactMode] = React.useState('email');
  const [data, setData] = React.useState({
    programId: initialProgramId || 'grenada',
    goal: 'family',
    family: 2,
    timing: 'med',
    name: '',
    email: '',
    phone: '',
    notes: '',
    consent: false,
  });
  const set = (patch) => setData({ ...data, ...patch });
  const program = all.find((p) => p.id === data.programId);

  const STEPS = lang === 'ru'
    ? ['Программа', 'Ваша ситуация', 'Контакт', 'Подтверждение']
    : ['Program', 'Your situation', 'Contact', 'Confirm'];

  const next = () => setStep(Math.min(step + 1, STEPS.length));
  const prev = () => setStep(Math.max(step - 1, 0));

  const canNext = (() => {
    if (step === 2) {
      // Call-mode: hand off to callback modal instead of validating email fields here.
      if (contactMode === 'call') return true;
      return data.name && data.email && data.consent;
    }
    return true;
  })();

  return (
    <div style={{ paddingTop: 32, paddingBottom: 80, animation: 'fade-up .4s var(--ease-out)' }}>
      <div className="container" style={{ maxWidth: 980 }}>
        {/* Breadcrumb / back */}
        <div style={{ marginBottom: 32 }}>
          <window.BackButton lang={lang} />
        </div>

        {/* Header */}
        <div style={{ marginBottom: 40 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>
            {lang === 'ru' ? '– Заявка на сопровождение' : '– Application'}
          </div>
          <h1 className="display" style={{ fontSize: 'clamp(36px, 4vw, 56px)', margin: 0, maxWidth: 700 }}>
            {lang === 'ru' ? <>30 минут <span className="ds">–</span> и у вас <em>точный</em> план</> : <>30 minutes <span className="ds">–</span> and you have a <em>precise</em> plan</>}
          </h1>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 40, alignItems: 'start' }}>
          {/* Left: form */}
          <div className="glass" style={{ padding: 32, borderRadius: 'var(--r-xl)', background: 'var(--bg-elev)' }}>
            {/* Step indicator */}
            <div style={{ display: 'flex', gap: 4, marginBottom: 32 }}>
              {STEPS.map((s, i) => (
                <div key={i} style={{
                  flex: 1, height: 4, borderRadius: 4,
                  background: i <= step ? 'var(--accent)' : 'var(--surface-hi)',
                  transition: 'background .3s',
                }} />
              ))}
            </div>

            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 8 }}>
              {lang === 'ru' ? `Шаг ${Math.min(step + 1, STEPS.length)} из ${STEPS.length}` : `Step ${Math.min(step + 1, STEPS.length)} of ${STEPS.length}`}
            </div>

            {/* Step 0: Program */}
            {step === 0 && (
              <div key="s0" style={{ animation: 'fade-up .3s var(--ease-out)' }}>
                <h3 className="display" style={{ fontSize: 28, marginTop: 0 }}>
                  {lang === 'ru' ? 'С какой программы начнём?' : 'Which program do we start with?'}
                </h3>
                <p style={{ color: 'var(--fg-muted)', fontSize: 14, marginTop: 6 }}>
                  {lang === 'ru' ? 'Можно изменить – мы предложим альтернативы на консультации.' : 'You can change this – we will suggest alternatives during the call.'}
                </p>
                <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                  {all.map((p) => (
                    <button key={p.id}
                      onClick={() => set({ programId: p.id })}
                      style={{
                        textAlign: 'left', padding: '14px 16px',
                        background: data.programId === p.id ? 'var(--accent-soft)' : 'var(--surface)',
                        border: '1px solid', borderColor: data.programId === p.id ? 'var(--accent)' : 'var(--border)',
                        borderRadius: 'var(--r-md)',
                        display: 'flex', alignItems: 'center', gap: 12,
                        color: 'var(--fg)',
                        transition: 'all .2s',
                      }}>
                      <window.FlagIcon emoji={p.flag} size={18} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{window.cn(p, lang)}</div>
                        <div className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)' }}>
                          {p.currency === 'USD' ? '$' : '€'}{(p.minInvest/1000).toFixed(0)}k · {window.termLabel(p.term, lang)}
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Step 1: Situation */}
            {step === 1 && (
              <div key="s1" style={{ animation: 'fade-up .3s var(--ease-out)' }}>
                <h3 className="display" style={{ fontSize: 28, marginTop: 0 }}>
                  {lang === 'ru' ? 'Расскажите о ситуации' : 'Tell us about your situation'}
                </h3>
                <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
                  <div>
                    <label style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 10, display: 'block' }}>
                      {lang === 'ru' ? 'Основная цель' : 'Main goal'}
                    </label>
                    <div className="tabs" style={{ width: '100%' }}>
                      {[
                        { v: 'travel', ru: 'Безвиз', en: 'Travel' },
                        { v: 'tax', ru: 'Налоги', en: 'Tax' },
                        { v: 'family', ru: 'Семья', en: 'Family' },
                        { v: 'planb', ru: 'План Б', en: 'Plan B' },
                      ].map((o) => (
                        <button key={o.v} onClick={() => set({ goal: o.v })} style={{ flex: 1 }}
                                className={`tab ${data.goal === o.v ? 'is-active' : ''}`}>{o[lang]}</button>
                      ))}
                    </div>
                  </div>
                  <div>
                    <label style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 10, display: 'block' }}>
                      {lang === 'ru' ? `Состав семьи: ${data.family} чел.` : `Family size: ${data.family}`}
                    </label>
                    <input type="range" min="1" max="8" value={data.family}
                           onChange={(e) => set({ family: +e.target.value })}
                           style={{ width: '100%', accentColor: 'var(--accent)' }} />
                  </div>
                  <div>
                    <label style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 10, display: 'block' }}>
                      {lang === 'ru' ? 'Желаемые сроки' : 'Desired timing'}
                    </label>
                    <div className="tabs" style={{ width: '100%' }}>
                      {[
                        { v: 'fast', ru: '1–3 мес', en: '1–3 mo' },
                        { v: 'med', ru: '4–9 мес', en: '4–9 mo' },
                        { v: 'slow', ru: '12+ мес', en: '12+ mo' },
                      ].map((o) => (
                        <button key={o.v} onClick={() => set({ timing: o.v })} style={{ flex: 1 }}
                                className={`tab ${data.timing === o.v ? 'is-active' : ''}`}>{o[lang]}</button>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Step 2: Contact – choose between e-mail plan and a phone callback */}
            {step === 2 && (
              <div key="s2" style={{ animation: 'fade-up .3s var(--ease-out)' }}>
                <h3 className="display" style={{ fontSize: 28, marginTop: 0 }}>
                  {lang === 'ru' ? 'Как удобнее получить план?' : 'How would you like the plan?'}
                </h3>
                <p style={{ color: 'var(--fg-muted)', fontSize: 14, marginTop: 6 }}>
                  {lang === 'ru'
                    ? 'Можно получить письменный план на e-mail – или сразу поговорить с менеджером 15-30 минут.'
                    : 'Get a written plan by e-mail – or speak with an advisor for 15-30 minutes.'}
                </p>

                {/* Mode switch */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 22 }}>
                  {[
                    { v: 'email', ru: 'Прислать план на e-mail', en: 'Send a plan to my e-mail', d: lang === 'ru' ? 'Письменный отчёт за 1 рабочий день' : 'Written report within 1 business day' },
                    { v: 'call',  ru: 'Заказать звонок',         en: 'Book a callback',           d: lang === 'ru' ? '15-30 минут, бесплатно, без обязательств' : '15-30 minutes, free, no commitment' },
                  ].map((o) => {
                    const selected = contactMode === o.v;
                    return (
                      <button key={o.v} type="button" onClick={() => setContactMode(o.v)} className="lift"
                        style={{
                          textAlign: 'left', padding: '14px 16px',
                          background: selected ? 'var(--accent-soft)' : 'var(--surface)',
                          border: '1px solid', borderColor: selected ? 'var(--accent)' : 'var(--border)',
                          color: 'var(--fg)', display: 'flex', flexDirection: 'column', gap: 6,
                          cursor: 'pointer', transition: 'all .2s',
                        }}>
                        <span style={{ fontSize: 14, fontWeight: 500 }}>{o[lang]}</span>
                        <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{o.d}</span>
                      </button>
                    );
                  })}
                </div>

                {/* Email mode: keep the original form */}
                {contactMode === 'email' && (
                  <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
                    <div className="field">
                      <input value={data.name} onChange={(e) => set({ name: e.target.value })}
                             placeholder={lang === 'ru' ? 'Имя' : 'Name'} />
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                      <div className="field">
                        <input type="email" value={data.email} onChange={(e) => set({ email: e.target.value })}
                               placeholder="email@example.com" />
                      </div>
                      <div className="field">
                        <input value={data.phone} onChange={(e) => set({ phone: e.target.value })}
                               placeholder="+1 555 0000" />
                      </div>
                    </div>
                    <div className="field" style={{ height: 88, alignItems: 'flex-start', padding: '12px 14px' }}>
                      <textarea value={data.notes} onChange={(e) => set({ notes: e.target.value })}
                                placeholder={lang === 'ru' ? 'Опционально: контекст, вопросы, специфика' : 'Optional: context, questions, specifics'}
                                style={{ resize: 'none', height: '100%' }} />
                    </div>
                    <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', fontSize: 13, color: 'var(--fg-muted)' }}>
                      <input type="checkbox" checked={data.consent}
                             onChange={(e) => set({ consent: e.target.checked })}
                             style={{ marginTop: 3, accentColor: 'var(--accent)' }} />
                      <span>{lang === 'ru'
                        ? 'Согласен с обработкой персональных данных. Migronis не передаёт данные третьим лицам.'
                        : 'I agree to data processing. Migronis does not share data with third parties.'}</span>
                    </label>
                  </div>
                )}

                {/* Call mode: explain that the next click opens the calendly modal */}
                {contactMode === 'call' && (
                  <div style={{
                    marginTop: 22, padding: '16px 18px',
                    background: 'var(--bg-elev-2)', border: '1px dashed var(--accent)',
                    fontSize: 13, lineHeight: 1.55, color: 'var(--fg-muted)',
                  }}>
                    {lang === 'ru'
                      ? <>На следующем шаге вы <strong>выберете удобный день и время</strong> – менеджер перезвонит вам на телефон, WhatsApp или Telegram. Программа <strong>{window.cn(program, lang)}</strong> и состав семьи (<strong>{data.family} чел.</strong>) будут переданы менеджеру заранее.</>
                      : <>On the next step you will <strong>pick a date and time</strong> – the advisor will call you on phone, WhatsApp or Telegram. Program <strong>{window.cn(program, lang)}</strong> and family size (<strong>{data.family}</strong>) are passed to the advisor up front.</>}
                  </div>
                )}
              </div>
            )}

            {/* Step 3: Done */}
            {step === 3 && (
              <div key="s3" style={{ animation: 'fade-up .3s var(--ease-out)', textAlign: 'center', padding: '20px 0' }}>
                <div style={{
                  width: 72, height: 72, borderRadius: 999, margin: '0 auto 24px',
                  background: 'var(--accent-soft)', color: 'var(--accent)',
                  display: 'grid', placeItems: 'center', fontSize: 32,
                }}>✓</div>
                <h3 className="display" style={{ fontSize: 32, margin: 0 }}>
                  {lang === 'ru' ? 'Заявка отправлена' : 'Application sent'}
                </h3>
                <p style={{ color: 'var(--fg-muted)', fontSize: 15, marginTop: 12, maxWidth: 480, marginLeft: 'auto', marginRight: 'auto' }}>
                  {lang === 'ru'
                    ? `Менеджер свяжется с вами в течение 4 часов в рабочее время. Кейс-номер: ${'MGR-' + Math.floor(Math.random() * 90000 + 10000)}.`
                    : `An advisor will contact you within 4 working hours. Case number: ${'MGR-' + Math.floor(Math.random() * 90000 + 10000)}.`}
                </p>
                <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 28 }}>
                  <button className="btn btn-primary" onClick={() => setRoute({ name: 'dashboard' })}>
                    {lang === 'ru' ? 'Открыть личный кабинет' : 'Open dashboard'} →
                  </button>
                  <button className="btn btn-ghost" onClick={() => setRoute({ name: 'home' })}>
                    {lang === 'ru' ? 'На главную' : 'Home'}
                  </button>
                </div>
              </div>
            )}

            {/* Nav */}
            {step < 3 && (
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32 }}>
                <button onClick={prev} disabled={step === 0}
                        className="btn btn-ghost"
                        style={{ opacity: step === 0 ? 0.3 : 1 }}>
                  ← {lang === 'ru' ? 'Назад' : 'Back'}
                </button>
                <button
                  onClick={() => {
                    // On contact step in call-mode, hand off to the callback modal instead of advancing
                    if (step === 2 && contactMode === 'call' && openCallback) {
                      openCallback({ programId: data.programId, family: data.family, goal: data.goal });
                      return;
                    }
                    next();
                  }}
                  disabled={!canNext}
                  className="btn btn-primary"
                  style={{ opacity: !canNext ? 0.4 : 1 }}>
                  {step === 2
                    ? (contactMode === 'call'
                        ? (lang === 'ru' ? 'Выбрать время звонка' : 'Pick a callback time')
                        : (lang === 'ru' ? 'Отправить заявку'      : 'Submit application'))
                    : (lang === 'ru' ? 'Далее' : 'Next')} →
                </button>
              </div>
            )}
          </div>

          {/* Right: summary */}
          <aside style={{
            padding: 24, background: 'var(--bg-elev)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-lg)', position: 'sticky', top: 100,
          }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>{lang === 'ru' ? 'Ваш кейс' : 'Your case'}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <window.FlagIcon emoji={program.flag} size={26} />
              <div>
                <div style={{ fontWeight: 500 }}>{window.cn(program, lang)}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{program.tagline[lang]}</div>
              </div>
            </div>
            <div className="hr" style={{ margin: '16px 0' }} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--fg-muted)' }}>{lang === 'ru' ? 'Инвестиция от' : 'Investment from'}</span>
                <span className="mono" style={{ color: 'var(--accent)' }}>
                  {program.currency === 'USD' ? '$' : '€'}{(program.minInvest/1000).toFixed(0)}k
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--fg-muted)' }}>{lang === 'ru' ? 'Срок' : 'Timeline'}</span>
                <span className="mono">{window.termLabel(program.term, lang)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--fg-muted)' }}>{lang === 'ru' ? 'Семья' : 'Family'}</span>
                <span className="mono">{data.family} {lang === 'ru' ? 'чел.' : 'pax'}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--fg-muted)' }}>{lang === 'ru' ? 'Цель' : 'Goal'}</span>
                <span style={{ textTransform: 'capitalize' }}>{data.goal}</span>
              </div>
            </div>
            <div className="hr" style={{ margin: '16px 0' }} />
            <div style={{ fontSize: 12, color: 'var(--fg-dim)', lineHeight: 1.6 }}>
              {lang === 'ru'
                ? '🔒 Все данные шифруются. Используются только для подготовки персонального предложения.'
                : '🔒 All data is encrypted. Used only to prepare your personalised proposal.'}
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

window.ApplicationFlow = ApplicationFlow;
