// Program detail screen
function ProgramDetail({ programId, lang, setRoute }) {
  const all = [...window.MIGRONIS_DATA.citizenship, ...window.MIGRONIS_DATA.residency];
  const p = all.find((x) => x.id === programId) || all[0];
  const isCBI = window.MIGRONIS_DATA.citizenship.includes(p);
  const cur = p.currency === 'USD' ? '$' : '€';
  const [tab, setTab] = React.useState('overview');

  // Title scales down for long names so it always fits one line (no crooked
  // wrap next to the flag). Tiers tuned by measured render width of every
  // program name (RU is the longest) against the ~600px hero column.
  const _name = window.cn(p, lang);
  const titleSize = _name.length <= 12 ? 'clamp(38px, 5vw, 64px)'
                  : _name.length <= 18 ? 'clamp(32px, 4vw, 50px)'
                  :                      'clamp(28px, 3.4vw, 42px)';
  const flagSize = _name.length <= 12 ? 40 : _name.length <= 18 ? 34 : 30;

  const TABS = lang === 'ru'
    ? [['overview','Обзор'],['requirements','Требования'],['process','Процесс'],['tax','Налоги'],['faq','FAQ'],['blog','Блог']]
    : [['overview','Overview'],['requirements','Requirements'],['process','Process'],['tax','Tax'],['faq','FAQ'],['blog','Blog']];

  return (
    <div style={{ paddingTop: 32, animation: 'fade-up .4s var(--ease-out)' }} data-accent={isCBI ? 'green' : 'teal'}>
      <div className="container-wide">
        {/* Back + breadcrumb */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
          <window.BackButton lang={lang} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--fg-muted)' }}>
            <a href="#" onClick={(e) => { e.preventDefault(); setRoute({ name: isCBI ? 'citizenship' : 'residency' }); }}
               style={{ color: 'inherit' }}>{isCBI ? (lang === 'ru' ? 'Гражданство' : 'Citizenship') : (lang === 'ru' ? 'Резидентство' : 'Residency')}</a>
            <span>/</span>
            <span style={{ color: 'var(--fg)' }}>{window.cn(p, lang)}</span>
          </div>
        </div>

        {/* Hero */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 56, alignItems: 'start' }}>
          <div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 16 }}>
              <span className="chip" style={{ background: 'var(--accent-soft)', color: 'var(--accent-strong)', borderColor: 'transparent' }}>
                {isCBI ? 'CBI' : 'RBI'}
              </span>
              <span className="chip">{window.regionLabel ? window.regionLabel(p.region, lang) : p.region}</span>
              <span className="chip mono">{window.termLabel(p.term, lang)}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 10 }}>
              <window.FlagIcon emoji={p.flag} size={flagSize} />
              <h1 className="display h-1" style={{ margin: 0, fontSize: titleSize, lineHeight: 1.04 }}>{_name}</h1>
            </div>
            <div className="display" style={{ fontSize: 'clamp(17px, 1.7vw, 22px)', color: isCBI ? '#1F4A2E' : '#2F6A6B', fontWeight: 600, lineHeight: 1.3, maxWidth: 520 }}>
              {p.tagline[lang]}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 36 }}>
              {[
                { l: lang === 'ru' ? 'инвестиция' : 'investment', v: `${cur}${(p.minInvest/1000).toFixed(0)}k`, hi: true },
                { l: lang === 'ru' ? 'срок' : 'term', v: window.termLabel(p.term, lang) },
                { l: lang === 'ru' ? 'безвиз стран' : 'visa-free', v: p.visaFree },
                { l: lang === 'ru' ? 'налоги' : 'tax', v: p.tax },
              ].map((m) => (
                <div key={m.l}>
                  <div className="eyebrow" style={{ marginBottom: 6 }}>{m.l}</div>
                  <div className="mono" style={{ fontSize: m.hi ? 22 : 16, color: m.hi ? 'var(--accent)' : 'var(--fg)' }}>
                    {m.v}
                  </div>
                </div>
              ))}
            </div>

            <div style={{ display: 'flex', gap: 12, marginTop: 32 }}>
              <button className="btn btn-primary btn-lg" onClick={() => setRoute({ name: 'apply', programId: p.id })}>
                {lang === 'ru' ? 'Начать оформление' : 'Start application'} →
              </button>
              <button className="btn btn-ghost btn-lg" onClick={() => setRoute({ name: 'home', scrollTo: 'tools' })}>
                {lang === 'ru' ? 'Калькулятор' : 'Calculator'}
              </button>
            </div>
          </div>

          {/* Right: highlights card */}
          <div className="glass" style={{
            padding: 28, borderRadius: 'var(--r-xl)',
            background: 'var(--bg-elev)', borderColor: 'var(--border-strong)',
          }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>
              {lang === 'ru' ? 'Ключевые преимущества' : 'Key benefits'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {p.highlights[lang].map((h, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <span style={{
                    flexShrink: 0, width: 22, height: 22, borderRadius: 999,
                    background: 'var(--accent-soft)', color: 'var(--accent)',
                    display: 'grid', placeItems: 'center', fontSize: 11,
                    marginTop: 2,
                  }}>✓</span>
                  <span style={{ fontSize: 15 }}>{h}</span>
                </div>
              ))}
            </div>
            <div className="hr" style={{ margin: '24px 0' }} />
            <div className="eyebrow" style={{ marginBottom: 10 }}>
              {lang === 'ru' ? 'Маршрут инвестиции' : 'Investment route'}
            </div>
            <div style={{ fontSize: 14, color: 'var(--fg-muted)' }}>{p.route}</div>
          </div>
        </div>

        {/* Tabs – sticky */}
        <div style={{
          marginTop: 64,
          position: 'sticky', top: 84, zIndex: 10,
          background: 'var(--bg)',
          borderBottom: '1px solid var(--border)',
          display: 'flex', gap: 0,
        }}>
          {TABS.map(([k, lbl]) => (
            <button key={k} onClick={() => setTab(k)}
              style={{
                padding: '14px 22px', position: 'relative',
                color: tab === k ? 'var(--fg)' : 'var(--fg-muted)',
                fontWeight: tab === k ? 500 : 400, fontSize: 14,
                transition: 'color .2s',
              }}>
              {lbl}
              {tab === k && (
                <div style={{
                  position: 'absolute', bottom: -1, left: 0, right: 0, height: 2,
                  background: 'var(--accent)',
                }} />
              )}
            </button>
          ))}
          <div style={{ flex: 1 }} />
          <button className="btn btn-primary btn-sm" style={{ margin: 8 }}
                  onClick={() => setRoute({ name: 'apply', programId: p.id })}>
            {lang === 'ru' ? 'Начать оформление' : 'Start application'} →
          </button>
        </div>

        <div style={{ padding: '40px 0 80px', minHeight: 360 }}>
          {tab === 'overview' && <ProgramOverview p={p} lang={lang} />}
          {tab === 'requirements' && <ProgramRequirements p={p} lang={lang} />}
          {tab === 'process' && <ProgramProcess p={p} lang={lang} isCBI={isCBI} setRoute={setRoute} />}
          {tab === 'tax' && <ProgramTax p={p} lang={lang} />}
          {tab === 'faq' && <ProgramFaqSection lang={lang} />}
          {tab === 'blog' && <ProgramBlogSection p={p} lang={lang} />}
        </div>
      </div>
    </div>
  );
}

function ProgramOverview({ p, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48 }}>
      <div>
        <h3 className="display" style={{ fontSize: 28, marginTop: 0 }}>
          {lang === 'ru' ? `Почему ${window.cn(p, 'ru')}?` : `Why ${window.cn(p, 'en')}?`}
        </h3>
        <p style={{ color: 'var(--fg-muted)', fontSize: 16, lineHeight: 1.7, maxWidth: 640 }}>
          {lang === 'ru'
            ? `Программа ${window.cn(p, 'ru')} остаётся одной из самых востребованных в сегменте инвестиционной иммиграции. Её ключевая ценность – ${p.tagline.ru.toLowerCase()}. Это делает её рациональным выбором как для предпринимателей, ищущих налоговую оптимизацию, так и для семей, нацеленных на глобальную мобильность.`
            : `The ${window.cn(p, 'en')} program remains one of the most sought-after in investment migration. Its core value – ${p.tagline.en.toLowerCase()} – makes it a rational choice both for entrepreneurs seeking tax optimisation and for families pursuing global mobility.`}
        </p>
        <p style={{ color: 'var(--fg-muted)', fontSize: 16, lineHeight: 1.7, maxWidth: 640, marginTop: 16 }}>
          {lang === 'ru'
            ? 'Migronis выступает лицензированным агентом и сопровождает кейс полностью: от первичного due diligence до получения документа и пост-натурализационной поддержки.'
            : 'Migronis acts as a licensed agent and runs the entire case: from initial due diligence to document collection and post-naturalisation support.'}
        </p>
      </div>
      {window.programPhoto(p.id)
        ? <img src={window.programPhoto(p.id)} alt={window.cn(p, lang)} loading="eager"
               style={{ width: '100%', aspectRatio: '4/3', objectFit: 'cover', borderRadius: 'var(--r-lg)' }} />
        : <div className="img-ph" data-label={lang === 'ru' ? `Локация · ${window.cn(p, 'ru')}` : `Imagery · ${window.cn(p, 'en')}`}
               style={{ aspectRatio: '4/3', borderRadius: 'var(--r-lg)' }} />}
    </div>
  );
}

function ProgramRequirements({ p, lang }) {
  const REQS = lang === 'ru' ? [
    'Возраст 18+',
    'Чистая криминальная история',
    'Подтверждение источника средств',
    'Медицинское освидетельствование',
    `Минимальная инвестиция ${p.currency === 'USD' ? '$' : '€'}${(p.minInvest/1000).toFixed(0)}k`,
    'Документы на семью (при необходимости)',
  ] : [
    'Age 18+',
    'Clean criminal record',
    'Proof of source of funds',
    'Medical clearance',
    `Minimum investment ${p.currency === 'USD' ? '$' : '€'}${(p.minInvest/1000).toFixed(0)}k`,
    'Family documents (if applicable)',
  ];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
      {REQS.map((r, i) => (
        <div key={i} style={{
          padding: 20, background: 'var(--bg-elev)',
          border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
          display: 'flex', gap: 14, alignItems: 'flex-start',
        }}>
          <span className="mono" style={{ color: 'var(--accent)', fontSize: 12, minWidth: 30 }}>
            {String(i + 1).padStart(2, '0')}
          </span>
          <span style={{ fontSize: 15 }}>{r}</span>
        </div>
      ))}
    </div>
  );
}

function ProgramProcess({ p, lang, isCBI, setRoute }) {
  const STEPS = lang === 'ru' ? [
    { t: 'Pre-DD проверка', d: 'Бесплатная оценка проходимости', dur: '3 дня' },
    { t: 'Контракт + ретейнер', d: 'Подписываем соглашение, открываем дело', dur: '1 неделя' },
    { t: 'Сбор документов', d: 'Легализация, апостили, переводы', dur: '4–8 недель' },
    { t: 'Подача и DD', d: 'Госагент проводит due diligence', dur: isCBI ? '3–4 мес' : '2–3 мес' },
    { t: 'Одобрение и инвестиция', d: 'Перевод в escrow, получение approval letter', dur: '2 недели' },
    { t: 'Выдача документа', d: 'Паспорт / резидент-карта', dur: '2–4 недели' },
  ] : [
    { t: 'Pre-DD check', d: 'Free eligibility assessment', dur: '3 days' },
    { t: 'Contract + retainer', d: 'Sign engagement, open case file', dur: '1 week' },
    { t: 'Document collection', d: 'Legalisation, apostilles, translations', dur: '4–8 weeks' },
    { t: 'Filing + DD', d: 'Government agent runs due diligence', dur: isCBI ? '3–4 mo' : '2–3 mo' },
    { t: 'Approval + investment', d: 'Wire to escrow, receive approval letter', dur: '2 weeks' },
    { t: 'Document issuance', d: 'Passport / residence card', dur: '2–4 weeks' },
  ];

  return (
    <div style={{
      background: 'var(--bg-elev)', border: '1px solid var(--border)',
      borderRadius: 'var(--r-lg)', overflow: 'hidden',
    }}>
      {STEPS.map((s, i) => (
        <div key={i} style={{
          display: 'grid',
          gridTemplateColumns: '64px 1.4fr 1.4fr 128px',
          gap: 24, alignItems: 'center',
          padding: '20px 24px',
          borderBottom: i < STEPS.length - 1 ? '1px solid var(--border)' : 'none',
          position: 'relative',
        }}>
          {/* Number with connector */}
          <div style={{ position: 'relative' }}>
            <div style={{
              width: 36, height: 36, borderRadius: 999,
              background: 'var(--accent-soft)', color: 'var(--accent-strong)',
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--f-mono)', fontSize: 13, fontWeight: 600,
              border: '1px solid var(--accent)',
            }}>
              {String(i + 1).padStart(2, '0')}
            </div>
            {i < STEPS.length - 1 && (
              <div style={{
                position: 'absolute', left: 18, top: 36, bottom: -20, width: 1,
                background: 'var(--border)',
              }} />
            )}
          </div>
          <div style={{ fontSize: 17, fontWeight: 500 }}>{s.t}</div>
          <div style={{ fontSize: 14, color: 'var(--fg-muted)' }}>{s.d}</div>
          <div style={{
            justifySelf: 'end',
            padding: '6px 12px', borderRadius: 999,
            background: 'var(--surface-hi)', border: '1px solid var(--border-strong)',
            fontFamily: 'var(--f-mono)', fontSize: 12, color: 'var(--fg)',
            whiteSpace: 'nowrap',
          }}>{s.dur}</div>
        </div>
      ))}
      <div style={{ padding: 24, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
        <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
          {lang === 'ru'
            ? 'Все шаги – параллельно где возможно. Менеджер на кейсе один.'
            : 'Steps run in parallel where possible. One advisor per case.'}
        </div>
        <button className="btn btn-primary" onClick={() => setRoute({ name: 'apply', programId: p.id })}>
          {lang === 'ru' ? 'Начать с шага 01' : 'Start at step 01'} →
        </button>
      </div>
    </div>
  );
}

function ProgramTax({ p, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
      <div style={{ padding: 28, background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>{lang === 'ru' ? 'Режим' : 'Regime'}</div>
        <div className="display" style={{ fontSize: 26, color: 'var(--accent)' }}>{p.tax}</div>
        <p style={{ color: 'var(--fg-muted)', fontSize: 14, lineHeight: 1.7, marginTop: 16 }}>
          {lang === 'ru'
            ? 'Налоговый режим страны применяется при получении статуса резидента для целей налогообложения. Для оптимизации эффекта рекомендуется индивидуальная консультация налогового консультанта.'
            : 'The country tax regime applies once you become a tax resident. For optimised effect we recommend a personal session with a tax adviser.'}
        </p>
      </div>
      <div style={{ padding: 28, background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>{lang === 'ru' ? 'Без двойного налогообложения' : 'Double-tax treaties'}</div>
        <div className="display" style={{ fontSize: 36, color: 'var(--fg)' }}>{Math.max(28, p.visaFree - 70)}</div>
        <div style={{ color: 'var(--fg-muted)', fontSize: 14, marginTop: 8 }}>
          {lang === 'ru' ? 'действующих соглашений' : 'active treaties'}
        </div>
        <p style={{ color: 'var(--fg-muted)', fontSize: 14, lineHeight: 1.7, marginTop: 16 }}>
          {lang === 'ru'
            ? 'Сеть DTA позволяет избежать двойного налогообложения при переезде или удалённой работе на иностранных контрагентов.'
            : 'The DTA network helps avoid double taxation when relocating or working remotely with foreign counterparties.'}
        </p>
      </div>
    </div>
  );
}

function ProgramFaqSection({ lang }) {
  return (
    <div>
      {window.MIGRONIS_DATA.faq.slice(0, 4).map((it, i) => (
        <div key={i} style={{ padding: '20px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 17, fontWeight: 500, marginBottom: 10 }}>{it.q[lang]}</div>
          <div style={{ color: 'var(--fg-muted)', fontSize: 15, lineHeight: 1.7, maxWidth: 720 }}>{it.a[lang]}</div>
        </div>
      ))}
    </div>
  );
}

function ProgramBlogSection({ p, lang }) {
  const POSTS = lang === 'ru' ? [
    {
      kicker: 'ГРАЖДАНСТВО · 6 МИН ЧТЕНИЯ',
      title: `${window.cn(p, 'ru')} в 2026: кому подходит и как проходит процесс`,
      excerpt: `Подробный разбор программы: бюджет, сроки, подходящий профиль клиента и пошаговый процесс вместе с Migronis.`,
      tag: 'ПОДРОБНЫЙ ГАЙД',
    },
    {
      kicker: 'КЕЙС · 4 МИН ЧТЕНИЯ',
      title: `Кейс: семья 4 чел. · срок ${p.term} · бюджет ${p.currency === 'USD' ? '$' : '€'}${(p.minInvest/1000).toFixed(0)}k`,
      excerpt: `Как прошёл due diligence, какие были возражения и как обошлись без сюрпризов.`,
      tag: 'ИСТОРИЯ КЛИЕНТА',
    },
    {
      kicker: 'НАЛОГИ · 5 МИН ЧТЕНИЯ',
      title: `${p.tax}: как применить после получения статуса`,
      excerpt: `Объясняем рабочие схемы оптимизации без схем. На реальных примерах 2024–2025.`,
      tag: 'НАЛОГОВОЕ ПЛАНИРОВАНИЕ',
    },
  ] : [
    {
      kicker: 'CITIZENSHIP · 6 MIN READ',
      title: `${window.cn(p, 'en')} in 2026: who it fits and how the process works`,
      excerpt: `A walkthrough of the program – budget, timeline, the client profile that fits, and the step-by-step process with Migronis.`,
      tag: 'DEEP GUIDE',
    },
    {
      kicker: 'CASE · 4 MIN READ',
      title: `Case study: family of 4 · ${p.term} · budget ${p.currency === 'USD' ? '$' : '€'}${(p.minInvest/1000).toFixed(0)}k`,
      excerpt: `How due diligence went, what objections came up, and how we closed without surprises.`,
      tag: 'CLIENT STORY',
    },
    {
      kicker: 'TAX · 5 MIN READ',
      title: `${p.tax}: how to apply it once you hold the status`,
      excerpt: `We explain working optimisation paths – no shady schemes. Backed by 2024–2025 cases.`,
      tag: 'TAX PLANNING',
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24, flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>
            – {lang === 'ru' ? `Блог · ${window.cn(p, 'ru')}` : `Blog · ${window.cn(p, 'en')}`}
          </div>
          <h3 className="display" style={{ fontSize: 'clamp(26px, 2.4vw, 36px)', margin: 0, maxWidth: 640 }}>
            {lang === 'ru'
              ? <>Экспертные статьи и <em>кейсы</em> по {window.cn(p, 'ru')}</>
              : <>Expert articles and <em>case studies</em> for {window.cn(p, 'en')}</>}
          </h3>
        </div>
        <button className="btn btn-line btn-sm">
          {lang === 'ru' ? 'Все статьи' : 'All articles'} →
        </button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
        {POSTS.map((post, i) => (
          <article key={i} className="lift card-surface" style={{
            display: 'flex', flexDirection: 'column', overflow: 'hidden', cursor: 'pointer',
          }}>
            <div className="img-ph" data-label={`PHOTO · ${window.cn(p, 'en').toUpperCase()}`}
                 style={{ aspectRatio: '4/3', border: 0, borderBottom: '1px solid var(--border)' }} />
            <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)', letterSpacing: '0.08em' }}>
                {post.kicker}
              </div>
              <div className="display" style={{ fontSize: 19, lineHeight: 1.2, fontWeight: 700 }}>
                {post.title}
              </div>
              <p style={{ margin: 0, color: 'var(--fg-muted)', fontSize: 14, lineHeight: 1.55 }}>
                {post.excerpt}
              </p>
              <div style={{ marginTop: 'auto', paddingTop: 14, borderTop: '1px solid var(--border)',
                            display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span className="mono" style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.08em' }}>
                  {post.tag}
                </span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--fg)' }}>
                  {lang === 'ru' ? 'Читать' : 'Read'} →
                </span>
              </div>
            </div>
          </article>
        ))}
      </div>
    </div>
  );
}

window.ProgramDetail = ProgramDetail;
