/* ─────────────────────────────────────────────────────────────────
   CorpSol — app shell (header, footer, modal, useT, helpers)
   ───────────────────────────────────────────────────────────────── */

// ── useT — re-render on language change ─────────────────────────────────────
function useT() {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => window.i18n.subscribe(() => force()), []);
  return window.i18n.t;
}

// ── Theme / typography / palette / radius / density driver ─────────────────
function applyTokens(t) {
  const root = document.documentElement;
  root.setAttribute('data-theme', t.dark ? 'dark' : 'light');
  root.setAttribute('data-density', t.density || 'regular');
  root.setAttribute('data-radius', t.radius || 'rounded');

  // font family
  const fonts = {
    manrope:    "'Manrope', system-ui, sans-serif",
    inter:      "'Inter', system-ui, sans-serif",
    space:      "'Space Grotesk', system-ui, sans-serif",
  };
  const fontDisplay = {
    manrope:    "'Manrope', system-ui, sans-serif",
    inter:      "'Inter Tight', 'Inter', system-ui, sans-serif",
    space:      "'Space Grotesk', system-ui, sans-serif",
  };
  root.style.setProperty('--font-body', fonts[t.font] || fonts.manrope);
  root.style.setProperty('--font-display', fontDisplay[t.font] || fontDisplay.manrope);

  // palette
  const palettes = {
    navy: {
      '--c-ink': '#0A1F44',
      '--c-ink-2': '#1a2a4e',
      '--c-mute': 'rgba(10, 31, 68, 0.58)',
      '--c-mute-2': 'rgba(10, 31, 68, 0.72)',
      '--c-faint': 'rgba(10, 31, 68, 0.36)',
      '--c-line': 'rgba(10, 31, 68, 0.08)',
      '--c-line-strong': 'rgba(10, 31, 68, 0.14)',
      '--c-accent': '#2563EB',
      '--c-accent-2': '#1d4ed8',
      '--c-accent-soft': 'rgba(37, 99, 235, 0.10)',
    },
    royal: {
      '--c-ink': '#001E5C',
      '--c-ink-2': '#0a2e75',
      '--c-mute': 'rgba(0, 30, 92, 0.58)',
      '--c-mute-2': 'rgba(0, 30, 92, 0.74)',
      '--c-faint': 'rgba(0, 30, 92, 0.36)',
      '--c-line': 'rgba(0, 30, 92, 0.08)',
      '--c-line-strong': 'rgba(0, 30, 92, 0.16)',
      '--c-accent': '#3B82F6',
      '--c-accent-2': '#2563EB',
      '--c-accent-soft': 'rgba(59, 130, 246, 0.12)',
    },
    teal: {
      '--c-ink': '#0F172A',
      '--c-ink-2': '#1e293b',
      '--c-mute': 'rgba(15, 23, 42, 0.6)',
      '--c-mute-2': 'rgba(15, 23, 42, 0.74)',
      '--c-faint': 'rgba(15, 23, 42, 0.36)',
      '--c-line': 'rgba(15, 23, 42, 0.08)',
      '--c-line-strong': 'rgba(15, 23, 42, 0.16)',
      '--c-accent': '#06B6D4',
      '--c-accent-2': '#0891B2',
      '--c-accent-soft': 'rgba(6, 182, 212, 0.12)',
    },
    mono: {
      '--c-ink': '#0B0B0F',
      '--c-ink-2': '#1c1c24',
      '--c-mute': 'rgba(11, 11, 15, 0.62)',
      '--c-mute-2': 'rgba(11, 11, 15, 0.78)',
      '--c-faint': 'rgba(11, 11, 15, 0.36)',
      '--c-line': 'rgba(11, 11, 15, 0.08)',
      '--c-line-strong': 'rgba(11, 11, 15, 0.16)',
      '--c-accent': '#1E40AF',
      '--c-accent-2': '#1e3a8a',
      '--c-accent-soft': 'rgba(30, 64, 175, 0.10)',
    },
  };
  const pal = palettes[t.palette] || palettes.navy;
  Object.entries(pal).forEach(([k, v]) => root.style.setProperty(k, v));
}

// ── Tweaks defaults — shared across all pages ──────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dark": false,
  "font": "manrope",
  "palette": "navy",
  "density": "regular",
  "radius": "rounded",
  "hero": "split"
}/*EDITMODE-END*/;

// ── Brand mark ──────────────────────────────────────────────────────────────
function Logo({ size = 28 }) {
  const h = Math.round(size * 1.5);
  return (
    <a href="/" aria-label="CorpSol" style={{ display: 'inline-flex', alignItems: 'center' }}>
      <img src="/corp-sol-loogoo.png.webp" alt="CorpSol" style={{ height: h, width: 'auto', display: 'block' }} />
    </a>
  );
}

// ── Lang switcher ──────────────────────────────────────────────────────────
function LangSwitch({ compact = false }) {
  const [lang, setLang] = React.useState(window.i18n.getLang());
  React.useEffect(() => window.i18n.subscribe((l) => setLang(l)), []);
  const labels = { ru: 'RU', kz: 'ҚАЗ', en: 'EN' };
  return (
    <div className="cs-lang" role="radiogroup" aria-label="Language">
      {window.i18n.langs().map((l) => (
        <button
          key={l}
          className={'cs-lang-btn' + (l === lang ? ' is-on' : '')}
          role="radio"
          aria-checked={l === lang}
          onClick={() => window.i18n.setLang(l)}
        >
          {labels[l]}
        </button>
      ))}
    </div>
  );
}

// ── Header ─────────────────────────────────────────────────────────────────
function Header({ current = 'home', onOpenModal }) {
  const t = useT();
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [svcOpen, setSvcOpen] = React.useState(false);

  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on(); window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  const nav = [
    { key: 'services', label: t('nav.services'), dropdown: [
      { label: t('nav.services.leadgen'), href: '/#services' },
      { label: t('nav.services.callbase'), href: '/#services' },
      { label: t('nav.services.pharma'), href: '/#services' },
      { label: t('nav.services.webinars'), href: '/#services' },
    ] },
    { key: 'quanta', label: t('nav.quanta'), href: 'https://omnivoice.tilda.ws/#rightsld', external: true },
    { key: 'insight', label: t('nav.insight'), href: 'https://insightlab.kz', external: true },
    { key: 'team', label: t('nav.team'), href: '/team' },
    { key: 'contacts', label: t('nav.contacts'), href: '/contacts' },
  ];

  return (
    <>
      <header className={'cs-header' + (scrolled ? ' is-scrolled' : '')}>
        <div className="cs-container cs-container--wide cs-header-inner">
          <Logo size={48} />
          <nav className="cs-nav" aria-label="Primary">
            {nav.map((n) => n.dropdown ? (
              <div key={n.key} className="cs-nav-item cs-nav-drop"
                   onMouseEnter={() => setSvcOpen(true)}
                   onMouseLeave={() => setSvcOpen(false)}>
                <button className={'cs-nav-link' + (current === n.key ? ' is-active' : '')}>
                  {n.label}
                  <svg width="10" height="6" viewBox="0 0 10 6" style={{ marginLeft: 4 }}>
                    <path d="M1 1l4 4 4-4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
                {svcOpen && (
                  <div className="cs-nav-menu">
                    {n.dropdown.map((d) => (
                      <a key={d.label} href={d.href} className="cs-nav-menu-item">{d.label}</a>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              <a key={n.key} href={n.href}
                 target={n.external ? '_blank' : undefined}
                 rel={n.external ? 'noopener' : undefined}
                 className={'cs-nav-link' + (current === n.key ? ' is-active' : '')}>
                {n.label}
                {n.external && (
                  <svg width="9" height="9" viewBox="0 0 10 10" style={{ marginLeft: 4, opacity: 0.5 }}>
                    <path d="M3 1h6v6M9 1L1 9" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" />
                  </svg>
                )}
              </a>
            ))}
          </nav>
          <div className="cs-header-right">
            <LangSwitch />
            <a className="cs-header-phone" href={'tel:' + t('nav.phone').replace(/\s|\(|\)|-/g, '')}>{t('nav.phone')}</a>
            <button className="cs-btn cs-btn--primary cs-btn--sm" onClick={onOpenModal}>
              {t('nav.cp')}
            </button>
            <button className="cs-burger" aria-label="Menu" onClick={() => setMobileOpen(true)}>
              <span /><span /><span />
            </button>
          </div>
        </div>
      </header>

      {mobileOpen && (
        <div className="cs-mobile-menu">
          <div className="cs-mobile-head">
            <Logo size={48} />
            <button className="cs-mobile-close" aria-label="Close" onClick={() => setMobileOpen(false)}>✕</button>
          </div>
          <div className="cs-mobile-body">
            <a href="/" className="cs-mobile-link">{t('nav.services')}</a>
            <a href="https://omnivoice.tilda.ws/#rightsld" target="_blank" rel="noopener" className="cs-mobile-link">{t('nav.quanta')}</a>
            <a href="https://insightlab.kz" target="_blank" rel="noopener" className="cs-mobile-link">{t('nav.insight')}</a>
            <a href="/team" className="cs-mobile-link">{t('nav.team')}</a>
            <a href="/contacts" className="cs-mobile-link">{t('nav.contacts')}</a>
            <div className="cs-mobile-foot">
              <LangSwitch />
              <a className="cs-btn cs-btn--primary cs-btn--block" onClick={() => { setMobileOpen(false); onOpenModal(); }}>
                {t('nav.cp')}
              </a>
            </div>
          </div>
        </div>
      )}

      <HeaderStyles />
    </>
  );
}

const HeaderStyles = () => (
  <style>{`
    .cs-header {
      position: sticky; top: 0; z-index: 50;
      background: color-mix(in oklab, var(--c-bg) 86%, transparent);
      backdrop-filter: blur(20px) saturate(150%);
      -webkit-backdrop-filter: blur(20px) saturate(150%);
      transition: padding 0.2s var(--ease), border-color 0.2s var(--ease);
      border-bottom: 1px solid transparent;
    }
    .cs-header.is-scrolled {
      border-bottom-color: var(--c-line);
    }
    .cs-header-inner {
      display: flex; align-items: center;
      gap: 36px;
      padding-top: 18px; padding-bottom: 18px;
      transition: padding 0.2s var(--ease);
    }
    .cs-header.is-scrolled .cs-header-inner { padding-top: 12px; padding-bottom: 12px; }
    .cs-nav { display: flex; align-items: center; gap: 4px; margin-left: 8px; }
    .cs-nav-link {
      display: inline-flex; align-items: center;
      padding: 8px 14px; border-radius: 999px;
      background: transparent; border: 0; cursor: pointer;
      color: var(--c-mute-2); font: inherit; font-size: 14.5px; font-weight: 500;
      transition: color 0.15s var(--ease), background 0.15s var(--ease);
    }
    .cs-nav-link:hover { color: var(--c-ink); background: var(--c-bg-soft); }
    .cs-nav-link.is-active { color: var(--c-ink); background: var(--c-bg-soft); }
    .cs-nav-drop { position: relative; }
    .cs-nav-menu {
      position: absolute; top: calc(100% + 8px); left: 0;
      min-width: 240px; padding: 8px;
      background: var(--c-bg); border-radius: 16px;
      box-shadow: var(--shadow-lg);
      display: flex; flex-direction: column; gap: 2px;
    }
    .cs-nav-menu-item {
      display: block; padding: 10px 12px; border-radius: 10px;
      color: var(--c-mute-2); font-size: 14px; font-weight: 500;
      transition: background 0.15s var(--ease), color 0.15s var(--ease);
    }
    .cs-nav-menu-item:hover { background: var(--c-bg-soft); color: var(--c-ink); }
    .cs-header-right { display: flex; align-items: center; gap: 12px; margin-left: auto; }
    .cs-header-phone {
      color: var(--c-ink); font-weight: 500; font-size: 14.5px;
      font-variant-numeric: tabular-nums;
    }
    .cs-burger { display: none; width: 40px; height: 40px; border: 0; background: var(--c-bg-soft); border-radius: 12px; cursor: pointer; flex-direction: column; gap: 4px; align-items: center; justify-content: center; }
    .cs-burger span { display: block; width: 18px; height: 1.5px; background: var(--c-ink); }

    .cs-lang { display: inline-flex; padding: 3px; background: var(--c-bg-soft); border-radius: 999px; }
    .cs-lang-btn {
      border: 0; background: transparent; cursor: pointer;
      padding: 5px 10px; border-radius: 999px;
      font: inherit; font-size: 11.5px; font-weight: 600; letter-spacing: 0.04em;
      color: var(--c-faint);
      transition: background 0.15s var(--ease), color 0.15s var(--ease);
    }
    .cs-lang-btn.is-on { background: var(--c-bg); color: var(--c-ink); box-shadow: 0 1px 2px rgba(10, 31, 68, 0.08); }
    .cs-lang-btn:hover:not(.is-on) { color: var(--c-mute-2); }

    @media (max-width: 1100px) {
      .cs-nav { display: none; }
      .cs-header-phone { display: none; }
    }
    @media (max-width: 720px) {
      .cs-lang { display: none; }
      .cs-burger { display: inline-flex; }
    }

    .cs-mobile-menu {
      position: fixed; inset: 0; z-index: 99;
      background: var(--c-bg);
      display: flex; flex-direction: column;
      animation: cs-fade 0.25s var(--ease);
    }
    .cs-mobile-head {
      display: flex; align-items: center; justify-content: space-between;
      padding: 18px var(--side-pad); border-bottom: 1px solid var(--c-line);
    }
    .cs-mobile-close {
      width: 40px; height: 40px; border: 0; background: var(--c-bg-soft); border-radius: 12px;
      font-size: 18px; cursor: pointer; color: var(--c-ink);
    }
    .cs-mobile-body { flex: 1; padding: 24px var(--side-pad); display: flex; flex-direction: column; gap: 4px; overflow: auto; }
    .cs-mobile-link {
      padding: 16px 0; font-size: 22px; font-weight: 600;
      color: var(--c-ink); border-bottom: 1px solid var(--c-line);
    }
    .cs-mobile-foot { margin-top: auto; padding-top: 24px; display: flex; flex-direction: column; gap: 16px; }
  `}</style>
);

// ── Footer ─────────────────────────────────────────────────────────────────
function Footer({ onOpenModal }) {
  const t = useT();
  return (
    <footer className="cs-footer">
      <div className="cs-container cs-container--wide">
        <div className="cs-footer-top">
          <div className="cs-footer-brand">
            <Logo size={60} />
            <p className="cs-footer-about">{t('foot.about')}</p>
            <div className="cs-footer-social">
              <a className="cs-social" href="https://t.me/iliyaszhakipbekov" target="_blank" rel="noopener" aria-label="Telegram">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M21.5 4.5L2.5 12.3c-.7.3-.7.7-.1.9l4.9 1.5 1.9 5.9c.2.6.6.6.9.3l2.7-2.5 5.4 4c1 .6 1.7.3 1.9-.9l3.4-15.9c.3-1.4-.5-2-1.4-1.6z"/></svg>
              </a>
              <a className="cs-social" href="https://www.instagram.com/corpsol_taraz/" target="_blank" rel="noopener" aria-label="Instagram">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></svg>
              </a>
            </div>
          </div>

          <div className="cs-footer-col">
            <h4 className="cs-footer-h">{t('foot.col.services')}</h4>
            <ul>
              <li><a href="/#services">{t('svc.1.t')}</a></li>
              <li><a href="/#services">{t('svc.2.t')}</a></li>
              <li><a href="https://omnivoice.tilda.ws/#rightsld" target="_blank" rel="noopener">Quanta — AI</a></li>
              <li><a href="https://insightlab.kz" target="_blank" rel="noopener">Insight Lab — CustDev</a></li>
              <li><a href="/#services">{t('svc.4.t')}</a></li>
              <li><a href="/#services">{t('svc.5.t')}</a></li>
            </ul>
          </div>

          <div className="cs-footer-col">
            <h4 className="cs-footer-h">{t('foot.col.contacts')}</h4>
            <ul>
              <li><span className="cs-mute">{t('foot.addr')}</span></li>
              <li><a href={'tel:' + t('foot.phone').replace(/\s|\(|\)|-/g, '')}>{t('foot.phone')}</a></li>
              <li><a href={'mailto:' + t('foot.email')}>{t('foot.email')}</a></li>
            </ul>
          </div>

          <div className="cs-footer-col">
            <h4 className="cs-footer-h">{t('foot.col.social')}</h4>
            <div className="cs-footer-ctas">
              <button className="cs-btn cs-btn--primary cs-btn--sm cs-btn--block" onClick={onOpenModal}>
                {t('foot.cta.client')}
              </button>
              <a className="cs-btn cs-btn--ghost cs-btn--sm cs-btn--block" href="/team">
                {t('foot.cta.team')}
              </a>
            </div>
          </div>
        </div>

        <div className="cs-footer-bot">
          <span>{t('foot.legal')}</span>
          <div className="cs-footer-legal">
            <a href="/privacy-policy">{t('foot.policy')}</a>
            <a href="/public-offer">{t('foot.offer')}</a>
          </div>
        </div>
      </div>

      <style>{`
        .cs-footer {
          background: var(--c-bg-soft);
          border-top: 1px solid var(--c-line);
          padding: 80px 0 32px;
        }
        .cs-footer-top {
          display: grid;
          grid-template-columns: 1.6fr 1fr 1fr 1fr;
          gap: 48px;
          padding-bottom: 56px;
          border-bottom: 1px solid var(--c-line);
        }
        .cs-footer-about { margin-top: 20px; color: var(--c-mute-2); max-width: 32ch; font-size: 14.5px; line-height: 1.55; }
        .cs-footer-social { display: flex; gap: 8px; margin-top: 20px; }
        .cs-social {
          display: inline-flex; align-items: center; justify-content: center;
          width: 40px; height: 40px; border-radius: 999px;
          background: var(--c-bg); color: var(--c-ink);
          transition: background 0.15s var(--ease), color 0.15s var(--ease);
        }
        .cs-social:hover { background: var(--c-ink); color: var(--c-bg); }
        .cs-footer-h { font-family: var(--font-display); font-size: 13px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--c-faint); margin-bottom: 18px; }
        .cs-footer-col ul { display: flex; flex-direction: column; gap: 10px; }
        .cs-footer-col a { color: var(--c-mute-2); font-size: 14.5px; transition: color 0.15s var(--ease); }
        .cs-footer-col a:hover { color: var(--c-ink); }
        .cs-footer-ctas { display: flex; flex-direction: column; gap: 10px; }
        .cs-footer-bot {
          display: flex; justify-content: space-between; flex-wrap: wrap;
          gap: 12px;
          padding-top: 24px;
          color: var(--c-faint); font-size: 13px;
        }
        .cs-footer-legal { display: flex; gap: 24px; }
        .cs-footer-legal a:hover { color: var(--c-ink); }
        @media (max-width: 900px) { .cs-footer-top { grid-template-columns: 1fr 1fr; gap: 32px; } }
        @media (max-width: 560px) { .cs-footer-top { grid-template-columns: 1fr; } }
      `}</style>
    </footer>
  );
}

// ── Modal: «Получить КП» — двухшаговая форма ───────────────────────────────
function CpModal({ open, onClose }) {
  const t = useT();
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    name: '', phone: '', company: '', sphere: '',
    services: [],
  });
  const [errors, setErrors] = React.useState({});
  const [done, setDone] = React.useState('idle'); // idle | loading | success | error

  React.useEffect(() => {
    if (open) {
      setStep(1); setErrors({}); setDone('idle');
      setForm({ name: '', phone: '', company: '', sphere: '', services: [] });
    }
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const toggleSvc = (s) => setForm((f) => ({
    ...f,
    services: f.services.includes(s) ? f.services.filter((x) => x !== s) : [...f.services, s],
  }));

  const validate1 = () => {
    const e = {};
    if (!form.name.trim()) e.name = t('err.required');
    const phoneClean = form.phone.replace(/[\s()\-+]/g, '');
    if (!form.phone.trim()) e.phone = t('err.required');
    else if (phoneClean.length < 10 || !/^\d+$/.test(phoneClean)) e.phone = t('err.phone');
    if (!form.company.trim()) e.company = t('err.required');
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (e) => {
    e.preventDefault();
    if (step === 1) {
      if (validate1()) setStep(2);
      return;
    }
    setDone('loading');
    fetch('/api/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    })
      .then((r) => (r.ok ? setDone('success') : setDone('error')))
      .catch(() => setDone('error'));
  };

  const svcOptions = [
    { k: 'lead', label: t('cta.svc.lead') },
    { k: 'call', label: t('cta.svc.call') },
    { k: 'custdev', label: t('cta.svc.custdev') },
    { k: 'ai', label: t('cta.svc.ai') },
    { k: 'other', label: t('cta.svc.other') },
  ];

  return (
    <div className="cs-modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="cs-modal cs-cp-modal" role="dialog" aria-modal="true" aria-label="Get proposal">
        <button className="cs-modal-close" aria-label="Close" onClick={onClose}>✕</button>

        {done === 'success' ? (
          <div className="cs-cp-thanks">
            <div className="cs-cp-check">
              <svg width="48" height="48" viewBox="0 0 48 48"><circle cx="24" cy="24" r="22" fill="var(--c-accent)" /><path d="M14 24l7 7 13-14" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h3 className="cs-h3" style={{ marginTop: 20 }}>{t('cta.thanks.t')}</h3>
            <p className="cs-mute" style={{ marginTop: 12, maxWidth: '42ch' }}>{t('cta.thanks.d')}</p>
            <button className="cs-btn cs-btn--primary" style={{ marginTop: 28 }} onClick={onClose}>
              {t('cta.thanks.close')}
            </button>
          </div>
        ) : done === 'error' ? (
          <div className="cs-cp-thanks">
            <div className="cs-cp-check">
              <svg width="48" height="48" viewBox="0 0 48 48"><circle cx="24" cy="24" r="22" fill="var(--c-warn)" /><path d="M16 16l16 16M32 16L16 32" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round"/></svg>
            </div>
            <h3 className="cs-h3" style={{ marginTop: 20 }}>Что-то пошло не так</h3>
            <p className="cs-mute" style={{ marginTop: 12, maxWidth: '42ch' }}>Пожалуйста, позвоните нам или напишите в Telegram — мы ответим в течение 15 минут.</p>
            <button className="cs-btn cs-btn--primary" style={{ marginTop: 28 }} onClick={() => setDone('idle')}>
              Попробовать снова
            </button>
          </div>
        ) : (
          <form onSubmit={submit} className="cs-cp-body">
            <div className="cs-cp-progress">
              <div className={'cs-cp-step ' + (step >= 1 ? 'is-on' : '')}>1</div>
              <div className="cs-cp-bar"><div style={{ width: step === 2 ? '100%' : '0%' }} /></div>
              <div className={'cs-cp-step ' + (step >= 2 ? 'is-on' : '')}>2</div>
            </div>

            <h3 className="cs-h3" style={{ marginTop: 16 }}>{t('cta.h2')}</h3>
            <p className="cs-mute" style={{ marginTop: 8 }}>{t('cta.sub')}</p>

            {step === 1 && (
              <div className="cs-cp-fields">
                <div>
                  <label className="cs-label">{t('cta.field.name')} *</label>
                  <input className={'cs-input' + (errors.name ? ' cs-input--error' : '')}
                         value={form.name} onChange={(e) => setField('name', e.target.value)} placeholder="Айгерим" />
                  {errors.name && <div className="cs-help-error">{errors.name}</div>}
                </div>
                <div>
                  <label className="cs-label">{t('cta.field.phone')} *</label>
                  <input className={'cs-input' + (errors.phone ? ' cs-input--error' : '')}
                         value={form.phone} onChange={(e) => setField('phone', e.target.value)} placeholder="+7 (___) ___-__-__" />
                  {errors.phone && <div className="cs-help-error">{errors.phone}</div>}
                </div>
                <div>
                  <label className="cs-label">{t('cta.field.company')} *</label>
                  <input className={'cs-input' + (errors.company ? ' cs-input--error' : '')}
                         value={form.company} onChange={(e) => setField('company', e.target.value)} placeholder="Astana Tech LLP" />
                  {errors.company && <div className="cs-help-error">{errors.company}</div>}
                </div>
                <div>
                  <label className="cs-label">{t('cta.field.sphere')}</label>
                  <input className="cs-input"
                         value={form.sphere} onChange={(e) => setField('sphere', e.target.value)} placeholder="SaaS / Fintech / Retail…" />
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="cs-cp-fields">
                <label className="cs-label">{t('cta.field.services')}</label>
                <div className="cs-cp-svcs">
                  {svcOptions.map((s) => (
                    <button type="button" key={s.k}
                            className={'cs-cp-svc' + (form.services.includes(s.k) ? ' is-on' : '')}
                            onClick={() => toggleSvc(s.k)}>
                      {form.services.includes(s.k) ? '✓' : '+'} {s.label}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="cs-cp-actions">
              {step === 2 && (
                <button type="button" className="cs-btn cs-btn--ghost" onClick={() => setStep(1)}>
                  {t('cta.back')}
                </button>
              )}
              <button type="submit" className="cs-btn cs-btn--primary" style={{ marginLeft: 'auto' }}
                      disabled={done === 'loading'}>
                {done === 'loading' ? '...' : step === 1 ? t('cta.next') : t('cta.submit')}
              </button>
            </div>

            <p className="cs-cp-policy"><a href="/privacy-policy" style={{ color: 'inherit', textDecoration: 'underline' }}>{t('cta.policy')}</a></p>
          </form>
        )}
      </div>

      <style>{`
        .cs-cp-modal { padding: 32px; position: relative; }
        .cs-modal-close {
          position: absolute; top: 16px; right: 16px;
          width: 36px; height: 36px; border: 0; border-radius: 999px;
          background: var(--c-bg-soft); color: var(--c-mute-2); cursor: pointer;
          font-size: 14px;
        }
        .cs-modal-close:hover { background: var(--c-ink); color: var(--c-bg); }

        .cs-cp-progress { display: flex; align-items: center; gap: 12px; }
        .cs-cp-step {
          width: 28px; height: 28px; border-radius: 999px;
          background: var(--c-bg-soft); color: var(--c-faint);
          font-size: 13px; font-weight: 600;
          display: inline-flex; align-items: center; justify-content: center;
          transition: background 0.2s var(--ease), color 0.2s var(--ease);
        }
        .cs-cp-step.is-on { background: var(--c-accent); color: #fff; }
        .cs-cp-bar { flex: 1; height: 2px; background: var(--c-bg-muted); border-radius: 999px; overflow: hidden; }
        .cs-cp-bar > div { height: 100%; background: var(--c-accent); transition: width 0.3s var(--ease); }

        .cs-cp-fields { display: grid; gap: 16px; grid-template-columns: 1fr 1fr; margin-top: 24px; }
        .cs-cp-fields > *:last-child { grid-column: 1 / -1; }
        .cs-cp-fields > *:first-child { grid-column: 1 / -1; }
        @media (max-width: 520px) { .cs-cp-fields { grid-template-columns: 1fr; } .cs-cp-fields > * { grid-column: 1 / -1 !important; } }

        .cs-cp-svcs { display: flex; flex-wrap: wrap; gap: 8px; }
        .cs-cp-svc {
          padding: 10px 16px; border-radius: 999px;
          border: 1px solid var(--c-line-strong); background: var(--c-bg);
          color: var(--c-mute-2); font: inherit; font-size: 14px; font-weight: 500;
          cursor: pointer; transition: all 0.15s var(--ease);
        }
        .cs-cp-svc:hover { border-color: var(--c-ink); color: var(--c-ink); }
        .cs-cp-svc.is-on { background: var(--c-accent); border-color: var(--c-accent); color: #fff; }

        .cs-cp-actions { display: flex; gap: 12px; margin-top: 24px; align-items: center; }
        .cs-cp-policy { margin-top: 16px; font-size: 12px; color: var(--c-faint); text-align: center; }

        .cs-cp-thanks { padding: 24px 0; text-align: center; display: flex; flex-direction: column; align-items: center; }
      `}</style>
    </div>
  );
}

// ── ModalProvider — global modal state + opener ────────────────────────────
function useModal() {
  const [open, setOpen] = React.useState(false);
  return { open, openModal: () => setOpen(true), closeModal: () => setOpen(false) };
}

// ── Scroll reveal ──────────────────────────────────────────────────────────
function useReveal() {
  React.useEffect(() => {
    const observe = () => {
      const els = document.querySelectorAll('.cs-reveal:not(.is-in)');
      if (els.length === 0) return;
      if (!('IntersectionObserver' in window)) {
        els.forEach((e) => e.classList.add('is-in'));
        return;
      }
      const io = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { e.target.classList.add('is-in'); io.unobserve(e.target); }
        });
      }, { threshold: 0.12, rootMargin: '0px 0px -60px 0px' });
      els.forEach((e) => io.observe(e));
    };
    // Initial pass + a follow-up after layout settles
    observe();
    const id = setTimeout(observe, 200);
    return () => clearTimeout(id);
  }, []);
}

// ── Tweaks panel — shared across pages ─────────────────────────────────────
function SiteTweaks({ tweaks, setTweak }) {
  const t = useT();
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Theme">
        <TweakToggle label="Dark mode" value={tweaks.dark} onChange={(v) => setTweak('dark', v)} />
      </TweakSection>
      <TweakSection label="Palette">
        <TweakColor label="Accent"
                    value={[
                      tweaks.palette === 'navy' ? '#0A1F44' :
                      tweaks.palette === 'royal' ? '#001E5C' :
                      tweaks.palette === 'teal' ? '#0F172A' : '#0B0B0F',
                      tweaks.palette === 'navy' ? '#2563EB' :
                      tweaks.palette === 'royal' ? '#3B82F6' :
                      tweaks.palette === 'teal' ? '#06B6D4' : '#1E40AF',
                    ]}
                    options={[
                      ['#0A1F44', '#2563EB'],
                      ['#001E5C', '#3B82F6'],
                      ['#0F172A', '#06B6D4'],
                      ['#0B0B0F', '#1E40AF'],
                    ]}
                    onChange={(v) => {
                      const map = { '#0a1f44': 'navy', '#001e5c': 'royal', '#0f172a': 'teal', '#0b0b0f': 'mono' };
                      setTweak('palette', map[String(v[0]).toLowerCase()] || 'navy');
                    }} />
      </TweakSection>
      <TweakSection label="Typography">
        <TweakRadio label="Font" value={tweaks.font}
                    options={[{ value: 'manrope', label: 'Manrope' }, { value: 'inter', label: 'Inter' }, { value: 'space', label: 'Space' }]}
                    onChange={(v) => setTweak('font', v)} />
      </TweakSection>
      <TweakSection label="Layout">
        <TweakRadio label="Density" value={tweaks.density}
                    options={[{ value: 'compact', label: 'Tight' }, { value: 'regular', label: 'Reg' }, { value: 'cozy', label: 'Roomy' }]}
                    onChange={(v) => setTweak('density', v)} />
        <TweakRadio label="Radius" value={tweaks.radius}
                    options={[{ value: 'sharp', label: 'Sharp' }, { value: 'rounded', label: 'Round' }, { value: 'pill', label: 'Pill' }]}
                    onChange={(v) => setTweak('radius', v)} />
      </TweakSection>
      <TweakSection label="Hero">
        <TweakRadio label="Layout" value={tweaks.hero}
                    options={[{ value: 'split', label: 'Split' }, { value: 'stack', label: 'Stack' }, { value: 'editorial', label: 'Big' }]}
                    onChange={(v) => setTweak('hero', v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// Minimal useTweaks for production: returns fixed defaults, ignores setTweak.
// In the design environment tweaks-panel.jsx overrides this with the full version.
if (!window.useTweaks) {
  window.useTweaks = function useTweaks(defaults) {
    return [defaults, () => {}];
  };
}

// expose to other Babel scripts
Object.assign(window, {
  useT, applyTokens, TWEAK_DEFAULTS,
  Logo, LangSwitch, Header, Footer, CpModal, useModal, useReveal,
  SiteTweaks,
});
