// AuroraRibbon — canvas-based aurora curtain rendering.
//
// Real auroras look like translucent vertical curtains of light that
// undulate across the sky — not horizontal gradient stripes. This component
// renders 3 overlapping "curtains" on a 2D canvas with:
//   - smooth sine-wave top edges that drift with phase + slow time
//   - a vertical gradient fill that fades to transparent at top and bottom
//   - "screen" composite blending so overlapping curtains brighten where they meet
//   - subtle vertical striations to evoke the rayed structure of an aurora
//
// The whole scene is one draw call per layer per frame — far smoother than
// animating SVG path d-attrs or filter blurs.

function AuroraRibbon({ intensity = 1, mode = 'ribbon' }) {
  // ----- Photo placeholder mode -----
  if (mode === 'photo') {
    return (
      <div className="hero-photo" aria-hidden>
        <div className="ph" />
        <svg width="100%" height="100%" style={{position:'absolute', inset:0, opacity:0.4, mixBlendMode:'screen'}}>
          <defs>
            <radialGradient id="ph-warm" cx="30%" cy="40%" r="60%">
              <stop offset="0%" stopColor="#F4A261" stopOpacity="0.25" />
              <stop offset="100%" stopColor="#F4A261" stopOpacity="0" />
            </radialGradient>
          </defs>
          <rect width="100%" height="100%" fill="url(#ph-warm)" />
        </svg>
      </div>
    );
  }

  // ----- Minimal mode -----
  if (mode === 'minimal') {
    return (
      <div className="hero-ribbon-stage" aria-hidden>
        <div style={{
          position:'absolute', inset:0,
          background:
            'radial-gradient(700px 400px at 20% 20%, rgba(74,143,231,0.12), transparent 70%),' +
            'radial-gradient(700px 400px at 80% 80%, rgba(139,92,246,0.10), transparent 70%)',
        }} />
        <CSSStarfield />
      </div>
    );
  }

  // ----- Default: canvas aurora -----
  return (
    <div className="hero-ribbon-stage aurora-stage" aria-hidden>
      <CSSStarfield />
      <AuroraCanvas intensity={intensity} />
      <div className="aurora-vignette" />
    </div>
  );
}
window.AuroraRibbon = AuroraRibbon;


function AuroraCanvas({ intensity = 1 }) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d', { alpha: true });

    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // ---- sizing ----
    let dpr = Math.min(window.devicePixelRatio || 1, 2);
    let W = 0, H = 0;
    const resize = () => {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      const rect = canvas.getBoundingClientRect();
      W = Math.max(1, Math.floor(rect.width));
      H = Math.max(1, Math.floor(rect.height));
      canvas.width  = Math.floor(W * dpr);
      canvas.height = Math.floor(H * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    // ---- pause when off-screen ----
    let visible = true;
    const io = new IntersectionObserver(entries => {
      visible = entries[0].isIntersecting;
      if (visible && rafRef.current == null) loop(performance.now());
    });
    io.observe(canvas);

    // ---- curtain definitions ----
    // Each curtain is a soft vertical "drape" with a sine-wave top edge
    // and a vertical gradient fill (transparent → color → transparent).
    // Colors layer in screen-blend so where they overlap you get aurora-y
    // brightening that doesn't muddy.
    const curtains = [
      {
        // Big lower-back green/teal — the dominant low-altitude band
        yFrac: 0.55,         // vertical center of the band
        height: 460,         // vertical extent in CSS px
        amp: 70,             // wave amplitude (peak-to-peak / 2)
        freq: 0.0019,        // wave spatial frequency (per px)
        speed: 0.24,         // phase drift speed (rad/sec scale)
        speed2: 0.06,        // slow horizontal drift
        phase: 0,
        colors: [            // gradient stops top→bottom: [t, color]
          [0.00, 'rgba(61,220,140,0)'],
          [0.18, 'rgba(46,184,198,0.45)'],
          [0.42, 'rgba(61,220,140,0.65)'],
          [0.72, 'rgba(46,184,198,0.30)'],
          [1.00, 'rgba(10,14,31,0)'],
        ],
      },
      {
        // Mid blue/teal sweep, faster ripple
        yFrac: 0.42,
        height: 520,
        amp: 95,
        freq: 0.0014,
        speed: 0.32,
        speed2: 0.10,
        phase: 1.7,
        colors: [
          [0.00, 'rgba(74,143,231,0)'],
          [0.22, 'rgba(74,143,231,0.55)'],
          [0.50, 'rgba(46,184,198,0.40)'],
          [0.80, 'rgba(74,143,231,0.20)'],
          [1.00, 'rgba(10,14,31,0)'],
        ],
      },
      {
        // Upper purple/magenta veil — slow and high
        yFrac: 0.30,
        height: 560,
        amp: 80,
        freq: 0.0011,
        speed: 0.18,
        speed2: 0.04,
        phase: 3.6,
        colors: [
          [0.00, 'rgba(139,92,246,0)'],
          [0.30, 'rgba(139,92,246,0.45)'],
          [0.55, 'rgba(192,74,184,0.30)'],
          [0.82, 'rgba(74,143,231,0.18)'],
          [1.00, 'rgba(10,14,31,0)'],
        ],
      },
      {
        // Thin red/coral whisp, very subtle, at the top
        yFrac: 0.18,
        height: 320,
        amp: 50,
        freq: 0.0017,
        speed: 0.28,
        speed2: 0.07,
        phase: 5.1,
        colors: [
          [0.00, 'rgba(243,107,107,0)'],
          [0.40, 'rgba(243,107,107,0.22)'],
          [0.60, 'rgba(192,74,184,0.18)'],
          [1.00, 'rgba(10,14,31,0)'],
        ],
      },
    ];

    // Precompute gradient builder
    const makeGradient = (cur) => {
      const top = cur._yTop, h = cur.height;
      const g = ctx.createLinearGradient(0, top, 0, top + h);
      for (const [t, c] of cur.colors) g.addColorStop(t, c);
      return g;
    };

    // ---- draw one curtain ----
    // Draw a filled "rectangle" between top sine edge and (top + height).
    // The vertical gradient does the soft fade out.
    const drawCurtain = (cur, time) => {
      const stepPx = 8; // horizontal sampling step — finer = smoother edge
      const phaseT = cur.phase + time * cur.speed * 0.001;
      const driftT = time * cur.speed2 * 0.001;
      const baseY = cur.yFrac * H;
      cur._yTop = baseY - cur.height * 0.5;

      ctx.beginPath();
      ctx.moveTo(-20, baseY + cur.height * 0.5);
      // top edge: smooth two-frequency sine
      for (let x = -20; x <= W + 20; x += stepPx) {
        const u = (x + driftT * 80) * cur.freq;
        const wave = Math.sin(u + phaseT) * cur.amp
                   + Math.sin(u * 1.7 + phaseT * 0.7) * cur.amp * 0.35;
        const y = baseY + wave - cur.height * 0.5;
        ctx.lineTo(x, y);
      }
      ctx.lineTo(W + 20, baseY + cur.height * 0.5);
      ctx.closePath();

      ctx.fillStyle = makeGradient(cur);
      ctx.fill();
    };

    // ---- striation overlay (vertical rayed structure) ----
    // Subtle moving vertical bands sampled from a low-freq noise-like
    // function to suggest the rayed crinkle of real curtains.
    let striationCache = null;
    const drawStriations = (time) => {
      // soft repeating gradient with horizontal phase drift, masked vertically
      const speed = time * 0.00010;
      const off = (Math.sin(speed) * 120) % 24;
      ctx.save();
      ctx.globalCompositeOperation = 'overlay';
      ctx.globalAlpha = 0.18 * intensity;
      // build a tiny offscreen pattern once
      if (!striationCache) {
        const oc = document.createElement('canvas');
        oc.width = 24; oc.height = 4;
        const octx = oc.getContext('2d');
        const g = octx.createLinearGradient(0, 0, 24, 0);
        g.addColorStop(0,   'rgba(255,255,255,0)');
        g.addColorStop(0.3, 'rgba(255,255,255,0.6)');
        g.addColorStop(0.5, 'rgba(255,255,255,0)');
        g.addColorStop(0.7, 'rgba(255,255,255,0.4)');
        g.addColorStop(1,   'rgba(255,255,255,0)');
        octx.fillStyle = g;
        octx.fillRect(0, 0, 24, 4);
        striationCache = ctx.createPattern(oc, 'repeat');
      }
      ctx.translate(off, 0);
      ctx.fillStyle = striationCache;
      // only paint over the aurora band (top half of screen)
      ctx.fillRect(-30, 0, W + 60, H * 0.75);
      ctx.restore();
    };

    // ---- main loop ----
    let last = performance.now();
    const loop = (now) => {
      rafRef.current = null;
      if (!visible) return;
      const dt = Math.min(64, now - last);
      last = now;

      // clear
      ctx.clearRect(0, 0, W, H);

      // draw curtains in screen mode so overlap brightens
      ctx.globalCompositeOperation = 'screen';
      ctx.globalAlpha = intensity;
      for (const cur of curtains) drawCurtain(cur, reduced ? 0 : now);

      // striations on top
      drawStriations(reduced ? 0 : now);

      ctx.globalCompositeOperation = 'source-over';
      ctx.globalAlpha = 1;

      if (!reduced) rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);

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

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'absolute',
        inset: 0,
        width: '100%',
        height: '100%',
        // canvas content is already blurred-ish; a tiny CSS blur smooths the
        // remaining hard edges of the sine-stepped polygon without re-rasterizing
        // the inner pixels (the canvas itself rasterizes only on resize).
        filter: 'blur(8px) saturate(115%)',
        display: 'block',
      }}
    />
  );
}
window.AuroraCanvas = AuroraCanvas;


// CSS-only twinkling starfield — no JS per-frame work
function CSSStarfield() {
  const stars = React.useMemo(() => {
    const out = [];
    const seed = (n) => {
      // tiny deterministic PRNG so stars don't reshuffle on re-render
      let t = n * 0x6D2B79F5 + 0x9E3779B9 | 0;
      t = Math.imul(t ^ t >>> 15, t | 1);
      t ^= t + Math.imul(t ^ t >>> 7, t | 61);
      return ((t ^ t >>> 14) >>> 0) / 4294967296;
    };
    for (let i = 0; i < 70; i++) {
      out.push({
        x: seed(i*2) * 100,
        y: seed(i*2+1) * 100,
        s: 0.5 + seed(i*7) * 1.8,
        d: 3 + seed(i*11) * 5,
        delay: seed(i*13) * 6,
        op: 0.25 + seed(i*17) * 0.5,
      });
    }
    return out;
  }, []);
  return (
    <div className="starfield" aria-hidden>
      {stars.map((s, i) => (
        <span
          key={i}
          className="star"
          style={{
            left: s.x + '%',
            top: s.y + '%',
            width: s.s + 'px',
            height: s.s + 'px',
            animationDuration: s.d + 's',
            animationDelay: s.delay + 's',
            opacity: s.op,
          }}
        />
      ))}
    </div>
  );
}
window.CSSStarfield = CSSStarfield;
// Back-compat shim (Footer.jsx and others still reference Starfield)
window.Starfield = ({ stars }) => (
  <div className="starfield" aria-hidden>
    {(stars || []).map((s, i) => (
      <span key={i} className="star" style={{
        left: s.x + '%', top: s.y + '%',
        width: s.s + 'px', height: s.s + 'px',
        animationDuration: s.d + 's', animationDelay: s.delay + 's',
        opacity: 0.2 + (s.s / 3),
      }} />
    ))}
  </div>
);
