/* TurboSwift — «Снабжение» landing kit. Shared sections + live feature widgets.
   Exposes window.SupplyKit. Loaded after header.jsx (which provides window.Site).
   NOTE: font-grotesk == Anton (very tall display face) — wrapping headings need
   generous inline line-height, so headings set lineHeight inline (purge-proof). */
;(function () {
  const { Icons, useLang, useTheme, Footer, ConsentCheck } = window.Site;

  /* ---------- extra line icons (lucide-style, same Svg contract as header) ---------- */
  const Svg = ({ size = 22, sw = 2, children }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">{children}</svg>
  );
  const Ico = {
    Search: (p) => <Svg {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></Svg>,
    Truck: (p) => <Svg {...p}><path d="M14 18V6H2v12h2"/><path d="M14 9h4l4 4v5h-2"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="18" r="2"/></Svg>,
    Shield: (p) => <Svg {...p}><path d="M12 3 4 6v6c0 4.5 3.3 7.7 8 9 4.7-1.3 8-4.5 8-9V6l-8-3z"/></Svg>,
    Send: (p) => <Svg {...p}><path d="M22 3 2 11l6 2.5L18 6 10 15v5l3.5-3.2L18 19l4-16z"/></Svg>,
    Target: (p) => <Svg {...p}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1"/></Svg>,
    Coins: (p) => <Svg {...p}><circle cx="8" cy="8" r="6"/><path d="M18.1 10.4a6 6 0 1 1-8 8"/><path d="M7 6h1v4M16.7 14.3v-1h-1"/></Svg>,
    Gauge: (p) => <Svg {...p}><path d="M12 14 9 9"/><path d="M3.3 16a9 9 0 1 1 17.4 0"/><circle cx="12" cy="14" r="1.5"/></Svg>,
    Database: (p) => <Svg {...p}><ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5"/><path d="M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/></Svg>,
    Check: Icons.Check, Arrow: Icons.Arrow, Bolt: Icons.Bolt,
    Clock: (p) => <Svg {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></Svg>,
  };

  const SHELL = 'max-w-[1120px] w-full mx-auto px-6 md:px-10';
  // line-heights tuned for Anton/Fjalla so wrapped headings never collide
  const LH = { hero: 1.08, h2: 1.12, card: 1.2, q: 1.22 };

  /* ---------- breadcrumb ---------- */
  function Crumb({ lang, current }) {
    const root = lang === 'ru' ? 'Снабжение' : 'Procurement';
    return (
      <div className="flex items-center gap-2 font-mono uppercase text-[11px] text-cream/45 mb-5">
        <a href="/agents?a=nina" className="hover:text-neon transition-colors">{root}</a>
        <span style={{ opacity: 0.5 }}>/</span>
        <span className="text-cream/70">{current}</span>
      </div>
    );
  }

  /* ---------- hero ---------- */
  function Hero({ hf, cf, lang, eyebrow, h1a, h1b, sub, current, visual, primaryEv }) {
    return (
      <section data-theme="dark" className="relative w-full overflow-hidden rounded-b-[32px]" style={{ background: 'radial-gradient(125% 120% at 15% 0%, #0a1c54 0%, #050f33 48%, #010828 100%)' }}>
        <div className={SHELL + ' relative z-10 pt-10 pb-20 md:pb-28'}>
          <div className="sup-hero-grid pt-8 md:pt-12">
            <div>
              <Crumb lang={lang} current={current} />
              <span className="sup-eyebrow mb-4">{eyebrow}</span>
              <h1 className={hf + ' uppercase text-cream text-[32px] sm:text-[46px] lg:text-[58px] mt-3'} style={{ lineHeight: LH.hero }}>
                {h1a} <span className="text-neon" style={{ textShadow: '0 0 38px rgba(111,255,0,0.28)' }}>{h1b}</span>
              </h1>
              <p className="font-mono text-[14px] sm:text-[15px] text-cream/80 leading-relaxed mt-6 max-w-[470px]">{sub}</p>
              <div className="flex flex-wrap items-center gap-3 mt-8">
                <a href="/register" data-ev={primaryEv} className={hf + ' inline-flex items-center gap-2 whitespace-nowrap bg-neon text-background uppercase text-[14px] px-7 py-4 rounded-[1rem] hover:scale-[1.02] transition-transform'}>
                  {lang === 'ru' ? 'Получить доступ' : 'Get access'} <Ico.Arrow size={17} />
                </a>
                <a href="#how" className={hf + ' inline-flex items-center gap-2 whitespace-nowrap liquid-glass text-cream uppercase text-[14px] px-7 py-4 rounded-[1rem] hover:text-neon transition-colors'}>
                  {lang === 'ru' ? 'Как это работает' : 'How it works'}
                </a>
              </div>
            </div>
            <div className="w-full min-w-0">{visual}</div>
          </div>
        </div>
      </section>
    );
  }

  /* ---------- how it works (3 steps) ---------- */
  function Steps({ hf, lang, eyebrow, title, steps }) {
    return (
      <section id="how" className="sup-anchor bg-background">
        <div className={SHELL + ' py-20 md:py-28'}>
          <span className="sup-eyebrow">{eyebrow}</span>
          <h2 className={hf + ' uppercase text-cream text-[28px] sm:text-[34px] lg:text-[42px] mt-4 mb-10 max-w-[640px]'} style={{ lineHeight: LH.h2 }}>{title}</h2>
          <div className="sup-steps-grid">
            {steps.map((s, i) => (
              <div key={i} className="liquid-glass rounded-[24px] p-8 flex flex-col" data-reveal>
                <div className="flex items-center gap-4 mb-5">
                  <div className="sup-step-num">{String(i + 1).padStart(2, '0')}</div>
                </div>
                <h3 className={hf + ' uppercase text-cream text-[18px] sm:text-[20px] mb-3'} style={{ lineHeight: LH.card }}>{s.title}</h3>
                <p className="font-mono text-[13px] text-cream/70 leading-relaxed">{s.text}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  /* ---------- benefits ---------- */
  function Benefits({ hf, lang, eyebrow, title, items }) {
    return (
      <section className="bg-background">
        <div className={SHELL + ' pb-20 md:pb-28'}>
          <span className="sup-eyebrow">{eyebrow}</span>
          <h2 className={hf + ' uppercase text-cream text-[28px] sm:text-[34px] lg:text-[42px] mt-4 mb-10 max-w-[640px]'} style={{ lineHeight: LH.h2 }}>{title}</h2>
          <div className="sup-benefits-grid">
            {items.map((b, i) => {
              const I = b.icon;
              return (
                <div key={i} className="liquid-glass rounded-[24px] p-8 flex flex-col" data-reveal>
                  <div className="sup-ico mb-5"><I size={22} /></div>
                  <h3 className={hf + ' uppercase text-cream text-[17px] sm:text-[19px] mb-3'} style={{ lineHeight: LH.card }}>{b.title}</h3>
                  <p className="font-mono text-[13px] text-cream/70 leading-relaxed">{b.text}</p>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    );
  }

  /* ---------- meet Nina — character band ---------- */
  const NINA = {
    ru: { cursive: 'знакомься', name: 'Нина', role: 'AI-снабженец', status: 'онлайн 24/7',
      desc: 'Нина — твой агент снабжения. Ищет поставщиков, считает доставку, проверяет контрагентов и рассылает запросы — а ты занимаешься бизнесом, а не рутиной.',
      skills: ['Находит и оценивает поставщиков', 'Считает доставку по 8+ транспортным', 'Проверяет контрагентов по ИНН', 'Рассылает запросы с твоих ящиков'],
      eff: 'статус', profile: 'Профиль Нины', cta: 'Получить доступ' },
    en: { cursive: 'meet', name: 'Nina', role: 'AI procurement', status: 'online 24/7',
      desc: 'Nina is your procurement agent. She sources suppliers, prices shipping, vets counterparties and sends RFQs — so you run the business, not the busywork.',
      skills: ['Finds & rates suppliers', 'Prices shipping across 8+ carriers', 'Vets counterparties by INN', 'Sends RFQs from your mailboxes'],
      eff: 'status', profile: 'Meet Nina', cta: 'Get access' },
  };
  function AgentBand({ hf, cf, lang, focusIndex }) {
    const t = NINA[lang];
    const vref = React.useRef(null);
    React.useEffect(() => {
      const v = vref.current; if (!v) return;
      let tries = 0;
      const id = setInterval(() => {
        tries++;
        const r = v.getBoundingClientRect();
        if (r.top < window.innerHeight + 200 && r.bottom > -200) {
          const s = v.getAttribute('src') || v.dataset.src;
          if (s && v.getAttribute('src') !== s) v.setAttribute('src', s);
          v.muted = true; v.style.opacity = '1';
          const p = v.play && v.play(); if (p && p.catch) p.catch(() => {});
        }
        if (tries > 12) clearInterval(id);
      }, 700);
      return () => clearInterval(id);
    }, []);
    return (
      <section data-theme="dark" className="relative w-full overflow-hidden" style={{ background: 'linear-gradient(180deg, #010828 0%, #04123a 50%, #010828 100%)' }}>
        <div className={SHELL + ' py-20 md:py-28'}>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 lg:gap-16 items-center">
            <div data-reveal className="order-2 lg:order-1">
              <span className={cf + ' text-neon text-[24px] sm:text-[30px] block mb-1'} style={{ transform: 'rotate(-1.5deg)' }}>{t.cursive}</span>
              <h2 className={hf + ' uppercase text-cream text-[34px] sm:text-[44px] lg:text-[52px]'} style={{ lineHeight: LH.hero }}>
                {t.name} <span className="text-neon align-top" style={{ fontSize: '0.34em' }}>AI</span>
              </h2>
              <div className="flex items-center gap-3 mt-3">
                <span className="font-mono uppercase text-[10px] text-cream/45">{t.role}</span>
                <span style={{ width: 4, height: 4, borderRadius: 99, background: 'rgba(255,255,255,0.3)' }} />
                <span className="inline-flex items-center gap-1.5">
                  <span className="sup-live-dot" />
                  <span className={hf + ' uppercase text-neon text-[12px]'}>{t.status}</span>
                </span>
              </div>
              <p className="font-mono text-[13.5px] sm:text-[14px] text-cream/80 leading-relaxed mt-5 max-w-[460px]">{t.desc}</p>
              <ul className="flex flex-col gap-3 mt-6">
                {t.skills.map((s, i) => (
                  <li key={i} className="flex items-start gap-3">
                    <span className="text-neon mt-[1px] shrink-0"><Ico.Check size={17} /></span>
                    <span className={'font-mono text-[13.5px] leading-snug ' + (i === focusIndex ? 'text-neon' : 'text-cream/85')}>{s}</span>
                  </li>
                ))}
              </ul>
              <div className="flex flex-wrap items-center gap-4 mt-8">
                <a href="/register" data-ev="cta_click:nina_band" className={hf + ' inline-flex items-center gap-2 whitespace-nowrap bg-neon text-background uppercase text-[13px] px-6 py-3.5 rounded-[1rem] hover:scale-[1.02] transition-transform'}>{t.cta} <Ico.Arrow size={16} /></a>
                <a href="/agents?a=nina" className={hf + ' inline-flex items-center gap-2 whitespace-nowrap text-cream uppercase text-[13px] hover:text-neon transition-colors'}>{t.profile} <Ico.Arrow size={15} /></a>
              </div>
            </div>
            <div data-reveal className="order-1 lg:order-2">
              <div className="relative rounded-[28px] overflow-hidden mx-auto" style={{ maxWidth: 440, background: 'radial-gradient(120% 120% at 32% 22%, #14306e 0%, #060f2e 100%)', boxShadow: '0 40px 90px rgba(1,8,40,0.6)' }}>
                <div className="relative w-full" style={{ paddingBottom: '116%' }}>
                  <div className="sup-scanline" style={{ opacity: 0.45 }} />
                  <video ref={vref} className="absolute inset-0 w-full h-full object-cover" src="media/card-nina.mp4" autoPlay loop muted playsInline preload="auto" style={{ background: 'transparent' }} />
                  <span className={hf + ' agent-tag absolute top-4 left-4 rounded-[999px] pl-3 pr-4 py-1.5 text-[12px] uppercase whitespace-nowrap'}>{lang === 'ru' ? 'Снабжение' : 'Procurement'}</span>
                  <div className="absolute left-4 right-4 bottom-4 liquid-glass rounded-[18px] px-4 py-3 flex items-center justify-between" style={{ background: 'rgba(1,8,40,0.5)' }}>
                    <span className={hf + ' uppercase text-cream text-[15px]'}>{t.name}</span>
                    <span className="inline-flex items-center gap-1.5 font-mono uppercase text-[10px] text-neon"><span className="sup-live-dot" />{t.status}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  /* ---------- feature showcase wrapper (caption + live widget) ---------- */
  function Feature({ hf, lang, eyebrow, title, text, children }) {
    return (
      <section className="bg-background">
        <div className={SHELL + ' py-20 md:py-28'}>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 lg:gap-16 items-start">
            <div data-reveal>
              <span className="sup-eyebrow">{eyebrow}</span>
              <h2 className={hf + ' uppercase text-cream text-[26px] sm:text-[32px] lg:text-[38px] mt-4 mb-5'} style={{ lineHeight: LH.h2 }}>{title}</h2>
              <p className="font-mono text-[14px] text-cream/75 leading-relaxed max-w-[440px]">{text}</p>
            </div>
            <div className="w-full min-w-0" data-reveal>{children}</div>
          </div>
        </div>
      </section>
    );
  }

  /* ---------- FAQ accordion ---------- */
  function FaqItem({ qa, open, onToggle, hf }) {
    return (
      <div className="liquid-glass rounded-[20px] overflow-hidden" data-reveal>
        <button onClick={onToggle} className="w-full flex items-center justify-between gap-4 text-left px-6 py-5">
          <span className={hf + ' uppercase text-cream text-[15px] sm:text-[16px]'} style={{ lineHeight: LH.q }}>{qa.q}</span>
          <span className={'shrink-0 w-8 h-8 rounded-full flex items-center justify-center transition-colors ' + (open ? 'bg-neon text-background' : 'text-neon')}
                style={{ boxShadow: open ? 'none' : 'inset 0 0 0 1.5px rgba(111,255,0,0.5)' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"
                 style={{ transform: open ? 'rotate(45deg)' : 'none', transition: 'transform .25s ease' }}><path d="M12 5v14M5 12h14"/></svg>
          </span>
        </button>
        <div style={{ display: 'grid', gridTemplateRows: open ? '1fr' : '0fr', transition: 'grid-template-rows .3s ease' }}>
          <div style={{ overflow: 'hidden' }}>
            <p className="font-mono text-[13.5px] text-cream/75 leading-relaxed px-6 pb-6 pr-12">{qa.a}</p>
          </div>
        </div>
      </div>
    );
  }
  function Faq({ hf, lang, eyebrow, title, qa }) {
    const [open, setOpen] = React.useState(0);
    return (
      <section className="bg-background">
        <div className="max-w-[860px] w-full mx-auto px-6 md:px-10 pt-12 pb-20 md:pt-16 md:pb-28">
          <span className="sup-eyebrow">{eyebrow}</span>
          <h2 className={hf + ' uppercase text-cream text-[28px] sm:text-[34px] lg:text-[42px] mt-4 mb-9'} style={{ lineHeight: LH.h2 }}>{title}</h2>
          <div className="flex flex-col gap-3">
            {qa.map((item, i) => (
              <FaqItem key={i} qa={item} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)} hf={hf} />
            ))}
          </div>
        </div>
      </section>
    );
  }

  /* ---------- CTA block ---------- */
  function CtaBlock({ hf, cf, lang, heading, ev }) {
    const [agree, setAgree] = React.useState(false);
    const go = (e) => { e.preventDefault(); if (!agree) return; window.tsTrack && window.tsTrack('cta_submit', { detail: ev }); window.location.href = '/register'; };
    return (
      <section data-theme="dark" className="bg-background">
        <div className="max-w-[1120px] w-full mx-auto px-6 md:px-10 pb-20 pt-4">
          <div className="rounded-[32px] px-7 py-12 md:px-14 md:py-16 relative overflow-hidden" style={{ background: 'radial-gradient(120% 140% at 0% 0%, #0a1c54 0%, #04123a 55%, #010828 100%)', border: '1px solid rgba(255,255,255,0.1)' }}>
            <div className="sup-scanline" style={{ opacity: 0.3 }} />
            <div className="relative max-w-[560px]">
              <span className={cf + ' text-neon text-[24px] sm:text-[32px] block mb-2'} style={{ transform: 'rotate(-1.5deg)' }}>{lang === 'ru' ? 'снабжение под ключ' : 'supply, sorted'}</span>
              <h2 className={hf + ' uppercase text-cream text-[30px] sm:text-[40px] lg:text-[46px]'} style={{ lineHeight: LH.h2 }}>{heading}</h2>
              <form onSubmit={go} className="mt-7 flex flex-col gap-4">
                <div className="flex flex-col sm:flex-row gap-3">
                  <input type="email" name="email" placeholder="your@email.com" className="glass-input sm:w-[280px]" style={{ textAlign: 'left' }} />
                  <button type="submit" disabled={!agree} data-ev={'cta_click:' + ev} className={hf + ' inline-flex items-center justify-center gap-2 whitespace-nowrap bg-neon text-background uppercase text-[14px] px-7 py-4 rounded-[1rem] transition-transform ' + (agree ? 'hover:scale-[1.02]' : 'opacity-50 cursor-not-allowed')}>
                    {lang === 'ru' ? 'Получить доступ' : 'Get access'} <Ico.Arrow size={16} />
                  </button>
                </div>
                <div className="max-w-[380px]"><ConsentCheck checked={agree} onChange={setAgree} lang={lang} /></div>
              </form>
              <p className="font-mono uppercase text-[11px] text-cream/55 mt-3">{lang === 'ru' ? 'Оставь заявку — подключим доступ и поможем со стартом.' : 'Leave a request — we set up access and help you start.'}</p>
            </div>
          </div>
        </div>
      </section>
    );
  }

  /* ---------- cross-link «связка» block ---------- */
  const LINKS = [
    { key: 'poisk', href: '/poisk-postavshchikov', icon: Ico.Search, label: { ru: 'Поиск поставщиков', en: 'Supplier search' }, sub: { ru: '200–300 контактов за 5 минут', en: '200–300 contacts in 5 min' } },
    { key: 'kalk', href: '/kalkulyator-dostavki', icon: Ico.Truck, label: { ru: 'Калькулятор доставки', en: 'Shipping calculator' }, sub: { ru: 'Сравни 8+ транспортных сразу', en: 'Compare 8+ carriers at once' } },
    { key: 'inn', href: '/proverka-kontragenta', icon: Ico.Shield, label: { ru: 'Проверка по ИНН', en: 'Counterparty check' }, sub: { ru: 'Скоринг и светофор надёжности', en: 'Reliability score & light' } },
    { key: 'rfq', href: '/register', icon: Ico.Send, label: { ru: 'Авторассылка запросов', en: 'Automated RFQs' }, sub: { ru: 'Запросы поставщикам с твоих ящиков', en: 'RFQs from your mailboxes' } },
  ];
  function SupplyLinks({ hf, cf, lang, current }) {
    return (
      <section data-theme="dark" className="relative w-full overflow-hidden rounded-t-[32px]" style={{ background: 'radial-gradient(125% 120% at 85% 100%, #0a1c54 0%, #050f33 48%, #010828 100%)' }}>
        <div className={SHELL + ' pt-20 pb-12 md:pt-28 md:pb-16'}>
          <div className="text-center max-w-[700px] mx-auto">
            <span className={cf + ' text-neon text-[24px] sm:text-[32px] block mb-2'}>{lang === 'ru' ? 'Нина · AI-снабженец' : 'Nina · AI procurement'}</span>
            <h2 className={hf + ' uppercase text-cream text-[28px] sm:text-[36px] lg:text-[44px]'} style={{ lineHeight: LH.h2 }}>{lang === 'ru' ? 'Всё снабжение в одном AI-отделе' : 'All of procurement in one AI department'}</h2>
            <p className="font-mono text-[13.5px] text-cream/70 leading-relaxed mt-5 max-w-[560px] mx-auto">{lang === 'ru' ? 'Поиск, доставка, проверка и рассылка запросов — части одного агента. Подключи весь блок снабжения сразу.' : 'Search, shipping, checks and RFQs — parts of one agent. Plug in the whole procurement block at once.'}</p>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-12">
            {LINKS.map((l) => {
              const I = l.icon; const active = l.key === current;
              return (
                <a key={l.key} href={l.href} data-ev={'xlink_click:' + l.key}
                   className={'liquid-glass rounded-[22px] p-6 flex flex-col group transition-colors ' + (active ? '' : 'hover:bg-white/10')}
                   style={active ? { boxShadow: 'inset 0 0 0 1.5px rgba(111,255,0,0.5)' } : undefined}>
                  <div className="sup-ico mb-5"><I size={22} /></div>
                  <div className={hf + ' uppercase text-cream text-[15px] group-hover:text-neon transition-colors'} style={{ lineHeight: LH.card }}>{l.label[lang]}</div>
                  <div className="font-mono text-[11.5px] text-cream/55 leading-relaxed mt-2">{l.sub[lang]}</div>
                  {active && <div className="font-mono uppercase text-[10px] text-neon mt-3">{lang === 'ru' ? 'ты здесь' : 'you are here'}</div>}
                </a>
              );
            })}
          </div>
          <div className="flex flex-wrap items-center justify-center gap-4 mt-12">
            <a href="/register" data-ev="cta_click:supply_links" className={hf + ' inline-flex items-center gap-2 whitespace-nowrap bg-neon text-background uppercase text-[14px] px-7 py-4 rounded-[1rem] hover:scale-[1.02] transition-transform'}>
              {lang === 'ru' ? 'Получить доступ' : 'Get access'} <Ico.Arrow size={16} />
            </a>
            <a href="/agents?a=nina" className={hf + ' inline-flex items-center gap-2 whitespace-nowrap text-cream uppercase text-[13px] hover:text-neon transition-colors'}>
              {lang === 'ru' ? 'Профиль агента Нина →' : 'Meet Nina →'}
            </a>
          </div>
        </div>
      </section>
    );
  }

  /* ====================================================================== */
  /* FEATURE WIDGET 1 — supplier results (animated mock)                    */
  /* ====================================================================== */
  function MockShell({ lang, label, children }) {
    return (
      <div data-theme="dark" className="sup-mock mx-auto" style={{ maxWidth: 520 }}>
        <div className="sup-mock-bar">
          <span className="sup-dot" style={{ background: '#ff5f57' }} /><span className="sup-dot" style={{ background: '#febc2e' }} /><span className="sup-dot" style={{ background: '#28c840' }} />
          <span className="font-mono text-[11px] text-cream/45 ml-2">{label}</span>
        </div>
        {children}
      </div>
    );
  }
  function SupplierMock({ lang }) {
    const rows = [
      { co: 'ПромПолимер', city: lang === 'ru' ? 'Москва' : 'Moscow' },
      { co: 'СтальТрейд', city: lang === 'ru' ? 'Екатеринбург' : 'Ekaterinburg' },
      { co: 'AsiaSupply Co', city: lang === 'ru' ? 'Гуанчжоу' : 'Guangzhou' },
      { co: 'ТД Логистик', city: lang === 'ru' ? 'Казань' : 'Kazan' },
      { co: 'NeoComponents', city: lang === 'ru' ? 'Шэньчжэнь' : 'Shenzhen' },
    ];
    return (
      <MockShell lang={lang} label={lang === 'ru' ? 'поиск поставщиков' : 'supplier search'}>
        <div className="px-5 py-4" style={{ borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
          <div className="flex items-center gap-3">
            <span className="text-neon"><Ico.Search size={16} /></span>
            <span className="font-mono text-[12.5px] text-cream/80">{lang === 'ru' ? 'полимерная упаковка оптом' : 'wholesale polymer packaging'}</span>
          </div>
          <div className="flex items-center justify-between mt-4">
            <span className="font-mono uppercase text-[10px] text-cream/45">{lang === 'ru' ? 'найдено контактов' : 'contacts found'}</span>
            <span className="font-mono text-[12px] text-neon">247 · 04:52</span>
          </div>
          <div style={{ position: 'relative', height: 6, borderRadius: 999, background: 'rgba(255,255,255,0.07)', marginTop: 8, overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, width: '82%', borderRadius: 999, background: 'rgb(var(--neon))' }} />
            <div className="sup-scanline" />
          </div>
        </div>
        <div>
          {rows.map((r, i) => (
            <div key={i} className="sup-row" style={{ gridTemplateColumns: '18px 1fr auto' }}>
              <span className="text-neon"><Ico.Check size={15} /></span>
              <span className="text-cream/85" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.co} <span className="text-cream/40">· {r.city}</span></span>
              <span className="text-cream/45">✉ · ☎</span>
            </div>
          ))}
        </div>
      </MockShell>
    );
  }

  /* ====================================================================== */
  /* FEATURE WIDGET 2 — live carrier calculator                            */
  /* ====================================================================== */
  const CITIES = {
    ru: ['Москва', 'Санкт-Петербург', 'Екатеринбург', 'Новосибирск', 'Казань', 'Краснодар', 'Владивосток'],
    en: ['Moscow', 'St. Petersburg', 'Ekaterinburg', 'Novosibirsk', 'Kazan', 'Krasnodar', 'Vladivostok'],
  };
  const DIST = [1.0, 1.1, 1.9, 2.6, 1.4, 1.7, 4.2];
  const CARRIERS = [
    { name: 'ПЭК', base: 230, perKg: 7, coef: 200, door: 380, days: '3–6' },
    { name: 'ЖелДорЭкспедиция', base: 220, perKg: 7.5, coef: 210, door: 360, days: '4–8' },
    { name: 'КИТ', base: 330, perKg: 9.5, coef: 230, door: 430, days: '3–6', noTerminalFrom: 6 },
    { name: 'Энергия', base: 300, perKg: 10, coef: 230, door: 400, days: '3–6' },
    { name: 'Деловые Линии', base: 420, perKg: 9, coef: 250, door: 500, days: '3–5' },
    { name: 'СДЭК', base: 350, perKg: 11, coef: 200, door: 450, days: '2–4' },
    { name: 'Почта России', base: 250, perKg: 14, coef: 280, door: 350, days: '5–9' },
    { name: 'Байкал Сервис', base: 380, perKg: 8.5, coef: 220, door: 480, days: '4–7' },
  ];
  const SHIP_TYPES = {
    ru: [
      ['ss', 'Склад → Склад (терминал-терминал, дешевле)'],
      ['sd', 'Склад → Дверь (привезём по адресу)'],
      ['ds', 'Дверь → Склад (заберём по адресу)'],
      ['dd', 'Дверь → Дверь (забор и доставка)'],
    ],
    en: [
      ['ss', 'Terminal → Terminal (cheapest)'],
      ['sd', 'Terminal → Door (delivered to address)'],
      ['ds', 'Door → Terminal (picked up at address)'],
      ['dd', 'Door → Door (pickup & delivery)'],
    ],
  };
  const METHOD = {
    ru: { ss: 'авто · склад→склад', sd: 'авто · склад→дверь', ds: 'авто · дверь→склад', dd: 'авто · дверь→дверь' },
    en: { ss: 'road · hub→hub', sd: 'road · hub→door', ds: 'road · door→hub', dd: 'road · door→door' },
  };
  function fmt(n) { return n.toLocaleString('ru-RU'); }
  function CarrierCalc({ lang, maxRows }) {
    const ru = lang === 'ru';
    const cities = CITIES[lang] || CITIES.ru;
    const [from, setFrom] = React.useState(2);
    const [to, setTo] = React.useState(0);
    const [type, setType] = React.useState('ss');
    const [mode, setMode] = React.useState('same');
    const [count, setCount] = React.useState(5);
    const [unitW, setUnitW] = React.useState(10);
    const [dim, setDim] = React.useState({ l: 30, w: 20, h: 15 });
    const [places, setPlaces] = React.useState([
      { w: 10, l: 30, wd: 20, h: 15 },
      { w: 25, l: 60, wd: 40, h: 30 },
    ]);
    const [result, setResult] = React.useState(null);

    const totals = React.useMemo(() => {
      if (mode === 'same') {
        const n = Math.max(1, count | 0);
        const vol = n * (dim.l * dim.w * dim.h / 1e6);
        return { n, weight: +(n * unitW).toFixed(1), vol: +vol.toFixed(4) };
      }
      const n = places.length;
      const weight = places.reduce((s, p) => s + (+p.w || 0), 0);
      const vol = places.reduce((s, p) => s + ((+p.l || 0) * (+p.wd || 0) * (+p.h || 0) / 1e6), 0);
      return { n, weight: +weight.toFixed(1), vol: +vol.toFixed(4) };
    }, [mode, count, unitW, dim, places]);

    const setPlace = (i, k, v) => setPlaces((ps) => ps.map((p, j) => j === i ? { ...p, [k]: v } : p));
    const addPlace = () => setPlaces((ps) => ps.length < 8 ? [...ps, { w: 10, l: 30, wd: 20, h: 15 }] : ps);
    const delPlace = (i) => setPlaces((ps) => ps.length > 1 ? ps.filter((_, j) => j !== i) : ps);

    const calc = () => {
      const d = (DIST[to] || 1) * (0.6 + DIST[from] * 0.25);
      const originDoor = type === 'dd' || type === 'ds';
      const destDoor = type === 'dd' || type === 'sd';
      const legs = (originDoor ? 1 : 0) + (destDoor ? 1 : 0);
      const rows = CARRIERS.map((c) => {
        const noT = c.noTerminalFrom != null && (to === c.noTerminalFrom || from === c.noTerminalFrom);
        const charge = Math.max(totals.weight, totals.vol * c.coef);
        let price = (c.base + c.perKg * charge) * d + legs * c.door;
        price = Math.round(price / 10) * 10;
        return { name: c.name, days: c.days, price, noT, charge: Math.round(charge) };
      });
      const priced = rows.filter((r) => !r.noT).sort((a, b) => a.price - b.price);
      const missing = rows.filter((r) => r.noT);
      window.tsTrack && window.tsTrack('calc_run', { detail: cities[from] + '→' + cities[to] });
      setResult({ priced, missing, charge: priced.length ? priced[0].charge : 0, legs, method: METHOD[lang][type] });
    };
    React.useEffect(() => { calc(); /* eslint-disable-next-line */ }, []);

    const lbl = 'font-mono uppercase text-[9.5px] text-cream/45';
    return (
      <MockShell lang={lang} label={ru ? 'калькулятор доставки · демо' : 'shipping calculator · demo'}>
        <div className="p-5 flex flex-col gap-4">
          {/* route */}
          <div className="grid grid-cols-2 gap-3">
            <label className="block">
              <span className={lbl}>{ru ? 'Город отправления' : 'From city'}</span>
              <select className="sup-field mt-1.5" value={from} onChange={(e) => setFrom(+e.target.value)}>
                {cities.map((c, i) => <option key={i} value={i} style={{ color: '#000' }}>{c}</option>)}
              </select>
            </label>
            <label className="block">
              <span className={lbl}>{ru ? 'Город назначения' : 'To city'}</span>
              <select className="sup-field mt-1.5" value={to} onChange={(e) => setTo(+e.target.value)}>
                {cities.map((c, i) => <option key={i} value={i} style={{ color: '#000' }}>{c}</option>)}
              </select>
            </label>
          </div>

          {/* shipping type + helper */}
          <label className="block">
            <span className={lbl}>{ru ? 'Тип перевозки' : 'Shipping type'}</span>
            <select className="sup-field mt-1.5" value={type} onChange={(e) => setType(e.target.value)}>
              {SHIP_TYPES[lang].map(([v, l]) => <option key={v} value={v} style={{ color: '#000' }}>{l}</option>)}
            </select>
            <span className="block font-mono text-[10.5px] text-cream/40 leading-relaxed mt-1.5">
              {ru ? '«Склад» = терминал ТК (дешевле, основной способ). «Дверь» = ТК заберёт/привезёт по адресу.'
                  : '"Terminal" = carrier hub (cheaper, default). "Door" = pickup / delivery at your address.'}
            </span>
          </label>

          {/* cargo places mode */}
          <div>
            <span className={lbl}>{ru ? 'Грузоместа' : 'Cargo places'}</span>
            <div className="sup-seg mt-1.5">
              <button className={mode === 'same' ? 'on' : ''} onClick={() => setMode('same')}>{ru ? 'Все места одинаковые' : 'All identical'}</button>
              <button className={mode === 'diff' ? 'on' : ''} onClick={() => setMode('diff')}>{ru ? 'Места разные' : 'Different'}</button>
            </div>
          </div>

          {mode === 'same' ? (
            <React.Fragment>
              <div className="grid grid-cols-2 gap-3">
                <label className="block">
                  <span className={lbl}>{ru ? 'Количество мест' : 'Places count'}</span>
                  <input type="number" min="1" className="sup-field mt-1.5" value={count} onChange={(e) => setCount(Math.max(1, +e.target.value || 1))} />
                </label>
                <label className="block">
                  <span className={lbl}>{ru ? 'Вес 1 места (кг)' : 'Weight per place (kg)'}</span>
                  <input type="number" min="0.1" step="0.1" className="sup-field mt-1.5" value={unitW} onChange={(e) => setUnitW(Math.max(0, +e.target.value || 0))} />
                </label>
              </div>
              <div className="grid grid-cols-3 gap-3">
                <label className="block">
                  <span className={lbl}>{ru ? 'Д (см)' : 'L (cm)'}</span>
                  <input type="number" min="1" className="sup-field mt-1.5" value={dim.l} onChange={(e) => setDim((d) => ({ ...d, l: Math.max(1, +e.target.value || 1) }))} />
                </label>
                <label className="block">
                  <span className={lbl}>{ru ? 'Ш (см)' : 'W (cm)'}</span>
                  <input type="number" min="1" className="sup-field mt-1.5" value={dim.w} onChange={(e) => setDim((d) => ({ ...d, w: Math.max(1, +e.target.value || 1) }))} />
                </label>
                <label className="block">
                  <span className={lbl}>{ru ? 'В (см)' : 'H (cm)'}</span>
                  <input type="number" min="1" className="sup-field mt-1.5" value={dim.h} onChange={(e) => setDim((d) => ({ ...d, h: Math.max(1, +e.target.value || 1) }))} />
                </label>
              </div>
            </React.Fragment>
          ) : (
            <div className="flex flex-col gap-2">
              <div className="grid gap-2 px-1" style={{ gridTemplateColumns: '1.1fr 1fr 1fr 1fr 26px' }}>
                {[ru ? 'кг' : 'kg', ru ? 'Д' : 'L', ru ? 'Ш' : 'W', ru ? 'В' : 'H', ''].map((h, i) => (
                  <span key={i} className="font-mono uppercase text-[9px] text-cream/35">{h}</span>
                ))}
              </div>
              {places.map((p, i) => (
                <div key={i} className="grid gap-2 items-center" style={{ gridTemplateColumns: '1.1fr 1fr 1fr 1fr 26px' }}>
                  <input type="number" min="0.1" step="0.1" className="sup-field" value={p.w} onChange={(e) => setPlace(i, 'w', Math.max(0, +e.target.value || 0))} />
                  <input type="number" min="1" className="sup-field" value={p.l} onChange={(e) => setPlace(i, 'l', Math.max(1, +e.target.value || 1))} />
                  <input type="number" min="1" className="sup-field" value={p.wd} onChange={(e) => setPlace(i, 'wd', Math.max(1, +e.target.value || 1))} />
                  <input type="number" min="1" className="sup-field" value={p.h} onChange={(e) => setPlace(i, 'h', Math.max(1, +e.target.value || 1))} />
                  <button onClick={() => delPlace(i)} aria-label="remove" className="w-[26px] h-[26px] rounded-[8px] flex items-center justify-center text-cream/45 hover:text-neon transition-colors" style={{ background: 'rgba(255,255,255,0.05)' }}>×</button>
                </div>
              ))}
              <button onClick={addPlace} className="font-mono uppercase text-[11px] text-neon hover:underline self-start mt-1">+ {ru ? 'Добавить место' : 'Add place'}</button>
            </div>
          )}

          {/* live summary */}
          <div className="font-mono text-[11.5px] text-cream/55 leading-relaxed" style={{ borderTop: '1px solid rgba(255,255,255,0.07)', paddingTop: 12 }}>
            {ru ? 'Мест' : 'Places'}: <b className="text-cream">{totals.n}</b> · {ru ? 'Вес' : 'Weight'}: <b className="text-cream">{fmt(totals.weight)}</b> {ru ? 'кг' : 'kg'} · {ru ? 'Объём' : 'Volume'}: <b className="text-cream">{totals.vol}</b> м³
          </div>

          <button onClick={calc} data-ev="calc_click:run" className="font-grotesk w-full inline-flex items-center justify-center gap-2 bg-neon text-background uppercase text-[13px] py-3 rounded-[1rem] hover:scale-[1.01] transition-transform">
            {ru ? 'Рассчитать' : 'Calculate'} <Ico.Bolt size={15} />
          </button>
        </div>

        {result && (
          <div className="sup-pop" key={result.priced.map((r) => r.price).join()}>
            <div className="sup-row" style={{ gridTemplateColumns: '1fr auto 84px', borderTop: '1px solid rgba(255,255,255,0.07)' }}>
              <span className="font-mono uppercase text-[9.5px] text-cream/40">{ru ? 'перевозчик' : 'carrier'}</span>
              <span className="font-mono uppercase text-[9.5px] text-cream/40">{ru ? 'срок в пути' : 'transit'}</span>
              <span className="font-mono uppercase text-[9.5px] text-cream/40" style={{ textAlign: 'right' }}>₽</span>
            </div>
            {(maxRows ? result.priced.slice(0, maxRows) : result.priced).map((r, i) => (
              <div key={r.name} className={'sup-row ' + (i === 0 ? 'sup-best' : '')} style={{ gridTemplateColumns: '1fr auto 84px' }}>
                <span className="flex flex-col gap-0.5 min-w-0">
                  <span className="text-cream/90 truncate">{r.name}{i === 0 && <span className="text-neon"> · {ru ? 'дешевле' : 'cheapest'}</span>}</span>
                  <span className="font-mono text-[9.5px] text-cream/35">{result.method}</span>
                </span>
                <span className="sup-days"><Ico.Clock size={12} /> {r.days} {ru ? 'дн' : 'd'}</span>
                <span className="sup-cell-price text-cream/90" style={{ textAlign: 'right' }}>{fmt(r.price)}</span>
              </div>
            ))}
            {maxRows && result.priced.length > maxRows ? (
              <a href="/register" data-ev="calc_click:more" className="sup-row" style={{ gridTemplateColumns: '1fr auto', borderTop: '1px solid rgba(255,255,255,0.07)' }}>
                <span className="font-mono text-[11px] text-cream/55">+ {ru ? 'ещё' : ''} {result.priced.length - maxRows} {ru ? 'ТК' : 'more carriers'}</span>
                <span className="font-mono uppercase text-[10px] text-neon">{ru ? 'весь список · по доступу' : 'full list · with access'}</span>
              </a>
            ) : null}
            {!maxRows && result.missing.map((r) => (
              <div key={r.name} className="sup-row" style={{ gridTemplateColumns: '1fr auto', opacity: 0.55 }}>
                <span className="text-cream/70">{r.name}</span>
                <span className="text-cream/45">{ru ? 'нет терминала' : 'no terminal'}</span>
              </div>
            ))}
            {!maxRows && (
              <div className="px-5 py-3 font-mono text-[10px] text-cream/40 leading-relaxed">
                {ru ? 'Платный вес' : 'Chargeable weight'}: <b className="text-cream/70">{fmt(result.charge)} {ru ? 'кг' : 'kg'}</b> — {ru ? 'максимум из фактического и объёмного веса' : 'max of actual and volumetric weight'}{result.legs ? (ru ? ' · включён забор/доставка по адресу' : ' · door legs included') : ''}.
              </div>
            )}
          </div>
        )}
      </MockShell>
    );
  }

  /* ====================================================================== */
  /* FEATURE WIDGET 3 — live ИНН check                                     */
  /* ====================================================================== */
  function InnCheck({ lang }) {
    const [inn, setInn] = React.useState('7707083893');
    const [res, setRes] = React.useState(null);
    const check = () => {
      const digits = (inn.match(/\d/g) || []).length;
      if (digits < 10) { setRes({ err: true }); return; }
      let sum = 0; for (const ch of inn) sum += (+ch || 0) * 7 + 3;
      const score = 30 + (sum % 70);
      const band = score >= 70 ? 'green' : score >= 45 ? 'yellow' : 'red';
      const verdict = { ru: { green: 'Надёжный — можно работать', yellow: 'Осторожно — проверь детали', red: 'Высокий риск — не рекомендуем' },
                        en: { green: 'Reliable — safe to work', yellow: 'Caution — review details', red: 'High risk — not advised' } }[lang][band];
      const L = lang === 'ru'
        ? [['Статус', band === 'red' ? 'В ликвидации' : 'Действующая'], ['Возраст', (3 + sum % 14) + ' лет'], ['Арбитражные дела', band === 'green' ? 'нет активных' : (sum % 5) + ' активных'], ['Налоговая задолженность', band === 'green' ? 'нет' : band === 'yellow' ? 'незначительная' : 'есть']]
        : [['Status', band === 'red' ? 'In liquidation' : 'Active'], ['Age', (3 + sum % 14) + ' yrs'], ['Court cases', band === 'green' ? 'none active' : (sum % 5) + ' active'], ['Tax debt', band === 'green' ? 'none' : band === 'yellow' ? 'minor' : 'yes']];
      window.tsTrack && window.tsTrack('inn_check', { detail: band });
      setRes({ score, band, verdict, rows: L });
    };
    React.useEffect(() => { check(); /* eslint-disable-next-line */ }, []);
    const C = { green: '#6FFF00', yellow: '#ffd23f', red: '#ff5470' };
    const r = 56, circ = 2 * Math.PI * r;
    return (
      <MockShell lang={lang} label={lang === 'ru' ? 'проверка по ИНН · демо' : 'INN check · demo'}>
        <div className="p-5">
          <div className="flex gap-3">
            <input className="sup-field" inputMode="numeric" maxLength={12} value={inn}
                   onChange={(e) => setInn(e.target.value.replace(/[^\d]/g, ''))} placeholder={lang === 'ru' ? 'ИНН поставщика' : 'Supplier INN'} />
            <button onClick={check} data-ev="inn_click:run" className="font-grotesk shrink-0 inline-flex items-center gap-2 bg-neon text-background uppercase text-[13px] px-5 rounded-[1rem] hover:scale-[1.01] transition-transform">
              {lang === 'ru' ? 'Проверить' : 'Check'}
            </button>
          </div>
        </div>
        {res && res.err && (
          <div className="px-5 pb-5 font-mono text-[12px] text-cream/55">{lang === 'ru' ? 'Введи 10 или 12 цифр ИНН.' : 'Enter a 10- or 12-digit INN.'}</div>
        )}
        {res && !res.err && (
          <div className="sup-pop px-5 pb-6" key={res.score}>
            <div className="flex items-center gap-5" style={{ borderTop: '1px solid rgba(255,255,255,0.07)', paddingTop: 18 }}>
              <div className="sup-gauge" style={{ flex: '0 0 auto' }}>
                <svg width="132" height="132">
                  <circle cx="66" cy="66" r={r} fill="none" stroke="rgba(255,255,255,0.1)" strokeWidth="11" />
                  <circle cx="66" cy="66" r={r} fill="none" stroke={C[res.band]} strokeWidth="11" strokeLinecap="round"
                          strokeDasharray={circ} strokeDashoffset={circ * (1 - res.score / 100)} style={{ transition: 'stroke-dashoffset .7s cubic-bezier(0.16,1,0.3,1)' }} />
                </svg>
                <div className="sup-gauge-val">
                  <span style={{ fontSize: 34, color: C[res.band], lineHeight: 1 }}>{res.score}</span>
                  <span className="font-mono text-[9px] text-cream/45 mt-1">{lang === 'ru' ? 'из 100' : 'of 100'}</span>
                </div>
              </div>
              <div>
                <div className="flex items-center gap-2.5 mb-2">
                  <span className={'tl tl-' + (res.band === 'green' ? 'green' : 'off')} />
                  <span className={'tl tl-' + (res.band === 'yellow' ? 'yellow' : 'off')} />
                  <span className={'tl tl-' + (res.band === 'red' ? 'red' : 'off')} />
                </div>
                <div className="font-grotesk uppercase text-[15px]" style={{ color: C[res.band], lineHeight: 1.2 }}>{res.verdict}</div>
              </div>
            </div>
            <div className="mt-4">
              {res.rows.map((row, i) => (
                <div key={i} className="sup-row" style={{ gridTemplateColumns: '1fr auto', paddingLeft: 0, paddingRight: 0 }}>
                  <span className="text-cream/55">{row[0]}</span>
                  <span className="text-cream/85">{row[1]}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </MockShell>
    );
  }

  window.SupplyKit = { Ico, Crumb, Hero, Steps, Benefits, AgentBand, Feature, Faq, CtaBlock, SupplyLinks, SupplierMock, CarrierCalc, InnCheck, useLang, Footer };
})();
