// Plazify · MAIN hub page (/) — sticky header + platform hero
// Reuses the approved /reviews + /supply header/hero patterns verbatim; only the
// active context (main /), copy and hero visual differ.
// Site architecture (single domain): / = THIS page · /reviews = reviews module · /supply = supply module
const NAV_M = [
  { label: 'Поставки', href: '/supply/', sub: true },
  { label: 'Автоответы', href: '/reviews/', sub: true },
  { label: 'Тарифы', href: '#tarify' },                     // TODO(route): pricing page not created yet
  { label: 'О компании', href: '/about/' },
];

function Header() {
  // Mobile burger menu state. Burger + menu are display:none by default (inline) and only
  // revealed at <=620px by the Home page CSS, so shared use on /about/ is visually unaffected.
  const [menuOpen, setMenuOpen] = React.useState(false);
  const closeMenu = () => setMenuOpen(false);
  return (
    <div className="hdr-wrap" style={{ position: 'sticky', top: 0, zIndex: 30, padding: '20px 40px 0' }}>
      <div style={{ maxWidth: 1360, margin: '0 auto' }}>
        <header className="hdr-bar" style={{
          background: '#0A0A0A', borderRadius: 24, padding: '14px 16px 14px 24px',
          display: 'flex', alignItems: 'center', gap: 28, position: 'relative',
        }}>
          {/* logo → / (current page) */}
          <a href="/" onClick={() => track('nav_click', { to: 'home' })} style={{ display: 'flex', alignItems: 'center', gap: 11, textDecoration: 'none' }}>
            <img src={window.__resources.mark} width="34" height="34" alt="Plazify" />
            <span className="plz-wordmark" style={{ fontSize: 23 }}>Plazify</span>
          </a>
          <nav className="hdr-nav" style={{ display: 'flex', gap: 26, marginLeft: 18 }}>
            {NAV_M.map((l) => (
              <a key={l.label} href={l.href} onClick={() => track('nav_click', { to: l.href })} style={{
                textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6,
                fontFamily: 'var(--plz-font-head)', fontWeight: 500, fontSize: 15,
                color: 'rgba(255,255,255,.62)',
              }}>{l.label}{l.sub && <MIcon name="chevronDown" size={16} color="rgba(255,255,255,.62)" />}</a>
            ))}
          </nav>
          <div className="hdr-cta" style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12 }}>
            <a href="https://app.plazify.ru" onClick={() => track('nav_click', { to: 'login' })} style={{ textDecoration: 'none', fontFamily: 'var(--plz-font-head)', fontWeight: 500, fontSize: 15, color: 'rgba(255,255,255,.62)', padding: '0 10px' }}>Войти</a>
            <MBtn variant="dark" onClick={() => goForm('header_demo')}>Запросить демо</MBtn>
            <MBtn variant="primary" onClick={() => goForm('header_try')}>Попробовать</MBtn>
          </div>

          {/* mobile-only burger button (hidden by default; shown <=620px via Home CSS) */}
          <button type="button" className="hdr-burger" aria-label="Меню" aria-expanded={menuOpen}
            onClick={() => setMenuOpen((o) => !o)} style={{ display: 'none', marginLeft: 'auto' }}>
            {menuOpen ? (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
            ) : (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16" /></svg>
            )}
          </button>

          {/* mobile-only dropdown menu (hidden by default; shown <=620px when open via Home CSS) */}
          <div className={'hdr-menu' + (menuOpen ? ' is-open' : '')} aria-label="Меню навигации" style={{ display: 'none' }}>
            <a className="hdr-menu-link" href="/supply/" onClick={() => { track('nav_click', { to: '/supply/' }); closeMenu(); }}>Поставки</a>
            <a className="hdr-menu-link" href="/reviews/" onClick={() => { track('nav_click', { to: '/reviews/' }); closeMenu(); }}>Автоответы</a>
            <a className="hdr-menu-link" href="/about/" onClick={() => { track('nav_click', { to: '/about/' }); closeMenu(); }}>О компании</a>
            <a className="hdr-menu-link" href="/about/#contacts" onClick={() => { track('nav_click', { to: '/about/#contacts' }); closeMenu(); }}>Контакты</a>
            <a className="hdr-menu-link" href="#faq" onClick={() => { track('nav_click', { to: '#faq' }); closeMenu(); }}>FAQ</a>
            <a className="hdr-menu-link" href="https://app.plazify.ru" onClick={() => { track('nav_click', { to: 'login' }); closeMenu(); }}>Личный кабинет</a>
            <div className="hdr-menu-cta">
              <MBtn variant="primary" full onClick={() => { goForm('header_try'); closeMenu(); }}>Попробовать 7 дней бесплатно</MBtn>
              <MBtn variant="dark" full onClick={() => { goForm('header_demo'); closeMenu(); }}>Запросить демо</MBtn>
            </div>
          </div>
        </header>
      </div>
    </div>
  );
}

const HERO_TRUST_M = ['Резидент Сколково', 'Официальное API Wildberries', 'Без привязки карты'];

// Hero product preview — no single shared platform mockup exists, so we compose the
// two REAL module screenshots into one interactive "spotlight" showcase (reviews inbox
// + supply/stock control). A two-card switcher: the active module is large and dominant
// near centre; the inactive module scales down as a WHOLE card and tucks to its own side,
// slightly lower. Hover or click switches focus. Mobile uses tabs + a single mockup.
// `key` is the state id ('reviews' | 'supply'); 'side' fixes which side each card lives on.
const HERO_MODULES = [
  { key: 'reviews', side: 'left', img: 'reviewsInbox', label: 'Автоответы и аналитика отзывов', short: 'Отзывы', href: '/reviews/' },
  { key: 'supply', side: 'right', img: 'skladScreen', label: 'Прогноз спроса и поставки', short: 'Поставки', href: '/supply/' },
];

const HERO_MODULE_NOTES = {
  reviews: {
    kicker: 'Что делает модуль',
    title: 'AI ответы на отзывы',
    body: 'Настраивайте передовые AI-модели для ответов на отзывы с учетом оценки, текста клиента, товара, CTA и рекомендаций на другие товары.',
    chips: ['Tone of voice', 'CTA', 'Режим публикации'],
  },
  supply: {
    kicker: 'Что делает модуль',
    title: 'AI-прогноз спроса',
    body: 'Модуль анализирует продажи, прогнозирует спрос, отслеживает риски OOS, кластеры пополнения и помогает собрать поставку.',
    chips: ['Прогноз спроса', 'OOS-риск', 'Поставка'],
  },
};

function HeroModuleNote({ active }) {
  if (!active) return null;

  const note = HERO_MODULE_NOTES[active];
  if (!note) return null;

  const side = active === 'reviews' ? 'right' : 'left';

  return (
    <div
      key={active}
      className={'hero-module-note hero-module-note-' + side}
      aria-live="polite"
    >
      <div className="hero-module-note-kicker">{note.kicker}</div>
      <div className="hero-module-note-title">{note.title}</div>
      <p className="hero-module-note-body">{note.body}</p>
      <div className="hero-module-note-chips" aria-hidden="true">
        {note.chips.map((chip) => (
          <span key={chip} className="hero-module-note-chip">{chip}</span>
        ))}
      </div>
    </div>
  );
}

function HeroVisual() {
  const [active, setActive] = React.useState(null); // null = idle/zero state, else 'reviews' | 'supply'

  // ----- zero-state cinematic overlay choreography (runs once per page session) -----
  const ZERO_TITLE = 'Выберите модуль';
  const ZERO_CAPTION = 'с которого начнётся автоматизация магазина';
  const [hubReady, setHubReady] = React.useState(false);       // hub fade-in gate
  const [breathing, setBreathing] = React.useState(false);     // idle card "breath"
  const activationTimer = React.useRef(null);

  React.useEffect(() => {
    const mq = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)');
    if (mq && mq.matches) {
      setHubReady(true);
      setBreathing(false);
      return;
    }

    const timers = [];
    timers.push(setTimeout(() => setHubReady(true), 360));
    timers.push(setTimeout(() => setBreathing(true), 980));

    return () => timers.forEach((t) => clearTimeout(t));
  }, []);

  React.useEffect(() => {
    return () => {
      if (activationTimer.current) {
        window.clearTimeout(activationTimer.current);
      }
    };
  }, []);

  // Three states per card: idle (both calm + equal), active (large, dominant),
  // inactive (smaller WHOLE card, tucked to its side + lower baseline).
  // Cards are anchored to the stage bottom with transform-origin at bottom-of-side,
  // so scaling keeps a shared lower baseline (inactive sits "behind and below").
  const selectModule = (key) => {
    if (active === key) return;

    const reduceMotion = window.matchMedia &&
      window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    if (active === null && !reduceMotion) {
      setHubReady(false);

      if (activationTimer.current) {
        window.clearTimeout(activationTimer.current);
      }

      activationTimer.current = window.setTimeout(() => {
        setActive(key);
        activationTimer.current = null;
      }, 180);

      return;
    }

    setActive(key);
  };

  const cardStyle = (m) => {
    const state = active === null ? 'idle' : (active === m.key ? 'active' : 'inactive');

    const activeX = m.side === 'left' ? 8 : -8;
    const inactiveX = m.side === 'left' ? -14 : 14;

    let transform, opacity, z;

    if (state === 'active') {
      transform = `translate(${activeX}%, -18px) scale(1.08)`;
      opacity = 1;
      z = 4;
    } else if (state === 'inactive') {
      transform = `translate(${inactiveX}%, 132px) scale(0.42)`;
      opacity = 0.58;
      z = 2;
    } else {
      transform = 'translateY(-24px) scale(0.64)';
      opacity = 0.78;
      z = 2;
    }

    return {
      [m.side]: 0,
      transformOrigin: `bottom ${m.side}`,
      transform,
      opacity,
      zIndex: z
    };
  };

  return (
    <div className="hero-visual" style={{ marginTop: 128 }}>
      {/* ---------- desktop / tablet: transform-based spotlight switcher (idle · reviews · supply) ---------- */}
      <div className="hero-module-stage" role="group" aria-label="Модули платформы">
        {/* invisible in-flow sizer reserves the large-card footprint → stable, responsive height */}
        <div className="hero-stage-sizer" aria-hidden="true">
          <div className="hero-module-label">{HERO_MODULES[0].label}</div>
          <div className="hero-module-frame2"></div>
        </div>
        <div className={'hero-zero-hub' + (active === null && hubReady ? ' is-visible' : '')} aria-hidden="true">
          <div className="hero-zero-backdrop" aria-hidden="true"></div>
          <div className="hero-zero-frost" aria-hidden="true"></div>

          <div className="hero-zero-copy">
            <div className="hero-zero-title">{ZERO_TITLE}</div>
            <div className="hero-zero-caption">{ZERO_CAPTION}</div>
            <div className="hero-zero-clickhint" aria-hidden="true">
              <span className="hero-zero-clickicon"></span>
              <span>кликните по модулю</span>
            </div>
          </div>

        </div>

        <HeroModuleNote active={active} />

        {HERO_MODULES.map((m) => {
          const isActive = active === m.key;
          const isInactive = active !== null && !isActive;
          return (
            <div
              key={m.key}
              className={
                'hero-module-card hero-module-card-' + m.side +
                (isActive ? ' is-active' : '') +
                (isInactive ? ' is-inactive' : '') +
                (active === null ? ' is-idle' : '') +
                (active === null && breathing ? ' is-breathing' : '')
              }
              style={cardStyle(m)}
              onClick={() => selectModule(m.key)}
              role="button"
              tabIndex={0}
              aria-pressed={isActive}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); selectModule(m.key); } }}
            >
              <div className="hero-module-breath">
                <div className="hero-module-label">{m.label}</div>
                <div className="hero-module-frame2">
                  <img src={window.__resources[m.img]} alt={m.label + ' — интерфейс Plazify'} />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* ---------- mobile: tabs + single active mockup (default Reviews) ---------- */}
      <div className="hero-switch-mobile">
        <div className="hero-tabs" role="tablist" aria-label="Модули платформы">
          {HERO_MODULES.map((m) => {
            const mActive = (active || 'reviews') === m.key;
            return (
              <button key={m.key} role="tab" aria-selected={mActive}
                className={'hero-tab' + (mActive ? ' is-active' : '')}
                onClick={() => setActive(m.key)}>{m.short}</button>
            );
          })}
        </div>
        {HERO_MODULES.filter((m) => m.key === (active || 'reviews')).map((m) => (
          <div key={m.key}>
            <div className="hero-module-label" style={{ marginTop: 18 }}>{m.label}</div>
            <div className="hero-module-frame2 is-active">
              <img src={window.__resources[m.img]} alt={m.label + ' — интерфейс Plazify'} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  return (
    <Section style={{ paddingTop: 64, paddingBottom: 32 }} max={1280}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 24 }}>
        <span style={{ visibility: 'hidden' }}><Eyebrow><span style={{ width: 7, height: 7, borderRadius: '50%', background: '#5E3EE5', display: 'inline-block' }}></span>AI/ML-платформа для селлеров Wildberries</Eyebrow></span>
        <h1 className="plz-h1 hero-h1" style={{ margin: 0, fontSize: 54, lineHeight: '1.06', maxWidth: 1040, letterSpacing: '-0.02em' }}>
          Отзывы, остатки и поставки Wildberries — под контролем Plazify
        </h1>
        <p className="plz-lead" style={{ margin: 0, maxWidth: 800, fontSize: 20 }}>
          Plazify помогает отвечать на отзывы, анализировать SKU, прогнозировать спрос и рассчитывать
          поставки. AI готовит ответы, прогнозы и рекомендации — вы принимаете решение.
        </p>
        <div className="hero-actions" style={{ display: 'flex', gap: 14, marginTop: 18, flexWrap: 'wrap', justifyContent: 'center' }}>
          <MBtn variant="primary" icon="arrowRight" big onClick={() => goForm('hero_try')}>Попробовать 7 дней бесплатно</MBtn>
          <MBtn variant="outline" big onClick={() => goForm('hero_demo')}>Запросить демо</MBtn>
        </div>
      </div>

      <HeroVisual />
    </Section>
  );
}
Object.assign(window, { Header, Hero });
