// process-wave.jsx — horizontal SVG wave timeline with 4 nodes; cards in a
// row below the wave, each connected by a vertical guide. Wave path animates
// drawn-in as the user scrolls through the section.

function ProcessWave() {
  const wrapRef = React.useRef(null);
  const pathRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const [pathLen, setPathLen] = React.useState(0);
  const m = useIsMobile();

  React.useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    let raf = 0;
    const update = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || 800;
      const start = vh * 0.85;
      const end = vh * 0.15;
      const p = (start - r.top) / (start - end);
      setProgress(Math.max(0, Math.min(1, p)));
    };
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(update);
    };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);

  React.useLayoutEffect(() => {
    if (pathRef.current) setPathLen(pathRef.current.getTotalLength());
  }, []);

  // Geometry. viewBox 0 0 1280 200. Path is a flowing wave with 4 stable
  // node positions at y=100.
  const PATH_D = 'M 80 100 C 220 20, 360 20, 480 100 S 720 180, 840 100 S 1080 20, 1200 100';
  const NODES = [
    { num: '01', x: 80,   tag: 'предоплата 50%', title: 'Знакомство · бриф',
      copy: 'Созвон. Разбираем нишу, продукт и текущую точку. Подписываем NDA, фиксируем метрики результата.' },
    { num: '02', x: 480,  tag: '7–10 дней', title: 'Стратегия · контент-план',
      copy: 'Стратегия, позиционирование, рубрикатор, визуальный язык и медиаплан. Утверждаем и идём в производство.' },
    { num: '03', x: 840,  tag: 'старт месяца', title: 'Производство',
      copy: 'Съёмка, монтаж, дизайн, копирайт, таргет — внутри команды. Контент сериями, реклама на тёплый поток.' },
    { num: '04', x: 1200, tag: 'разбор', title: 'Отчёт · итоги',
      copy: 'Отчёт по выручке, заявкам и метрикам, не по охватам. Решаем, что усиливаем в следующем цикле.' },
  ];

  return (
    <div ref={wrapRef} style={{ position: 'relative', width: '100%' }}>
      {m ?
      /* ===== Mobile: vertical timeline ================================= */
      <div style={{ position: 'relative', paddingLeft: 8 }}>
        <div style={{ position: 'absolute', left: 24, top: 12, bottom: 12, width: 2, background: 'rgba(244,241,236,0.1)' }} />
        <div style={{
          position: 'absolute', left: 24, top: 12, width: 2,
          height: `${progress * 100}%`,
          background: 'linear-gradient(180deg, #5b8bff, #8aa9ff)',
          boxShadow: '0 0 8px rgba(91,139,255,0.6)',
          transition: 'height .2s linear'
        }} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {NODES.map((n, i) => {
            const activeAt = i / (NODES.length - 1);
            const active = progress >= activeAt - 0.12;
            return (
              <div key={n.num} style={{ position: 'relative', paddingLeft: 56, transition: 'opacity .5s', opacity: active ? 1 : 0.45 }}>
                <span style={{
                  position: 'absolute', left: 13, top: 18,
                  width: 24, height: 24, borderRadius: '50%',
                  background: '#0c0e12',
                  border: `2px solid ${active ? '#5b8bff' : 'rgba(244,241,236,0.3)'}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'border-color .4s'
                }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: active ? '#5b8bff' : 'rgba(244,241,236,0.45)', transition: 'background .4s' }} />
                </span>
                <div style={{
                  padding: '18px 18px 20px',
                  background: 'rgba(16,19,25,0.82)',
                  border: `1px solid ${active ? 'rgba(91,139,255,0.4)' : 'rgba(244,241,236,0.1)'}`,
                  borderRadius: 16,
                  transition: 'border-color .4s'
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                    <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: active ? '#5b8bff' : 'var(--muted)', letterSpacing: '0.06em' }}>{n.num}</span>
                    <span style={{ fontSize: 10, padding: '4px 10px', borderRadius: 999, background: active ? 'rgba(91,139,255,0.15)' : 'rgba(244,241,236,0.06)', color: active ? '#a8bfff' : 'var(--muted)', letterSpacing: '0.05em', textTransform: 'uppercase', fontWeight: 500 }}>{n.tag}</span>
                  </div>
                  <h4 style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 10, color: 'var(--fg)' }}>{n.title}</h4>
                  <p style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>{n.copy}</p>
                </div>
              </div>);
          })}
        </div>
      </div>
      :
      <>
      {/* ===== Wave (svg) =================================================== */}
      <div style={{ width: '100%', position: 'relative' }}>
        <svg
          viewBox="0 0 1280 200"
          width="100%"
          preserveAspectRatio="none"
          style={{ display: 'block', height: 220, overflow: 'visible' }}
        >
          {/* baseline */}
          <line x1="0" y1="100" x2="1280" y2="100"
            stroke="rgba(244,241,236,0.06)" strokeDasharray="2 8" />

          {/* dim wave */}
          <path d={PATH_D}
            stroke="rgba(244,241,236,0.16)" strokeWidth="2"
            fill="none" strokeLinecap="round" />

          {/* accent wave (drawn-in) */}
          <path ref={pathRef} d={PATH_D}
            stroke="url(#wave-grad)" strokeWidth="3"
            fill="none" strokeLinecap="round"
            style={{
              strokeDasharray: pathLen,
              strokeDashoffset: pathLen * (1 - progress),
              transition: 'stroke-dashoffset .2s linear',
              filter: 'drop-shadow(0 0 8px rgba(91,139,255,0.6))',
            }} />

          <defs>
            <linearGradient id="wave-grad" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%"   stopColor="#5b8bff" stopOpacity="0.4" />
              <stop offset="50%"  stopColor="#5b8bff" stopOpacity="1" />
              <stop offset="100%" stopColor="#8aa9ff" stopOpacity="1" />
            </linearGradient>
          </defs>

          {/* Nodes */}
          {NODES.map((n, i) => {
            const activeAt = i / (NODES.length - 1);
            const active = progress >= activeAt - 0.05;
            return (
              <g key={n.num}>
                <circle cx={n.x} cy="100" r={active ? 26 : 16}
                  fill={active ? 'rgba(91,139,255,0.18)' : 'rgba(244,241,236,0.04)'}
                  style={{ transition: 'r .4s cubic-bezier(.2,.7,.2,1), fill .4s' }} />
                <circle cx={n.x} cy="100" r="14"
                  fill="#0c0e12"
                  stroke={active ? '#5b8bff' : 'rgba(244,241,236,0.3)'}
                  strokeWidth="2"
                  style={{ transition: 'stroke .4s' }} />
                <circle cx={n.x} cy="100" r="5"
                  fill={active ? '#5b8bff' : 'rgba(244,241,236,0.45)'}
                  style={{ transition: 'fill .4s' }} />
                <text x={n.x} y="135"
                  textAnchor="middle"
                  fill={active ? '#5b8bff' : 'rgba(244,241,236,0.4)'}
                  style={{
                    fontFamily: 'JetBrains Mono, monospace',
                    fontSize: 11, letterSpacing: '0.06em',
                    transition: 'fill .4s',
                  }}>{n.num}</text>
              </g>
            );
          })}
        </svg>
      </div>

      {/* ===== Card row (below wave) ======================================== */}
      <div style={{
        marginTop: 40,
        display: 'grid',
        gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 20,
        position: 'relative',
      }}>
        {NODES.map((n, i) => {
          const activeAt = i / (NODES.length - 1);
          const active = progress >= activeAt - 0.05;
          return (
            <div
              key={n.num}
              style={{
                position: 'relative',
                transition: 'opacity .5s, transform .5s cubic-bezier(.2,.7,.2,1)',
                opacity: active ? 1 : 0.4,
                transform: active ? 'none' : 'translateY(12px)',
              }}
            >
              {/* Top connector */}
              <div style={{
                position: 'absolute',
                left: '50%', top: -40, width: 1, height: 32,
                background: active
                  ? 'linear-gradient(180deg, rgba(91,139,255,0.7), rgba(91,139,255,0.15))'
                  : 'rgba(244,241,236,0.12)',
                transition: 'background .4s',
              }} />

              <div style={{
                padding: '22px 22px 24px',
                background: 'rgba(16,19,25,0.82)',
                border: `1px solid ${active ? 'rgba(91,139,255,0.4)' : 'rgba(244,241,236,0.1)'}`,
                borderRadius: 18,
                transition: 'border-color .4s, background .4s',
                height: '100%',
              }}>
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  marginBottom: 14,
                }}>
                  <span style={{
                    fontFamily: 'JetBrains Mono, monospace',
                    fontSize: 11,
                    color: active ? '#5b8bff' : 'var(--muted)',
                    letterSpacing: '0.06em',
                    transition: 'color .4s',
                  }}>{n.num}</span>
                  <span style={{
                    fontSize: 10, padding: '4px 10px',
                    borderRadius: 999,
                    background: active ? 'rgba(91,139,255,0.15)' : 'rgba(244,241,236,0.06)',
                    color: active ? '#a8bfff' : 'var(--muted)',
                    letterSpacing: '0.05em',
                    textTransform: 'uppercase',
                    fontWeight: 500,
                    transition: 'background .4s, color .4s',
                  }}>{n.tag}</span>
                </div>
                <h4 style={{
                  fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em',
                  lineHeight: 1.1, marginBottom: 12,
                  color: 'var(--fg)',
                }}>{n.title}</h4>
                <p style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>{n.copy}</p>
              </div>
            </div>
          );
        })}
      </div>
      </>
      }
    </div>
  );
}

window.ProcessWave = ProcessWave;
