/* TurboSwift site — shared header, icons, lang hook. Exposes window.Site */
;(function () {
  const BRAND = 'TurboSwift';
  try { document.documentElement.dataset.theme = localStorage.getItem('ts_theme') || 'dark'; } catch (e) { document.documentElement.dataset.theme = 'dark'; }

  /* ---- lucide icons ---- */
  const Svg = ({ size = 20, 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 Icons = {
    Mail: (p) => <Svg {...p}><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></Svg>,
    Twitter: (p) => <Svg {...p}><path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"/></Svg>,
    Github: (p) => <Svg {...p}><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.4 5.4 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/></Svg>,
    Check: (p) => <Svg {...p} sw={2.6}><path d="M20 6 9 17l-5-5"/></Svg>,
    Arrow: (p) => <Svg {...p}><path d="M5 12h14M13 6l6 6-6 6"/></Svg>,
    Bolt: (p) => <Svg {...p}><path d="M13 2 4 14h6l-1 8 9-12h-6l1-8z"/></Svg>,
    Telegram: (p) => <Svg {...p}><path d="M22 3 2 11l6 2.5L18 6 10 15v5l3.5-3.2L18 19l4-16z"/></Svg>,
    Phone: (p) => <Svg {...p}><path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z"/></Svg>,
    Sun: (p) => <Svg {...p}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6 19 19M19 5l-1.4 1.4M6.4 17.6 5 19"/></Svg>,
    Moon: (p) => <Svg {...p}><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></Svg>,
  };

  /* ---- persisted language hook ---- */
  function useLang() {
    const get = () => { try { return localStorage.getItem('ts_lang') || 'ru'; } catch (e) { return 'ru'; } };
    const [lang, setLangState] = React.useState(get());
    React.useEffect(() => {
      const h = () => setLangState(get());
      window.addEventListener('ts-lang', h);
      return () => window.removeEventListener('ts-lang', h);
    }, []);
    const setLang = (l) => { try { localStorage.setItem('ts_lang', l); } catch (e) {} setLangState(l); window.dispatchEvent(new Event('ts-lang')); };
    return [lang, setLang];
  }

  /* ---- persisted theme hook ---- */
  function useTheme() {
    const get = () => { try { return localStorage.getItem('ts_theme') || 'dark'; } catch (e) { return 'dark'; } };
    const [theme, setT] = React.useState(get());
    React.useEffect(() => {
      const h = () => setT(get());
      window.addEventListener('ts-theme', h);
      return () => window.removeEventListener('ts-theme', h);
    }, []);
    const setTheme = (t) => { try { localStorage.setItem('ts_theme', t); } catch (e) {} const r = document.documentElement; r.classList.add('theme-transition'); r.dataset.theme = t; setT(t); window.dispatchEvent(new Event('ts-theme')); setTimeout(() => r.classList.remove('theme-transition'), 520); };
    return [theme, setTheme];
  }

  function ThemeToggle({ hf }) {
    const [theme, setTheme] = useTheme();
    return (
      <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} aria-label="theme"
        className={hf + ' whitespace-nowrap shrink-0 liquid-glass rounded-[1rem] w-9 h-9 flex items-center justify-center text-cream hover:text-neon transition-colors'}>
        {theme === 'dark' ? <Icons.Sun size={16} /> : <Icons.Moon size={16} />}
      </button>
    );
  }

  const NAV = {
    en: [['Home', '/', 'home'], ['Agents', '/agents', 'agents'], ['Cases', '/cases', 'cases'], ['Pricing', '/price', 'pricing'], ['FAQ', '/faq', 'faq'], ['Contact', '/contacts', 'contact']],
    ru: [['Главная', '/', 'home'], ['Агенты', '/agents', 'agents'], ['Кейсы', '/cases', 'cases'], ['Цены', '/price', 'pricing'], ['FAQ', '/faq', 'faq'], ['Контакты', '/contacts', 'contact']],
  };
  const REG = { en: 'Sign up', ru: 'Регистрация' };
  const LOGIN = { en: 'Log in', ru: 'Войти' };

  function Header({ lang, setLang, active }) {
    const hf = lang === 'ru' ? 'font-grotesk-ru' : 'font-grotesk';
    const [menuOpen, setMenuOpen] = React.useState(false);
    return (
      <header className="relative z-30 w-full">
        {menuOpen && (
          <div data-theme="dark" className="lg:hidden fixed inset-0 z-[80] flex flex-col" style={{ background: 'rgba(1,8,40,0.97)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)' }}>
            <div className="flex items-center justify-between px-6 pt-8">
              <span className={hf + ' text-[14px] uppercase tracking-wide text-cream'}>{lang === 'ru' ? 'Меню' : 'Menu'}</span>
              <button onClick={() => setMenuOpen(false)} aria-label="close" className="w-10 h-10 rounded-full glass-pill flex items-center justify-center text-cream">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>
              </button>
            </div>
            <nav className="flex-1 flex flex-col items-center justify-center gap-7">
              {NAV[lang].map(([label, href, id]) => (
                <a key={id} href={href} className={hf + ' text-[28px] uppercase ' + (active === id ? 'text-neon' : 'text-cream')}>{label}</a>
              ))}
              <div className="flex items-center gap-3 mt-6">
                <a href="https://app.turboswift.online/login" className={hf + ' liquid-glass rounded-[1rem] px-6 py-3 text-[13px] uppercase text-cream'}>{LOGIN[lang]}</a>
                <a href="/register" className={hf + ' bg-neon text-background rounded-[1rem] px-6 py-3 text-[13px] uppercase'}>{REG[lang]}</a>
              </div>
            </nav>
          </div>
        )}
        <div className="relative max-w-[1831px] mx-auto px-6 md:px-10 flex items-center pt-8 pb-6 md:pb-8">
          <nav className="absolute left-1/2 -translate-x-1/2 hidden lg:block liquid-glass rounded-[28px] px-[40px] py-[18px]">
            <ul className="flex items-center gap-8">
              {NAV[lang].map(([label, href, id]) => (
                <li key={id}>
                  <a href={href} className={hf + ' text-[12px] uppercase transition-colors ' + (active === id ? 'text-neon' : 'text-cream hover:text-neon')}>{label}</a>
                </li>
              ))}
            </ul>
          </nav>
          <div className="ml-auto flex items-center gap-3">
            <a href="https://app.turboswift.online/login" className={hf + ' hidden md:inline-flex items-center whitespace-nowrap shrink-0 text-[12px] uppercase text-cream hover:text-neon transition-colors px-2'}>{LOGIN[lang]}</a>
            <a href="/register" className={hf + ' hidden sm:inline-flex items-center whitespace-nowrap shrink-0 liquid-glass rounded-[1rem] px-5 py-[10px] text-[12px] uppercase text-cream hover:text-neon transition-colors'}>{REG[lang]}</a>
            <ThemeToggle hf={hf} />
            <button onClick={() => setLang(lang === 'en' ? 'ru' : 'en')}
              className={hf + ' whitespace-nowrap shrink-0 liquid-glass rounded-[1rem] px-4 py-[10px] text-[12px] uppercase text-cream hover:text-neon transition-colors'}>
              {lang === 'en' ? 'RU' : 'EN'}
            </button>
            <button onClick={() => setMenuOpen(true)} aria-label="menu" className="lg:hidden shrink-0 w-9 h-9 flex items-center justify-center text-cream hover:text-neon transition-colors">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
            </button>
          </div>
        </div>
      </header>
    );
  }

  const FOOT = {
    en: {
      tagline: 'A department of AI employees — sales, supply & marketing, working 24/7.',
      cols: [
        ['Product', [['Agents', '/agents'], ['Cases', '/cases'], ['Pricing', '/price'], ['FAQ', '/faq']]],
        ['Supply', [['Supplier search', '/poisk-postavshchikov'], ['Shipping calculator', '/kalkulyator-dostavki'], ['Counterparty check', '/proverka-kontragenta']]],
        ['Company', [['About', '/about'], ['Contact', '/contacts'], ['Log in', 'https://app.turboswift.online/login']]],
        ['Documents', [['Terms', '/terms'], ['Privacy', '/privacy'], ['Cookies', '/cookie']]],
      ],
      copy: '© 2026 TurboSwift. All rights reserved.',
      req: ['Materik LLC · INN 9810002549 · KPP 781001001', 'Legal address: 196128, St. Petersburg,', 'Novoizmaylovskoye municipal district, Kuznetsovskaya St. 11,', 'lit. A, room 63N, workplace 15'],
    },
    ru: {
      tagline: 'Отдел AI-сотрудников — продажи, снабжение и маркетинг, 24/7.',
      cols: [
        ['Продукт', [['Агенты', '/agents'], ['Кейсы', '/cases'], ['Цены', '/price'], ['FAQ', '/faq']]],
        ['Снабжение', [['Поиск поставщиков', '/poisk-postavshchikov'], ['Калькулятор доставки', '/kalkulyator-dostavki'], ['Проверка по ИНН', '/proverka-kontragenta']]],
        ['Компания', [['О нас', '/about'], ['Контакты', '/contacts'], ['Войти', 'https://app.turboswift.online/login']]],
        ['Документы', [['Условия', '/terms'], ['Конфиденциальность', '/privacy'], ['Cookies', '/cookie']]],
      ],
      copy: '© 2026 TurboSwift. Все права защищены.',
      req: ['ООО «Материк» · ИНН 9810002549 · КПП 781001001', 'Юр. адрес: 196128, г. Санкт-Петербург,', 'вн. тер. г. муниципальный округ Новоизмайловское, ул. Кузнецовская, д. 11,', 'литера А, помещ. 63Н, рабочее место 15'],
    },
  };

  function Footer({ lang }) {
    const hf = lang === 'ru' ? 'font-grotesk-ru' : 'font-grotesk';
    const f = FOOT[lang];
    const socials = [
      [Icons.Mail, 'mailto:efimovroman44@yandex.ru'],
      [Icons.Telegram, 'https://t.me/efimov44'],
      [Icons.Phone, 'tel:+79109231000'],
    ];
    return (
      <footer className="ts-footer" data-lang={lang}>
        <div className="ts-footer__inner">
          <div className="ts-footer__grid">
            <div className="ts-brand">
              <a className="ts-brand__logo" href="/">
                <span className="ts-brand__name">TurboSwift</span>
                <span className="ts-brand__sub">Technologies</span>
              </a>
              <p className="ts-brand__tag">{f.tagline}</p>
              <div className="ts-social">
                {socials.map(([Icon, href], i) => (
                  <a key={i} href={href} target={href.startsWith('http') ? '_blank' : undefined} rel="noopener noreferrer" aria-label="link"><Icon size={18} /></a>
                ))}
              </div>
            </div>
            <div className="ts-footer__cols">
              {f.cols.map(([title, links]) => (
                <div className="ts-col" key={title}>
                  <div className="ts-col__title">{title}</div>
                  <ul className="ts-col__list">
                    {links.map(([label, href]) => (
                      <li key={label}><a href={href}>{label}</a></li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </div>
          <div className="ts-footer__bottom">
            <span className="ts-footer__copy">{f.copy}</span>
            <a className="ts-footer__cta" href="/register">{lang === 'ru' ? 'Получить доступ →' : 'Get access →'}</a>
          </div>
        </div>
      </footer>
    );
  }

  // styled consent checkbox for forms
  function ConsentCheck({ checked, onChange, lang }) {
    const txt = lang === 'ru'
      ? ['Подтверждаю и даю согласие на обработку персональных данных, принимаю ', 'политику конфиденциальности']
      : ['I confirm and consent to the processing of my personal data and accept the ', 'privacy policy'];
    return (
      <label className="flex items-start gap-3 cursor-pointer select-none">
        <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} className="sr-only" />
        <span className="mt-[1px] shrink-0 w-5 h-5 rounded-[6px] flex items-center justify-center transition-colors"
              style={{ background: checked ? '#6FFF00' : 'rgb(var(--text) / 0.06)', boxShadow: checked ? 'none' : 'inset 0 0 0 1.5px rgb(var(--text) / 0.4)' }}>
          {checked && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#010828" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>}
        </span>
        <span className="font-mono text-[11px] leading-relaxed text-cream/55">{txt[0]}<a href="#" className="text-neon hover:underline" onClick={(e) => e.stopPropagation()}>{txt[1]}</a>.</span>
      </label>
    );
  }

  // cookie consent banner (self-mounts once per page)
  function CookieBanner() {
    const [lang] = useLang();
    const [show, setShow] = React.useState(false);
    React.useEffect(() => { try { if (!localStorage.getItem('ts_cookie')) setShow(true); } catch (e) {} }, []);
    if (!show) return null;
    const hf = lang === 'ru' ? 'font-grotesk-ru' : 'font-grotesk';
    const t = lang === 'ru'
      ? { txt: 'Мы используем cookie, чтобы сайт работал быстрее и удобнее. Продолжая, ты соглашаешься с этим.', ok: 'Принять', no: 'Только нужные' }
      : { txt: 'We use cookies to make the site faster and smoother. By continuing you agree to this.', ok: 'Accept', no: 'Essential only' };
    const close = (v) => { try { localStorage.setItem('ts_cookie', v); } catch (e) {} setShow(false); };
    return (
      <div data-theme="dark" className="fixed z-[70] left-4 right-4 bottom-4 sm:left-auto sm:right-6 sm:bottom-6 sm:w-[400px]">
        <div className="liquid-glass rounded-[22px] p-5" style={{ background: 'rgba(3,11,38,0.92)' }}>
          <div className="flex items-center gap-2 mb-2">
            <span className="text-neon"><Icons.Bolt size={16} /></span>
            <span className={hf + ' uppercase text-cream text-[13px] tracking-wide'}>Cookie</span>
          </div>
          <p className="font-mono text-[12px] text-cream/70 leading-relaxed">{t.txt}</p>
          <div className="flex items-center gap-3 mt-4">
            <button onClick={() => close('all')} className={hf + ' bg-neon text-background uppercase text-[12px] px-5 py-2.5 rounded-[1rem] hover:scale-[1.03] transition-transform'}>{t.ok}</button>
            <button onClick={() => close('essential')} className={hf + ' uppercase text-[12px] text-cream/70 hover:text-neon transition-colors'}>{t.no}</button>
          </div>
        </div>
      </div>
    );
  }

  // sticky nav that slides down on scroll (all pages)
  function StickyNav() {
    const [lang, setLang] = useLang();
    const [show, setShow] = React.useState(false);
    React.useEffect(() => {
      const onScroll = () => setShow(window.scrollY > 560);
      window.addEventListener('scroll', onScroll, { passive: true });
      onScroll();
      return () => window.removeEventListener('scroll', onScroll);
    }, []);
    const hf = lang === 'ru' ? 'font-grotesk-ru' : 'font-grotesk';
    return (
      <div data-theme="dark" className="fixed top-0 left-0 right-0 z-[55]" style={{ transform: show ? 'translateY(0)' : 'translateY(-110%)', transition: 'transform .35s cubic-bezier(0.16,1,0.3,1)', background: 'rgba(1,8,40,0.82)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
        <div className="relative max-w-[1831px] mx-auto px-6 md:px-10 h-16 flex items-center">
          <nav className="hidden lg:flex items-center gap-8 absolute left-1/2 -translate-x-1/2">
            {NAV[lang].map(([label, href, id]) => (<a key={id} href={href} className={hf + ' text-[12px] uppercase text-cream hover:text-neon transition-colors'}>{label}</a>))}
          </nav>
          <div className="ml-auto flex items-center gap-3">
            <a href="https://app.turboswift.online/login" className={hf + ' hidden md:inline-flex whitespace-nowrap text-[12px] uppercase text-cream hover:text-neon transition-colors'}>{LOGIN[lang]}</a>
            <a href="/register" className={hf + ' whitespace-nowrap text-[12px] uppercase text-background bg-neon px-4 py-2 rounded-[10px] hover:scale-[1.03] transition-transform'}>{REG[lang]}</a>
            <ThemeToggle hf={hf} />
            <button onClick={() => setLang(lang === 'en' ? 'ru' : 'en')} className={hf + ' whitespace-nowrap text-[12px] uppercase text-cream hover:text-neon transition-colors'}>{lang === 'en' ? 'RU' : 'EN'}</button>
          </div>
        </div>
      </div>
    );
  }

  window.Site = { BRAND, Icons, useLang, useTheme, Header, Footer, ConsentCheck };

  // mount the cookie banner once
  (function () {
    if (window.__tsCookie) return; window.__tsCookie = true;
    const mount = () => { const m = document.createElement('div'); document.body.appendChild(m); ReactDOM.createRoot(m).render(React.createElement(CookieBanner)); };
    if (document.body) mount(); else document.addEventListener('DOMContentLoaded', mount);
  })();

  // mount the sticky nav once
  (function () {
    if (window.__tsSticky) return; window.__tsSticky = true;
    const mount = () => { const m = document.createElement('div'); document.body.appendChild(m); ReactDOM.createRoot(m).render(React.createElement(StickyNav)); };
    if (document.body) mount(); else document.addEventListener('DOMContentLoaded', mount);
  })();

  // perf: lazy-load videos + play only when visible
  (function () {
    if (window.__tsLazyVid) return; window.__tsLazyVid = true;
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => {
        const v = e.target;
        if (e.isIntersecting) {
          if (v.dataset.src && !v.getAttribute('src')) { v.setAttribute('src', v.dataset.src); try { v.load(); } catch (x) {} }
          const p = v.play(); if (p && p.catch) p.catch(() => {});
          v.style.opacity = '1';
        } else { try { v.pause(); } catch (x) {} }
      });
    }, { rootMargin: '300px 0px' });
    const lazify = (v) => {
      if (v.__lz) return; v.__lz = true;
      v.style.opacity = '0';
      const s = v.getAttribute('src');
      if (s) { v.dataset.src = s; v.removeAttribute('src'); v.preload = 'none'; }
      io.observe(v);
    };
    const rio = new IntersectionObserver((ents) => {
      ents.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); rio.unobserve(e.target); } });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
    const reveal = (el) => { if (el.__rv) return; el.__rv = true; el.classList.add('reveal'); rio.observe(el); };
    const scan = () => { document.querySelectorAll('video').forEach(lazify); document.querySelectorAll('[data-reveal]').forEach(reveal); };
    const start = () => { new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true }); scan(); };
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else start();
  })();
})();
