// hero.jsx — polished Gap chart + inflection moment ("team starts Workroom")
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

// ---------------- The Gap ----------------
// Output per team member over the last 12 months.
// Two lines: "AI-native" pulls away fast. "Everyone else" is nearly flat.
// At month 5, a marker lands on the AI-native line labelled
// "Team starts with Workroom" — showing the inflection.

const GAP_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// Output velocity index, 12 points each
// LEADERS is truly flat pre-inflection, then dramatic hockey-stick after
const LEADERS  = [1.00, 1.00, 1.02, 1.01, 1.03, 1.05, 1.60, 2.60, 3.80, 5.00, 6.20, 7.50];
const LAGGARDS = [1.00, 1.01, 1.02, 1.02, 1.03, 1.04, 1.04, 1.05, 1.06, 1.05, 1.07, 1.09];

// The inflection index — where "Team starts with Workroom" fires
const INFLECTION = 5; // after Jun

function TheGap() {
  const [t, setT] = useStateH(0);

  useEffectH(() => {
    let raf;
    const dur = 6500;   // draw-in
    const hold = 2500;  // hold at full
    const cycle = dur + hold;
    const start = performance.now();
    const loop = (now) => {
      const elapsed = (now - start) % cycle;
      const p = elapsed < dur ? elapsed / dur : 1;
      // easeOutCubic
      const eased = 1 - Math.pow(1 - p, 2.4);
      setT(eased * 11);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Chart geometry
  const W = 620, H = 360;
  const padL = 52, padR = 28, padT = 28, padB = 56;
  const plotW = W - padL - padR;
  const plotH = H - padT - padB;
  const maxY = 7.8;

  const xAt = (i) => padL + (i / 11) * plotW;
  const yAt = (v) => padT + plotH - ((v - 1) / (maxY - 1)) * plotH;

  const buildPath = (series) => {
    const iMax = Math.min(11, Math.floor(t));
    const frac = t - iMax;
    const pts = [];
    for (let i = 0; i <= iMax; i++) pts.push([xAt(i), yAt(series[i])]);
    if (iMax < 11 && frac > 0) {
      const xi = xAt(iMax) + (xAt(iMax + 1) - xAt(iMax)) * frac;
      const yi = yAt(series[iMax]) + (yAt(series[iMax + 1]) - yAt(series[iMax])) * frac;
      pts.push([xi, yi]);
    }
    if (!pts.length) return "";
    if (pts.length < 2) return `M ${pts[0][0]} ${pts[0][1]}`;
    // Catmull-Rom -> Bezier for a single clean curve (less wobble)
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = pts[i - 1] || pts[i];
      const p1 = pts[i];
      const p2 = pts[i + 1];
      const p3 = pts[i + 2] || p2;
      const smooth = 0.18; // lower = less wobble
      const c1x = p1[0] + (p2[0] - p0[0]) * smooth;
      const c1y = p1[1] + (p2[1] - p0[1]) * smooth;
      const c2x = p2[0] - (p3[0] - p1[0]) * smooth;
      const c2y = p2[1] - (p3[1] - p1[1]) * smooth;
      d += ` C ${c1x} ${c1y}, ${c2x} ${c2y}, ${p2[0]} ${p2[1]}`;
    }
    return d;
  };

  const leaderPath  = buildPath(LEADERS);
  const laggardPath = buildPath(LAGGARDS);

  // Current marker positions
  const iNow = Math.min(11, Math.floor(t));
  const frac = t - iNow;
  const interp = (a) => {
    if (iNow >= 11) return a[11];
    return a[iNow] + (a[iNow + 1] - a[iNow]) * frac;
  };
  const leaderNow  = Number.isFinite(interp(LEADERS))  ? interp(LEADERS)  : LEADERS[0];
  const laggardNow = Number.isFinite(interp(LAGGARDS)) ? interp(LAGGARDS) : LAGGARDS[0];
  const markerX    = xAt(iNow) + (iNow < 11 ? (xAt(iNow + 1) - xAt(iNow)) * frac : 0);

  // Area under leaders, above laggards (the gap)
  const gapArea = (() => {
    const iMax = Math.min(11, Math.floor(t));
    const pts = [];
    for (let i = 0; i <= iMax; i++) pts.push([xAt(i), yAt(LEADERS[i])]);
    if (iMax < 11 && frac > 0) pts.push([markerX, yAt(leaderNow)]);
    const rev = [];
    for (let i = 0; i <= iMax; i++) rev.push([xAt(i), yAt(LAGGARDS[i])]);
    if (iMax < 11 && frac > 0) rev.push([markerX, yAt(laggardNow)]);
    rev.reverse();
    const all = [...pts, ...rev];
    if (!all.length) return "";
    let d = `M ${all[0][0]} ${all[0][1]}`;
    for (let i = 1; i < all.length; i++) d += ` L ${all[i][0]} ${all[i][1]}`;
    return d + " Z";
  })();

  const pastInflection = t >= INFLECTION;
  const leaderLabelY = yAt(leaderNow);
  const laggardLabelY = yAt(laggardNow);

  // Inflection flag position
  const flagX = xAt(INFLECTION);
  const flagY = yAt(LEADERS[INFLECTION]);
  const showFlag = t >= INFLECTION - 0.3;

  // Final multiplier callout — only at end when curve is nearly done
  const showMultiplier = t >= 10.8;
  const finalMult = LEADERS[11] / LAGGARDS[11];

  return (
    <div className="hv hv-gap">
      <div className="hv-head">
        <div className="hv-head-l">
          <span className="hv-dot"/>
          <span className="hv-title">Output per team member · 12 months</span>
        </div>
        <div className="hv-gap-legend">
          <span className="is-lead"><i/>AI-native</span>
          <span className="is-lag"><i/>Everyone else</span>
        </div>
      </div>

      <div className="hv-stage gap-stage">
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" className="gap-svg">
          <defs>
            <linearGradient id="leaderGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="var(--accent)" stopOpacity="0.24"/>
              <stop offset="1" stopColor="var(--accent)" stopOpacity="0"/>
            </linearGradient>
            <linearGradient id="leaderLine" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0" stopColor="var(--accent)" stopOpacity="0.55"/>
              <stop offset="0.5" stopColor="var(--accent)" stopOpacity="0.95"/>
              <stop offset="1" stopColor="var(--accent)" stopOpacity="1"/>
            </linearGradient>
            <filter id="leaderGlow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="3" result="blur"/>
              <feMerge>
                <feMergeNode in="blur"/>
                <feMergeNode in="SourceGraphic"/>
              </feMerge>
            </filter>
          </defs>

          {/* grid */}
          {[1, 2, 3, 4, 5, 6, 7].map(v => (
            <line key={v}
              x1={padL} x2={W - padR}
              y1={yAt(v)} y2={yAt(v)}
              stroke="var(--ink-whisper)" strokeWidth="0.5"
              strokeDasharray={v === 1 ? "0" : "2 4"}
            />
          ))}
          {/* Y labels */}
          {[1, 3, 5, 7].map(v => (
            <text key={v}
              x={padL - 10} y={yAt(v) + 4}
              fill="var(--ink-faint)" fontSize="10"
              fontFamily="var(--f-mono)" textAnchor="end"
              style={{letterSpacing: "0.06em"}}
            >{v}×</text>
          ))}
          {/* X labels */}
          {GAP_MONTHS.map((m, i) => (
            (i % 2 === 0 || i === 11) && (
              <text key={m}
                x={xAt(i)} y={H - padB + 20}
                fill="var(--ink-faint)" fontSize="10"
                fontFamily="var(--f-mono)" textAnchor="middle"
                style={{letterSpacing: "0.1em"}}
              >{m.toUpperCase()}</text>
            )
          ))}

          {/* Gap fill */}
          <path d={gapArea} fill="url(#leaderGrad)"/>

          {/* Laggard line (white-ish) */}
          <path d={laggardPath}
            stroke="var(--ink)" strokeWidth="2.4" strokeOpacity="0.65"
            fill="none" strokeLinecap="round" strokeLinejoin="round"
          />
          {/* Leader line + glow */}
          <path d={leaderPath}
            stroke="url(#leaderLine)" strokeWidth="2.8"
            fill="none" strokeLinecap="round" strokeLinejoin="round"
            filter="url(#leaderGlow)"
          />

          {/* Marker dots */}
          <circle cx={markerX} cy={yAt(laggardNow)} r="4.5"
            fill="var(--ground)" stroke="var(--ink)" strokeOpacity="0.7" strokeWidth="1.8"/>
          <circle cx={markerX} cy={yAt(leaderNow)} r="6"
            fill="var(--accent)" stroke="var(--ground)" strokeWidth="2.4"/>
          <circle cx={markerX} cy={yAt(leaderNow)} r="12"
            fill="none" stroke="var(--accent)" strokeOpacity="0.35" strokeWidth="1"
            style={{
              animation: "gapPing 1.4s var(--ease-out) infinite",
              transformOrigin: `${markerX}px ${yAt(leaderNow)}px`,
            }}
          />

          {/* Inflection flag */}
          {showFlag && (
            <g className="gap-flag" transform={`translate(${flagX}, ${flagY})`}>
              <line x1="0" y1="0" x2="0" y2="-42" stroke="var(--accent)" strokeWidth="1" strokeDasharray="2 3"/>
              <g transform="translate(-105, -70)">
                <rect x="0" y="0" width="210" height="30" rx="4"
                  fill="var(--ground)" stroke="var(--accent)" strokeWidth="1"/>
                <circle cx="14" cy="15" r="3" fill="var(--accent)"/>
                <text x="26" y="19"
                  fill="var(--ink)" fontSize="11"
                  fontFamily="var(--f-mono)" style={{letterSpacing:"0.04em"}}
                >Team starts with Workroom</text>
              </g>
            </g>
          )}

          {/* Floating multiplier — only at end, once curve is settled */}
          {showMultiplier && (
            <g transform={`translate(${xAt(11) - 86}, ${yAt(leaderNow) - 44})`} className="gap-mult">
              <rect x="0" y="0" width="84" height="30" rx="4"
                fill="var(--accent)"/>
              <text x="42" y="19"
                fill="var(--accent-ink)" fontSize="12"
                fontFamily="var(--f-mono)" textAnchor="middle"
                style={{fontWeight:600, letterSpacing:"0.06em"}}
              >{finalMult.toFixed(1)}× AHEAD</text>
              <path d="M84 15 L88 15" stroke="var(--accent)" strokeWidth="1.5"/>
            </g>
          )}
        </svg>

        <div className="gap-foot">
          <div className="gap-foot-l">
            <span className="gap-foot-k">Your output per team member, annualised</span>
            <span className="gap-foot-sub">Teams that install a shared AI operating system compound fast. Most teams don't, and fall behind quietly.</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------------- Hero ----------------

function Hero({ config }) {
  const tagline = TAGLINES[config.heroTagline] || TAGLINES.headline_primary;
  return (
    <section className="hero">
      <div className="hero-bg">
        <div className="hero-bg-grid"/>
        <div className="hero-bg-glow"/>
      </div>
      <div className="wrap">
        <div className="hero-meta">
          <span className="dot"/>
          <span className="t-mono" style={{fontSize:12, color:"var(--ink-dim)", letterSpacing:"0.04em"}}>
            WORKROOM · <span style={{color:"var(--ink)"}}>AI training, tools and operating system for teams</span>
          </span>
        </div>

        <div className="hero-grid">
          <div>
            <h1 className="hero-tagline">{tagline.headline}</h1>
            <p className="hero-sub">
              Teams rewiring around AI are pulling ahead, fast. Most are still guessing: a few ChatGPT seats, half-used tools, nothing connecting. We plug your team into a shared AI operating system and train them to actually use it.
            </p>

            <div className="hero-ctas">
              <a className="btn btn-primary" href="#book">
                Book a free working session <Icon.arrow/>
              </a>
              <a className="btn btn-ghost" href="#how">
                How it works <Icon.arrow/>
              </a>
            </div>

            <div className="hero-fine">
              <Icon.calendar/> 60 minutes · one of your people · one of your problems
            </div>
          </div>

          <div className="hv-wrap">
            <TheGap/>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero });
