/* Ava Solutions — bilingual layer (EN default + RU).
   Loaded BEFORE components.jsx. Every component that renders copy MUST call
   useLang() so it re-renders when the language switches. Default on first load
   is EN (localStorage remembers the choice; no browser auto-detect, by design).
   The marquee and the floating AI button are intentionally NOT localized. */

const T = {
  en: {
    doc: {
      title: 'Ava Solutions — custom business platforms, automation & AI agents',
      desc: 'Boutique full-cycle custom software: CRM / ERP / BI platforms, automation and practical AI agents built around your processes. First working MVP in 3 months.',
    },
    hero: {
      meta: { left: '(01 / 08) — Boutique development · Business systems', mid: 'Kyiv · Astana · Dubai', right: 'Est. 2024' },
      title: { line1: 'We find the solutions.', pre2: 'You get your ', accent: 'time.' },
      sub: "Ava Solutions is a boutique full-cycle custom software company. We build you an independent platform designed exclusively around your business processes. No bloated code, no overpaying for someone else's software. Your own system. The first working MVP — in just 3 months.",
      cta: 'Discuss your task',
      cta2: 'See our products',
    },
    foundation: {
      chapter: { left: '(02 / 08) — What we believe', right: 'Business architects, not just coders' },
      title: { a: 'Our foundation is ', accent: 'the real sector', b: ', not dry theory.' },
      body: [
        "Before becoming IT architects, our team spent more than 20 years running our own companies in the real business sector. We lived through operational routine, cash gaps, scaling and expensive mistakes firsthand. You don't learn that on programming courses.",
        "At some point we brought technology into our own processes — and saw how many thousands of hours it gives back. That's how Ava Solutions was born.",
        "We are businesspeople who build software for business. We look at processes from the same side as you, and we speak your language.",
      ],
      pillars: [
        { num: '01', title: 'The task', body: 'Every company has its own operating logic. We start there.' },
        { num: '02', title: 'The build', body: 'We connect roles, data and decisions into one working contour.' },
        { num: '03', title: 'The result', body: 'Fewer manual steps, clearer responsibility, more time for the actual work.' },
      ],
    },
    approach: {
      chapter: { left: '(03 / 08) — How we start', right: 'Approach' },
      title: { line1: "We don't need a spec.", pre2: 'Show us your ', accent: 'bottlenecks.' },
      body: [
        'Most IT companies start with a demand: "Give us a detailed technical specification." But to write a good spec, you already have to understand what the solution looks like — and that’s the hardest part.',
        'Our approach is different. We need your bottlenecks:',
      ],
      list: ['Where does the company lose time?', 'Which departments are out of sync?', 'Where is data duplicated manually?'],
      closing: "We immerse ourselves in your routine and design the solution. Often it's not at all what you had in mind at the start. Formalizing the task and writing the spec is our job, not yours.",
    },
    how: {
      chapter: { left: '(04 / 08) — Method', right: 'Method · Stack' },
      title: { line1: 'Speed and value:', accent: 'MVP in 3 months.' },
      body: "In business, time is the main asset. You shouldn't wait a year to see first results. Our advantage is speed without losing quality. In three months you get a working first version of the platform (MVP). It's not a presentation or a deck of slides — it's a tool your team already uses and that immediately saves time and money.",
      steps: [
        { num: '01', title: 'We start with your process.', body: 'First conversation — a walkthrough of a real workflow: what hurts, where time disappears, what to automate.' },
        { num: '02', title: 'We design the future contour.', body: 'We turn the task into architecture: data model, roles, integrations, reporting, automation points.' },
        { num: '03', title: 'We build custom where it matters.', body: 'CRM, ERP, ECM, BI, MES, internal portals, operational dashboards, industry-specific platforms.' },
        { num: '04', title: 'We ship and improve in iterations.', body: 'We launch the first working version fast, collect feedback, stabilize and keep improving.' },
      ],
      stackEyebrow: '§ Stack',
      stackLine: 'A modern stack for reliable business software and controlled AI.',
    },
    ownership: {
      chapter: { left: '(05 / 08) — Your asset', right: 'Ownership' },
      title: { line1: 'Ownership, not rent.', accent: 'And nothing extra.' },
      body: [
        'Most companies live in a "zoo" of someone else’s software: dozens of SaaS subscriptions, of which only 10–15% is actually used. And not one of those systems belongs to you.',
        'We build your own asset. We act like surgeons: we precisely "cut out" from third-party systems exactly the functions you keep them for, and seamlessly integrate them into your platform. All company information converges in one point.',
        "You pay only for what you use. The platform belongs 100% to you — it isn't tied to us and can live autonomously. But we do everything so that you'll want to stay with us for years.",
      ],
    },
    philosophy: {
      chapter: { left: '(06 / 08) — Philosophy', right: 'What we believe' },
      title: { accent: 'Foundation first,', line2: 'then technology.' },
      body: [
        "We are architects. Anyone can throw together a system from ready-made modules in a hurry. But a platform that survives multiple growth won't be built that way. Anyone can buy access to an AI agent today — but without the right architecture it's just a toy.",
        'We lay a solid, unique foundation with years of headroom. Any technology mounts easily onto it: automation, end-to-end analytics, agentic AI — or whatever appears tomorrow. A new wave of progress arrives — we simply add it, without rebuilding the whole system. The platform grows with you.',
      ],
    },
    work: {
      chapter: { left: '(07 / 08) — Work', right: 'Architecture in action' },
      title: { line1: 'Architecture in action:', accent: 'from foundation to interface.' },
      disclaimer: 'We don’t sell "boxes" or templates. Everything below is only examples of our custom development. No two companies are alike — so no two platforms are either. Every module and all logic are designed for a specific partner. We show the architecture of complex nodes on conceptual mockups, and the operational base on real screenshots (without confidential data).',
      viewDemo: 'View demo →',
      parts: [
        {
          num: 'Part 1', title: 'Core modules', subLabel: 'Complex business logic',
          cards: [
            { title: 'Finance & P&L management', tag: 'Demo', demo: 'koshi', desc: 'The financial heart of the company. We pull data from every unit into a single dashboard. Real margin of each process in real time. Configured to your metrics.' },
            { title: 'Inventory & logistics', tag: 'Demo', demo: 'ava-platform-horeca', desc: 'Killing warehouse chaos. Automatic turnover calculation, stock control, supplier integration. The logic is programmed to your real physical processes.' },
          ],
        },
        {
          num: 'Part 2', title: 'Operational modules', subLabel: 'Real interfaces',
          cards: [
            { title: 'CRM & client database', tag: 'Demo', demo: 'ava-platform-horeca', desc: 'A single window for client work. History of interactions, transactions and preferences in one profile.' },
            { title: 'HR module & tasks', tag: 'On request', demo: null, desc: 'Team transparency. Task assignment, deadline control, KPI calculation — in one tracker.' },
            { title: 'Requests & document flow', tag: 'On request', demo: null, desc: 'No more paper bureaucracy. Instant reaction to requests, a digital archive, approval chains mapped to your hierarchy.' },
          ],
        },
        {
          num: 'Part 3', title: 'AI agents & analytics', subLabel: 'A layer on the right foundation',
          cards: [
            { title: 'AI analytics & anomaly detection', tag: 'Demo', demo: 'ava-assistant', desc: 'Instead of dry tables — ready business conclusions. The AI agent itself highlights the cause of a margin drop or finds non-obvious growth points.' },
            { title: 'AI forecasting', tag: 'Demo', demo: 'toros', desc: 'A look into the future. Modeling cash gaps, demand forecasting, probability of key-client churn. Algorithms train strictly on your historical data.' },
          ],
        },
      ],
      closing: "These screens are only a demonstration. We can build similar ones for you, adapt them to your industry, or write from scratch something that doesn't yet exist on the market.",
      cta: 'Discuss a custom solution for my business',
      example: {
        eyebrow: 'Example build · SoloTrack · Dubai logistics',
        head: { a: 'From scattered ', strike: 'spreadsheets', b: ' to one ', accent: 'system.' },
        beforeLabel: 'Before', beforeTitle: 'Chaos of files.',
        afterLabel: 'After · custom platform', afterTitle: 'One system. Every role.',
        body: 'The same platform can include agentic workflows: one agent reads documents and messages, another prepares a structured task, a third checks rules or numbers, and a human approves the final action. This keeps AI practical, auditable and tied to the business system.',
      },
    },
    contact: {
      chapter: { left: "(08 / 08) — Let's talk", right: 'Contact' },
      title: { line1: 'Tell us', ital: 'about', accent: 'your task.' },
      body: [
        "Your business deserves its own foundation. Choosing an IT partner defines how you'll work and scale for the next 5, 10, 20 years.",
        "We don't expect a perfect spec from you. You bring the bottlenecks and business goals — we take on architecture, development and implementation. The first working MVP — in 3 months. Let's skip the formalities and talk about where your company is losing time right now.",
      ],
      orDrop: 'Or drop a note',
      prompt: 'What do you do, and which process needs its own system or AI?',
      promise: 'First reply within one business day.',
    },
    form: {
      name: 'Name', email: 'Email', company: 'Company · role',
      message: 'The system, workflow or AI assistant you want to build',
      submit: 'Tell us about your task',
      alert: 'Thanks — your email app should open with the project request and attribution context.',
    },
    teaser: {
      chapter: { left: 'Our products', right: 'Interactive demos' },
      title: { pre: 'Our', accent: 'products.' },
      cta: 'Explore all products →',
    },
    footer: {
      tagline: 'Custom software development, automation and practical AI agents for business operations.',
      products: 'Products', allProducts: 'All products →',
      build: 'What we build',
      buildItems: ['CRM / ERP / ECM / BI / MES systems', 'Operational platforms', 'Internal portals', 'AI agents and dashboards'],
      industries: 'Industries',
      industryItems: ['Manufacturing', 'HoReCa', 'Logistics', 'Service companies', 'Education and teams'],
      contact: 'Contact', emailLabel: 'Email', tgLabel: 'Telegram',
      locations: 'Kyiv · Astana · Dubai · Remote',
      nda: 'We guarantee full protection of your data from the first minute. NDA on request.',
    },
  },

  ru: {
    doc: {
      title: 'Ava Solutions — кастомные бизнес-платформы, автоматизация и AI-агенты',
      desc: 'Бутиковая разработка ПО полного цикла: платформы CRM / ERP / BI, автоматизация и практичные AI-агенты под ваши процессы. Первый рабочий MVP за 3 месяца.',
    },
    hero: {
      meta: { left: '(01 / 08) — Бутиковая разработка · Бизнес-системы', mid: 'Киев · Астана · Дубай', right: 'Осн. 2024' },
      title: { line1: 'Мы находим решения.', pre2: 'Вы получаете ', accent: 'время.' },
      sub: 'Ava Solutions — бутиковая компания полного цикла по разработке индивидуального ПО. Мы строим для вас независимую платформу, созданную исключительно под ваши бизнес-процессы. Без лишнего кода, без переплат за чужой софт. Ваша собственная система. Первый рабочий MVP — уже через 3 месяца.',
      cta: 'Обсудить вашу задачу',
      cta2: 'Смотреть продукты',
    },
    foundation: {
      chapter: { left: '(02 / 08) — Во что мы верим', right: 'Бизнес-архитекторы, а не просто кодеры' },
      title: { a: 'Наш фундамент — ', accent: 'реальный сектор', b: ', а не сухая теория.' },
      body: [
        'Прежде чем стать IT-архитекторами, наша команда больше 20 лет управляла собственными компаниями в реальном секторе бизнеса. Мы на практике прошли через операционную рутину, кассовые разрывы, масштабирование и дорогие ошибки. Такому не учат на курсах программирования.',
        'В какой-то момент мы внедрили технологии в свои процессы — и увидели, сколько тысяч часов они возвращают. Так появилась Ava Solutions.',
        'Мы — бизнесмены, которые делают софт для бизнеса. Мы смотрим на процессы с той же стороны, что и вы, и говорим с вами на одном языке.',
      ],
      pillars: [
        { num: '01', title: 'Задача', body: 'У каждой компании своя операционная логика. Мы начинаем отсюда.' },
        { num: '02', title: 'Сборка', body: 'Связываем роли, данные и решения в единый рабочий контур.' },
        { num: '03', title: 'Результат', body: 'Меньше ручных шагов, чёткая ответственность, больше времени на само дело.' },
      ],
    },
    approach: {
      chapter: { left: '(03 / 08) — С чего мы начинаем', right: 'Подход' },
      title: { line1: 'Нам не нужно ТЗ.', pre2: 'Покажите ваши ', accent: 'узкие места.' },
      body: [
        'Обычно IT-компании начинают с требования: «Дайте нам подробное техническое задание». Но чтобы составить хорошее ТЗ, нужно уже понимать, как выглядит решение. А это — самое трудное.',
        'Наш подход другой. Нам нужны ваши «узкие места»:',
      ],
      list: ['Где компания теряет время?', 'Какие отделы не синхронизированы?', 'Где данные дублируются вручную?'],
      closing: 'Мы погружаемся в вашу рутину и проектируем решение. Зачастую это совсем не то, о чём вы думали вначале. Формализация задачи и написание ТЗ — это наша работа, а не ваша.',
    },
    how: {
      chapter: { left: '(04 / 08) — Метод', right: 'Метод · Стек' },
      title: { line1: 'Скорость и польза:', accent: 'MVP за 3 месяца.' },
      body: 'В бизнесе время — главный актив. Вы не должны ждать год, чтобы увидеть первые результаты. Наше преимущество — скорость без потери качества. За три месяца вы получаете работающую первую версию платформы (MVP). Это не презентация и не набор слайдов — это инструмент, которым ваша команда уже пользуется и который сразу экономит время и деньги.',
      steps: [
        { num: '01', title: 'Начинаем с вашего процесса.', body: 'Первый разговор — разбор реального рабочего процесса: что болит, где исчезает время, что автоматизировать.' },
        { num: '02', title: 'Проектируем будущий контур.', body: 'Превращаем задачу в архитектуру: модель данных, роли, интеграции, отчётность, точки автоматизации.' },
        { num: '03', title: 'Строим кастом там, где это важно.', body: 'CRM, ERP, ECM, BI, MES, внутренние порталы, операционные дашборды, отраслевые платформы.' },
        { num: '04', title: 'Запускаем и улучшаем итерациями.', body: 'Быстро запускаем первую версию, собираем обратную связь, стабилизируем и развиваем.' },
      ],
      stackEyebrow: '§ Стек',
      stackLine: 'Современный стек для надёжного бизнес-софта и управляемого AI.',
    },
    ownership: {
      chapter: { left: '(05 / 08) — Ваш актив', right: 'Владение' },
      title: { line1: 'Владение, а не аренда.', accent: 'И ничего лишнего.' },
      body: [
        'Большинство компаний живут в «зоопарке» чужого софта: десятки SaaS-подписок, из которых используется 10–15%. И ни одна из этих систем вам не принадлежит.',
        'Мы строим ваш собственный актив. Мы действуем как хирурги: филигранно «вырезаем» из сторонних систем ровно те функции, ради которых вы их держите, и бесшовно интегрируем в вашу платформу. Вся информация компании сходится в одной точке.',
        'Вы платите только за то, что используете. Платформа на 100% принадлежит вам — она не привязана к нам и может жить автономно. Но мы делаем всё, чтобы вы захотели остаться с нами на годы.',
      ],
    },
    philosophy: {
      chapter: { left: '(06 / 08) — Философия', right: 'Во что мы верим' },
      title: { accent: 'Сначала фундамент,', line2: 'потом технологии.' },
      body: [
        'Мы — архитекторы. Собрать систему из готовых модулей на скорую руку может кто угодно. Но платформа, которая выдержит кратный рост, так не строится. Купить доступ к AI-агенту сегодня может каждый — но без правильной архитектуры это просто игрушка.',
        'Мы закладываем прочный уникальный фундамент с запасом на годы. На него легко наращиваются любые технологии: автоматизация, сквозная аналитика, агентский AI — или то, что появится завтра. Приходит новый виток прогресса — мы просто добавляем его, не перестраивая систему заново. Платформа растёт вместе с вами.',
      ],
    },
    work: {
      chapter: { left: '(07 / 08) — Работы', right: 'Архитектура в действии' },
      title: { line1: 'Архитектура в действии:', accent: 'от фундамента до интерфейса.' },
      disclaimer: 'Мы не продаём «коробки» и шаблоны. Всё ниже — лишь примеры нашей кастомной разработки. Нет двух одинаковых компаний — нет и двух одинаковых платформ. Каждый модуль и вся логика проектируются под конкретного партнёра. Архитектуру сложных узлов показываем на концептуальных макапах, операционную базу — на реальных скриншотах (без конфиденциальных данных).',
      viewDemo: 'Открыть демо →',
      parts: [
        {
          num: 'Часть 1', title: 'Базовые модули', subLabel: 'Сложная бизнес-логика',
          cards: [
            { title: 'Финансы и P&L', tag: 'Демо', demo: 'koshi', desc: 'Финансовое сердце компании. Сводим данные всех подразделений в единый дашборд. Реальная маржинальность каждого процесса в реальном времени. Настраивается под ваши метрики.' },
            { title: 'Склад и логистика', tag: 'Демо', demo: 'ava-platform-horeca', desc: 'Ликвидация хаоса на складе. Автоматический расчёт оборачиваемости, контроль остатков, интеграция с поставщиками. Логика — под ваши физические процессы.' },
          ],
        },
        {
          num: 'Часть 2', title: 'Операционные модули', subLabel: 'Реальные интерфейсы',
          cards: [
            { title: 'CRM и база клиентов', tag: 'Демо', demo: 'ava-platform-horeca', desc: 'Единое окно работы с клиентом. История взаимодействий, транзакций и предпочтений в одном профиле.' },
            { title: 'HR-модуль и задачи', tag: 'Под запрос', demo: null, desc: 'Прозрачность команды. Постановка задач, контроль дедлайнов, расчёт KPI — в едином трекере.' },
            { title: 'Заявки и документооборот', tag: 'Под запрос', demo: null, desc: 'Отказ от бумаги. Мгновенная реакция на запросы, цифровой архив, цепочки согласования по вашей иерархии.' },
          ],
        },
        {
          num: 'Часть 3', title: 'AI-агенты и аналитика', subLabel: 'Слой на правильном фундаменте',
          cards: [
            { title: 'AI-аналитика и поиск аномалий', tag: 'Демо', demo: 'ava-assistant', desc: 'Вместо сухих таблиц — готовые бизнес-выводы. AI-агент сам подсвечивает причину падения маржинальности или находит неочевидные точки роста.' },
            { title: 'AI-прогнозирование', tag: 'Демо', demo: 'toros', desc: 'Взгляд в будущее. Моделирование кассовых разрывов, прогноз спроса, вероятность оттока ключевых клиентов. Алгоритмы учатся строго на ваших исторических данных.' },
          ],
        },
      ],
      closing: 'Эти экраны — лишь демонстрация. Мы можем собрать аналогичные для вас, адаптировать под вашу отрасль или написать с нуля то, чего ещё нет на рынке.',
      cta: 'Обсудить кастомное решение для моего бизнеса',
      example: {
        eyebrow: 'Пример · SoloTrack · логистика, Дубай',
        head: { a: 'От разрозненных ', strike: 'таблиц', b: ' — к одной ', accent: 'системе.' },
        beforeLabel: 'До', beforeTitle: 'Хаос файлов.',
        afterLabel: 'После · кастомная платформа', afterTitle: 'Одна система. Каждая роль.',
        body: 'Та же платформа может включать агентские сценарии: один агент читает документы и сообщения, другой готовит структурированную задачу, третий проверяет правила или цифры, а человек утверждает финальное действие. Так AI остаётся практичным, проверяемым и привязанным к бизнес-системе.',
      },
    },
    contact: {
      chapter: { left: '(08 / 08) — Давайте познакомимся', right: 'Контакт' },
      title: { line1: 'Расскажите', ital: 'о', accent: 'вашей задаче.' },
      body: [
        'Ваш бизнес заслуживает собственного фундамента. Выбор IT-партнёра определяет, как вы будете работать и масштабироваться следующие 5, 10, 20 лет.',
        'Мы не ждём от вас идеального ТЗ. Вы приносите узкие места и бизнес-цели — мы берём на себя архитектуру, разработку и внедрение. Первый рабочий MVP — через 3 месяца. Давайте пропустим формальности и поговорим о том, где ваша компания теряет время прямо сейчас.',
      ],
      orDrop: 'Или оставьте сообщение',
      prompt: 'Чем вы занимаетесь и какому процессу нужна своя система или AI?',
      promise: 'Первый ответ — в течение одного рабочего дня.',
    },
    form: {
      name: 'Имя', email: 'Email', company: 'Компания · роль',
      message: 'Система, процесс или AI-ассистент, который хотите построить',
      submit: 'Рассказать о своей задаче',
      alert: 'Спасибо — ваше почтовое приложение откроется с заявкой и контекстом.',
    },
    teaser: {
      chapter: { left: 'Наши продукты', right: 'Интерактивные демо' },
      title: { pre: 'Наши', accent: 'продукты.' },
      cta: 'Смотреть все продукты →',
    },
    footer: {
      tagline: 'Бутиковая разработка ПО, автоматизация и практичные AI-агенты для бизнес-процессов.',
      products: 'Продукты', allProducts: 'Все продукты →',
      build: 'Что мы строим',
      buildItems: ['CRM / ERP / ECM / BI / MES системы', 'Операционные платформы', 'Внутренние порталы', 'AI-агенты и дашборды'],
      industries: 'Отрасли',
      industryItems: ['Производство', 'HoReCa', 'Логистика', 'Сервис', 'Образование и команды'],
      contact: 'Контакт', emailLabel: 'Email', tgLabel: 'Telegram',
      locations: 'Киев · Астана · Дубай · Remote',
      nda: 'Гарантируем полную защиту ваших данных с первой минуты общения. NDA по запросу.',
    },
  },
};

const LangContext = React.createContext({ lang: 'en', setLang: () => {}, L: T.en });

function LangProvider({ children }) {
  const [lang, setLangState] = React.useState(() => {
    try { return localStorage.getItem('ava_lang') || 'en'; } catch { return 'en'; }
  });
  const setLang = React.useCallback((next) => {
    if (next !== 'en' && next !== 'ru') return;
    setLangState(next);
    try { localStorage.setItem('ava_lang', next); } catch {}
    if (typeof document !== 'undefined') document.documentElement.lang = next;
    window.avaTrack?.('lang_switch', { lang: next });
  }, []);
  React.useEffect(() => {
    if (typeof document !== 'undefined') document.documentElement.lang = lang;
  }, [lang]);
  const value = React.useMemo(() => ({ lang, setLang, L: T[lang] || T.en }), [lang, setLang]);
  return <LangContext.Provider value={value}>{children}</LangContext.Provider>;
}

function useLang() { return React.useContext(LangContext); }

/* Sets <title> + meta description for the current language. Render once inside
   LangProvider on pages that should follow the home <title> (not the products
   page, which keeps its own title). */
function DocMeta() {
  const { L } = useLang();
  React.useEffect(() => {
    if (typeof document === 'undefined' || !L.doc) return;
    document.title = L.doc.title;
    let m = document.querySelector('meta[name="description"]');
    if (!m) { m = document.createElement('meta'); m.setAttribute('name', 'description'); document.head.appendChild(m); }
    m.setAttribute('content', L.doc.desc);
  }, [L]);
  return null;
}

function LangToggle() {
  const { lang, setLang } = useLang();
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      {['en', 'ru'].map((code) => (
        <button
          key={code}
          type="button"
          className={lang === code ? 'is-active' : ''}
          aria-pressed={lang === code}
          onClick={() => setLang(code)}
        >{code.toUpperCase()}</button>
      ))}
    </div>
  );
}

Object.assign(window, { T, LangContext, LangProvider, useLang, LangToggle, DocMeta });
