"use client";

import { useEffect, useRef } from "react";
import { prefersReducedMotion, ScrollSmoother } from "./gsap-setup";
import type { LandingTheme } from "./useLandingTheme";

/* Colour per theme, as RGB channel triplets so alpha can be applied per
   element. Dark is pale silk on navy; light inverts to ink-toned lines at
   lower alpha, because dark lines on a light ground read heavier at equal
   opacity. */
const PALETTE = {
  dark: {
    line: "214, 226, 214",
    lineAlpha: 0.16,
    accent: "122, 199, 133",
    accentAlpha: 0.38,
    node: "122, 199, 133",
    nodeAlpha: 0.6,
  },
  light: {
    line: "38, 72, 50",
    lineAlpha: 0.085,
    accent: "53, 122, 63",
    accentAlpha: 0.26,
    node: "53, 122, 63",
    nodeAlpha: 0.45,
  },
} as const;

/** Silk band: a stack of fine lines sharing one slow wave field, so they
    bunch and separate like layered yield curves. */
const LINE_COUNT = 26;
/** Fraction of the viewport height the band occupies. */
const BAND = 0.4;
/** Where the band centre sits, as a fraction of viewport height.
    Kept low deliberately: this layer is fixed, so every section scrolls
    through it. Centred, it cut straight across the reading column and the
    threads competed with body copy. Sunk to the lower viewport it reads as a
    floor the content travels over, and text meets it only on the way in. */
const BAND_CENTER = 0.8;
/** Horizontal sampling interval in px. */
const STEP = 12;

/** The one brand line: a performance curve climbing left to right through
    the band, the way a portfolio chart does. */
const ACCENT = { base: 0.88, rise: 0.2, a1: 24, f1: 1.2, s1: 0.1, a2: 11, f2: 2.9, s2: 0.07 };

/** Fixed sample positions (0..1 of width) carrying pulsing markers on the
    accent curve — the data points of the ambient chart. */
const MARKERS = [0.24, 0.5, 0.76] as const;

/** Cursor field: threads within this radius of the pointer bow away from it,
    like fabric yielding under touch. */
const POINTER_RADIUS = 160;
const POINTER_STRENGTH = 36;

/** Sparse pulsing nodes pinned to (position, line index) pairs in the silk,
    so the band reads as carrying data rather than being decoration. */
const NODES = [
  [0.14, 5],
  [0.31, 19],
  [0.46, 9],
  [0.63, 22],
  [0.79, 13],
  [0.9, 3],
] as const;

/**
 * The ambient scene behind the whole page: a silk field of fine layered
 * curves breathing slowly under the content, with one brand performance line
 * climbing through it. Hand-rolled canvas 2D — a line field is a few sines,
 * and it keeps ~150KB of WebGL runtime off a marketing page. The field
 * answers gently to the pointer and sinks with scroll, so it has parallax
 * against the sections without being pinned to any of them.
 */
export default function AmbientScene({ theme }: { theme: LandingTheme }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  // Read via a ref inside the draw loop so a theme flip recolours the next
  // frame without tearing down and restarting the whole animation.
  const themeRef = useRef(theme);
  themeRef.current = theme;

  // Under reduced motion there is no loop; a theme flip repaints the one
  // still frame through this handle instead.
  const redrawRef = useRef<(() => void) | null>(null);
  useEffect(() => {
    if (prefersReducedMotion()) redrawRef.current?.();
  }, [theme]);

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

    let width = 0;
    let height = 0;
    let frame = 0;
    let running = true;

    // Pointer and scroll are read into targets and eased toward every frame,
    // so a fast flick glides instead of snapping the field.
    const pointer = { x: 0, y: 0, tx: 0, ty: 0 };
    let scrollNorm = 0;
    let scrollTarget = 0;

    // The cursor field fades in only once the pointer has actually moved and
    // fades back out when it leaves the window — otherwise a phantom dent
    // would sit at the viewport centre on touch devices and at load.
    let energy = 0;
    let energyTarget = 0;

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      width = window.innerWidth;
      height = window.innerHeight;
      canvas.width = Math.floor(width * dpr);
      canvas.height = Math.floor(height * dpr);
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };

    const onPointerMove = (e: PointerEvent) => {
      pointer.tx = e.clientX / window.innerWidth - 0.5;
      pointer.ty = e.clientY / window.innerHeight - 0.5;
      energyTarget = 1;
    };

    const onPointerLeave = () => {
      energyTarget = 0;
    };

    const onScroll = () => {
      const max = document.documentElement.scrollHeight - window.innerHeight;
      scrollTarget = max > 0 ? window.scrollY / max : 0;
    };

    const onVisibility = () => {
      running = document.visibilityState === "visible";
      if (running) {
        last = performance.now();
        frame = requestAnimationFrame(render);
      } else {
        cancelAnimationFrame(frame);
      }
    };

    let last = performance.now();
    let elapsed = 0;

    /** Vertical position of silk line `i` at horizontal position `u` (0..1). */
    const lineY = (i: number, u: number, t: number) => {
      const centered = i / (LINE_COUNT - 1) - 0.5;
      // The band breathes: per-line amplitude drifts so neighbouring lines
      // bunch and separate, which is what reads as silk rather than stripes.
      const breathe = 1 + 0.45 * Math.sin(i * 0.33 + t * 0.05);
      // Amplitude envelope: calm at the viewport edges, fullest mid-screen.
      const env = 0.3 + 0.7 * Math.sin(Math.PI * Math.min(Math.max(u, 0), 1)) ** 1.5;
      return (
        height * (BAND_CENTER + centered * BAND) +
        pointer.y * 30 * (1 - Math.abs(centered)) -
        scrollNorm * height * 0.1 +
        Math.sin(u * Math.PI * 2.2 + t * 0.1 + i * 0.28 + pointer.x * 0.6) * 34 * env * breathe +
        Math.sin(u * Math.PI * 4.7 - t * 0.06 + i * 0.11) * 14 * env +
        Math.sin(u * Math.PI * 1.1 + t * 0.04 + i * 0.05) * 46 * env
      );
    };

    /** Vertical position of the accent performance curve at `u`. */
    const accentY = (u: number, t: number) =>
      height * (ACCENT.base - u * ACCENT.rise) +
      pointer.y * 12 -
      scrollNorm * height * 0.12 +
      Math.sin(u * ACCENT.f1 * Math.PI * 2 + t * ACCENT.s1) * ACCENT.a1 +
      Math.sin(u * ACCENT.f2 * Math.PI * 2 - t * ACCENT.s2) * ACCENT.a2;

    const draw = (time: number) => {
      const palette = PALETTE[themeRef.current];
      ctx.clearRect(0, 0, width, height);

      pointer.x += (pointer.tx - pointer.x) * 0.045;
      pointer.y += (pointer.ty - pointer.y) * 0.045;
      scrollNorm += (scrollTarget - scrollNorm) * 0.06;
      energy += (energyTarget - energy) * 0.05;

      // Fade the field after leaving the hero so copy-heavy sections do not
      // compete with the silk. The scene wrapper keeps the page ground; only
      // the canvas goes quiet.
      const smoother = ScrollSmoother.get();
      const y = smoother ? smoother.scrollTop() : window.scrollY;
      const fade = Math.max(
        0.12,
        1 - Math.max(0, y - height * 0.4) / Math.max(height * 1.15, 1)
      );
      canvas.style.opacity = String(fade);

      // Cursor field for this frame: a soft vertical push away from the
      // pointer, falling off as a Gaussian so the bow has no visible edge.
      const px = (pointer.x + 0.5) * width;
      const py = (pointer.y + 0.5) * height;
      const sigma2 = 2 * POINTER_RADIUS * POINTER_RADIUS;
      const bow = (x: number, y: number) => {
        if (energy < 0.01) return 0;
        const dx = x - px;
        const dy = y - py;
        const influence = Math.exp(-(dx * dx + dy * dy) / sigma2);
        // tanh keeps the push smooth through the pointer's own line — a hard
        // sign flip there put visible kinks in the nearest threads.
        return Math.tanh(dy / 48) * influence * POINTER_STRENGTH * energy;
      };

      // --- Silk band. One shared gradient fades every line at the viewport
      //     edges; per-line weight is a bell across the band, so it has a
      //     bright spine and soft outer threads. ---
      const silkGrad = ctx.createLinearGradient(0, 0, width, 0);
      silkGrad.addColorStop(0, `rgba(${palette.line}, 0)`);
      silkGrad.addColorStop(0.14, `rgba(${palette.line}, 1)`);
      silkGrad.addColorStop(0.86, `rgba(${palette.line}, 1)`);
      silkGrad.addColorStop(1, `rgba(${palette.line}, 0)`);
      ctx.strokeStyle = silkGrad;
      ctx.lineWidth = 1;

      for (let i = 0; i < LINE_COUNT; i++) {
        const centered = Math.abs(i / (LINE_COUNT - 1) - 0.5) * 2;
        ctx.globalAlpha = palette.lineAlpha * (0.15 + 0.85 * Math.pow(1 - centered, 1.4));
        ctx.beginPath();
        for (let x = 0; x <= width + STEP; x += STEP) {
          const y0 = lineY(i, x / Math.max(width, 1), time);
          const y = y0 + bow(x, y0);
          if (x === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.stroke();
      }
      ctx.globalAlpha = 1;

      // --- Data nodes pinned into the silk, pulsing out of phase. ---
      for (let n = 0; n < NODES.length; n++) {
        const [u, i] = NODES[n];
        const pulse = 0.5 + 0.5 * Math.sin(time * 0.8 + n * 1.9);
        ctx.globalAlpha = palette.nodeAlpha * (0.25 + pulse * 0.55);
        ctx.fillStyle = `rgb(${palette.node})`;
        const nodeY = lineY(i, u, time);
        ctx.beginPath();
        ctx.arc(u * width, nodeY + bow(u * width, nodeY), 1.5 + pulse * 1.2, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.globalAlpha = 1;

      // --- The brand performance line, over the silk. Fades in from the
      //     edges so it never terminates hard against the viewport. ---
      const accentGrad = ctx.createLinearGradient(0, 0, width, 0);
      accentGrad.addColorStop(0, `rgba(${palette.accent}, 0)`);
      accentGrad.addColorStop(0.18, `rgba(${palette.accent}, ${palette.accentAlpha})`);
      accentGrad.addColorStop(0.82, `rgba(${palette.accent}, ${palette.accentAlpha})`);
      accentGrad.addColorStop(1, `rgba(${palette.accent}, 0)`);
      ctx.strokeStyle = accentGrad;
      ctx.lineWidth = 1.5;
      ctx.beginPath();
      for (let x = 0; x <= width + STEP; x += STEP) {
        const y0 = accentY(x / Math.max(width, 1), time);
        const y = y0 + bow(x, y0);
        if (x === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
      }
      ctx.stroke();

      for (let m = 0; m < MARKERS.length; m++) {
        const u = MARKERS[m];
        const pulse = 0.5 + 0.5 * Math.sin(time * 0.9 + m * 2.1);
        ctx.globalAlpha = palette.accentAlpha * (0.5 + pulse * 0.5);
        ctx.fillStyle = `rgb(${palette.accent})`;
        const markerY = accentY(u, time);
        ctx.beginPath();
        ctx.arc(u * width, markerY + bow(u * width, markerY), 2 + pulse * 1.4, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.globalAlpha = 1;
    };

    const render = (now: number) => {
      if (!running) return;
      // Clamp dt so a backgrounded tab does not resume with a huge time jump.
      const dt = Math.min((now - last) / 1000, 0.05);
      last = now;
      elapsed += dt;
      draw(elapsed);
      frame = requestAnimationFrame(render);
    };

    resize();
    onScroll();
    window.addEventListener("resize", resize);
    window.addEventListener("scroll", onScroll, { passive: true });
    document.addEventListener("visibilitychange", onVisibility);

    if (prefersReducedMotion()) {
      // One still frame: the texture without the motion.
      draw(0);
      redrawRef.current = () => draw(0);
      return () => {
        redrawRef.current = null;
        window.removeEventListener("resize", resize);
        window.removeEventListener("scroll", onScroll);
        document.removeEventListener("visibilitychange", onVisibility);
      };
    }

    window.addEventListener("pointermove", onPointerMove, { passive: true });
    document.documentElement.addEventListener("pointerleave", onPointerLeave);
    frame = requestAnimationFrame(render);

    return () => {
      running = false;
      cancelAnimationFrame(frame);
      window.removeEventListener("resize", resize);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("pointermove", onPointerMove);
      document.documentElement.removeEventListener("pointerleave", onPointerLeave);
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, []);

  return (
    <div className="immersive-scene" aria-hidden>
      <canvas ref={canvasRef} className="h-full w-full" />
    </div>
  );
}
