// Compare screen – side-by-side passport/program comparison
function ComparePage({ lang, setRoute, initialKind, openCallback }) {
  const t = (ru, en) => (lang === 'ru' ? ru : en);
  const [kind, setKind] = React.useState(initialKind || 'cbi');
  const list = kind === 'cbi' ? window.MIGRONIS_DATA.citizenship : window.MIGRONIS_DATA.residency;
  const [selected, setSelected] = React.useState(list.slice(0, 4).map((p) => p.id));

  React.useEffect(() => {
    setSelected(list.slice(0, 4).map((p) => p.id));
  }, [kind]);

  const programs = selected.map((id) => list.find((p) => p.id === id)).filter(Boolean);

  const ROWS = [
    {
      k: t('Минимальная инвестиция', 'Min investment'),
      get: (p) => `${p.currency === 'USD' ? '$' : '€'}${(p.minInvest/1000).toFixed(0)}k`,
      raw: (p) => p.minInvest,
      bestIs: 'min',
      mono: true, hi: true,
    },
    {
      k: t('Срок', 'Timeline'),
      get: (p) => window.termLabel(p.term, lang),
      raw: (p) => parseInt(p.term, 10) || 99,
      bestIs: 'min',
      mono: true,
    },
    {
      k: t('Визовый доступ', 'Visa-free'),
      get: (p) => `${p.visaFree} ${t('стран','countries')}`,
      raw: (p) => p.visaFree,
      bestIs: 'max',
      mono: true,
    },
    { k: t('Налоги', 'Tax'),     get: (p) => p.tax },
    { k: t('Регион', 'Region'),  get: (p) => (window.regionLabel ? window.regionLabel(p.region, lang) : p.region) },
    { k: t('Маршрут', 'Route'),  get: (p) => p.route },
  ];

  const togglePick = (id) => {
    if (selected.includes(id)) {
      if (selected.length > 2) setSelected(selected.filter((x) => x !== id));
    } else if (selected.length < 5) {
      setSelected([...selected, id]);
    }
  };

  return (
    <div style={{ paddingTop: 32, paddingBottom: 80 }}>
      <div className="container-wide">
        <div style={{ marginBottom: 24 }}>
          <window.BackButton lang={lang} />
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 32, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>{t('– Сравнение программ', '– Compare')}</div>
            <h1 className="display" style={{ fontSize: 'clamp(36px, 4vw, 56px)', margin: 0 }}>
              {lang === 'ru'
                ? <>Параметры рядом<br/>Выбор <span className="ds">–</span> <em>проще</em></>
                : <>All parameters side-by-side<br/>Choice <span className="ds">–</span> <em>easier</em></>}
            </h1>
          </div>
          <div className="tabs">
            <button className={`tab ${kind === 'cbi' ? 'is-active' : ''}`} onClick={() => setKind('cbi')}>
              {t('Гражданство', 'Citizenship')}
            </button>
            <button className={`tab ${kind === 'rbi' ? 'is-active' : ''}`} onClick={() => setKind('rbi')}>
              {t('Резидентство', 'Residency')}
            </button>
          </div>
        </div>

        {/* Action bar */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexWrap: 'wrap', gap: 8 }}>
          <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
            {t('Выберите 2–5 программ для сравнения. Лучшие значения отмечены зелёным.',
               'Pick 2–5 programs to compare. Best values highlighted in green.')}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => window.print()}>
              ⬇ {t('Скачать PDF', 'Download PDF')}
            </button>
            <button className="btn btn-ghost btn-sm"
              onClick={() => {
                const url = window.location.href + `#compare-${kind}-${selected.join(',')}`;
                navigator.clipboard?.writeText(url);
                alert(t('Ссылка скопирована', 'Link copied'));
              }}>
              ⎘ {t('Поделиться', 'Share link')}
            </button>
          </div>
        </div>

        {/* Picker */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 24, flexWrap: 'wrap' }}>
          {list.map((p) => (
            <button key={p.id} onClick={() => togglePick(p.id)}
              className="chip"
              style={{
                height: 34, background: selected.includes(p.id) ? 'var(--accent-soft)' : 'var(--surface)',
                borderColor: selected.includes(p.id) ? 'var(--accent)' : 'var(--border)',
                color: 'var(--fg)', cursor: 'pointer',
              }}>
              <window.FlagIcon emoji={p.flag} size={14} />
              <span>{window.cn(p, lang)}</span>
              {selected.includes(p.id) && <span style={{ color: 'var(--accent)' }}>✓</span>}
            </button>
          ))}
        </div>

        {/* Table */}
        <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
          {/* Heads */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: `220px repeat(${programs.length}, minmax(160px, 1fr))`,
            background: 'var(--surface)', borderBottom: '1px solid var(--border)',
          }}>
            <div style={{ padding: 18 }}></div>
            {programs.map((p) => (
              <div key={p.id} style={{ padding: 18, textAlign: 'left' }}>
                <div><window.FlagIcon emoji={p.flag} size={20} /></div>
                <div style={{ fontWeight: 500, marginTop: 6 }}>{window.cn(p, lang)}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>{p.tagline[lang]}</div>
              </div>
            ))}
          </div>
          {/* Rows */}
          {ROWS.map((row, i) => {
            // Compute best value per row
            let bestVal = null, worstVal = null;
            if (row.bestIs && row.raw) {
              const vals = programs.map(row.raw);
              bestVal = row.bestIs === 'min' ? Math.min(...vals) : Math.max(...vals);
              worstVal = row.bestIs === 'min' ? Math.max(...vals) : Math.min(...vals);
            }
            return (
              <div key={i} style={{
                display: 'grid',
                gridTemplateColumns: `220px repeat(${programs.length}, minmax(160px, 1fr))`,
                borderBottom: i < ROWS.length - 1 ? '1px solid var(--border)' : 'none',
              }}>
                <div style={{ padding: 18, fontSize: 13, color: 'var(--fg-muted)' }}>{row.k}</div>
                {programs.map((p) => {
                  const v = row.raw ? row.raw(p) : null;
                  const isBest = bestVal !== null && v === bestVal && bestVal !== worstVal;
                  return (
                    <div key={p.id} style={{
                      padding: 18,
                      fontSize: row.hi ? 18 : 14,
                      fontFamily: row.mono ? 'var(--f-mono)' : 'inherit',
                      color: isBest ? 'var(--ok)' : (row.hi ? 'var(--accent)' : 'var(--fg)'),
                      fontWeight: isBest ? 600 : 'inherit',
                      position: 'relative',
                      background: isBest ? 'rgba(111,178,138,0.06)' : 'transparent',
                    }}>
                      {row.get(p)}
                      {isBest && (
                        <span style={{
                          position: 'absolute', right: 14, top: 18,
                          fontSize: 10, color: 'var(--ok)', fontFamily: 'var(--f-mono)',
                          letterSpacing: '0.06em', textTransform: 'uppercase',
                        }}>{t('лучшее','best')}</span>
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })}
          {/* CTA row */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: `220px repeat(${programs.length}, minmax(160px, 1fr))`,
            background: 'var(--surface)', borderTop: '1px solid var(--border)',
          }}>
            <div style={{ padding: 14 }}></div>
            {programs.map((p) => (
              <div key={p.id} style={{ padding: 14 }}>
                <button className="btn btn-line btn-sm" style={{ width: '100%' }}
                        onClick={() => setRoute({ name: 'program', id: p.id })}>
                  {t('Подробнее', 'Details')} →
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Post-table consultation block – per Nastya */}
        {openCallback && (
          <div style={{
            marginTop: 32, padding: '36px 40px',
            background: '#191C1F', color: '#FFFFFF',
            display: 'grid', gridTemplateColumns: '1.6fr auto',
            gap: 32, alignItems: 'center',
          }}>
            <div>
              <div className="mono" style={{
                fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase',
                color: 'rgba(255,255,255,0.6)', marginBottom: 10,
              }}>– {t('Сравнили — что дальше', 'Done comparing — what next')}</div>
              <h3 className="display" style={{
                margin: 0, fontSize: 'clamp(22px, 2.4vw, 32px)',
                lineHeight: 1.1, letterSpacing: '-0.02em', fontWeight: 700,
                color: '#FFFFFF',
              }}>
                {lang === 'ru'
                  ? <>Не уверены, какая программа <em>ваша</em>?</>
                  : <>Not sure which program <em>fits you</em>?</>}
              </h3>
              <p style={{ margin: '10px 0 0', color: 'rgba(255,255,255,0.74)', fontSize: 14, lineHeight: 1.55, maxWidth: 560 }}>
                {t('30-минутный звонок с лицензированным агентом. Соберём личный шорт-лист под бюджет, сроки и состав семьи.',
                  '30-min call with a licensed agent. We will build a personal shortlist for your budget, timeline and family.')}
              </p>
            </div>
            <button onClick={openCallback}
              style={{
                height: 52, padding: '0 26px',
                background: '#FFFFFF', color: '#191C1F', border: '1px solid #FFFFFF',
                fontSize: 13, fontWeight: 600, letterSpacing: '0.04em',
                textTransform: 'uppercase', fontFamily: 'var(--f-sans)',
                cursor: 'pointer', whiteSpace: 'nowrap',
              }}>
              {t('Бесплатная консультация →', 'Free consultation →')}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function AboutPage({ lang, setRoute, openCallback }) {
  const t = (ru, en) => (lang === 'ru' ? ru : en);
  const team = window.MIGRONIS_DATA.team;
  return (
    <div style={{ paddingTop: 32, paddingBottom: 80 }}>
      <div className="container" style={{ maxWidth: 880 }}>
        <div style={{ marginBottom: 24 }}>
          <window.BackButton lang={lang} />
        </div>

        <div className="eyebrow" style={{ marginBottom: 12 }}>{t('– О компании', '– About')}</div>
        <h1 className="display" style={{
          fontSize: 'clamp(36px, 4.5vw, 64px)', margin: 0,
          lineHeight: 1.05, letterSpacing: '-0.02em', fontWeight: 700,
          maxWidth: 820,
        }}>
          {lang === 'ru'
            ? <>С <em>2012</em> года помогаем семьям жить <em>без границ</em></>
            : <>Since <em>2012</em> we help families live <em>without borders</em></>}
        </h1>

        <p style={{ fontSize: 18, color: 'var(--fg-muted)', lineHeight: 1.6, marginTop: 32, maxWidth: 700 }}>
          {window.MIGRONIS_DATA.founderStory[lang]}
        </p>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24, marginTop: 48 }}>
          {window.MIGRONIS_DATA.trust.metrics.map((m, i) => (
            <div key={i}>
              <div className="display" style={{ fontSize: 40, color: 'var(--accent)' }}>{m.value}</div>
              <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 6 }}>{m.label[lang]}</div>
            </div>
          ))}
        </div>

        {/* Where the team lives – Borderless map line */}
        <div style={{ marginTop: 64, paddingTop: 24, borderTop: '1px solid var(--border-strong)' }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>{t('– Где живёт команда', '– Where the team lives')}</div>
          <div className="display" style={{ fontSize: 'clamp(22px, 2.4vw, 36px)', lineHeight: 1.15 }}>
            {lang === 'ru'
              ? <>Эшторил · Лиссабон · <em>Флорианополис</em> · Меделин</>
              : <>Estoril · Lisbon · <em>Florianópolis</em> · Medellín</>}
          </div>
        </div>

        {/* Team – quote per member + column */}
        <h2 className="display" style={{ fontSize: 'clamp(28px, 3vw, 44px)', marginTop: 80 }}>
          {t('Команда – прямая речь', 'The team – in their own words')}
        </h2>

        <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          {team.map((m) => (
            <article key={m.name} style={{
              padding: 28, background: 'var(--bg)', border: '1px solid var(--border)',
              display: 'flex', flexDirection: 'column', gap: 16,
            }}>
              <header style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                <div className="img-ph" data-label={m.name.split(' ')[0]}
                     style={{ width: 64, height: 64, flexShrink: 0, borderRadius: 0 }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--f-sans)', fontWeight: 600, fontSize: 16, letterSpacing: '-0.01em' }}>{lang === 'ru' && m.nameRu ? m.nameRu : m.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2, lineHeight: 1.4 }}>{m.role[lang]}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)', marginTop: 6, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                    {m.basedIn[lang]}
                  </div>
                </div>
              </header>

              <blockquote style={{
                margin: 0, fontFamily: 'var(--f-display)', fontStyle: 'italic',
                fontSize: 18, lineHeight: 1.45, color: 'var(--fg)', fontWeight: 400,
              }}>
                {m.quote[lang]}
              </blockquote>

              <footer style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
                paddingTop: 14, borderTop: '1px solid var(--border)', flexWrap: 'wrap',
              }}>
                {m.column ? (
                  <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', letterSpacing: '0.02em' }}>
                    {m.column[lang]} →
                  </div>
                ) : <span />}
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {(m.socials || []).map((s) => (
                    <a key={s.label}
                       href={lang === 'en' && s.urlEn ? s.urlEn : s.url}
                       target="_blank" rel="noopener noreferrer"
                       className="chip" style={{ fontSize: 10 }}>{s.label}</a>
                  ))}
                </div>
              </footer>
            </article>
          ))}
        </div>

        <h2 className="display" style={{ fontSize: 'clamp(28px, 3vw, 44px)', marginTop: 96 }}>
          {t('Принципы работы', 'Operating principles')}
        </h2>
        <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          {[
            { n: '01', t: t('Прозрачный процесс', 'Transparent process'), d: t('Никаких скрытых расходов. Прозрачная цена и чёткий график платежей.', 'No hidden costs. Transparent pricing and a clear payment schedule.') },
            { n: '02', t: t('Личный менеджер на кейс', 'A personal case manager'), d: t('С первого звонка до выдачи паспорта/ВНЖ и будущего продления.', 'From the first call to passport/residency issuance and future renewals.') },
            { n: '03', t: t('Максимальная честность', 'Maximum honesty'), d: t('Честно говорим о недостатках и рисках программ.', 'We speak openly about program downsides and risks.') },
            { n: '04', t: t('Всегда свежие данные', 'Always fresh data'), d: t('Программы меняются постоянно — и мы всегда в курсе новых правил и тенденций рынка.', 'Programs change constantly — we stay on top of new rules and market trends.') },
          ].map((p) => (
            <div key={p.n} style={{ padding: 24, background: 'var(--bg)', border: '1px solid var(--border)' }}>
              <div className="mono" style={{ color: 'var(--fg-dim)', marginBottom: 12 }}>{p.n}</div>
              <div style={{ fontSize: 18, fontWeight: 500 }}>{p.t}</div>
              <div style={{ fontSize: 14, color: 'var(--fg-muted)', marginTop: 6 }}>{p.d}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Consultation slab – same as home (per Nastya 11.06) */}
      {openCallback && (
        <div style={{ marginTop: 64 }}>
          <window.CTABanner lang={lang} openCallback={() => openCallback()}
            variant="dark"
            kicker={t('Готовы начать?', 'Ready to start?')}
            title={lang === 'ru'
              ? <>Начните с <em>бесплатного звонка</em></>
              : <>Start with a <em>free call</em></>}
            body={t('30 минут с юристом Migronis. Получите чёткое понимание сроков, бюджета и следующих шагов.',
                    '30 minutes with a Migronis lawyer. Walk away with a clear timeline, budget and next steps.')} />
        </div>
      )}
    </div>
  );
}

window.ComparePage = ComparePage;
window.AboutPage = AboutPage;
