// final.jsx — Aizy final landing
// Best of v1/v2/v3 in a cobalt-blue palette · bilingual RU/EN
// Reuses V3* helpers exposed by v3-landing.jsx

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "ru",
  "theme": "light"
}/*EDITMODE-END*/;

// Extra copy for new sections (versus, player, pricing) — keyed by lang
const FINAL_COPY = {
  ru: {
    versus_eyebrow: "Сравнение",
    versus_h: <>Пока оператор занят, <em>Aizy</em> уже принимает следующий звонок</>,
    versus_off_t: "Живой оператор",
    versus_off_tag: "не в смене",
    versus_off_unit: "%",
    versus_off_num: "30",
    versus_off_label: "пропущенных в час пик",
    versus_on_t: "Aizy",
    versus_on_tag: "на линии",
    versus_on_unit: "%",
    versus_on_num: "0",
    versus_on_label: "пропущенных за неделю",
    versus_rows: [
      { k: "Часы",          h: "9:00–21:00",                a: "24/7, без перерывов" },
      { k: "Скорость",      h: "3–4 гудка",                 a: "0.4 сек после соединения" },
      { k: "Пропущенные",   h: "до 30% в час пик",          a: "0%" },
      { k: "Стоимость",     h: "от 45 000 ₽/мес",           a: "от 9 900 ₽/мес" },
      { k: "Качество",      h: "плавает по настроению",     a: "одинаковое всегда" },
      { k: "Память",        h: "если узнал по голосу",      a: "по номеру — вся история" },
    ],
    player_eyebrow: "Послушать пример",
    player_h: <>Реальный звонок: <em>барбершоп</em>, вечер пятницы.</>,
    player_sub: "Аудио синхронизировано с расшифровкой. Кликните по реплике — переход к ней.",
    player_title: "Lumen · входящий · 38 сек",
    player_chips: ["заявка создана", "клиент узнан · 3-й звонок", "услуга: стрижка + борода", "мастер: Денис · 21:30"],
    pricing_eyebrow: "Тарифы",
    pricing_h: <>Платите за <em>минуты</em>, а не за зарплату.</>,
    pricing_plans: [
      { id: "basic", t: "Basic", price: "$900", unit: "/ мес", desc: "Для: барбершоп, салон красоты, небольшой ресторан, кафе, небольшой отель, клиника на 1 точку", cta: "попробовать", primary: false, list: [
        "1 200 минут (≈ 400–600 звонков/мес, 13–20 звонков в день)",
        "1 AI-ассистент",
        "1 основной тип обращений",
        "Базовая обработка звонков",
        "Запись / бронь / первичная квалификация",
        "Передача лида в Telegram / email / таблицу",
        "Базовая настройка и базовая поддержка",
        "Доп. минута сверх лимита: $0.65",
      ] },
      { id: "business", t: "Business", price: "$1 700", unit: "/ мес", desc: "Для: загруженные салоны, рестораны, отели, клиники, автосервис, недвижимость, сервисный бизнес", cta: "попробовать", primary: true, badge: "рекомендуемый", list: [
        "2 500 минут (≈ 830–1 250 звонков/мес, 28–42 звонка в день)",
        "1 AI-ассистент",
        "До 2 типов обращений",
        "1 CRM-интеграция или базовая API-интеграция",
        "Аналитика и приоритетная поддержка",
        "Регулярные корректировки",
        "Более гибкая логика разговора",
        "Доп. минута сверх лимита: $0.55",
      ] },
      { id: "enterprise", t: "Enterprise", price: "$3 000", unit: "/ мес", desc: "Для: сети отелей, клиники, отделы продаж, сети, высоконагруженный бизнес", cta: "Обсудить", primary: false, list: [
        "4 500 минут (≈ 1 500–2 250 звонков/мес, 50–75 звонков в день)",
        "Несколько типов обращений",
        "CRM + API / несколько интеграций",
        "Более сложная маршрутизация",
        "Расширенная аналитика",
        "Приоритетное сопровождение",
        "Поддержка отделов / филиалов / команд",
        "Доп. минута сверх лимита: $0.45",
      ] },
      { id: "custom", t: "Custom", price: "от $4 500", unit: "/ мес", desc: "Индивидуально", cta: "Обсудить", primary: false, list: [
        "Сложные интеграции",
        "Несколько филиалов",
        "Кастомная логика",
        "Высокая нагрузка",
        "SLA",
      ] },
    ],
    tweaks_lang: "Язык",
    tweaks_lang_iface: "Интерфейс",
    tweaks_theme: "Тема",
    tweaks_theme_label: "Палитра",
    tweaks_light: "светлая",
    tweaks_dark:  "тёмная",
  },
  en: {
    versus_eyebrow: "Compare",
    versus_h: <>While your operator is busy, <em>Aizy</em> is already taking the next call</>,
    versus_off_t: "Human operator",
    versus_off_tag: "off shift",
    versus_off_unit: "%",
    versus_off_num: "30",
    versus_off_label: "missed in rush hour",
    versus_on_t: "Aizy",
    versus_on_tag: "on the line",
    versus_on_unit: "%",
    versus_on_num: "0",
    versus_on_label: "missed last week",
    versus_rows: [
      { k: "Hours",          h: "9am–9pm",                  a: "24/7, no breaks" },
      { k: "Pickup",         h: "3–4 rings",                a: "0.4s after connect" },
      { k: "Missed",         h: "up to 30% in rush hour",   a: "0%" },
      { k: "Cost",           h: "from ₽45,000 / mo",         a: "from ₽9,900 / mo" },
      { k: "Quality",        h: "varies by mood",            a: "the same, every time" },
      { k: "Memory",         h: "if recognized by voice",    a: "full history by number" },
    ],
    player_eyebrow: "Hear an example",
    player_h: <>A real call: <em>barbershop</em>, Friday night.</>,
    player_sub: "Audio synced to transcript. Click any line to jump there.",
    player_title: "Lumen · inbound · 38 sec",
    player_chips: ["lead created", "returning caller · 3rd call", "service: cut + beard", "stylist: Denis · 9:30 PM"],
    pricing_eyebrow: "Pricing",
    pricing_h: <>Pay for <em>minutes</em>, not salaries.</>,
    pricing_plans: [
      { id: "basic", t: "Basic", price: "$900", unit: "/ mo", desc: "For: barbershop, beauty salon, small restaurant, café, small hotel, single-location clinic", cta: "Try it", primary: false, list: [
        "1,200 minutes (≈ 400–600 calls/mo, 13–20 calls/day)",
        "1 AI assistant",
        "1 main request type",
        "Basic call handling",
        "Booking / reservation / primary qualification",
        "Lead handoff to Telegram / email / spreadsheet",
        "Basic setup and basic support",
        "Extra minute over limit: $0.65",
      ] },
      { id: "business", t: "Business", price: "$1,700", unit: "/ mo", desc: "For: busy salons, restaurants, hotels, clinics, auto service, real estate, service businesses", cta: "Try it", primary: true, badge: "recommended", list: [
        "2,500 minutes (≈ 830–1,250 calls/mo, 28–42 calls/day)",
        "1 AI assistant",
        "Up to 2 request types",
        "1 CRM integration or basic API integration",
        "Analytics and priority support",
        "Regular adjustments",
        "More flexible conversation logic",
        "Extra minute over limit: $0.55",
      ] },
      { id: "enterprise", t: "Enterprise", price: "$3,000", unit: "/ mo", desc: "For: hotel groups, clinics, sales teams, networks, high-load businesses", cta: "Talk to us", primary: false, list: [
        "4,500 minutes (≈ 1,500–2,250 calls/mo, 50–75 calls/day)",
        "Multiple request types",
        "CRM + API / multiple integrations",
        "More complex routing",
        "Extended analytics",
        "Priority support",
        "Support for departments / branches / teams",
        "Extra minute over limit: $0.45",
      ] },
      { id: "custom", t: "Custom", price: "from $4,500", unit: "/ mo", desc: "Individual", cta: "Talk to us", primary: false, list: [
        "Complex integrations",
        "Multiple branches",
        "Custom logic",
        "High load",
        "SLA",
      ] },
    ],
    tweaks_lang: "Language",
    tweaks_lang_iface: "Interface",
    tweaks_theme: "Theme",
    tweaks_theme_label: "Palette",
    tweaks_light: "light",
    tweaks_dark:  "dark",
  },
};

// ── New section: Versus cards ─────────────────────────────
function FnVersus({ lang }) {
  const f = FINAL_COPY[lang];
  return (
    <div className="fn-versus">
      <article className="fn-vcard fn-vcard--off">
        <div className="fn-vcard__top">
          <h3 className="fn-vcard__t">{f.versus_off_t}</h3>
          <span className="fn-vcard__tag">{f.versus_off_tag}</span>
        </div>
        <div className="fn-vcard__big">
          <span className="fn-vcard__num">{f.versus_off_num}<span className="fn-vcard__unit">{f.versus_off_unit}</span></span>
          <span className="fn-vcard__label">{f.versus_off_label}</span>
        </div>
        <div className="fn-vcard__rows">
          {f.versus_rows.map((r, i) => (
            <div key={i} className="fn-vcard__row">
              <span className="k">{r.k}</span>
              <span className="v">{r.h}</span>
            </div>
          ))}
        </div>
      </article>
      <article className="fn-vcard fn-vcard--on">
        <div className="fn-vcard__top">
          <h3 className="fn-vcard__t">{f.versus_on_t}</h3>
          <span className="fn-vcard__tag">{f.versus_on_tag}</span>
        </div>
        <div className="fn-vcard__big">
          <span className="fn-vcard__num">{f.versus_on_num}<span className="fn-vcard__unit">{f.versus_on_unit}</span></span>
          <span className="fn-vcard__label">{f.versus_on_label}</span>
        </div>
        <div className="fn-vcard__rows">
          {f.versus_rows.map((r, i) => (
            <div key={i} className="fn-vcard__row">
              <span className="k">{r.k}</span>
              <span className="v">{r.a}</span>
            </div>
          ))}
        </div>
      </article>
    </div>
  );
}

// ── New section: live call player ─────────────────────────
function FnPlayer({ lang }) {
  const c = window.AZ_COPY[lang];
  const f = FINAL_COPY[lang];
  const lines = c.demo_transcript;
  const duration = 38;
  const [playing, setPlaying] = React.useState(false);
  const [t, setT] = React.useState(0);
  const rafRef = React.useRef(0);
  const lastRef = React.useRef(0);

  React.useEffect(() => {
    if (!playing) { cancelAnimationFrame(rafRef.current); return; }
    lastRef.current = performance.now();
    const tick = (now) => {
      const dt = (now - lastRef.current) / 1000;
      lastRef.current = now;
      setT((prev) => {
        const next = prev + dt;
        if (next >= duration) { setPlaying(false); return 0; }
        return next;
      });
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [playing]);

  const idx = (() => {
    let i = 0;
    for (let j = 0; j < lines.length; j++) if (t >= lines[j].t) i = j;
    return i;
  })();

  const fmt = (s) => {
    const m = Math.floor(s / 60), r = Math.floor(s % 60);
    return `${m}:${String(r).padStart(2, '0')}`;
  };

  const onScrub = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    const ratio = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));
    setT(ratio * duration);
  };

  const bars = 96;
  const heights = React.useMemo(() => {
    // mulberry32 seed=41
    let s = 41 * 9301 + 49297;
    const rng = () => {
      s = Math.imul(s ^ (s >>> 15), s | 1);
      s ^= s + Math.imul(s ^ (s >>> 7), s | 61);
      return ((s ^ (s >>> 14)) >>> 0) / 4294967296;
    };
    const arr = Array.from({ length: bars }, () => 0.18 + Math.pow(rng(), 1.3) * 0.82);
    // Boost where Aizy speaks
    lines.forEach((line, j) => {
      const start = Math.floor((line.t / duration) * bars);
      const span = j < lines.length - 1
        ? Math.floor(((lines[j+1].t - line.t) / duration) * bars) - 2
        : 6;
      for (let i = start; i < Math.min(bars, start + span); i++) {
        const peak = 0.55 + Math.sin((i - start) / Math.max(1, span) * Math.PI) * 0.42;
        arr[i] = Math.max(arr[i], peak);
      }
    });
    return arr;
  }, [lines]);
  const playedBars = Math.round((t / duration) * bars);

  return (
    <div className="fn-player">
      <div className="fn-player__left">
        <div className="fn-player__head">
          <button className="fn-player__play" onClick={() => setPlaying((p) => !p)} aria-label={playing ? 'Pause' : 'Play'}>
            {playing ? (
              <svg width="18" height="18" viewBox="0 0 18 18"><rect x="4" y="3" width="3.5" height="12" fill="currentColor"/><rect x="10.5" y="3" width="3.5" height="12" fill="currentColor"/></svg>
            ) : (
              <svg width="18" height="18" viewBox="0 0 18 18"><path d="M6 3l9 6-9 6z" fill="currentColor"/></svg>
            )}
          </button>
          <div className="fn-player__meta">
            <div className="fn-player__title">{f.player_title}</div>
            <div className="fn-player__sub">
              <span className="v3-num">{fmt(t)} / {fmt(duration)}</span>
              <span className="fn-player__rec"><i/>REC</span>
            </div>
          </div>
        </div>
        <div className="fn-player__wave" onClick={onScrub}>
          {heights.map((v, i) => {
            const tCur = (i / bars) * duration;
            const isAizy = (() => {
              let k = -1;
              for (let j = 0; j < lines.length; j++) if (tCur >= lines[j].t) k = j;
              return k >= 0 && lines[k].who === 'aizy';
            })();
            return (
              <i key={i} style={{
                height: `${Math.round(v * 48)}px`,
                background: i < playedBars
                  ? (isAizy ? 'var(--amber)' : 'var(--ink-2)')
                  : 'var(--line-2)',
              }}/>
            );
          })}
          <div className="fn-player__cursor" style={{ left: `${(t / duration) * 100}%` }}/>
        </div>
        <div className="fn-player__chips">
          {f.player_chips.map((tag, i) => <span key={i} className="fn-player__chip">{tag}</span>)}
        </div>
      </div>
      <div className="fn-player__right">
        {lines.map((line, i) => {
          const active = i === idx && playing;
          const past = i < idx;
          return (
            <button key={i}
              className={`fn-player__line ${line.who === 'aizy' ? 'is-aizy' : 'is-caller'} ${active ? 'is-active' : ''} ${past ? 'is-past' : ''}`}
              onClick={() => { setT(line.t); setPlaying(true); }}>
              <span className="t v3-num">{fmt(line.t)}</span>
              <span className="who">{line.who === 'aizy' ? c.demo_aizy : c.demo_caller}</span>
              <span className="tx">{line[lang]}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ── New section: pricing ───────────────────────────────────
function FnPricing({ lang }) {
  const f = FINAL_COPY[lang];
  return (
    <>
      <div className="fn-pricing">
        {f.pricing_plans.map((p) => (
          <article key={p.id} className={`fn-plan ${p.primary ? 'is-primary' : ''}`}>
            <div className="fn-plan__top">
              <h3 className="fn-plan__t">{p.t}</h3>
              {p.badge && <span className="fn-plan__badge">{p.badge}</span>}
            </div>
            <div className="fn-plan__price">
              <span className="num">{p.price}</span>
              <span className="unit">{p.unit}</span>
            </div>
            <p className="fn-plan__desc">{p.desc}</p>
            <ul className="fn-plan__list">
              {p.list.map((it, j) => <li key={j}>{it}</li>)}
            </ul>
            <a href="#cta" className={`v3-btn ${p.primary ? 'v3-btn--ghost' : 'v3-btn--amber'} fn-plan__cta`} style={p.primary ? { background: '#fff', color: 'var(--amber)' } : undefined}>
              {p.cta}
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9L9 3M5 3h4v4"/></svg>
            </a>
          </article>
        ))}
      </div>
    </>
  );
}

// ── Final landing — composition ────────────────────────────
function FinalNav({ lang, onLangChange, themeToggle }) {
  const c = window.AZ_COPY[lang];
  return (
    <nav className="v3-nav">
      <div className="v3__wrap v3-nav__row">
        <a className="v3-logo" href="#"><span className="v3-logo__mark"/>aizy</a>
        <div className="v3-nav__links">
          <a href="#industries">{c.nav.industries}</a>
          <a href="#capabilities">{c.nav.product}</a>
          <a href="#how">{c.nav.how}</a>
          <a href="#pricing">{c.nav.pricing}</a>
          <a href="#faq">FAQ</a>
        </div>
        <div className="v3-nav__right">
          {themeToggle}
          <div className="v3-lang">
            <button className={lang === 'ru' ? 'is-active' : ''} onClick={() => onLangChange('ru')}>RU</button>
            <button className={lang === 'en' ? 'is-active' : ''} onClick={() => onLangChange('en')}>EN</button>
          </div>
          <a href={`/account/login?lang=${lang}`} className="v3-btn v3-btn--ghost" style={{ padding: '10px 16px', fontSize: 13 }}>
            <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M7 4V2a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1v-2M9 7H1m0 0l3-3M1 7l3 3"/></svg>
            {c.nav.login}
          </a>
          <a href="#cta" className="v3-btn v3-btn--amber" style={{ padding: '10px 18px', fontSize: 13 }}>{c.nav.pilot}
            <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9L9 3M5 3h4v4"/></svg>
          </a>
        </div>
      </div>
    </nav>
  );
}

// Website-link onboarding entry. The visitor pastes their site URL; we POST it to
// /onboarding/start, which extracts a draft business profile, spins up a tenant,
// and returns the editor URL we navigate to. This is the "start via website link"
// path (the pricing cards remain the "buy a package" path).
function WebsiteIngestForm({ lang, variant }) {
  const c = window.AZ_COPY[lang];
  const o = (c && c.onboard) || {};
  const [url, setUrl] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setError("");
    setBusy(true);
    try {
      const res = await fetch("/onboarding/start", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ url: url })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data && data.error ? data.error : (o.err_generic || "Не удалось обработать сайт."));
      // The crawl runs in the background — go to the progress page, which polls
      // until the draft is ready and then forwards to the editor.
      if (data && data.progressUrl) { window.location = data.progressUrl; return; }
      throw new Error(o.err_generic || "Не удалось обработать сайт.");
    } catch (err) {
      setError(err && err.message ? err.message : (o.err_generic || "Ошибка."));
      setBusy(false);
    }
  }

  return (
    <form className={`az-ingest az-ingest--${variant || "hero"}`} onSubmit={submit}>
      <div className="az-ingest__row">
        <input
          type="text"
          inputMode="url"
          autoComplete="url"
          className="az-ingest__input"
          placeholder={o.placeholder || "your-site.com"}
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          disabled={busy}
          required
        />
        <button type="submit" className="v3-btn v3-btn--amber az-ingest__btn" disabled={busy}>
          {busy ? (o.busy || "Анализируем…") : (o.cta || "Создать ассистента по сайту")}
          {!busy && <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11L11 3M5 3h6v6"/></svg>}
        </button>
      </div>
      {error
        ? <p className="az-ingest__error">{error}</p>
        : <p className="az-ingest__hint">{o.hint || "Соберём данные с сайта в черновик профиля и дадим протестировать ассистента — без регистрации."}</p>}
    </form>
  );
}

function AzFinalLanding({ lang, theme, onLangChange, themeToggle }) {
  const c = window.AZ_COPY[lang];
  const f = FINAL_COPY[lang];

  return (
    <div className={`v3 is-final ${theme === "dark" ? "v3-dark" : ""}`}>
      <FinalNav lang={lang} onLangChange={onLangChange} themeToggle={themeToggle} />

      {/* HERO */}
      <section className="v3-hero" id="product">
        <div className="v3-dots"/>
        <div className="v3-glow g1"/>
        <div className="v3-glow g2"/>
        <div className="v3__wrap">
          <div className="v3-hero__head">
            <span className="v3-hero__tag"><i/>Voice AI · Russia</span>
            <span className="v3-hero__arrow">
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 17L17 5M8 5h9v9"/>
              </svg>
            </span>
          </div>
          <div className="v3-hero__grid">
            <div>
              <h1 className="v3-hero__title">
                {lang === 'ru' ? (
                  <>AI-админ, который не пропускает <span className="underline">ни одного звонка</span></>
                ) : (
                  <>An AI receptionist that<br/>never misses <span className="underline">a call</span></>
                )}
              </h1>
              <p className="v3-hero__lede">{c.hero_lede}</p>
              <WebsiteIngestForm lang={lang} variant="hero" />
              <div className="v3-hero__cta">
                <a className="v3-btn v3-btn--ghost" href="#demo">{c.hero_cta_secondary}</a>
                <a className="v3-btn v3-btn--ghost" href="#pricing">{c.hero_cta_primary}</a>
              </div>
              <div className="v3-hero__stat">
                {c.metrics.slice(0, 3).map((m, i) => (
                  <div key={i} className="v3-hero__stat-item">
                    <span className="v v3-num">{m.v}{m.u && <sup>{m.u}</sup>}</span>
                    <span className="k">{m.k}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="v3-hero__viz">
              <V3HeroPhone lang={lang} />
              <div className="v3-hero__chip c1">
                <span className="label">{lang === 'ru' ? 'Заявка → CRM' : 'Lead → CRM'}</span>
                <span className="val">amoCRM <span className="acc">✓</span></span>
              </div>
              <div className="v3-hero__chip c2">
                <span className="label">{lang === 'ru' ? 'Время ответа' : 'Pickup'}</span>
                <span className="val v3-num"><span className="acc">0.4</span> {lang === 'ru' ? 'сек' : 'sec'}</span>
              </div>
              <div className="v3-hero__chip c3">
                <span className="label">{lang === 'ru' ? 'Узнаёт' : 'Recognizes'}</span>
                <span className="val">{lang === 'ru' ? '3-й звонок' : '3rd call'}</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* VERSUS — Operator vs Aizy */}
      <section className="v3-sec">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{f.versus_eyebrow}</span>
              <h2 className="v3-sec__h">{f.versus_h}</h2>
            </div>
          </div>
          <FnVersus lang={lang} />
        </div>
      </section>

      {/* CAPABILITIES — 3D keyboard */}
      <section className="v3-sec" id="capabilities">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{lang === 'ru' ? 'Что под капотом' : 'Under the hood'}</span>
              <h2 className="v3-sec__h">{lang === 'ru' ? <>От звонка до заявки — <em>один Aizy</em></> : <>From call to lead — <em>one Aizy</em></>}</h2>
            </div>
          </div>
          <V3Keyboard lang={lang} />
          <div className="v3-kb-hint">
            <svg className="cursor" viewBox="0 0 14 14" fill="none">
              <path d="M2 2l4 10 2-4 4-2z" fill="var(--amber)"/>
            </svg>
            {lang === 'ru' ? 'наведите · подвигайте курсор' : 'hover · move your cursor'}
          </div>
        </div>
      </section>

      {/* LIVE CALL PLAYER */}
      <section className="v3-sec" id="demo">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{f.player_eyebrow}</span>
              <h2 className="v3-sec__h">{f.player_h}</h2>
            </div>
            <p className="v3-sec__sub">{f.player_sub}</p>
          </div>
          <FnPlayer lang={lang} />
        </div>
      </section>

      {/* INDUSTRIES — portfolio cards */}
      <section className="v3-sec" id="industries">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{c.industries_eyebrow}</span>
              <h2 className="v3-sec__h">{lang === 'ru' ? <>Aizy уже знает, как работать <em>в вашей нише</em></> : <>Aizy already knows how to work <em>in your niche</em></>}</h2>
            </div>
            <p className="v3-sec__sub">{c.industries_sub}</p>
          </div>
          <V3Portfolio lang={lang} />
        </div>
      </section>

      {/* HOW IT WORKS — roadmap */}
      <section className="v3-sec" id="how">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{c.how_eyebrow}</span>
              <h2 className="v3-sec__h">{lang === 'ru' ? <>От заявки до <em>первого</em> звонка</> : <>From signup to <em>first</em> call</>}</h2>
            </div>
          </div>
          <V3Roadmap lang={lang} />
        </div>
      </section>

      {/* PRICING */}
      <section className="v3-sec" id="pricing">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{f.pricing_eyebrow}</span>
              <h2 className="v3-sec__h">{f.pricing_h}</h2>
            </div>
          </div>
          <FnPricing lang={lang} />
        </div>
      </section>

      {/* FAQ */}
      <section className="v3-sec" id="faq">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{lang === 'ru' ? 'Вопросы' : 'FAQ'}</span>
              <h2 className="v3-sec__h">{lang === 'ru' ? <>Часто <em>спрашивают</em></> : <>Frequently <em>asked</em></>}</h2>
            </div>
          </div>
          <V3Faq lang={lang} />
        </div>
      </section>

      {/* FINAL CTA */}
      <section className="v3-sec" id="cta">
        <div className="v3__wrap">
          <div className="v3-cta-card">
            <div>
              <h2>{c.cta_h}</h2>
              <p>{c.cta_sub}</p>
            </div>
            <div className="v3-cta-card__buttons">
              <WebsiteIngestForm lang={lang} variant="cta" />
            </div>
          </div>
        </div>
      </section>

      <footer className="v3-foot">
        <div className="v3__wrap v3-foot__row">
          <span className="v3-foot__tag">{c.footer_tag}</span>
          <div className="v3-foot__links">
            {c.footer_links.map((l, i) => <a key={i} href="#">{l}</a>)}
          </div>
        </div>
      </footer>
    </div>
  );
}

function FinalApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const setLang = (lang) => setTweak("lang", lang);
  const toggleTheme = () => setTweak("theme", t.theme === "dark" ? "light" : "dark");
  const f = FINAL_COPY[t.lang];

  const themeToggle = (
    <button
      onClick={toggleTheme}
      title={t.theme === "dark" ? "Light" : "Dark"}
      style={{
        width: 36, height: 36, borderRadius: 999,
        background: "var(--bg-2)",
        border: "1px solid var(--line)",
        color: "var(--ink-2)",
        cursor: "pointer",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        transition: "background .15s, color .15s",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.color = "var(--ink)"; e.currentTarget.style.background = "var(--bg-3)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.color = "var(--ink-2)"; e.currentTarget.style.background = "var(--bg-2)"; }}
    >
      {t.theme === "dark" ? (
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="8" r="3"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M2.8 2.8l1.5 1.5M11.7 11.7l1.5 1.5M2.8 13.2l1.5-1.5M11.7 4.3l1.5-1.5"/></svg>
      ) : (
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M13 9.5A5.5 5.5 0 0 1 6.5 3a5.5 5.5 0 1 0 6.5 6.5z"/></svg>
      )}
    </button>
  );

  return (
    <>
      <AzFinalLanding lang={t.lang} theme={t.theme} onLangChange={setLang} themeToggle={themeToggle} />

      <TweaksPanel title="Tweaks">
        <TweakSection label={f.tweaks_lang} />
        <TweakRadio label={f.tweaks_lang_iface} value={t.lang}
          options={[{value:"ru",label:"RU"},{value:"en",label:"EN"}]}
          onChange={setLang} />

        <TweakSection label={f.tweaks_theme} />
        <TweakRadio label={f.tweaks_theme_label} value={t.theme}
          options={[
            {value:"light", label: f.tweaks_light},
            {value:"dark",  label: f.tweaks_dark},
          ]}
          onChange={(v) => setTweak("theme", v)} />
      </TweaksPanel>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<FinalApp/>);
