function HowMinicornWorks() {
  const [activeStep, setActiveStep] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [hasIntersected, setHasIntersected] = React.useState(false);

  React.useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setHasIntersected(true);
        obs.disconnect();
      }
    }, { threshold: 0.3 });
    const el = document.getElementById('how-works');
    if (el) obs.observe(el);
    return () => obs.disconnect();
  }, []);

  React.useEffect(() => {
    if (paused || !hasIntersected) return;
    const id = setInterval(() => setActiveStep(s => (s + 1) % 4), 9600);
    return () => clearInterval(id);
  }, [paused, hasIntersected]);

  const steps = [
    {
      n: '01',
      color: '#A78BFA',
      tag: 'Сбор данных',
      title: 'Легко и быстро',
      body: 'Еда, вода, сон, активность, день цикла, настроение — Миникорн берёт на себя скучную часть и помогает её интерпретировать.',
      items: ['Фото, голос или текст — 15 сек', 'Сон и шаги подтягиваются автоматом', 'День цикла и настроение — один тап', 'Нутриенты и БАДы — с напоминаниями'],
      icon: (c) => (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 2a10 10 0 1 0 0 20A10 10 0 0 0 12 2z"/>
          <path d="M8 12h8M12 8v8"/>
        </svg>
      ),
    },
    {
      n: '02',
      color: '#34D399',
      tag: 'AI-анализ',
      title: 'Поиск паттернов',
      body: 'Миникорн видит то, что сложно заметить в моменте — причинно-следственные связи. В связке «симптом + данные».',
      bodyMobile: 'Миникорн видит то, что сложно заметить в моменте — причинно-следственные связи твоего организма. В связке «симптом + данные».',
      items: ['Корреляции между сном и тягой к сладкому', 'Дефициты нутриентов, которые воруют ресурс', '«Ты чаще устаёшь в четверг» — и почему', 'Цепочка: стресс → недоедание → срыв'],
      icon: (c) => (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/>
        </svg>
      ),
    },
    {
      n: '03',
      color: '#FBBF24',
      tag: 'Персонализация',
      title: 'Точный тюнинг',
      body: 'Не советы из интернета, а персональные настройки для своего организма. С контекстом, что было на ужин, как прошла ночь, какие планы на завтра.',
      items: ['Рекомендации на основе твоей истории', 'Учитывает аллергии и предпочтения', 'Адаптируется под ритм жизни', 'Без универсальных диет — только твоё'],
      icon: (c) => (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/>
          <line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/>
          <line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/>
          <line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/>
          <line x1="17" y1="16" x2="23" y2="16"/>
        </svg>
      ),
    },
    {
      n: '04',
      color: '#FB7185',
      tag: 'Результат',
      title: 'Глубокие выводы',
      body: 'Не статистика в телефоне — а глубокие инсайты, которые ты чувствуешь в моменте. Твоё тело начинает работать предсказуемо.',
      items: ['Энергия без кофе во второй половине дня', 'Понимание, почему именно так, а не «попробуй»', 'Изменения, которые держатся, а не откатываются', 'Ты в контакте с собой, а не в борьбе'],
      icon: (c) => (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
          <path d="M22 4L12 14.01l-3-3"/>
        </svg>
      ),
    },
  ];

  const current = steps[activeStep];

  return (
    <section id="how-works" className="pad-y-lg" style={{ position: 'relative', overflow: 'hidden' }}>

      {/* bg texture */}
      <div aria-hidden style={{
        position: 'absolute', top: '30%', left: '50%', transform: 'translateX(-50%)',
        width: '80%', height: '50%', pointerEvents: 'none',
        background: `radial-gradient(ellipse at center, ${current.color}0d 0%, transparent 70%)`,
        filter: 'blur(80px)', transition: 'background 0.6s ease',
      }}/>

      <div className="wrap">

        {/* ── Header ── */}
        <Reveal>
          <SectionLabel n={2}>Как это работает</SectionLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'center', marginBottom: 56 }} className="hmw-header">
            <h2 className="display" style={{ fontSize: 'clamp(38px, 5.5vw, 72px)', margin: 0, lineHeight: 0.95 }}>
              За счёт чего<br/>
              <span style={{
                background: `linear-gradient(120deg, #ffffff 10%, var(--violet) 55%, var(--pink) 100%)`,
                WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
              }}>меняется всё.</span>
            </h2>
            <p className="lede" style={{ margin: 0 }}>
              Не очередной счётчик калорий.<br/>
              Интеллектуальная модель + твой личный контекст — результат глубже, чем у любого трекера.
            </p>
          </div>
        </Reveal>

        {/* ── Step selector + content ── */}
        <Reveal delay={80}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 24, alignItems: 'stretch' }} className="hmw-grid">

            {/* Left: step list */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {steps.map((s, i) => {
                const isActive = activeStep === i;
                return (
                  <button key={i} onClick={() => {
                    if (activeStep === i) { setPaused(p => !p); }
                    else { setActiveStep(i); setPaused(false); }
                  }} style={{
                    appearance: 'none', border: 0, cursor: 'pointer', textAlign: 'left',
                    padding: '20px 24px', borderRadius: 16, transition: 'all .3s ease',
                    background: isActive
                      ? `linear-gradient(135deg, ${s.color}18, ${s.color}08)`
                      : 'rgba(255,255,255,0.025)',
                    border: `1px solid ${isActive ? s.color + '50' : 'rgba(255,255,255,0.06)'}`,
                    boxShadow: isActive ? `0 8px 32px -8px ${s.color}44` : 'none',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                      {/* Step icon */}
                      <div style={{
                        width: 48, height: 48, borderRadius: 12, flexShrink: 0,
                        background: isActive
                          ? `linear-gradient(135deg, ${s.color}30, ${s.color}10)`
                          : 'rgba(255,255,255,0.04)',
                        border: `1px solid ${isActive ? s.color + '50' : 'rgba(255,255,255,0.08)'}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        transition: 'all .3s',
                      }}>
                        {s.icon(isActive ? s.color : 'rgba(255,255,255,0.25)')}
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{
                          fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.16em',
                          color: isActive ? s.color : 'var(--ink-4)',
                          textTransform: 'uppercase', marginBottom: 4, transition: 'color .3s',
                        }}>{s.n} · {s.tag}</div>
                        <div style={{
                          fontFamily: 'var(--display)', fontWeight: 700,
                          fontSize: 20, letterSpacing: '-0.02em', lineHeight: 1.1,
                          color: isActive ? 'var(--ink)' : 'var(--ink-3)',
                          transition: 'color .3s',
                        }}>{s.title}</div>
                      </div>
                      {/* Active indicator: play/pause icon */}
                      <div style={{
                        width: 18, height: 18, flexShrink: 0,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        opacity: isActive ? 1 : 0,
                        transition: 'opacity .2s',
                      }}>
                        {paused ? (
                          <svg width="14" height="14" viewBox="0 0 14 14" fill={s.color}>
                            <path d="M3 2 L11 7 L3 12 Z"/>
                          </svg>
                        ) : (
                          <svg width="14" height="14" viewBox="0 0 14 14" fill={s.color}>
                            <rect x="3" y="2" width="3" height="10"/>
                            <rect x="8" y="2" width="3" height="10"/>
                          </svg>
                        )}
                      </div>
                    </div>

                    {/* Progress bar at bottom of active */}
                    {isActive && hasIntersected && (
                      <div style={{ marginTop: 14, height: 2, borderRadius: 1, background: 'rgba(255,255,255,0.06)', overflow: 'hidden' }}>
                        <div style={{
                          height: '100%', borderRadius: 1, background: s.color,
                          animation: 'hmwProgress 9.6s linear',
                          animationPlayState: paused ? 'paused' : 'running',
                        }}/>
                      </div>
                    )}
                  </button>
                );
              })}
            </div>

            {/* Right: detail panel */}
            <div className="glass-strong" key={activeStep} style={{
              padding: '40px 44px',
              border: `1px solid ${current.color}28`,
              background: `linear-gradient(160deg, ${current.color}0d, rgba(255,255,255,0.02))`,
              position: 'relative', overflow: 'hidden',
              animation: 'hmwFadeIn .3s ease',
            }}>
              {/* Glow */}
              <div aria-hidden style={{
                position: 'absolute', top: -80, right: -80, width: 280, height: 280, borderRadius: '50%',
                background: `radial-gradient(circle, ${current.color}22, transparent 70%)`,
                filter: 'blur(40px)', pointerEvents: 'none',
              }}/>

              {/* Step badge */}
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '6px 14px', borderRadius: 999, marginBottom: 28,
                background: `linear-gradient(135deg, ${current.color}28, ${current.color}10)`,
                border: `1px solid ${current.color}44`,
              }}>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.16em', color: current.color, textTransform: 'uppercase' }}>
                  Шаг {current.n}
                </span>
                <span style={{ width: 4, height: 4, borderRadius: '50%', background: current.color }}/>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.12em', color: current.color, textTransform: 'uppercase' }}>
                  {current.tag}
                </span>
              </div>

              <p style={{ margin: '0 0 32px', fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.65 }}>
                <span className="hmw-body-desktop">{current.body}</span>
                <span className="hmw-body-mobile">{current.bodyMobile || current.body}</span>
              </p>

              {/* Detail items */}
              <div className="hmw-items" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {current.items.map((item, i) => (
                  <div key={i} className="hmw-item" style={{
                    display: 'flex', gap: 12, alignItems: 'center',
                    padding: '10px 16px', borderRadius: 10,
                    background: 'rgba(255,255,255,0.03)',
                    border: '1px solid rgba(255,255,255,0.06)',
                    opacity: 0, animation: `hmwItemIn .35s ease ${0.05 + i * 0.07}s forwards`,
                  }}>
                    <span style={{
                      width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
                      background: current.color, boxShadow: `0 0 8px ${current.color}`,
                    }}/>
                    <span style={{ fontSize: 14, color: 'var(--ink-2)' }}>{item}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </Reveal>
      </div>

      <style>{`
        @keyframes hmwProgress {
          from { width: 0%; }
          to   { width: 100%; }
        }
        @keyframes hmwFadeIn {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: none; }
        }
        @keyframes hmwItemIn {
          from { opacity: 0; transform: translateX(-6px); }
          to   { opacity: 1; transform: none; }
        }
        .hmw-body-mobile { display: none; }
        .hmw-body-desktop { display: inline; }
        @media (max-width: 880px) {
          .hmw-grid { grid-template-columns: 1fr !important; }
          .hmw-header { grid-template-columns: 1fr !important; gap: 20px !important; }
          .hmw-grid .glass-strong { padding: 28px 24px !important; }
          .hmw-item { min-height: 64px !important; }
          .hmw-body-mobile { display: inline; }
          .hmw-body-desktop { display: none; }
        }
      `}</style>
    </section>
  );
}
window.HowMinicornWorks = HowMinicornWorks;
