// Stable Growth section — visual guarantee: the line trends up through every market condition.
// SVG line that wobbles (simulating turbulence) but always closes higher.
// Plus a side panel of "stability pillars".

function StableGrowth({ t }) {
  const ref = React.useRef(null);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          // animate 0 → 1 over 2.6s
          const start = performance.now();
          const dur = 2600;
          const tick = (now) => {
            const p = Math.min(1, (now - start) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            setProgress(eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.disconnect();
        }
      });
    }, { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Waypoints: x from 0 to 1000 in viewBox, y from 420 (low) to 40 (high)
  // Wobbles include turbulence events (labelled), but trajectory always improves.
  const waypoints = [
    { x: 20,  y: 380, label: null },
    { x: 120, y: 340, label: null },
    { x: 200, y: 360, label: 'Covid' },
    { x: 280, y: 290, label: null },
    { x: 360, y: 310, label: null },
    { x: 440, y: 230, label: null },
    { x: 520, y: 260, label: 'Rate hikes' },
    { x: 600, y: 190, label: null },
    { x: 680, y: 170, label: null },
    { x: 760, y: 200, label: 'AI shift' },
    { x: 840, y: 120, label: null },
    { x: 920, y: 90,  label: null },
    { x: 980, y: 60,  label: 'Now' }
  ];

  // Build smooth bezier path
  const path = React.useMemo(() => {
    let d = `M ${waypoints[0].x} ${waypoints[0].y}`;
    for (let i = 1; i < waypoints.length; i++) {
      const p0 = waypoints[i - 1];
      const p1 = waypoints[i];
      const cx1 = p0.x + (p1.x - p0.x) * 0.5;
      const cx2 = p0.x + (p1.x - p0.x) * 0.5;
      d += ` C ${cx1} ${p0.y}, ${cx2} ${p1.y}, ${p1.x} ${p1.y}`;
    }
    return d;
  }, []);

  // Compute how much of the path to reveal
  const pathRef = React.useRef(null);
  const [len, setLen] = React.useState(0);
  React.useEffect(() => {
    if (pathRef.current) setLen(pathRef.current.getTotalLength());
  }, []);

  // Visible waypoint labels based on progress
  const visibleLabels = waypoints.filter((w, i) => w.label && (w.x / 1000) <= progress + 0.02);

  return (
    <section ref={ref} className="growth" data-screen-label="06 Stable Growth">
      <div className="growth-head">
        <span className="kicker kicker-light">{t.growth.kicker}</span>
        <AutoFitHeadline className="growth-title" maxLines={3}>
          <SplitReveal text={t.growth.title} />
        </AutoFitHeadline>
        <p className="growth-sub">{t.growth.sub}</p>
      </div>

      <div className="growth-grid">
        <div className="growth-chart-wrap">
          <svg viewBox="0 0 1000 460" className="growth-chart" preserveAspectRatio="none">
            <defs>
              <linearGradient id="growth-area" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="#E8192C" stopOpacity="0.35" />
                <stop offset="100%" stopColor="#E8192C" stopOpacity="0" />
              </linearGradient>
              <linearGradient id="growth-line" x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor="#B30E1F" />
                <stop offset="100%" stopColor="#FF3344" />
              </linearGradient>
              <filter id="growth-glow">
                <feGaussianBlur stdDeviation="4" />
              </filter>
            </defs>

            {/* Grid */}
            <g stroke="rgba(245,243,238,0.08)" strokeDasharray="2 6">
              {[1, 2, 3, 4].map(i => (
                <line key={i} x1="0" y1={i * 92} x2="1000" y2={i * 92} />
              ))}
            </g>

            {/* Axis labels */}
            <g fill="rgba(245,243,238,0.4)" fontFamily="JetBrains Mono, monospace" fontSize="11">
              <text x="10" y="450">2014</text>
              <text x="490" y="450">2020</text>
              <text x="955" y="450">Now</text>
            </g>

            {/* Filled area under path */}
            <path
              d={`${path} L 980 460 L 20 460 Z`}
              fill="url(#growth-area)"
              style={{
                clipPath: `inset(0 ${(1 - progress) * 100}% 0 0)`,
                transition: 'clip-path 0.1s linear'
              }}
            />

            {/* Glow under the line */}
            <path
              ref={pathRef}
              d={path}
              fill="none"
              stroke="url(#growth-line)"
              strokeWidth="6"
              strokeLinecap="round"
              filter="url(#growth-glow)"
              opacity="0.6"
              strokeDasharray={len}
              strokeDashoffset={len * (1 - progress)}
            />
            {/* Main line */}
            <path
              d={path}
              fill="none"
              stroke="url(#growth-line)"
              strokeWidth="3.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeDasharray={len}
              strokeDashoffset={len * (1 - progress)}
            />

            {/* Turbulence markers */}
            {waypoints.filter(w => w.label).map((w, i) => {
              const show = (w.x / 1000) <= progress + 0.02;
              return (
                <g key={i} style={{ opacity: show ? 1 : 0, transition: 'opacity 0.4s' }}>
                  <circle cx={w.x} cy={w.y} r="4" fill="#F5F3EE" />
                  <circle cx={w.x} cy={w.y} r="8" fill="none" stroke="#F5F3EE" strokeOpacity="0.3" />
                  <line x1={w.x} y1={w.y + 10} x2={w.x} y2={w.y + 28} stroke="rgba(245,243,238,0.4)" strokeDasharray="2 3" />
                  <text
                    x={w.x}
                    y={w.y + 44}
                    fill="rgba(245,243,238,0.7)"
                    fontFamily="JetBrains Mono, monospace"
                    fontSize="11"
                    textAnchor="middle"
                  >{w.label}</text>
                </g>
              );
            })}

            {/* Head dot */}
            {progress > 0.02 && (() => {
              const i = Math.max(0, Math.min(waypoints.length - 1, Math.floor(progress * (waypoints.length - 1))));
              const a = waypoints[i];
              const b = waypoints[Math.min(waypoints.length - 1, i + 1)];
              const localP = (progress * (waypoints.length - 1)) - i;
              const hx = a.x + (b.x - a.x) * localP;
              const hy = a.y + (b.y - a.y) * localP;
              return (
                <g>
                  <circle cx={hx} cy={hy} r="12" fill="#E8192C" opacity="0.3" />
                  <circle cx={hx} cy={hy} r="6" fill="#FF3344" />
                  <circle cx={hx} cy={hy} r="2" fill="#F5F3EE" />
                </g>
              );
            })()}
          </svg>

          <div className="growth-legend">
            <div className="growth-legend-item">
              <span className="growth-legend-dot" /> {t.growth.legend_line}
            </div>
            <div className="growth-legend-item">
              <span className="growth-legend-circle" /> {t.growth.legend_shock}
            </div>
          </div>
        </div>

        <div className="growth-pillars">
          {t.growth.pillars.map((p, i) => (
            <div key={i} className="growth-pillar" style={{ transitionDelay: `${i * 80}ms` }}>
              <div className="growth-pillar-n">0{i + 1}</div>
              <div className="growth-pillar-k">{p.k}</div>
              <div className="growth-pillar-v">{p.v}</div>
            </div>
          ))}
          <div className="growth-promise">
            <span className="growth-promise-arrow">↗</span>
            <span>{t.growth.promise}</span>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { StableGrowth });
