// Hero: animated neon wavy lines (Resonance-style)
// Variants: 0 = neon waves (default), 1 = waveform bars, 2 = lifecycle ring

const HeroOrb = ({ variant = 0, motion = "standard" }) => {
  if (variant === 1) return <HeroWaveform motion={motion} />;
  if (variant === 2) return <HeroLifecycle motion={motion} />;
  return <NeonWaves motion={motion} />;
};

// ─────────────────────────────────────────────────────────────────────
// Neon Waves — multiple flowing sine paths with strong glow + bloom
// ─────────────────────────────────────────────────────────────────────
const NeonWaves = ({ motion }) => {
  const speedMul = motion === "calm" ? 0.5 : motion === "hyper" ? 2.2 : 1;
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(0);
  const startRef = React.useRef(performance.now());

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let w = 0, h = 0, dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    // 5 waves. Smooth, elegant, ocean-like — peaks/valleys breathe via a
    // 6-second ease-in-out cycle. Each wave has a unique phase offset so the
    // composition stays interesting without ever feeling start-stoppy.
    const waves = [
      { color: "#ff2bd6", anchor: 0.48, freq: 0.85, ampBase: 0.08, ampMod: 0.08, width: 1.6, cycleOffset: 0.00, freqOffset: 0.10, shapeOffset: 0.0 },
      { color: "#00e5ff", anchor: 0.54, freq: 1.05, ampBase: 0.10, ampMod: 0.10, width: 1.7, cycleOffset: 0.20, freqOffset: 0.55, shapeOffset: 1.6 },
      { color: "#a855f7", anchor: 0.58, freq: 0.75, ampBase: 0.12, ampMod: 0.09, width: 1.8, cycleOffset: 0.45, freqOffset: 0.20, shapeOffset: 3.1 },
      { color: "#ff8c00", anchor: 0.50, freq: 1.20, ampBase: 0.07, ampMod: 0.08, width: 1.4, cycleOffset: 0.65, freqOffset: 0.80, shapeOffset: 4.4 },
      { color: "#06d6a0", anchor: 0.56, freq: 0.95, ampBase: 0.09, ampMod: 0.09, width: 1.5, cycleOffset: 0.85, freqOffset: 0.35, shapeOffset: 5.2 },
    ];

    // Smoothstep — gives ease-in-out without the linear feel of raw sine.
    // Combining it with cosine yields a fluid, ocean-like swell that loops
    // perfectly every CYCLE seconds.
    const CYCLE = 6;
    const easeSwell = (cyclePos) => {
      // cyclePos ∈ [0,1) — produce a [-1,1] value with smooth peaks/troughs
      const angle = cyclePos * Math.PI * 2;
      const raw = Math.cos(angle); // -1 at 0.5, 1 at 0/1 — smooth turnaround
      // shape it further so rises and falls feel like swells, not sine rides
      const sign = raw < 0 ? -1 : 1;
      const mag = Math.abs(raw);
      // smoothstep on magnitude
      const eased = mag * mag * (3 - 2 * mag);
      return sign * eased;
    };

    const drawWave = (wv, t) => {
      const yBase = h * wv.anchor;
      const k = (Math.PI * 2 * wv.freq) / w;
      const tt = t * speedMul;

      // Position within this wave's 6s loop
      const cyclePos = (((tt / CYCLE) + wv.cycleOffset) % 1 + 1) % 1;
      const swell = easeSwell(cyclePos); // -1..1, smooth ease in/out

      // Slow, drifting carrier phase (so the waveform reshapes ever so slightly
      // over time — but smoothly, no scrolling feel)
      const carrierPhase = wv.shapeOffset + Math.sin(tt * 0.18 + wv.shapeOffset) * 0.7;

      // Amplitude swells from base toward (base + mod) and back, smoothly.
      // A second envelope offset across x makes peaks rise/fall non-uniformly.
      const ampPeak = wv.ampBase + wv.ampMod * (0.5 + 0.5 * swell);

      ctx.beginPath();
      const steps = Math.max(120, Math.floor(w / 4));
      for (let i = 0; i <= steps; i++) {
        const x = (i / steps) * w;
        // Per-x envelope: each segment of the wave has a slightly different
        // phase in the swell cycle, so peaks and valleys breathe in place
        // rather than uniformly pumping.
        const localCycle = (cyclePos + Math.sin(x * k * 0.6 + wv.shapeOffset) * 0.12 + wv.freqOffset) % 1;
        const localSwell = easeSwell(((localCycle % 1) + 1) % 1);
        const localAmp = h * (wv.ampBase + wv.ampMod * (0.5 + 0.5 * localSwell));

        const y =
          yBase +
          Math.sin(x * k + carrierPhase) * localAmp +
          Math.sin(x * k * 2.0 + carrierPhase * 1.2) * localAmp * 0.10;
        if (i === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
      }

      ctx.lineCap = "round";
      ctx.lineJoin = "round";

      // Outer soft bloom
      ctx.shadowColor = wv.color;
      ctx.shadowBlur = 32;
      ctx.strokeStyle = wv.color + "2e";
      ctx.lineWidth = wv.width * 4.5;
      ctx.stroke();

      // Mid glow
      ctx.shadowBlur = 16;
      ctx.strokeStyle = wv.color + "99";
      ctx.lineWidth = wv.width * 2;
      ctx.stroke();

      // Crisp colored core (no white)
      ctx.shadowBlur = 6;
      ctx.strokeStyle = wv.color;
      ctx.lineWidth = wv.width;
      ctx.stroke();

      ctx.shadowBlur = 0;
    };

    const tick = () => {
      const t = (performance.now() - startRef.current) / 1000;
      // Trail fade — semi-transparent black overlay creates motion blur
      ctx.globalCompositeOperation = "source-over";
      ctx.fillStyle = "rgba(5,5,5,0.32)";
      ctx.fillRect(0, 0, w, h);

      ctx.globalCompositeOperation = "lighter";
      for (const wv of waves) drawWave(wv, t);

      rafRef.current = requestAnimationFrame(tick);
    };
    tick();

    return () => {
      cancelAnimationFrame(rafRef.current);
      ro.disconnect();
    };
  }, [speedMul]);

  return (
    <div className="neon-waves-wrap">
      <style>{`
        .neon-waves-wrap {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
        }
        .neon-waves-canvas {
          width: 100%;
          height: 100%;
          display: block;
        }
        .neon-waves-vignette {
          position: absolute;
          inset: 0;
          pointer-events: none;
          background:
            radial-gradient(ellipse 60% 55% at center 45%, rgba(5,5,5,0.55) 0%, rgba(5,5,5,0) 50%),
            linear-gradient(to bottom, rgba(5,5,5,0.5) 0%, transparent 20%, transparent 70%, rgba(5,5,5,0.85) 100%);
        }
      `}</style>
      <canvas ref={canvasRef} className="neon-waves-canvas" />
      <div className="neon-waves-vignette" />
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────
// Variant 1: Waveform bars
// ─────────────────────────────────────────────────────────────────────
const HeroWaveform = ({ motion }) => {
  const speed = motion === "calm" ? 1 : motion === "hyper" ? 2.4 : 1.4;
  const bars = 80;
  const colors = ["#ff3366", "#ff8c42", "#ffd23f", "#06d6a0"];
  return (
    <div className="hero-waveform">
      <style>{`
        .hero-waveform {
          width: 100%;
          max-width: 1100px;
          height: 420px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 4px;
          padding: 0 5vw;
        }
        @keyframes wavePulse {
          0%, 100% { transform: scaleY(0.2); opacity: 0.5; }
          50% { transform: scaleY(1); opacity: 1; }
        }
        .wave-bar {
          flex: 1;
          height: 240px;
          border-radius: 4px;
          transform-origin: center;
        }
      `}</style>
      {Array.from({ length: bars }).map((_, i) => {
        const ci = Math.floor((i / bars) * colors.length);
        const delay = (Math.sin(i * 0.4) * 0.5 + i * 0.04).toFixed(2);
        const dur = (1.2 + (i % 5) * 0.15) / speed;
        return (
          <div
            key={i}
            className="wave-bar"
            style={{
              background: colors[ci],
              animation: `wavePulse ${dur}s ease-in-out infinite ${delay}s`,
              opacity: 0.6,
            }}
          />
        );
      })}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────
// Variant 2: Lifecycle ring
// ─────────────────────────────────────────────────────────────────────
const HeroLifecycle = ({ motion }) => {
  const speed = motion === "calm" ? 1 : motion === "hyper" ? 2.4 : 1.5;
  const stages = [
    { label: "Subscriber", color: "#3a86ff" },
    { label: "Lead", color: "#06d6a0" },
    { label: "MQL", color: "#ffd23f" },
    { label: "SQL", color: "#ff8c42" },
    { label: "Opportunity", color: "#ff3366" },
    { label: "Customer", color: "#fff" },
  ];
  const radius = 240;
  return (
    <div className="hero-lifecycle">
      <style>{`
        .hero-lifecycle {
          width: 640px; height: 640px;
          max-width: 90vw; max-height: 90vw;
          position: relative;
        }
        @keyframes lcRotate { to { transform: rotate(360deg); } }
        @keyframes lcDot {
          0%, 100% { transform: scale(1); box-shadow: 0 0 0 rgba(255,255,255,0); }
          50% { transform: scale(1.15); box-shadow: 0 0 30px currentColor; }
        }
        .lc-ring {
          position: absolute; inset: 0;
          animation: lcRotate ${40 / speed}s linear infinite;
        }
        .lc-stage {
          position: absolute;
          left: 50%; top: 50%;
          width: 16px; height: 16px;
          border-radius: 50%;
          margin: -8px 0 0 -8px;
        }
        .lc-stage-label {
          position: absolute;
          font-family: var(--mono);
          font-size: 11px;
          color: var(--ink-dim);
          white-space: nowrap;
          transform: translate(-50%, -50%);
          top: 50%; left: 50%;
        }
        .lc-center {
          position: absolute; left: 50%; top: 50%;
          width: 80px; height: 80px;
          margin: -40px 0 0 -40px;
          border-radius: 50%;
          background: radial-gradient(circle at 30% 30%, #fff, var(--c-orange));
          box-shadow: 0 0 60px rgba(255,140,66,0.6);
        }
        .lc-arc {
          position: absolute; inset: 0;
          border: 1px solid var(--line);
          border-radius: 50%;
        }
      `}</style>
      <div className="lc-arc" style={{ transform: "scale(0.4)" }}></div>
      <div className="lc-arc" style={{ transform: "scale(0.7)" }}></div>
      <div className="lc-arc" style={{ transform: "scale(1)" }}></div>
      <div className="lc-ring">
        {stages.map((s, i) => {
          const angle = (i / stages.length) * Math.PI * 2 - Math.PI / 2;
          const x = Math.cos(angle) * radius;
          const y = Math.sin(angle) * radius;
          const lx = Math.cos(angle) * (radius + 36);
          const ly = Math.sin(angle) * (radius + 36);
          return (
            <React.Fragment key={s.label}>
              <div
                className="lc-stage"
                style={{
                  transform: `translate(${x}px, ${y}px)`,
                  background: s.color,
                  color: s.color,
                  animation: `lcDot ${(2 + i * 0.2) / speed}s ease-in-out infinite ${i * 0.2}s`,
                }}
              />
              <div
                className="lc-stage-label"
                style={{ transform: `translate(calc(-50% + ${lx}px), calc(-50% + ${ly}px))` }}
              >
                {s.label}
              </div>
            </React.Fragment>
          );
        })}
      </div>
      <div className="lc-center"></div>
    </div>
  );
};

window.HeroOrb = HeroOrb;
