function AIHero() {
  const messages = [
    { kind: 'user', name: 'Вы', time: '14 мая, 09:31',
      lines: ['Что выросло в жалобах за последнюю неделю?'] },
    { kind: 'ai', name: 'Фидли', time: '14 мая, 09:31',
      lines: [
        'За 7 дней тема «Apple Pay не проходит» выросла x4 — 412 → 1 680 упоминаний.',
        'Эпицентр — клиенты на iOS 17.4 после релиза 4.12.',
      ] },
    { kind: 'user', name: 'Вы', time: '14 мая, 09:33',
      lines: ['Разбей по сегментам и сравни с прошлым кварталом.'] },
    { kind: 'ai', name: 'Фидли', time: '14 мая, 09:33',
      lines: [
        'В прошлом квартале тема не входила в топ-20. Сейчас — №2 по объёму.',
        '78% жалоб — Премиум на iPhone 13/14.',
      ] },
    { kind: 'ai-chart', name: 'Фидли', time: '14 мая, 09:34',
      lines: ['Вот динамика темы за последние 30 дней:'],
      chart: {
        title: 'Apple Pay не проходит',
        sub: 'Упоминания · 30 дней',
        delta: '+312%',
        points: [22, 24, 26, 28, 32, 28, 34, 38, 42, 40, 48, 54, 62, 68, 78, 92, 108, 128, 152, 168],
      },
      sources: true },
  ];

  const [visible, setVisible] = React.useState(1);
  const [typing, setTyping] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [started, setStarted] = React.useState(false);
  const sectionRef = React.useRef(null);

  // Запускаем анимацию чата только когда секция реально появилась на экране —
  // так пользователь видит сторителлинг, а не пропускает его, открыв страницу.
  React.useEffect(() => {
    if (started || !sectionRef.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && e.intersectionRatio > 0.35) {
          setStarted(true);
          io.disconnect();
        }
      });
    }, { threshold: [0, 0.35, 0.6, 1] });
    io.observe(sectionRef.current);
    return () => io.disconnect();
  }, [started]);

  React.useEffect(() => {
    if (!started) return;
    if (visible >= messages.length) {
      const reset = setTimeout(() => setVisible(1), 9000);
      return () => clearTimeout(reset);
    }
    const next = messages[visible];
    if (next.kind === 'ai') {
      const t1 = setTimeout(() => setTyping(true), 600);
      const t2 = setTimeout(() => {
        setTyping(false);
        setVisible(v => v + 1);
      }, 1900);
      return () => { clearTimeout(t1); clearTimeout(t2); };
    } else if (next.kind === 'ai-chart') {
      // Сначала Фидли «печатает», потом серый скелетон-генератор графика,
      // потом сообщение с текстом и графиком — как у GPT при генерации картинки.
      const t1 = setTimeout(() => setTyping(true), 500);
      const t2 = setTimeout(() => { setTyping(false); setLoading(true); }, 1400);
      const t3 = setTimeout(() => { setLoading(false); setVisible(v => v + 1); }, 3200);
      return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
    } else {
      const t = setTimeout(() => setVisible(v => v + 1), 1400);
      return () => clearTimeout(t);
    }
  }, [visible, started]);

  React.useEffect(() => {
    const el = document.getElementById('aihero-chat-scroll');
    if (!el) return;
    // Несколько проходов: моментально вниз (без анимации, чтобы наверняка
    // прижать) + потом плавно — на случай, если контент дорос после layout
    // (например, появился чарт или картинка-скелетон).
    const jumpNow = () => { el.scrollTop = el.scrollHeight; };
    const smooth = () => { el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' }); };
    jumpNow();
    const r = requestAnimationFrame(jumpNow);
    const t1 = setTimeout(jumpNow, 80);
    const t2 = setTimeout(smooth, 260);
    const t3 = setTimeout(smooth, 700);
    return () => {
      cancelAnimationFrame(r);
      clearTimeout(t1); clearTimeout(t2); clearTimeout(t3);
    };
  }, [visible, typing, loading]);

  const AiAvatar = () => (
    <img
      src="uploads/star_minilogo.svg"
      alt="Фидли"
      style={{ width: 20, height: 20, flexShrink: 0, display: 'block' }}
    />
  );

  const ActionRow = ({ sources }) => (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      marginTop: 10, flexWrap: 'wrap',
    }}>
      <button type="button" className="aih-btn" data-tip="Уточнить" aria-label="Уточнить">
        <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
          <path d="M11.5 4 A 4.5 4.5 0 1 0 12 8.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
          <path d="M11.5 1.5 V4 H9" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
        </svg>
      </button>
      <button type="button" className="aih-btn" data-tip="Создать задачу" aria-label="Создать задачу">
        <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
          <path d="M3 7.5 L6 10.5 L11.5 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>
      <button type="button" className="aih-btn" data-tip="Лайк" aria-label="Лайк">
        <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
          <path d="M5 6 L5 12 H3.5 V6 H5 Z M5 6 L7 1.5 C8.5 1.5 8.5 3 8 5 H11 C11.8 5 12.2 5.8 12 6.5 L11 11 C10.8 11.7 10.2 12 9.5 12 H5" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" fill="none" />
        </svg>
      </button>
      <button type="button" className="aih-btn" data-tip="Дизлайк" aria-label="Дизлайк">
        <svg width="13" height="13" viewBox="0 0 14 14" fill="none" style={{ transform: 'rotate(180deg)' }}>
          <path d="M5 6 L5 12 H3.5 V6 H5 Z M5 6 L7 1.5 C8.5 1.5 8.5 3 8 5 H11 C11.8 5 12.2 5.8 12 6.5 L11 11 C10.8 11.7 10.2 12 9.5 12 H5" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" fill="none" />
        </svg>
      </button>
      {sources && (
        <span style={{
          marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '3px 9px 3px 4px', borderRadius: 999,
          border: '1px solid #ececef', fontSize: 11, color: '#0d0d12', fontWeight: 500,
        }}>
          <span style={{ display: 'inline-flex' }}>
            {['#7a60ff', '#b997ff', '#ffb27a'].map((c, idx) => (
              <span key={idx} style={{
                width: 12, height: 12, borderRadius: '50%',
                background: c, marginLeft: idx === 0 ? 0 : -4,
                border: '1.5px solid #fff',
              }} />
            ))}
          </span>
          Источники
        </span>
      )}
    </div>
  );

  const AnimatedChart = ({ points }) => {
    const W = 540, H = 92;
    const max = Math.max(...points), min = Math.min(...points);
    const step = W / (points.length - 1);
    const ys = points.map(p => H - 6 - ((p - min) / (max - min || 1)) * (H - 12));
    const path = points.map((_, i) => `${i === 0 ? 'M' : 'L'} ${(i * step).toFixed(1)} ${ys[i].toFixed(1)}`).join(' ');
    const area = `${path} L ${W} ${H} L 0 ${H} Z`;
    return (
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ height: 92, display: 'block' }}>
        <defs>
          <linearGradient id="aih-chart-grad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="#7a60ff" stopOpacity="0.28" />
            <stop offset="1" stopColor="#7a60ff" stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d={area} fill="url(#aih-chart-grad)"
          style={{ opacity: 0, animation: 'aih-area 1.6s ease 0.2s forwards' }} />
        <path d={path} stroke="#7a60ff" strokeWidth="2" fill="none"
          strokeLinecap="round" strokeLinejoin="round"
          style={{
            strokeDasharray: 1400, strokeDashoffset: 1400,
            animation: 'aih-draw 1.8s cubic-bezier(0.65, 0, 0.35, 1) forwards',
          }} />
        <circle cx={W} cy={ys[ys.length - 1]} r="3.5" fill="#7a60ff"
          style={{ opacity: 0, animation: 'aih-dot 0.35s ease 1.7s forwards' }} />
      </svg>
    );
  };

  return (
    <section ref={sectionRef} style={{
      background: 'var(--bg)', color: 'var(--ink)',
      padding: '96px 0 120px', position: 'relative', overflow: 'hidden',
    }}>
      <div className="container" style={{ position: 'relative', textAlign: 'center', maxWidth: 1100 }}>
        <div style={{
          fontSize: 11, letterSpacing: '0.18em', color: 'var(--muted)',
          textTransform: 'uppercase', fontWeight: 500, marginBottom: 14,
          fontFamily: "'Golos Text', sans-serif",
        }}>
          Как это работает
        </div>

        <h2 className="display" style={{
          fontSize: 44, lineHeight: 1.0, fontWeight: 500,
          letterSpacing: '-0.025em', color: 'var(--ink)', marginBottom: 6,
        }}>
          ИИ ускоряет анализ клиентов.
        </h2>
        <h2 className="display" style={{
          fontSize: 44, lineHeight: 1.0, fontWeight: 500,
          letterSpacing: '-0.025em', color: '#b6b9c2', marginBottom: 20,
          whiteSpace: 'nowrap',
        }}>
          Из тысяч отзывов в конкретные решения
        </h2>

        <p style={{
          fontSize: 17, lineHeight: 1.45, color: 'var(--muted)',
          maxWidth: 560, margin: '0 auto 56px',
        }}>
          Фидли держит контекст, цитаты и доказательства. Спрашивайте, как у аналитика —
          получайте приоритеты, а не голые цифры.
        </p>

        {/* Photo backdrop + chat overlay */}
        <div style={{
          position: 'relative',
          borderRadius: 18, overflow: 'hidden',
          maxWidth: 1040, margin: '0 auto',
          aspectRatio: '16 / 9',
          backgroundColor: '#e2d2a8',
          backgroundImage: 'url(uploads/aihero-bg.webp)',
          backgroundSize: 'cover', backgroundPosition: 'center',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 24,
        }}>
          <div className="aih-chat-card" style={{
            width: '100%', maxWidth: 580,
            background: '#fff',
            borderRadius: 14,
            boxShadow: '0 18px 50px -18px rgba(0,0,0,0.35)',
            display: 'flex', flexDirection: 'column',
            overflow: 'hidden',
            maxHeight: '90%',
          }}>
            {/* Header */}
            <div style={{
              padding: '14px 18px 12px',
              borderBottom: '1px solid #f0f0f3',
              textAlign: 'left',
            }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#0d0d12' }}>Фидли</div>
              <div style={{ fontSize: 11.5, color: '#8c8f99', marginTop: 1 }}>
                Atlas · команда Платформа
              </div>
            </div>

            {/* Messages */}
            <div id="aihero-chat-scroll" style={{
              padding: '14px 18px', overflowY: 'auto',
              display: 'flex', flexDirection: 'column', gap: 14,
              textAlign: 'left', minHeight: 280,
              scrollBehavior: 'smooth',
            }}>
              {messages.slice(0, visible).map((m, i) => (
                <div key={i} style={{
                  animation: 'aihero-msg 0.45s ease both',
                }}>
                  {m.kind === 'system' && (
                    <div style={{
                      paddingLeft: 12, borderLeft: '2px solid #d9d6e8',
                      fontSize: 12, color: '#8c8f99',
                    }}>{m.text}</div>
                  )}
                  {m.kind === 'ai' && (
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                        <AiAvatar />
                        <span style={{ fontSize: 13, fontWeight: 600, color: '#0d0d12' }}>{m.name}</span>
                        <span style={{ fontSize: 11.5, color: '#9fa1a8' }}>{m.time}</span>
                      </div>
                      {m.lines.map((l, j) => (
                        <div key={j} style={{
                          fontSize: 13.5, color: '#232329', lineHeight: 1.45,
                          marginBottom: j < m.lines.length - 1 ? 8 : 0,
                        }}>{l}</div>
                      ))}
                      <ActionRow sources={m.sources} />
                    </div>
                  )}
                  {m.kind === 'ai-chart' && (
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                        <AiAvatar />
                        <span style={{ fontSize: 13, fontWeight: 600, color: '#0d0d12' }}>{m.name}</span>
                        <span style={{ fontSize: 11.5, color: '#9fa1a8' }}>{m.time}</span>
                      </div>
                      {m.lines.map((l, j) => (
                        <div key={j} style={{
                          fontSize: 13.5, color: '#232329', lineHeight: 1.45,
                          marginBottom: 10,
                        }}>{l}</div>
                      ))}
                      <div style={{
                        border: '1px solid #ececef', borderRadius: 12,
                        padding: '12px 14px', background: '#fafbfc',
                      }}>
                        <div style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                          marginBottom: 8, gap: 10,
                        }}>
                          <div>
                            <div style={{ fontSize: 12.5, fontWeight: 600, color: '#0d0d12' }}>{m.chart.title}</div>
                            <div style={{ fontSize: 10.5, color: '#9fa1a8', marginTop: 1 }}>{m.chart.sub}</div>
                          </div>
                          <span style={{
                            fontSize: 11, fontWeight: 700, color: '#b8324a',
                            padding: '3px 9px', borderRadius: 999,
                            background: 'rgba(184,50,74,0.08)',
                          }}>{m.chart.delta}</span>
                        </div>
                        <AnimatedChart points={m.chart.points} />
                      </div>
                      <ActionRow sources={m.sources} />
                    </div>
                  )}
                  {m.kind === 'user' && (
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: '#0d0d12' }}>{m.name}</span>
                        <span style={{ fontSize: 11.5, color: '#9fa1a8' }}>{m.time}</span>
                      </div>
                      {m.lines.map((l, j) => (
                        <div key={j} style={{ fontSize: 13.5, color: '#232329', lineHeight: 1.45 }}>{l}</div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
              {typing && (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 8,
                  animation: 'aihero-msg 0.3s ease both',
                }}>
                  <AiAvatar />
                  <span style={{
                    display: 'inline-flex', gap: 3,
                    padding: '7px 10px', borderRadius: 12,
                    background: '#f3f3f6',
                  }}>
                    {[0, 1, 2].map(i => (
                      <span key={i} style={{
                        width: 5, height: 5, borderRadius: '50%', background: '#9fa1a8',
                        animation: `aihero-typing 1.2s ${i * 0.15}s infinite ease-in-out`,
                      }} />
                    ))}
                  </span>
                </div>
              )}
              {loading && (
                <div style={{
                  display: 'flex', gap: 10, alignItems: 'flex-start',
                  animation: 'aihero-msg 0.3s ease both',
                }}>
                  <AiAvatar />
                  <div style={{
                    flex: 1, height: 152, borderRadius: 12,
                    background: 'linear-gradient(110deg, #ececef 8%, #f5f5f7 18%, #ececef 33%)',
                    backgroundSize: '200% 100%',
                    animation: 'aih-shimmer 1.4s linear infinite',
                    position: 'relative',
                  }}>
                    <div style={{
                      position: 'absolute', inset: 0,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      gap: 8, color: '#7c7f88', fontSize: 12.5,
                    }}>
                      <span style={{
                        width: 12, height: 12, borderRadius: '50%',
                        border: '2px solid #b8babf', borderTopColor: '#7c7f88',
                        animation: 'aih-spin 0.9s linear infinite',
                        display: 'inline-block',
                      }} />
                      Строю график динамики…
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        <style>{`
          @keyframes aihero-msg {
            from { opacity: 0; transform: translateY(6px); }
            to   { opacity: 1; transform: translateY(0); }
          }
          @keyframes aihero-typing {
            0%, 80%, 100% { transform: translateY(0); opacity: 0.4; }
            40% { transform: translateY(-3px); opacity: 1; }
          }
          @keyframes aih-draw { to { stroke-dashoffset: 0; } }
          @keyframes aih-area { to { opacity: 1; } }
          @keyframes aih-dot  { to { opacity: 1; } }
          @keyframes aih-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
          @keyframes aih-spin    { to { transform: rotate(360deg); } }

          .aih-btn {
            position: relative;
            display: inline-flex; align-items: center; justify-content: center;
            width: 28px; height: 28px; border-radius: 50%;
            border: 1px solid #ececef; background: #fff;
            color: #4a4d56; cursor: pointer;
            font-family: inherit; padding: 0;
            transition: background 0.15s, color 0.15s, border-color 0.15s;
          }
          .aih-btn:hover { background: #f5f5f7; color: #0d0d12; border-color: #d9d9de; }
          .aih-btn::after {
            content: attr(data-tip);
            position: absolute; bottom: calc(100% + 6px); left: 50%;
            transform: translateX(-50%) translateY(2px);
            background: #0d0d12; color: #fff;
            font-size: 11px; line-height: 1; font-weight: 500;
            padding: 5px 8px; border-radius: 6px;
            white-space: nowrap; pointer-events: none;
            opacity: 0; transition: opacity 0.15s, transform 0.15s;
            z-index: 5;
          }
          .aih-btn::before {
            content: ''; position: absolute; bottom: calc(100% + 2px); left: 50%;
            transform: translateX(-50%);
            border: 4px solid transparent; border-top-color: #0d0d12;
            opacity: 0; transition: opacity 0.15s;
            pointer-events: none;
          }
          .aih-btn:hover::after { opacity: 1; transform: translateX(-50%) translateY(0); }
          .aih-btn:hover::before { opacity: 1; }
        `}</style>
      </div>
    </section>
  );
}

window.AIHero = AIHero;
