// v3-landing.jsx — Aizy v3 (niro-inspired with 3D keyboard)
// Exports: AzLandingV3

function AzLandingV3({ lang = "ru", onLangChange, theme = "light", themeToggle }) {
  const c = window.AZ_COPY[lang];

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

      {/* HERO */}
      <section className="v3-hero">
        <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' ? (
                  <>Принимаем ваши звонки,<br/>
                    пока вы заняты <span className="underline">делом</span>.
                  </>
                ) : (
                  <>We answer your calls<br/>
                    while you're <span className="underline">working</span>.
                  </>
                )}
              </h1>
              <p className="v3-hero__lede">{c.hero_lede}</p>
              <div className="v3-hero__cta">
                <a className="v3-btn v3-btn--amber" href="#cta">{c.hero_cta_primary}
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11L11 3M5 3h6v6"/></svg>
                </a>
                <a className="v3-btn v3-btn--ghost" href="#demo">{c.hero_cta_secondary}</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> сек</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>

      {/* PORTFOLIO — industries */}
      <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 fits <em>any</em> business</>}</h2>
            </div>
            <p className="v3-sec__sub">{c.industries_sub}</p>
          </div>
          <V3Portfolio lang={lang} />
        </div>
      </section>

      {/* FEATURED CASE */}
      <section className="v3-sec" id="demo">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{lang === 'ru' ? 'Кейс · Барбершоп Lumen' : 'Case · Lumen Barbershop'}</span>
              <h2 className="v3-sec__h">{lang === 'ru' ? <>147 звонков<br/>за неделю. <em>0 пропущенных.</em></> : <>147 calls<br/>in a week. <em>0 missed.</em></>}</h2>
            </div>
          </div>
          <V3Case lang={lang} />
        </div>
      </section>

      {/* KEYBOARD of capabilities */}
      <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>клавиш</em>,<br/>один сотрудник</> : <>Six <em>keys</em>,<br/>one employee</>}</h2>
            </div>
            <p className="v3-sec__sub">{lang === 'ru' ? 'Каждая возможность — отдельный модуль. Наведите курсор, чтобы увидеть, как они приподнимаются.' : 'Each capability is its own module. Hover to see them lift.'}</p>
          </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>

      {/* 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>
            <p className="v3-sec__sub">{lang === 'ru' ? 'Четыре шага. Все обычно занимают меньше дня — пилот возвращает первую заявку через 6–10 часов после старта.' : 'Four steps. Usually under a day end-to-end — pilots return their first lead in 6-10 hours.'}</p>
          </div>
          <V3Roadmap lang={lang} />
        </div>
      </section>

      {/* REVIEWS */}
      <section className="v3-sec">
        <div className="v3__wrap">
          <div className="v3-sec__hd">
            <div>
              <span className="v3-sec__eyebrow">{lang === 'ru' ? 'Отзывы' : 'Reviews'}</span>
              <h2 className="v3-sec__h">{lang === 'ru' ? <>Бизнесы, которые <em>больше</em><br/>не пропускают звонки</> : <>Businesses that <em>stopped</em><br/>missing calls</>}</h2>
            </div>
          </div>
        </div>
        <V3Reviews lang={lang} />
      </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">
              <a className="v3-btn v3-btn--dark" href="#">{c.cta_primary}
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11L11 3M5 3h6v6"/></svg>
              </a>
              <a className="v3-btn v3-btn--outline" href="#">{c.cta_secondary}</a>
            </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 V3Nav({ 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="#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="#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>
  );
}

function V3HeroPhone({ lang }) {
  const c = window.AZ_COPY[lang];
  return (
    <div className="v3-phone">
      <div className="v3-phone__notch"/>
      <div className="v3-phone__screen">
        <div className="v3-phone__status v3-num">
          <span>9:41</span>
          <span>● ● ●●●</span>
        </div>
        <div className="v3-phone__call">{lang === 'ru' ? 'входящий · aizy' : 'inbound · aizy'}</div>
        <div className="v3-phone__name">{lang === 'ru' ? 'Артём' : 'Artem'}
          <span className="v3-phone__num" style={{display:'block', marginTop: 2}}>+7 905 ··· · 3-й звонок</span>
        </div>
        <div className="v3-phone__wave">
          {Array.from({length: 28}, (_, i) => {
            const heights = [6,10,14,8,18,12,20,14,10,16,22,12,8,14,18,10,16,20,12,8,14,18,10,12,16,8,14,6];
            return <i key={i} style={{ '--h': `${heights[i]}px`, animationDelay: `${(i * 50) % 700}ms` }}/>;
          })}
        </div>
        <div className="v3-phone__transcript">
          <span className="v3-phone__line is-aizy">{lang === 'ru' ? 'Барбершоп Lumen, слушаю' : 'Lumen, how can I help'}</span>
          <span className="v3-phone__line is-caller">{lang === 'ru' ? 'есть на сегодня?' : 'anything tonight?'}</span>
          <span className="v3-phone__line is-aizy">{lang === 'ru' ? 'Денис в 21:30 — подходит?' : 'Denis at 9:30 PM — works?'}</span>
        </div>
        <div className="v3-phone__cta">
          <button>{lang === 'ru' ? 'СБРОСИТЬ' : 'END'}</button>
          <button className="is-amber">{lang === 'ru' ? 'НА МЕНЕДЖЕРА' : 'TRANSFER'}</button>
        </div>
      </div>
    </div>
  );
}

function V3Portfolio({ lang }) {
  const c = window.AZ_COPY[lang];
  const items = [
    ...c.industries.map((it, i) => ({ ...it, i })),
  ];
  const iconEls = {
    beauty: <PathIcon d="M3 14l8-8 8 8M11 6V4M7 18l4-4 4 4M11 18v3"/>,
    clinic: <PathIcon d="M12 4v16M4 12h16"/>,
    resto:  <PathIcon d="M4 4v16M8 4v8a2 2 0 0 1-2 2H4M16 4h4l-1 16M16 4l-1 9h2"/>,
    hotel:  <PathIcon d="M3 20V8l9-5 9 5v12M9 20v-6h6v6M3 20h18"/>,
    service:<PathIcon d="M14.7 6.3a3.5 3.5 0 0 1-4.9 4.9L4 17l3 3 5.8-5.8a3.5 3.5 0 0 1 4.9-4.9l-1.6 1.6 1.4 1.4z"/>,
    studio: <PathIcon d="M4 6h16v12H4zM4 10h16M8 6V4M16 6V4"/>,
  };
  const tags = lang === 'ru'
    ? { beauty: 'Услуги', clinic: 'Здоровье', resto: 'HoReCa', hotel: 'HoReCa', service: 'Сервис', studio: 'Производство' }
    : { beauty: 'Services', clinic: 'Health', resto: 'HoReCa', hotel: 'HoReCa', service: 'Service', studio: 'Production' };

  return (
    <div className="v3-port">
      {items.map((it) => (
        <article key={it.id} className="v3-port__card">
          <div className="v3-port__head">
            <span className="v3-port__icon">{iconEls[it.id]}</span>
            <span className="v3-port__tag">{tags[it.id]}</span>
          </div>
          <div className="v3-port__viz">
            <V3PortViz id={it.id} />
          </div>
          <div>
            <h3 className="v3-port__t">{it.t}</h3>
            <p className="v3-port__d" style={{marginTop: 8}}>{it.ex}</p>
          </div>
          <span className="v3-port__cta">
            {lang === 'ru' ? 'Смотреть пресет' : 'See preset'}
            <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9L9 3M5 3h4v4"/></svg>
          </span>
        </article>
      ))}
    </div>
  );
}

function PathIcon({ d }) {
  return <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d={d}/></svg>;
}

function V3PortViz({ id }) {
  const vizMap = {
    beauty: (
      <svg viewBox="0 0 200 120" width="80%" height="80%">
        <circle cx="60" cy="60" r="22" fill="none" stroke="var(--amber)" strokeWidth="2"/>
        <circle cx="140" cy="60" r="22" fill="none" stroke="var(--amber)" strokeWidth="2"/>
        <line x1="100" y1="60" x2="100" y2="80" stroke="var(--ink-3)" strokeWidth="2"/>
        <line x1="80" y1="60" x2="120" y2="60" stroke="var(--ink-3)" strokeWidth="2"/>
        <text x="60" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)" letterSpacing=".06em">10:30</text>
        <text x="140" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber)" letterSpacing=".06em">14:00 ✓</text>
      </svg>
    ),
    clinic: (
      <svg viewBox="0 0 200 120" width="80%" height="80%">
        <rect x="40" y="40" width="120" height="40" rx="6" fill="none" stroke="var(--line-2)" strokeWidth="1.5"/>
        <rect x="40" y="40" width="80" height="40" rx="6" fill="var(--amber)" opacity=".25"/>
        <line x1="120" y1="30" x2="120" y2="90" stroke="var(--amber)" strokeWidth="2"/>
        <text x="120" y="106" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber)" letterSpacing=".08em">СЕЙЧАС</text>
        <text x="50" y="32" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">ОЧЕРЕДЬ · 8 МИН</text>
      </svg>
    ),
    resto: (
      <svg viewBox="0 0 200 120" width="80%" height="80%">
        {[0,1,2,3].map(i => (
          <g key={i} transform={`translate(${30 + i*42}, 28)`}>
            <rect x="0" y="0" width="28" height="28" rx="4" fill={i === 1 ? 'var(--amber)' : 'var(--bg-4)'}/>
            <circle cx="6" cy="40" r="3" fill={i === 1 ? 'var(--amber)' : 'var(--ink-4)'}/>
            <circle cx="22" cy="40" r="3" fill={i === 1 ? 'var(--amber)' : 'var(--ink-4)'}/>
          </g>
        ))}
        <text x="100" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber)" letterSpacing=".06em">СТОЛ 2 · ПТ 20:00 · 4 ГОСТЯ</text>
      </svg>
    ),
    hotel: (
      <svg viewBox="0 0 200 120" width="85%" height="85%">
        <g transform="translate(20, 30)">
          {Array.from({length: 7}, (_, i) => (
            <g key={i} transform={`translate(${i*23}, 0)`}>
              <rect x="0" y="0" width="20" height="20" rx="2" fill="var(--bg-4)"/>
              <text x="10" y="13" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">{12 + i}</text>
            </g>
          ))}
          <rect x="46" y="0" width="46" height="20" rx="2" fill="var(--amber)" opacity=".25"/>
          <rect x="46" y="0" width="46" height="20" rx="2" fill="none" stroke="var(--amber)" strokeWidth="1.5"/>
        </g>
        <text x="100" y="80" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber)" letterSpacing=".06em">2 НОЧИ · DBL · 14 — 15</text>
      </svg>
    ),
    service: (
      <svg viewBox="0 0 200 120" width="85%" height="85%">
        <g transform="translate(30, 24)">
          <rect x="0" y="0" width="140" height="70" rx="6" fill="none" stroke="var(--line-2)" strokeWidth="1.5"/>
          <line x1="0" y1="22" x2="140" y2="22" stroke="var(--line-2)"/>
          <text x="8" y="14" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">ЗАЯВКА #4128</text>
          <text x="124" y="14" textAnchor="end" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber)">В РАБОТЕ</text>
          <text x="8" y="38" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-2)">macbook pro · экран</text>
          <text x="8" y="54" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-2)">от 8 500 ₽ · 2 дня</text>
          <circle cx="124" cy="50" r="10" fill="var(--amber)"/>
          <text x="124" y="53" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber-ink)" fontWeight="700">✓</text>
        </g>
      </svg>
    ),
    studio: (
      <svg viewBox="0 0 200 120" width="85%" height="85%">
        <rect x="20" y="20" width="80" height="80" rx="4" fill="none" stroke="var(--line-2)" strokeWidth="1.5"/>
        <line x1="20" y1="60" x2="100" y2="60" stroke="var(--line-2)" strokeDasharray="2 3"/>
        <line x1="60" y1="20" x2="60" y2="100" stroke="var(--line-2)" strokeDasharray="2 3"/>
        <text x="60" y="14" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">2.4 М</text>
        <text x="14" y="63" textAnchor="end" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)" transform="rotate(-90 14 60)">1.8 М</text>
        <g transform="translate(120, 30)">
          <rect x="0" y="0" width="60" height="14" rx="2" fill="var(--bg-4)"/>
          <text x="6" y="10" fontFamily="var(--font-mono)" fontSize="8" fill="var(--amber)">ЗАМЕР · СБ</text>
          <rect x="0" y="22" width="60" height="14" rx="2" fill="var(--bg-4)"/>
          <text x="6" y="32" fontFamily="var(--font-mono)" fontSize="8" fill="var(--ink-2)">42 800 ₽</text>
          <rect x="0" y="44" width="60" height="14" rx="2" fill="var(--amber)"/>
          <text x="6" y="54" fontFamily="var(--font-mono)" fontSize="8" fill="var(--amber-ink)">ЗАКАЗ ✓</text>
        </g>
      </svg>
    ),
  };
  return vizMap[id] || null;
}

function V3Case({ lang }) {
  const c = window.AZ_COPY[lang];
  const isRu = lang === 'ru';
  const rows = isRu ? [
    { i: 'АА', name: 'Артём А.', sub: 'стрижка + борода · 3-й звонок', tag: 'заявка', t: '21:32', lead: true },
    { i: 'МП', name: 'Мария П.', sub: 'окрашивание', tag: 'перевод', t: '20:55', lead: false },
    { i: 'ИС', name: 'Игорь С.', sub: 'стрижка · 2-й звонок', tag: 'заявка', t: '20:14', lead: true },
    { i: 'СГ', name: 'Светлана Г.', sub: 'детская стрижка · 5-й', tag: 'заявка', t: '19:22', lead: true },
  ] : [
    { i: 'AA', name: 'Artem A.', sub: 'cut + beard · 3rd call', tag: 'lead', t: '9:32', lead: true },
    { i: 'MP', name: 'Maria P.', sub: 'color', tag: 'handoff', t: '8:55', lead: false },
    { i: 'IS', name: 'Igor S.', sub: 'haircut · 2nd call', tag: 'lead', t: '8:14', lead: true },
    { i: 'SG', name: 'Svetlana G.', sub: 'kids cut · 5th', tag: 'lead', t: '7:22', lead: true },
  ];
  return (
    <div className="v3-case">
      <div style={{ position: 'relative' }}>
        <h3 className="v3-case__h">{isRu ? 'Барбершоп Lumen' : 'Lumen Barbershop'}</h3>
        <p className="v3-case__sub">{isRu ? 'Сеть из трёх точек в Москве. Подключили Aizy в начале месяца. Aizy принимает звонки 24/7, ведёт запись через YClients, переводит сложные случаи на менеджеров.' : 'A 3-location chain in Moscow. Hooked up Aizy at the start of the month. Aizy answers 24/7, books through YClients, hands off complex cases to managers.'}</p>
        <div className="v3-case__metrics">
          <div className="v3-case__metric"><span className="v v3-num">147</span><span className="k">{isRu ? 'звонков / 7 дней' : 'calls / 7 days'}</span></div>
          <div className="v3-case__metric"><span className="v v3-num">83<sup>%</sup></span><span className="k">{isRu ? 'довели до заявки' : 'reach booking'}</span></div>
          <div className="v3-case__metric"><span className="v v3-num">0.4<sup>сек</sup></span><span className="k">{isRu ? 'время ответа' : 'pickup'}</span></div>
        </div>
        <div className="v3-case__tags">
          <span className="v3-case__tag">openai realtime</span>
          <span className="v3-case__tag">voximplant</span>
          <span className="v3-case__tag">yclients</span>
          <span className="v3-case__tag">amocrm</span>
          <span className="v3-case__tag">telegram</span>
        </div>
      </div>
      <div className="v3-case__viz">
        <div className="v3-case__viz-h">
          <strong>{isRu ? 'Aizy · последние звонки' : 'Aizy · recent calls'}</strong>
          <span>{isRu ? 'LIVE · 21:38' : 'LIVE · 9:38 PM'}</span>
        </div>
        {rows.map((r, i) => (
          <div key={i} className="v3-case__row">
            <span className="av">{r.i}</span>
            <span className="nm">{r.name}<small>{r.sub}</small></span>
            <span className={`tg ${r.lead ? 'is-lead' : ''}`}>{r.tag}</span>
            <span className="tm">{r.t}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 3D KEYBOARD with mouse-follow tilt ──────────────────────
function V3Keyboard({ lang }) {
  const c = window.AZ_COPY[lang];
  const ref = React.useRef(null);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0, targetX = 0, targetY = 0, curX = 0, curY = 0;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width - 0.5;
      const y = (e.clientY - r.top) / r.height - 0.5;
      targetX = x * 8;
      targetY = -y * 6;
    };
    const onLeave = () => { targetX = 0; targetY = 0; };
    const tick = () => {
      curX += (targetX - curX) * 0.1;
      curY += (targetY - curY) * 0.1;
      el.style.transform = `rotateY(${curX}deg) rotateX(${curY}deg)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      cancelAnimationFrame(raf);
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  const keys = [
    { big: true,  t: c.features[0].t, d: c.features[0].d, icon: <PathIcon d="M5 15c2 3 5 5 7 5s5-2 7-5M12 4v12M9 11l3 3 3-3"/> },
    { t: c.features[1].t, d: c.features[1].d, icon: <PathIcon d="M4 6h16M4 12h16M4 18h10"/> },
    { t: c.features[2].t, d: c.features[2].d, icon: <PathIcon d="M12 12c2.5 0 4-2 4-4s-1.5-4-4-4-4 2-4 4 1.5 4 4 4zM4 21c0-4 4-7 8-7s8 3 8 7"/> },
    { t: c.features[3].t, d: c.features[3].d, icon: <PathIcon d="M4 5h12l4 4v10H4zM4 9h16M9 13h6M9 16h6"/> },
    { t: c.features[4].t, d: c.features[4].d, icon: <PathIcon d="M16 3l5 5-5 5M3 7h18M8 21l-5-5 5-5M21 16H3"/> },
    { t: c.features[5].t, d: c.features[5].d, icon: <PathIcon d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3zM19 11a7 7 0 0 1-14 0M12 18v4M8 22h8"/> },
  ];

  return (
    <div className="v3-kb-wrap">
      <div className="v3-kb" ref={ref}>
        {keys.map((k, i) => (
          <article key={i} className={`v3-key ${k.big ? 'v3-key--big' : ''}`}>
            <div className="v3-key__top">
              <span className="v3-key__icon">{k.icon}</span>
              <span className="v3-key__num v3-mono">0{i+1} / 06</span>
            </div>
            <h3 className="v3-key__t">{k.t}</h3>
            <p className="v3-key__d">{k.d}</p>
          </article>
        ))}
      </div>
    </div>
  );
}

function V3Roadmap({ lang }) {
  const c = window.AZ_COPY[lang];
  const isRu = lang === 'ru';
  const steps = [
    { t: isRu ? 'Заявка и звонок' : 'Apply and a call',          d: isRu ? 'Расскажите про бизнес: тип, количество звонков, ожидания. 20 минут.' : 'Tell us about your business: type, call volume, expectations. 20 minutes.', viz: <RmVizCall/> },
    { t: isRu ? 'Подключение номера' : 'Hooking up the number',  d: isRu ? 'Подключаем номер или переадресацию. Параллельно с операторами — без переноса.' : 'We connect a number or call forwarding. Runs alongside your operators — no porting.', viz: <RmVizPhone/> },
    { t: isRu ? 'Настройка ассистента' : 'Tuning the assistant', d: isRu ? 'Услуги, прайс, график, правила записи. Готово к вечеру того же дня.' : 'Services, pricing, schedule, booking rules. Ready by end of day.',         viz: <RmVizTune/> },
    { t: isRu ? 'Первая заявка' : 'First lead',                  d: isRu ? 'Aizy принимает, ведёт диалог, создаёт заявки. Уведомление в Telegram.' : 'Aizy picks up, talks, creates leads. Telegram alert.',                     viz: <RmVizLead/> },
  ];
  return (
    <div className="v3-rm">
      {steps.map((s, i) => (
        <div key={i} className="v3-rm__step">
          <span className="v3-rm__step-n v3-num">0{i+1}</span>
          <div className="v3-rm__step-viz">{s.viz}</div>
          <h3 className="v3-rm__step-t">{s.t}</h3>
          <p className="v3-rm__step-d">{s.d}</p>
        </div>
      ))}
    </div>
  );
}

function RmVizCall() {
  return (
    <svg viewBox="0 0 180 100" width="80%" height="80%">
      <rect x="10" y="20" width="160" height="60" rx="8" fill="none" stroke="var(--line-2)" strokeWidth="1.5"/>
      <circle cx="30" cy="50" r="10" fill="var(--amber)" opacity=".25"/>
      <text x="30" y="54" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fill="var(--amber)" fontWeight="700">☎</text>
      <text x="50" y="46" fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-3)" letterSpacing=".06em">SETUP CALL · 20 МИН</text>
      <line x1="50" y1="56" x2="120" y2="56" stroke="var(--amber)" strokeWidth="2"/>
      <line x1="50" y1="62" x2="100" y2="62" stroke="var(--line-2)" strokeWidth="2"/>
    </svg>
  );
}
function RmVizPhone() {
  return (
    <svg viewBox="0 0 180 100" width="80%" height="80%">
      <rect x="60" y="14" width="60" height="80" rx="10" fill="var(--bg-4)" stroke="var(--line-2)"/>
      <rect x="66" y="22" width="48" height="56" rx="3" fill="var(--bg)"/>
      <text x="90" y="52" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fill="var(--amber)" fontWeight="700">+7</text>
      <circle cx="90" cy="86" r="3" fill="var(--ink-3)"/>
      <path d="M30 50l25-3M125 50l25 3" stroke="var(--amber)" strokeWidth="1.5" strokeDasharray="3 2"/>
      <text x="20" y="40" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">PBX</text>
      <text x="155" y="40" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">AIZY</text>
    </svg>
  );
}
function RmVizTune() {
  return (
    <svg viewBox="0 0 180 100" width="85%" height="85%">
      <g transform="translate(20, 18)">
        {[0,1,2,3].map(i => (
          <g key={i} transform={`translate(0, ${i*16})`}>
            <text x="0" y="8" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)" letterSpacing=".06em">{['СТРИЖКА', 'БОРОДА', 'ЗАПИСЬ', 'ПРАВИЛА'][i]}</text>
            <rect x="60" y="2" width="80" height="6" rx="1" fill="var(--bg-4)"/>
            <rect x="60" y="2" width={["52", "40", "70", "60"][i]} height="6" rx="1" fill="var(--amber)"/>
          </g>
        ))}
      </g>
    </svg>
  );
}
function RmVizLead() {
  return (
    <svg viewBox="0 0 180 100" width="85%" height="85%">
      <rect x="20" y="18" width="80" height="64" rx="6" fill="var(--bg-4)" stroke="var(--line-2)"/>
      <text x="28" y="34" fontFamily="var(--font-mono)" fontSize="9" fill="var(--amber)">ЗАЯВКА #001</text>
      <text x="28" y="48" fontFamily="var(--font-mono)" fontSize="8" fill="var(--ink-3)">артём · 21:30</text>
      <text x="28" y="62" fontFamily="var(--font-mono)" fontSize="8" fill="var(--ink-3)">стрижка + борода</text>
      <text x="28" y="76" fontFamily="var(--font-mono)" fontSize="8" fill="var(--ink-3)">3 200 ₽</text>
      <rect x="116" y="28" width="44" height="44" rx="22" fill="var(--amber)"/>
      <text x="138" y="56" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="22" fill="var(--amber-ink)" fontWeight="700">✓</text>
      <path d="M100 50h16" stroke="var(--amber)" strokeWidth="2" strokeDasharray="3 2"/>
    </svg>
  );
}

function V3Reviews({ lang }) {
  const isRu = lang === 'ru';
  const a = isRu ? [
    { i: 'Х', n: 'Хирург', d: '12 марта 2026', t: 'Подключили Aizy на пилот — на третий день она поймала звонок, который мы бы пропустили: семейный приём, чек на 38 тысяч. Окупила себя за неделю.' },
    { i: 'Z', n: 'ZetovDesign', d: '2 февраля 2026', t: 'Боялись, что клиенты заметят. За месяц — ни одной жалобы. Зато менеджеры наконец занимаются работой, а не сидят на телефоне.' },
    { i: 'r', n: 'r0d0xx', d: '25 января 2026', t: 'У нас 4 точки. Aizy узнаёт постоянных по номеру и предлагает любимого мастера. Мелочь, а клиенты в восторге.' },
    { i: 'n', n: 'n0ctcode', d: '18 января 2026', t: 'Самое полезное — что 0% пропущенных. Раньше теряли по 5-8 звонков в день в час пик. Сейчас всё в CRM.' },
    { i: 'F', n: 'FitClub Энергия', d: '7 ноября 2025', t: 'Подключили перед январём — старт сезона. Aizy справилась с потоком новых записей без операторов. Чисто маркетинг.' },
    { i: 'К', n: 'Клиника Доктор Плюс', d: '19 октября 2025', t: 'Думала, голосовой AI — это всегда «нажмите 1». Aizy разговаривает как живая, поняла даже мою бабушку, которая звонила записаться.' },
  ] : [
    { i: 'X', n: 'Surgeon', d: 'Mar 12, 2026', t: 'Hooked up Aizy as a pilot — on day three she caught a call we would have missed. ₽38k ticket. Paid for itself in a week.' },
    { i: 'Z', n: 'ZetovDesign', d: 'Feb 2, 2026', t: 'Worried clients would notice. Zero complaints in a month. Meanwhile managers actually work instead of sitting on phones.' },
    { i: 'r', n: 'r0d0xx', d: 'Jan 25, 2026', t: 'We run 4 locations. Aizy recognizes returning callers by number and offers their usual stylist. Customers love it.' },
    { i: 'n', n: 'n0ctcode', d: 'Jan 18, 2026', t: 'Most useful — 0% missed. We used to lose 5-8 calls a day at rush. Now everything is in CRM.' },
    { i: 'F', n: 'FitClub Energy', d: 'Nov 7, 2025', t: 'Hooked up before January — peak season. Aizy handled the new bookings without operators. Pure marketing.' },
    { i: 'C', n: 'Doctor Plus Clinic', d: 'Oct 19, 2025', t: 'I thought voice AI was always "press 1". Aizy talks like a person — even understood my grandma calling to book.' },
  ];
  const b = isRu ? [
    { i: 'С', n: 'Салон Марси', d: '5 сентября 2025', t: 'Окупаемость — 11 принятых звонков в месяц. У нас в день столько. Логика простая.' },
    { i: 'm', n: 'mopedy', d: '22 августа 2025', t: 'Понравилось, что не «робот». Скрипты гибкие, тон спокойный, без агрессии.' },
    { i: '_', n: '_syntex', d: '10 августа 2025', t: 'Хорошо ловит сложные запросы — переводит на менеджера без лишних кругов.' },
    { i: 'p', n: 'pm_sash', d: '30 июля 2025', t: 'Спасибо за транскрипты — теперь видим, что реально говорят клиенты. Маркетинг рад.' },
    { i: 'k', n: 'k_ilya93', d: '14 июля 2025', t: 'Подключилось за день, без переноса номера. Это вообще лучшее.' },
    { i: 'n', n: 'neurobit', d: '28 июня 2025', t: 'Хороший саппорт. По любым вопросам отвечают в Telegram быстро.' },
  ] : [
    { i: 'M', n: 'Marsy Salon', d: 'Sep 5, 2025', t: 'Pays for itself with 11 picked-up calls a month. We get that daily. Simple math.' },
    { i: 'm', n: 'mopedy', d: 'Aug 22, 2025', t: 'I like that it doesn\'t sound like a "robot". Scripts are flexible, tone calm, no pushiness.' },
    { i: '_', n: '_syntex', d: 'Aug 10, 2025', t: 'Catches complex queries well — hands off to humans without loops.' },
    { i: 'p', n: 'pm_sash', d: 'Jul 30, 2025', t: 'Thanks for transcripts — now we see what customers actually say. Marketing is happy.' },
    { i: 'k', n: 'k_ilya93', d: 'Jul 14, 2025', t: 'Set up in a day, no number porting. That alone is the best part.' },
    { i: 'n', n: 'neurobit', d: 'Jun 28, 2025', t: 'Good support. Quick replies in Telegram for any question.' },
  ];
  const renderRow = (list, cls) => (
    <div className={`v3-rev__row ${cls}`}>
      {[...list, ...list].map((r, i) => (
        <article key={i} className="v3-rev__card">
          <div className="v3-rev__top">
            <span className="v3-rev__av">{r.i}</span>
            <div>
              <div className="v3-rev__name">{r.n}</div>
              <div className="v3-rev__date">{r.d}</div>
            </div>
            <span className="v3-rev__stars">★★★★★</span>
          </div>
          <p className="v3-rev__t">{r.t}</p>
        </article>
      ))}
    </div>
  );
  return (
    <div className="v3-rev">
      {renderRow(a, 'r1')}
      {renderRow(b, 'r2')}
    </div>
  );
}

function V3Faq({ lang }) {
  const isRu = lang === 'ru';
  const items = isRu ? [
    { q: 'Как быстро можно запустить Aizy?', a: 'Обычно пилот можно запустить за 1 день. Мы разбираем ваши звонки, загружаем услуги, цены, график и правила записи, после чего подключаем номер или переадресацию.' },
    { q: 'Нужно ли менять мой номер телефона?', a: 'Нет. Aizy можно подключить к текущей линии через переадресацию или телефонию. На пилоте ассистент может работать параллельно с вашей командой, без остановки бизнеса.' },
    { q: 'Что Aizy делает во время звонка?', a: 'Отвечает клиенту голосом, уточняет запрос, консультирует по вашим правилам, записывает или принимает заявку, а после разговора отправляет итог в CRM, Telegram или другой канал.' },
    { q: 'Что если клиент попросит живого человека?', a: 'Aizy спокойно переведет звонок на менеджера или создаст задачу на обратный звонок. При передаче сохраняется контекст: кто звонил, что хотел и на каком моменте остановился разговор.' },
    { q: 'А если ассистент не знает ответа?', a: 'Он не должен выдумывать. В таком случае Aizy уточнит детали, зафиксирует обращение и передаст его менеджеру с пометкой, что нужен ответ человека.' },
    { q: 'Клиенты поймут, что говорят с AI?', a: 'Aizy говорит естественным голосом, понимает паузы и перебивания. Если клиенту нужен человек, ассистент не спорит и переводит диалог дальше по сценарию.' },
    { q: 'Какие звонки Aizy может обрабатывать?', a: 'Запись на услугу, бронь, первичные консультации, ответы на частые вопросы, уточнение цены, прием заявок, перенос записи, статус заказа и передача сложных вопросов менеджеру.' },
    { q: 'Куда попадает результат звонка?', a: 'После разговора вы получаете контакт клиента, суть запроса, выбранную услугу, время, комментарий, запись и краткое summary. Итог можно отправлять в CRM, Telegram, email, Google Sheets или webhook.' },
    { q: 'Можно ли контролировать, что говорит ассистент?', a: 'Да. Мы задаем сценарии, базу знаний, ограничения, тон общения и правила передачи менеджеру. Вы можете обновлять услуги, цены, график и ответы на частые вопросы.' },
    { q: 'Подойдет ли Aizy моему бизнесу?', a: 'Если клиенты звонят вам, чтобы записаться, забронировать, узнать цену, оставить заявку или уточнить статус, Aizy почти наверняка подойдет. Особенно для салонов, клиник, ресторанов, сервисов, отелей и локальных услуг.' },
  ] : [
    { q: 'How fast can Aizy go live?', a: 'Usually a pilot can launch in 1 day. We review your calls, load your services, prices, schedule and booking rules, then connect a number or call forwarding.' },
    { q: 'Do I need to change my phone number?', a: 'No. Aizy connects to your current line via call forwarding or telephony. During the pilot it can run in parallel with your team, without disrupting the business.' },
    { q: 'What does Aizy do during a call?', a: 'It answers the caller by voice, clarifies the request, advises based on your rules, books or takes the request, and after the call sends the result to your CRM, Telegram or another channel.' },
    { q: 'What if a caller asks for a real person?', a: 'Aizy calmly transfers the call to a manager or creates a callback task. The context is preserved on hand-off: who called, what they wanted, and where the conversation left off.' },
    { q: 'What if the assistant doesn\'t know the answer?', a: 'It shouldn\'t make things up. In that case Aizy clarifies the details, logs the request and passes it to a manager flagged as needing a human reply.' },
    { q: 'Will customers realize they\'re talking to an AI?', a: 'Aizy speaks with a natural voice and understands pauses and interruptions. If a caller wants a human, the assistant doesn\'t argue and moves the conversation along per the scenario.' },
    { q: 'What kinds of calls can Aizy handle?', a: 'Service bookings, reservations, first-line consultations, answers to common questions, price checks, taking requests, rescheduling, order status, and handing complex questions to a manager.' },
    { q: 'Where does the call result go?', a: 'After the call you get the customer\'s contact, the gist of the request, the chosen service, time, a comment, the recording and a short summary. The result can be sent to your CRM, Telegram, email, Google Sheets or a webhook.' },
    { q: 'Can I control what the assistant says?', a: 'Yes. We set the scenarios, knowledge base, limits, tone of voice and hand-off rules. You can update services, prices, schedule and answers to common questions.' },
    { q: 'Is Aizy a fit for my business?', a: 'If customers call you to book, reserve, ask a price, leave a request or check a status, Aizy is almost certainly a fit — especially for salons, clinics, restaurants, services, hotels and local businesses.' },
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <div className="v3-faq">
      {items.map((it, i) => (
        <div key={i} className={`v3-faq__item ${open === i ? 'is-open' : ''}`}>
          <button className="v3-faq__btn" onClick={() => setOpen(open === i ? -1 : i)}>
            <span>{it.q}</span>
            <span className="v3-faq__icon">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M7 2v10M2 7h10"/></svg>
            </span>
          </button>
          <div className="v3-faq__body">
            <p>{it.a}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  AzLandingV3,
  V3Nav, V3HeroPhone, V3Portfolio, V3Case, V3Keyboard, V3Roadmap, V3Reviews, V3Faq,
  V3PortViz, PathIcon, RmVizCall, RmVizPhone, RmVizTune, RmVizLead,
});
