function BlackBox() {
  const [visible, setVisible] = React.useState(false);
  const trackRef = React.useRef(null);

  React.useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight) { setVisible(true); return; }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVisible(true); io.disconnect(); }
    }, { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const withoutEvents = [
    { pos: 10, month: 'Январь', note: 'Визит к врачу' },
    { pos: 48, month: 'Апрель', note: 'Анализы' },
    { pos: 86, month: 'Август', note: 'Снова визит' },
  ];

  const withTimes = [
    '08:14','10:20','13:45','16:00','18:30','20:45','23:05',
  ];

  // ECG pulse path tiled across 800px viewBox
  const beatW = 100;
  const beats = 8;
  let pulsePath = 'M0,16';
  for (let b = 0; b < beats; b++) {
    const x = b * beatW;
    pulsePath += ` L${x + 30},16 L${x + 38},16 L${x + 44},3 L${x + 52},30 L${x + 58},16 L${x + beatW},16`;
  }

  return (
    <section id="blackbox" className="pad-y-lg" style={{ position: 'relative' }}>
      <div className="wrap">

        {/* ── Header ── */}
        <Reveal>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
            <span className="eyebrow">[ ✦ ]</span>
            <span style={{ height: 1, width: 32, background: 'var(--line-2)', flexShrink: 0 }}/>
            <span className="eyebrow" style={{ color: 'var(--ink-3)' }}>Чёрный ящик</span>
          </div>
          <h2 className="display" style={{ fontSize: 'clamp(40px, 6vw, 80px)', margin: '0 0 20px', maxWidth: '18ch' }}>
            Один приём в месяц или<br/>
            <span style={{
              background: 'linear-gradient(120deg, #ffffff 20%, var(--violet) 55%, var(--pink) 100%)',
              WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
            }}>30 дней данных?</span>
          </h2>
          <p className="lede" style={{ marginBottom: 64 }}>
            Здоровье случается не на консультации раз в квартал. Его время в 8:00 за завтраком, в 14:00 на переговорах, в 23:00 при бессоннице. Каждый день.
          </p>
        </Reveal>

        {/* ── Timeline visualization ── */}
        <Reveal>
          <div ref={trackRef} className="glass" style={{
            padding: '36px 40px 40px', marginBottom: 14, overflow: 'hidden', position: 'relative',
          }}>
            {/* Subtle glow bg */}
            <div aria-hidden style={{
              position: 'absolute', top: -60, right: -60, width: 320, height: 320, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(167,139,250,0.12), transparent 70%)',
              filter: 'blur(40px)', pointerEvents: 'none',
            }}/>

            {/* WITHOUT row */}
            <div style={{ marginBottom: 44 }}>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em',
                color: 'var(--ink-3)', textTransform: 'uppercase', marginBottom: 18,
              }}>
                Без миникорна — редкие снимки
              </div>
              <div style={{ position: 'relative', height: 52 }}>
                {/* Dashed baseline */}
                <div style={{
                  position: 'absolute', top: 10, left: 0, right: 0, height: 1,
                  backgroundImage: 'repeating-linear-gradient(90deg, rgba(255,255,255,0.1) 0, rgba(255,255,255,0.1) 5px, transparent 5px, transparent 16px)',
                }}/>
                {withoutEvents.map((ev, i) => (
                  <div key={i} style={{ position: 'absolute', left: `${ev.pos}%`, top: 0, transform: 'translateX(-50%)' }}>
                    <div style={{
                      width: 20, height: 20, borderRadius: '50%',
                      background: 'var(--bg-1)',
                      border: '1.5px solid rgba(255,255,255,0.45)',
                      margin: '0 auto',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'rgba(255,255,255,0.55)' }}/>
                    </div>
                    <div style={{ textAlign: 'center', marginTop: 8, whiteSpace: 'nowrap' }}>
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-3)', letterSpacing: '0.08em' }}>{ev.month}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-2)' }}>{ev.note}</div>
                    </div>
                  </div>
                ))}
                {/* Gap labels */}
                {[
                  { left: '29%', text: '← 3 мес. →' },
                  { left: '67%', text: '← 4 мес. →' },
                ].map((g, i) => (
                  <div key={i} style={{
                    position: 'absolute', left: g.left, top: 14, transform: 'translateX(-50%)',
                    fontFamily: 'var(--mono)', fontSize: 9, color: 'rgba(255,255,255,0.12)',
                    letterSpacing: '0.06em', whiteSpace: 'nowrap', pointerEvents: 'none',
                  }}>{g.text}</div>
                ))}
              </div>
            </div>

            {/* Divider */}
            <div style={{ borderTop: '1px solid var(--line)', marginBottom: 36 }}/>

            {/* WITH row */}
            <div>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em',
                color: 'var(--violet)', textTransform: 'uppercase', marginBottom: 18,
              }}>
                С миникорном — непрерывно
              </div>
              <div style={{ position: 'relative', height: 52 }}>
                {/* Animated ECG */}
                <svg
                  viewBox="0 0 800 32"
                  preserveAspectRatio="none"
                  style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: 28, overflow: 'visible' }}
                >
                  <defs>
                    <linearGradient id="bbPulseGrad" x1="0%" y1="0%" x2="100%" y2="0%">
                      <stop offset="0%"   stopColor="var(--violet)" stopOpacity="0.3"/>
                      <stop offset="35%"  stopColor="var(--violet)" stopOpacity="1"/>
                      <stop offset="65%"  stopColor="var(--pink)"   stopOpacity="0.9"/>
                      <stop offset="100%" stopColor="var(--pink)"   stopOpacity="0.3"/>
                    </linearGradient>
                    {/* Glow filter */}
                    <filter id="bbGlow">
                      <feGaussianBlur stdDeviation="2" result="blur"/>
                      <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
                    </filter>
                  </defs>
                  {/* Faint area fill */}
                  <path
                    d={pulsePath + ' L800,32 L0,32 Z'}
                    fill="url(#bbPulseGrad)"
                    fillOpacity="0.06"
                  />
                  {/* Main pulse line */}
                  <path
                    d={pulsePath}
                    stroke="url(#bbPulseGrad)"
                    strokeWidth="1.8"
                    fill="none"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    filter="url(#bbGlow)"
                    style={{
                      strokeDasharray: 4000,
                      strokeDashoffset: visible ? 0 : 4000,
                      transition: 'stroke-dashoffset 2.8s cubic-bezier(.4,0,.2,1)',
                    }}
                  />
                </svg>

                {/* Time labels */}
                {withTimes.map((t, i) => (
                  <div key={i} style={{
                    position: 'absolute',
                    left: `${4 + i * (92 / (withTimes.length - 1))}%`,
                    top: 32,
                    transform: 'translateX(-50%)',
                    fontFamily: 'var(--mono)', fontSize: 9,
                    color: i === 0 ? 'var(--violet)' : i === withTimes.length - 1 ? 'var(--pink)' : 'var(--ink-3)',
                    letterSpacing: '0.04em', whiteSpace: 'nowrap',
                    opacity: visible ? 1 : 0,
                    transition: `opacity .4s ease ${0.6 + i * 0.12}s`,
                  }}>{t}</div>
                ))}
              </div>
            </div>
          </div>
        </Reveal>

        {/* ── Contrast cards ── */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="bb-cards">

          {/* WITHOUT card */}
          <Reveal>
            <div className="glass" style={{
              padding: 32, height: '100%', display: 'flex', flexDirection: 'column',
              border: '1px solid rgba(251,113,133,0.32)',
              background: 'linear-gradient(160deg, rgba(251,113,133,0.10), rgba(251,113,133,0.02))',
              position: 'relative', overflow: 'hidden',
            }}>
              <div aria-hidden style={{
                position: 'absolute', bottom: -60, left: -60, width: 220, height: 220, borderRadius: '50%',
                background: 'radial-gradient(circle, rgba(251,113,133,0.22), transparent 70%)',
                filter: 'blur(40px)', pointerEvents: 'none',
              }}/>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.18em',
                color: 'var(--rose)', textTransform: 'uppercase', fontWeight: 700,
                marginBottom: 24, position: 'relative',
              }}>Без миникорна</div>

              {/* Chat bubbles */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
                <div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-4)', letterSpacing: '0.08em', marginBottom: 6 }}>СПЕЦИАЛИСТ</div>
                  <div style={{
                    background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)',
                    borderRadius: '14px 14px 14px 4px', padding: '11px 15px',
                    fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55,
                  }}>
                    Как вы питались последние три месяца?
                  </div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <div style={{ maxWidth: '82%' }}>
                    <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-4)', letterSpacing: '0.08em', marginBottom: 6, textAlign: 'right' }}>ВЫ</div>
                    <div style={{
                      background: 'rgba(255,255,255,0.06)', border: '1px solid var(--line-2)',
                      borderRadius: '14px 14px 4px 14px', padding: '11px 15px',
                      fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55,
                    }}>
                      Как обычно — каша на завтрак, сэндвичи на работе, гарнир и мясо на ужин.
                    </div>
                  </div>
                </div>
                {/* Outcome */}
                <div style={{
                  padding: '10px 14px', borderRadius: 10,
                  background: 'rgba(251,113,133,0.08)', border: '1px solid rgba(251,113,133,0.32)',
                  fontSize: 13, color: 'var(--rose)', lineHeight: 1.55, fontStyle: 'italic',
                  marginTop: 'auto',
                }}>
                  Между визитами — чёрный ящик.<br/>Рекомендации будут составлены по однотипным ответам.
                </div>
              </div>
            </div>
          </Reveal>

          {/* WITH card */}
          <Reveal delay={80}>
            <div className="glass-strong" style={{
              padding: 32, height: '100%', display: 'flex', flexDirection: 'column',
              border: '1px solid rgba(52,211,153,0.38)',
              background: 'linear-gradient(160deg, rgba(52,211,153,0.12), rgba(167,139,250,0.05))',
              position: 'relative', overflow: 'hidden',
              boxShadow: '0 20px 60px -20px rgba(52,211,153,0.25)',
            }}>
              <div aria-hidden style={{
                position: 'absolute', bottom: -60, right: -60, width: 220, height: 220, borderRadius: '50%',
                background: 'radial-gradient(circle, rgba(52,211,153,0.30), transparent 70%)',
                filter: 'blur(40px)', pointerEvents: 'none',
              }}/>
              <div aria-hidden style={{
                position: 'absolute', top: -40, left: -40, width: 180, height: 180, borderRadius: '50%',
                background: 'radial-gradient(circle, rgba(167,139,250,0.18), transparent 70%)',
                filter: 'blur(30px)', pointerEvents: 'none',
              }}/>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.18em',
                color: 'var(--green)', textTransform: 'uppercase', fontWeight: 700,
                marginBottom: 24, position: 'relative',
              }}>С миникорном</div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
                {[
                  { dot: 'var(--violet)', label: '90 дней непрерывных данных',  tag: '2 184 записи' },
                  { dot: 'var(--rose)',   label: 'Хронический дефицит B6',       tag: '31 день подряд' },
                  { dot: 'var(--green)',  label: 'Омега-3 в норме с ноября',     tag: 'после корректировки' },
                  { dot: 'var(--amber)',  label: 'Отчёт для специалиста',         tag: '1 нажатие' },
                ].map((row, i) => (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '10px 14px', borderRadius: 10,
                    background: 'rgba(255,255,255,0.03)', border: '1px solid var(--line)',
                  }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: '50%',
                      background: row.dot, flexShrink: 0,
                      boxShadow: `0 0 7px ${row.dot}`,
                    }}/>
                    <span style={{ flex: 1, fontSize: 14, color: 'var(--ink-2)' }}>{row.label}</span>
                    <span style={{
                      fontFamily: 'var(--mono)', fontSize: 9,
                      color: row.dot, letterSpacing: '0.06em', whiteSpace: 'nowrap',
                    }}>{row.tag}</span>
                  </div>
                ))}
                {/* Outcome */}
                <div style={{
                  padding: '10px 14px', borderRadius: 10,
                  background: 'rgba(52,211,153,0.10)', border: '1px solid rgba(52,211,153,0.35)',
                  fontSize: 13, color: 'var(--green)', lineHeight: 1.55, fontStyle: 'italic',
                  marginTop: 'auto',
                }}>
                  Специалист видит факты, не рассказ.<br/>Миникорн не заменяет врача — он даёт обоим фундамент из данных.
                </div>
              </div>
            </div>
          </Reveal>
        </div>

      </div>
      <style>{`
        @media (max-width: 720px) {
          .bb-cards { grid-template-columns: 1fr !important; }
          .bb-timeline { padding: 24px 20px 28px !important; }
          .bb-gap-label { display: none !important; }
        }
      `}</style>
    </section>
  );
}
window.BlackBox = BlackBox;
