"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";

import styles from "./Gooserun.module.css";

type LaneIndex = 0 | 1 | 2;
type Season = "summer" | "fall" | "winter";

interface Bounds {
  left: number;
  right: number;
  top: number;
  bottom: number;
}

function isColliding(a: Bounds, b: Bounds): boolean {
  return (
    a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top
  );
}

type Difficulty = "easy" | "medium" | "hard";

interface DifficultySettings {
  gooseSpeedFactorBase: number;
  gooseSpeedFactorVariance: number;
  spawnIntervalStart: number;
  spawnIntervalFloor: number;
  geeseCanSwitchLanes: boolean;
  baseRunSpeed: number;
  maxRunSpeed: number;
}

const DIFFICULTY_SETTINGS: Record<Difficulty, DifficultySettings> = {
  easy: {
    gooseSpeedFactorBase: 0.95,
    gooseSpeedFactorVariance: 0.08,
    spawnIntervalStart: 1.6,
    spawnIntervalFloor: 0.9,
    geeseCanSwitchLanes: false,
    baseRunSpeed: 100,
    maxRunSpeed: 180,
  },
  medium: {
    gooseSpeedFactorBase: 1.0,
    gooseSpeedFactorVariance: 0.1,
    spawnIntervalStart: 1.2,
    spawnIntervalFloor: 0.5,
    geeseCanSwitchLanes: false,
    baseRunSpeed: 140,
    maxRunSpeed: 250,
  },
  hard: {
    gooseSpeedFactorBase: 1.08,
    gooseSpeedFactorVariance: 0.12,
    spawnIntervalStart: 1.0,
    spawnIntervalFloor: 0.4,
    geeseCanSwitchLanes: true,
    baseRunSpeed: 180,
    maxRunSpeed: 350,
  },
};

const PALETTE = {
  skyTop: "#12142c",
  skyBottom: "#262b5e",
  windowGlow: "#ffd166",
  path: "#333868",
  pathDark: "#282c54",
} as const;

const CANVAS_W = 480;
const CANVAS_H = 720;
const HORIZON_Y = CANVAS_H * 0.42;
const VANISHING_X = CANVAS_W / 2;
const PLAYER_ROW_Y = CANVAS_H - 120;

function depthT(y: number, nearY: number): number {
  const raw = (y - HORIZON_Y) / (nearY - HORIZON_Y);
  return Math.max(0, Math.min(1, raw));
}

function perspectiveX(logicalX: number, y: number, nearY: number): number {
  const t = depthT(y, nearY);
  return VANISHING_X + (logicalX - VANISHING_X) * t;
}

function perspectiveScale(y: number, nearY: number, minScale = 0.2): number {
  const t = depthT(y, nearY);
  return minScale + (1 - minScale) * t;
}

// ------------------------------------------------------------
// WEATHER & PARTICLE EFFECTS
// ------------------------------------------------------------
type ParticleType = "leaf" | "snow";

class OverlayParticle {
  x: number;
  y: number;
  baseVx: number;
  vy: number;
  size: number;
  angle: number;
  va: number;
  color: string;
  type: ParticleType;
  seed: number;

  isFading = false;
  fadeTimer = 0;

  constructor(w: number, type: ParticleType) {
    this.type = type;
    this.x = Math.random() * w;
    this.y = -20;
    this.angle = Math.random() * Math.PI * 2;
    this.seed = Math.random() * 100;

    if (type === "leaf") {
      this.size = 8 + Math.random() * 8;
      this.baseVx = (Math.random() - 0.5) * 20;
      this.vy = 30 + Math.random() * 40;
      this.va = (Math.random() - 0.5) * 0.05;
      const colors = ["#b33912", "#c97618", "#d9aa16", "#8a2410"];
      this.color = colors[Math.floor(Math.random() * colors.length)];
    } else {
      this.size = 2 + Math.random() * 4;
      this.baseVx = (Math.random() - 0.5) * 30;
      this.vy = 50 + Math.random() * 40;
      this.va = 0;
      this.color = `rgba(255, 255, 255, ${0.4 + Math.random() * 0.6})`;
    }
  }

  startFade() {
    this.isFading = true;
  }

  update(dt: number) {
    const sway =
      Math.sin(this.y * 0.03 + this.seed) * (this.type === "leaf" ? 40 : 20);
    this.x += (this.baseVx + sway) * dt;
    this.y += this.vy * dt;
    this.angle += this.va;

    if (this.isFading) {
      this.fadeTimer += dt;
    }
  }

  draw(ctx: CanvasRenderingContext2D) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);

    let alphaMod = 1.0;
    if (this.isFading) {
      alphaMod = Math.max(0, 1.0 - this.fadeTimer / 2.0);
    }

    if (this.type === "leaf") {
      ctx.globalAlpha = 0.85 * alphaMod;
      ctx.fillStyle = this.color;

      ctx.beginPath();
      ctx.moveTo(0, -this.size);
      ctx.bezierCurveTo(
        this.size * 0.8,
        -this.size * 0.3,
        this.size * 0.6,
        this.size,
        0,
        this.size
      );
      ctx.bezierCurveTo(
        -this.size * 0.6,
        this.size,
        -this.size * 0.8,
        -this.size * 0.3,
        0,
        -this.size
      );
      ctx.fill();

      ctx.strokeStyle = "rgba(0, 0, 0, 0.25)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(0, -this.size * 0.9);
      ctx.lineTo(0, this.size * 0.8);
      ctx.moveTo(0, -this.size * 0.2);
      ctx.lineTo(this.size * 0.4, -this.size * 0.4);
      ctx.moveTo(0, -this.size * 0.2);
      ctx.lineTo(-this.size * 0.4, -this.size * 0.4);
      ctx.moveTo(0, this.size * 0.3);
      ctx.lineTo(this.size * 0.35, 0);
      ctx.moveTo(0, this.size * 0.3);
      ctx.lineTo(-this.size * 0.35, 0);
      ctx.stroke();
    } else {
      ctx.globalAlpha = alphaMod;
      ctx.fillStyle = this.color;
      ctx.beginPath();
      ctx.arc(0, 0, this.size, 0, Math.PI * 2);
      ctx.fill();
    }

    ctx.restore();
  }
}

// ------------------------------------------------------------
// SCENERY (Trees, Snowmen, Lampposts, Candy Canes, Flowers)
// ------------------------------------------------------------
type SceneryType = "tree" | "lamppost" | "snowman" | "candy_cane" | "flower";

class Scenery {
  scaleMod: number;
  treeVariant: number;
  seed: number;

  constructor(public x: number, public y: number, public type: SceneryType) {
    if (this.type === "tree") this.scaleMod = 1.2 + Math.random() * 1.0;
    else if (this.type === "candy_cane")
      this.scaleMod = 1.2 + Math.random() * 0.8;
    else if (this.type === "flower") this.scaleMod = 0.3 + Math.random() * 0.25;
    // Smaller flowers
    else this.scaleMod = 1.0;

    this.treeVariant = Math.random() < 0.5 ? 1 : 2;
    this.seed = Math.random();
  }

  update(dt: number, worldSpeed: number): void {
    if (worldSpeed === 0) return;
    this.y += worldSpeed * dt;
  }

  isOffScreen(canvasHeight: number): boolean {
    return this.y > canvasHeight + 100;
  }

  draw(ctx: CanvasRenderingContext2D, season: Season): void {
    const screenX = perspectiveX(this.x, this.y, PLAYER_ROW_Y);
    const scale = perspectiveScale(this.y, PLAYER_ROW_Y, 0.05) * this.scaleMod;

    ctx.save();
    ctx.translate(screenX, this.y);
    ctx.scale(scale, scale);
    ctx.translate(0, -10);

    if (this.type === "tree") {
      ctx.fillStyle = "#4a2f1d";
      ctx.fillRect(-6, -20, 12, 24);

      if (season === "winter") {
        ctx.strokeStyle = "#2c1c11";
        ctx.lineCap = "round";
        ctx.lineJoin = "round";

        const flip = this.seed > 0.5 ? 1 : -1;
        const hSpread = 1 + this.seed * 0.4;

        ctx.lineWidth = 14;
        ctx.beginPath();
        ctx.moveTo(0, 5);
        ctx.lineTo(0, -60 * hSpread);
        ctx.stroke();

        ctx.lineWidth = 7;
        ctx.beginPath();
        ctx.moveTo(0, -35 * hSpread);
        ctx.quadraticCurveTo(
          -35 * flip,
          -60 * hSpread,
          -60 * flip,
          -100 * hSpread
        );
        ctx.moveTo(0, -45 * hSpread);
        ctx.quadraticCurveTo(
          45 * flip,
          -70 * hSpread,
          65 * flip,
          -115 * hSpread
        );
        ctx.moveTo(0, -55 * hSpread);
        ctx.quadraticCurveTo(
          -15 * flip,
          -90 * hSpread,
          -20 * flip,
          -140 * hSpread
        );
        ctx.stroke();

        ctx.lineWidth = 3.5;
        ctx.beginPath();
        ctx.moveTo(-35 * flip, -60 * hSpread);
        ctx.lineTo(-65 * flip, -50 * hSpread);
        ctx.moveTo(-45 * flip, -80 * hSpread);
        ctx.lineTo(-25 * flip, -110 * hSpread);
        ctx.moveTo(45 * flip, -70 * hSpread);
        ctx.lineTo(70 * flip, -60 * hSpread);
        ctx.moveTo(55 * flip, -95 * hSpread);
        ctx.lineTo(35 * flip, -125 * hSpread);
        ctx.moveTo(-15 * flip, -90 * hSpread);
        ctx.lineTo(25 * flip, -115 * hSpread);
        ctx.moveTo(-18 * flip, -115 * hSpread);
        ctx.lineTo(-40 * flip, -135 * hSpread);
        ctx.stroke();

        ctx.fillStyle = "#f0f4f8";
        const snowCaps = [
          { x: -60 * flip, y: -100 * hSpread },
          { x: 65 * flip, y: -115 * hSpread },
          { x: -20 * flip, y: -140 * hSpread },
          { x: -65 * flip, y: -50 * hSpread },
          { x: -25 * flip, y: -110 * hSpread },
          { x: 70 * flip, y: -60 * hSpread },
          { x: 35 * flip, y: -125 * hSpread },
          { x: 25 * flip, y: -115 * hSpread },
          { x: -40 * flip, y: -135 * hSpread },
          { x: -45 * flip, y: -80 * hSpread },
        ];

        snowCaps.forEach((cap) => {
          ctx.beginPath();
          ctx.ellipse(
            cap.x,
            cap.y - 3,
            7 + this.seed * 4,
            4 + this.seed * 2,
            0,
            0,
            Math.PI * 2
          );
          ctx.fill();
        });
      } else {
        ctx.fillStyle = "#4a2f1d";
        ctx.fillRect(-8, -25, 16, 30);

        let dark, light;
        if (season === "summer") {
          const greens = [
            ["#162e10", "#2d5c1e"],
            ["#11240d", "#1e4016"],
          ];
          const pal = greens[Math.floor(this.seed * greens.length)];
          dark = pal[0];
          light = pal[1];
        } else {
          const autumns = [
            ["#5c1e10", "#a83a18"],
            ["#6b3b08", "#c97618"],
            ["#73580a", "#d9aa16"],
          ];
          const pal = autumns[Math.floor(this.seed * autumns.length)];
          dark = pal[0];
          light = pal[1];
        }

        if (this.treeVariant === 1) {
          ctx.fillStyle = dark;
          ctx.beginPath();
          ctx.moveTo(0, -140);
          ctx.lineTo(45, -15);
          ctx.lineTo(-45, -15);
          ctx.fill();
          ctx.fillStyle = light;
          ctx.beginPath();
          ctx.moveTo(0, -140);
          ctx.lineTo(0, -15);
          ctx.lineTo(-45, -15);
          ctx.fill();
        } else {
          ctx.fillStyle = dark;
          ctx.beginPath();
          ctx.arc(12, -60, 35, 0, Math.PI * 2);
          ctx.arc(-20, -45, 30, 0, Math.PI * 2);
          ctx.fill();
          ctx.fillStyle = light;
          ctx.beginPath();
          ctx.arc(-10, -70, 35, 0, Math.PI * 2);
          ctx.arc(-30, -50, 26, 0, Math.PI * 2);
          ctx.fill();
        }
      }
    } else if (this.type === "flower" && season === "summer") {
      const isPink = this.seed < 0.5;
      const petalColor = isPink ? "#ff77cc" : "#77ccff";
      const petalShadow = isPink ? "#d65bb3" : "#5bb3d6";
      const sway = Math.sin(this.seed * Math.PI * 2) * 5;

      // Stem
      ctx.strokeStyle = "#4ca638";
      ctx.lineWidth = 4;
      ctx.lineCap = "round";
      ctx.beginPath();
      ctx.moveTo(0, 5);
      ctx.quadraticCurveTo(sway, -20, sway, -45);
      ctx.stroke();

      // Leaves
      ctx.fillStyle = "#3a7a28";
      ctx.beginPath();
      ctx.ellipse(-8 + sway * 0.3, -15, 10, 5, Math.PI / 4, 0, Math.PI * 2);
      ctx.fill();

      ctx.beginPath();
      ctx.ellipse(8 + sway * 0.6, -28, 9, 4.5, -Math.PI / 5, 0, Math.PI * 2);
      ctx.fill();

      // Flower Head
      ctx.translate(sway, -45);

      // Petals
      ctx.fillStyle = petalColor;
      ctx.strokeStyle = petalShadow;
      ctx.lineWidth = 1;
      const numPetals = 6;
      for (let i = 0; i < numPetals; i++) {
        ctx.save();
        ctx.rotate((i * Math.PI * 2) / numPetals);
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.bezierCurveTo(12, -12, 12, -28, 0, -32);
        ctx.bezierCurveTo(-12, -28, -12, -12, 0, 0);
        ctx.fill();
        ctx.stroke();

        // Petal vein detail
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -18);
        ctx.stroke();
        ctx.restore();
      }

      // Center
      ctx.fillStyle = "#ffcc00";
      ctx.beginPath();
      ctx.arc(0, 0, 8, 0, Math.PI * 2);
      ctx.fill();

      // Pollen detail dots
      ctx.fillStyle = "#cc9900";
      const dotCoords = [
        [0, 0],
        [-3, -3],
        [3, 3],
        [3, -3],
        [-3, 3],
        [0, -4],
        [0, 4],
        [4, 0],
        [-4, 0],
      ];
      dotCoords.forEach(([dx, dy]) => {
        ctx.beginPath();
        ctx.arc(dx, dy, 1, 0, Math.PI * 2);
        ctx.fill();
      });
    } else if (this.type === "candy_cane" && season === "winter") {
      const caneH = 110;
      const caneW = 16;
      const hookR = 22;

      ctx.fillStyle = "rgba(0,0,0,0.15)";
      ctx.beginPath();
      ctx.ellipse(0, 0, 14, 4, 0, 0, Math.PI * 2);
      ctx.fill();

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(-hookR, -caneH);
      ctx.lineTo(-hookR, 0);
      ctx.lineTo(-hookR + caneW, 0);
      ctx.lineTo(-hookR + caneW, -caneH);
      ctx.arc(0, -caneH, hookR, Math.PI, 0, false);
      ctx.arc(0, -caneH, hookR - caneW, 0, Math.PI, true);
      ctx.closePath();
      ctx.clip();

      ctx.fillStyle = "#fff8f0";
      ctx.fillRect(
        -hookR * 2,
        -caneH - hookR * 2,
        hookR * 4,
        caneH + hookR * 4
      );

      ctx.fillStyle = "#d31c1c";
      for (let i = -caneH - 50; i < 20; i += 25) {
        ctx.beginPath();
        ctx.moveTo(-hookR * 2, i);
        ctx.lineTo(hookR * 2, i + 20);
        ctx.lineTo(hookR * 2, i + 32);
        ctx.lineTo(-hookR * 2, i + 12);
        ctx.fill();
      }
      ctx.restore();
    } else if (this.type === "snowman" && season === "winter") {
      ctx.fillStyle = "#fff";
      ctx.beginPath();
      ctx.arc(0, -10, 12, 0, Math.PI * 2);
      ctx.fill();
      ctx.beginPath();
      ctx.arc(0, -28, 9, 0, Math.PI * 2);
      ctx.fill();
      ctx.beginPath();
      ctx.arc(0, -42, 7, 0, Math.PI * 2);
      ctx.fill();

      ctx.fillStyle = "#111";
      ctx.fillRect(-3, -44, 2, 2);
      ctx.fillRect(3, -44, 2, 2);
      ctx.fillRect(-1, -30, 2, 2);
      ctx.fillRect(-1, -24, 2, 2);

      ctx.fillStyle = "#f5a623";
      ctx.beginPath();
      ctx.moveTo(0, -42);
      ctx.lineTo(8, -40);
      ctx.lineTo(0, -39);
      ctx.fill();
    } else if (this.type === "lamppost") {
      ctx.fillStyle = "#111";
      ctx.fillRect(-3, -90, 6, 90);
      ctx.fillRect(-15, -95, 25, 6);

      const glow = ctx.createRadialGradient(-10, -90, 0, -10, -90, 25);
      glow.addColorStop(0, "rgba(255, 209, 102, 0.8)");
      glow.addColorStop(1, "rgba(255, 209, 102, 0)");
      ctx.fillStyle = glow;
      ctx.fillRect(-40, -120, 60, 60);

      ctx.fillStyle = "#fff";
      ctx.beginPath();
      ctx.arc(-10, -90, 4, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.restore();
  }
}

// ------------------------------------------------------------
// BACKGROUND WITH SPACED PARALLAX & SEASONS
// ------------------------------------------------------------
class CampusBackground {
  private cloudOffset = 0;
  private skylineOffset = 0;
  private distantOffset = 0;
  private pathOffset = 0;
  private readonly pathStripe = 56;

  constructor(private w: number, private h: number) {}

  update(dt: number, runSpeed: number): void {
    this.cloudOffset = (this.cloudOffset + dt * 10) % this.w;

    if (runSpeed > 0) {
      this.skylineOffset =
        (this.skylineOffset + dt * runSpeed * 0.15) % (280 * 6);
      this.distantOffset = (this.distantOffset + dt * runSpeed * 0.05) % this.w;
      this.pathOffset =
        (this.pathOffset + dt * runSpeed) % (this.pathStripe * 2);
    }
  }

  draw(ctx: CanvasRenderingContext2D, season: Season): void {
    const w = this.w;
    const h = this.h;
    const skylineBaseline = HORIZON_Y;

    // 1. Sky & Moon
    const sky = ctx.createLinearGradient(0, 0, 0, skylineBaseline);
    sky.addColorStop(0, PALETTE.skyTop);
    sky.addColorStop(1, PALETTE.skyBottom);
    ctx.fillStyle = sky;
    ctx.fillRect(0, 0, w, skylineBaseline);

    const moonX = w * 0.78;
    const moonY = skylineBaseline * 0.45;
    const glow = ctx.createRadialGradient(moonX, moonY, 2, moonX, moonY, 70);
    glow.addColorStop(0, "rgba(92,175,249,0.35)");
    glow.addColorStop(1, "rgba(92,175,249,0)");
    ctx.fillStyle = glow;
    ctx.fillRect(moonX - 70, moonY - 70, 140, 140);
    ctx.fillStyle = "rgba(230,240,255,0.9)";
    ctx.beginPath();
    ctx.arc(moonX, moonY, 11, 0, Math.PI * 2);
    ctx.fill();

    // 2. Clouds
    ctx.fillStyle = "rgba(255,255,255,0.05)";
    for (const baseX of [60, 220, 360]) {
      for (const rep of [0, -w]) {
        const x = ((baseX - this.cloudOffset + w * 2) % w) + rep + w;
        ctx.beginPath();
        ctx.ellipse(x, 70, 46, 14, 0, 0, Math.PI * 2);
        ctx.fill();
      }
    }

    // 3. LAYER 1: Distant Generic Skyline
    ctx.fillStyle = "#1b1d3d";
    for (let i = -2; i < Math.ceil(w / 70) + 2; i++) {
      const bx = i * 70 - this.distantOffset;
      const buildingH = 30 + ((i * 47) % 35);
      ctx.fillRect(bx, skylineBaseline - buildingH, 60, buildingH);
    }

    // 4. LAYER 2: Waterloo Landmarks
    const buildingW = 280;
    const startIdx = Math.floor(this.skylineOffset / buildingW);
    const offset = this.skylineOffset % buildingW;
    const buildingCount = Math.ceil(w / buildingW) + 2;

    for (let i = -1; i < buildingCount; i++) {
      const worldIdx = startIdx + i;
      const bx = i * buildingW - offset;
      const kind = ((worldIdx % 6) + 6) % 6;

      if (kind === 0) {
        // DP LIBRARY
        const towerH = 115;
        const towerW = 115;
        const baseW = 160;
        const baseH = 35;
        const towerX = bx + 45;
        const baseLeft = towerX - (baseW - towerW) / 2;

        ctx.fillStyle = "rgba(255, 209, 102, 0.4)";
        ctx.fillRect(baseLeft, skylineBaseline - baseH, baseW, baseH);

        ctx.fillStyle = "#222230";
        for (let px = 0; px <= baseW; px += 40) {
          ctx.beginPath();
          ctx.moveTo(baseLeft + px - 12, skylineBaseline - baseH);
          ctx.lineTo(baseLeft + px + 12, skylineBaseline - baseH);
          ctx.quadraticCurveTo(
            baseLeft + px + 6,
            skylineBaseline - baseH / 2,
            baseLeft + px + 6,
            skylineBaseline
          );
          ctx.lineTo(baseLeft + px - 6, skylineBaseline);
          ctx.quadraticCurveTo(
            baseLeft + px - 6,
            skylineBaseline - baseH / 2,
            baseLeft + px - 12,
            skylineBaseline - baseH
          );
          ctx.fill();
        }

        ctx.fillStyle = "#11111a";
        ctx.fillRect(
          baseLeft - 5,
          skylineBaseline - baseH - 12,
          baseW + 10,
          12
        );

        ctx.fillStyle = "#aab2bf";
        ctx.fillRect(
          towerX,
          skylineBaseline - baseH - 12 - towerH,
          towerW,
          towerH
        );

        ctx.fillStyle = "#ffe699";
        for (let wx = 8; wx < towerW - 5; wx += 12) {
          for (let wy = 10; wy < towerH - 10; wy += 22) {
            ctx.fillRect(
              towerX + wx,
              skylineBaseline - baseH - 12 - towerH + wy,
              4,
              15
            );
          }
        }

        const penthouseY = skylineBaseline - baseH - 12 - towerH - 18;
        ctx.fillStyle = "#1c1c28";
        ctx.fillRect(towerX + 25, penthouseY, towerW - 50, 18);

        ctx.fillStyle = "#555566";
        ctx.fillRect(towerX + towerW / 2 - 2, penthouseY - 25, 4, 25);
      } else if (kind === 1) {
        // MC (Math & Computer)
        const mcH = 110;
        const mcW = 180;
        ctx.fillStyle = "#2c2c44";

        ctx.fillRect(bx, skylineBaseline - mcH + 30, mcW, mcH - 30);
        ctx.fillRect(bx - 10, skylineBaseline - mcH, mcW + 20, 55);
        ctx.fillRect(bx + 20, skylineBaseline - mcH - 25, 30, mcH + 25);

        ctx.fillStyle = "#9ba1ad";
        for (
          let y = skylineBaseline - mcH + 10;
          y < skylineBaseline - mcH + 40;
          y += 20
        ) {
          for (let x = -5; x < mcW + 15; x += 12) {
            if (x > 20 && x < 50) continue;
            ctx.fillRect(bx + x, y, 8, 12);
          }
        }

        ctx.fillStyle = "rgba(0,0,0,0.4)";
        ctx.fillRect(bx, skylineBaseline - mcH + 55, mcW, 8);

        ctx.fillStyle = "#1a1a2e";
        for (let x = 10; x < mcW; x += 25) {
          ctx.fillRect(bx + x, skylineBaseline - mcH + 65, 12, mcH - 65);
        }
      } else if (kind === 2) {
        // QNC (Quantum Nano Centre)
        const qncH = 145;
        const qncW = 120;
        ctx.fillStyle = "#182c47";
        ctx.fillRect(bx, skylineBaseline - qncH, qncW, qncH);
        ctx.strokeStyle = "rgba(255,255,255,0.12)";
        ctx.lineWidth = 1;
        ctx.beginPath();
        for (let y = skylineBaseline - qncH; y < skylineBaseline; y += 14) {
          ctx.moveTo(bx, y);
          ctx.lineTo(bx + qncW, y + 16);
          ctx.moveTo(bx, y + 16);
          ctx.lineTo(bx + qncW, y);
        }
        ctx.stroke();
      } else if (kind === 3) {
        // DC (Davis Centre)
        const dcH = 100;
        const dcW = 160;

        ctx.save();
        ctx.fillStyle = "#334c6b";
        ctx.beginPath();
        ctx.moveTo(bx, skylineBaseline);
        ctx.lineTo(bx, skylineBaseline - dcH + 40);
        ctx.quadraticCurveTo(
          bx + dcW / 2,
          skylineBaseline - dcH - 10,
          bx + dcW,
          skylineBaseline - dcH + 40
        );
        ctx.lineTo(bx + dcW, skylineBaseline);
        ctx.closePath();
        ctx.fill();
        ctx.clip();

        ctx.strokeStyle = "rgba(255,255,255,0.25)";
        ctx.lineWidth = 1;
        ctx.beginPath();
        for (let x = 15; x < dcW; x += 15) {
          ctx.moveTo(bx + x, skylineBaseline);
          ctx.lineTo(bx + x, skylineBaseline - dcH - 20);
        }
        for (let y = 15; y < dcH + 20; y += 15) {
          ctx.moveTo(bx, skylineBaseline - y);
          ctx.lineTo(bx + dcW, skylineBaseline - y);
        }
        ctx.stroke();
        ctx.restore();

        ctx.fillStyle = "#a62424";
        ctx.fillRect(bx + 20, skylineBaseline - dcH, 12, dcH);
        ctx.fillRect(bx + 60, skylineBaseline - dcH, 12, dcH);
        ctx.fillRect(bx + 115, skylineBaseline - dcH + 20, 12, dcH - 20);

        ctx.fillRect(bx + 10, skylineBaseline - 60, 65, 8);
        ctx.fillRect(bx + 10, skylineBaseline - 30, 65, 8);
        ctx.fillRect(bx + 105, skylineBaseline - 50, 32, 6);
        ctx.fillRect(bx + 105, skylineBaseline - 30, 32, 6);

        ctx.fillRect(bx + 16, skylineBaseline - dcH, 20, 6);
        ctx.fillRect(bx + 56, skylineBaseline - dcH, 20, 6);
        ctx.fillRect(bx + 111, skylineBaseline - dcH + 20, 20, 6);
      } else if (kind === 4) {
        // SLC / PAC Expansion
        const bLine = skylineBaseline;

        ctx.fillStyle = "#1a2536";
        ctx.fillRect(bx, bLine - 35, 100, 35);
        ctx.fillStyle = "#0d131f";
        for (let x = 5; x < 100; x += 12)
          ctx.fillRect(bx + x, bLine - 35, 2, 35);

        ctx.fillStyle = "#253b54";
        ctx.fillRect(bx - 5, bLine - 75, 105, 40);
        ctx.fillStyle = "#131f2e";
        for (let x = -3; x < 100; x += 6)
          ctx.fillRect(bx + x, bLine - 75, 2, 40);
        ctx.fillStyle = "#0d131f";
        ctx.fillRect(bx - 5, bLine - 75, 105, 4);

        ctx.fillStyle = "#22222a";
        ctx.fillRect(bx + 100, bLine - 130, 65, 130);
        ctx.fillStyle = "#15151a";
        ctx.fillRect(bx + 95, bLine - 135, 75, 5);

        ctx.fillStyle = "#d4b322";
        ctx.beginPath();
        ctx.moveTo(bx + 130, bLine);
        ctx.lineTo(bx + 130, bLine - 80);
        ctx.lineTo(bx + 165, bLine - 105);
        ctx.lineTo(bx + 165, bLine);
        ctx.fill();

        ctx.fillStyle = "rgba(30, 45, 65, 0.5)";
        ctx.fillRect(bx + 125, bLine - 130, 40, 130);

        ctx.strokeStyle = "rgba(0,0,0,0.6)";
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(bx + 135, bLine);
        ctx.lineTo(bx + 135, bLine - 130);
        ctx.moveTo(bx + 145, bLine);
        ctx.lineTo(bx + 145, bLine - 130);
        ctx.moveTo(bx + 155, bLine);
        ctx.lineTo(bx + 155, bLine - 130);
        for (let y = 20; y < 130; y += 20) {
          ctx.moveTo(bx + 125, bLine - y);
          ctx.lineTo(bx + 165, bLine - y);
        }
        ctx.stroke();

        const cx = bx + 113;
        const cy = bLine - 110;

        ctx.fillStyle = "#d4b322";
        ctx.beginPath();
        ctx.arc(cx, cy, 10, 0, Math.PI * 2);
        ctx.fill();

        ctx.fillStyle = "#701616";
        ctx.beginPath();
        ctx.arc(cx - 1, cy - 4, 6, Math.PI, 0);
        ctx.lineTo(cx + 6, cy - 1);
        ctx.lineTo(cx - 8, cy - 1);
        ctx.fill();

        ctx.fillStyle = "#111";
        ctx.beginPath();
        ctx.arc(cx - 2, cy + 2, 6, Math.PI / 2, Math.PI * 1.5);
        ctx.lineTo(cx + 4, cy - 4);
        ctx.lineTo(cx + 6, cy);
        ctx.lineTo(cx + 1, cy + 1);
        ctx.lineTo(cx + 5, cy + 3);
        ctx.lineTo(cx + 5, cy + 7);
        ctx.lineTo(cx - 2, cy + 8);
        ctx.fill();
      } else {
        const bH = 50 + (worldIdx % 3) * 20;
        ctx.fillStyle = "#1d1d3a";
        ctx.fillRect(bx, skylineBaseline - bH, 105, bH);
        ctx.fillStyle = PALETTE.windowGlow;
        ctx.globalAlpha = 0.4;
        ctx.fillRect(bx + 15, skylineBaseline - bH + 15, 8, 12);
        ctx.fillRect(bx + 35, skylineBaseline - bH + 15, 8, 12);
        ctx.globalAlpha = 1;
      }
    }

    // 5. Grass & Path
    const nearHalfWidth = w / 2;
    const farHalfWidth = 0;
    const leftAt = (t: number) =>
      VANISHING_X - (farHalfWidth + (nearHalfWidth - farHalfWidth) * t);
    const rightAt = (t: number) =>
      VANISHING_X + (farHalfWidth + (nearHalfWidth - farHalfWidth) * t);

    const grassGrad = ctx.createLinearGradient(0, skylineBaseline, 0, h);
    if (season === "winter") {
      grassGrad.addColorStop(0, "#8a9ba8");
      grassGrad.addColorStop(1, "#dce4eb");
    } else {
      grassGrad.addColorStop(0, "#080d14");
      grassGrad.addColorStop(1, "#0d2614");
    }
    ctx.fillStyle = grassGrad;

    ctx.beginPath();
    ctx.moveTo(0, skylineBaseline);
    ctx.lineTo(leftAt(0), skylineBaseline);
    ctx.lineTo(leftAt(1), h);
    ctx.lineTo(0, h);
    ctx.closePath();
    ctx.fill();

    ctx.beginPath();
    ctx.moveTo(w, skylineBaseline);
    ctx.lineTo(rightAt(0), skylineBaseline);
    ctx.lineTo(rightAt(1), h);
    ctx.lineTo(w, h);
    ctx.closePath();
    ctx.fill();

    const pathGrad = ctx.createLinearGradient(0, skylineBaseline, 0, h);
    if (season === "winter") {
      pathGrad.addColorStop(0, "#5b6d80");
      pathGrad.addColorStop(1, "#8395a8");
    } else {
      pathGrad.addColorStop(0, PALETTE.pathDark);
      pathGrad.addColorStop(1, PALETTE.path);
    }
    ctx.fillStyle = pathGrad;

    ctx.beginPath();
    ctx.moveTo(leftAt(0), skylineBaseline);
    ctx.lineTo(rightAt(0), skylineBaseline);
    ctx.lineTo(rightAt(1), h);
    ctx.lineTo(leftAt(1), h);
    ctx.closePath();
    ctx.fill();

    // 6. Rungs
    const rungCount = 7;
    const scrollT = this.pathOffset / (this.pathStripe * 2);
    ctx.fillStyle = "rgba(255,255,255,0.05)";
    for (let i = 0; i < rungCount; i++) {
      const tLinear = (i / rungCount + scrollT) % 1;
      const t = tLinear * tLinear;
      const y = skylineBaseline + t * (h - skylineBaseline);
      const thickness = 2 + t * 6;
      ctx.fillRect(leftAt(t), y, rightAt(t) - leftAt(t), thickness);
    }

    // 7. Atmospheric Fog
    const fog = ctx.createLinearGradient(
      0,
      skylineBaseline - 60,
      0,
      skylineBaseline + 140
    );
    if (season === "winter") {
      fog.addColorStop(0, "rgba(138, 155, 168, 0)");
      fog.addColorStop(0.3, "rgba(138, 155, 168, 0.9)");
      fog.addColorStop(1, "rgba(138, 155, 168, 0)");
    } else {
      fog.addColorStop(0, "rgba(38, 43, 94, 0)");
      fog.addColorStop(0.3, "rgba(38, 43, 94, 1)");
      fog.addColorStop(1, "rgba(38, 43, 94, 0)");
    }
    ctx.fillStyle = fog;
    ctx.fillRect(0, skylineBaseline - 60, w, 200);

    const vignette = ctx.createRadialGradient(
      w / 2,
      h / 2,
      h * 0.35,
      w / 2,
      h / 2,
      h * 0.75
    );
    vignette.addColorStop(0, "rgba(0,0,0,0)");
    vignette.addColorStop(1, "rgba(0,0,0,0.35)");
    ctx.fillStyle = vignette;
    ctx.fillRect(0, 0, w, h);
  }
}

// ------------------------------------------------------------
// PLAYER
// ------------------------------------------------------------
const MASCOT_ASPECT = 148 / 130;
const PLAYER_SPRITE_H = 46;
const PLAYER_SPRITE_W = PLAYER_SPRITE_H * MASCOT_ASPECT;

class Player {
  lane: LaneIndex = 1;
  x: number;
  y: number;
  width = PLAYER_SPRITE_W;
  height = PLAYER_SPRITE_H;
  isBoosted = false;
  private runTime = 0;
  private prevX: number;

  constructor(
    private laneX: readonly number[],
    canvasHeight: number,
    private sprite: HTMLImageElement
  ) {
    this.x = laneX[this.lane];
    this.y = canvasHeight - 120;
    this.prevX = this.x;
  }

  moveLeft(): void {
    if (this.lane > 0) this.lane = (this.lane - 1) as LaneIndex;
  }

  moveRight(): void {
    if (this.lane < 2) this.lane = (this.lane + 1) as LaneIndex;
  }

  update(dt: number): void {
    const targetX = this.laneX[this.lane];
    this.prevX = this.x;
    this.x += (targetX - this.x) * 0.2;
    this.runTime += dt;
  }

  getBounds(): Bounds {
    const groundY = this.y + 27;
    const hitRadiusX = this.width * 0.3;
    const hitRadiusY = 12;
    return {
      left: this.x - hitRadiusX,
      right: this.x + hitRadiusX,
      top: groundY - hitRadiusY,
      bottom: groundY + hitRadiusY,
    };
  }

  draw(ctx: CanvasRenderingContext2D, isDead = false, deathTime = 0): void {
    const bobSpeed = this.isBoosted ? 18 : 10;
    const bob = isDead ? 0 : Math.sin(this.runTime * bobSpeed) * 3;

    const lean = isDead
      ? Math.sin(deathTime * 10) * 0.25
      : Math.max(-0.12, Math.min(0.12, (this.x - this.prevX) * 0.05));

    const drawY = this.y + bob;

    ctx.fillStyle = "rgba(0,0,0,0.28)";
    ctx.beginPath();
    ctx.ellipse(
      this.x,
      this.y + this.height / 2 + 4,
      this.width * 0.38,
      7,
      0,
      0,
      Math.PI * 2
    );
    ctx.fill();

    if (this.isBoosted && !isDead) {
      const aura = ctx.createRadialGradient(
        this.x,
        drawY,
        4,
        this.x,
        drawY,
        this.width * 0.9
      );
      aura.addColorStop(0, "rgba(255,209,102,0.4)");
      aura.addColorStop(1, "rgba(255,209,102,0)");
      ctx.fillStyle = aura;
      ctx.fillRect(
        this.x - this.width,
        drawY - this.width,
        this.width * 2,
        this.width * 2
      );
    }

    ctx.save();
    ctx.translate(this.x, drawY);
    ctx.rotate(lean);

    if (this.sprite.complete && this.sprite.naturalWidth > 0) {
      ctx.drawImage(
        this.sprite,
        -this.width / 2,
        -this.height / 2,
        this.width,
        this.height
      );
    } else {
      ctx.fillStyle = "#ffd54a";
      ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
    }
    ctx.restore();

    if (isDead) {
      for (let i = 0; i < 3; i++) {
        const orbitAngle = deathTime * 5 + (i * Math.PI * 2) / 3;
        const sx = this.x + Math.cos(orbitAngle) * 25;
        const sy = drawY - this.height * 0.8 + Math.sin(orbitAngle) * 6;

        ctx.save();
        ctx.translate(sx, sy);
        ctx.rotate(deathTime * 8);

        ctx.fillStyle = "#ffd166";
        ctx.beginPath();
        for (let j = 0; j < 10; j++) {
          const a = (j * Math.PI) / 5 - Math.PI / 2;
          const r = j % 2 === 0 ? 6 : 2.5;
          ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r);
        }
        ctx.closePath();
        ctx.fill();
        ctx.restore();
      }
    }
  }
}

// ------------------------------------------------------------
// GOOSE
// ------------------------------------------------------------
class Goose {
  width = 46;
  height = 34;
  private laneIndex: number;
  private targetX: number;
  private switchCheckTimer = 0;
  private nextSwitchCheck = 1.5 + Math.random() * 2;
  private waddleTime = Math.random() * 10;

  constructor(
    public x: number,
    public y: number,
    private speedFactor: number,
    laneIndex: number,
    private laneX: readonly number[],
    private canSwitchLanes: boolean
  ) {
    this.laneIndex = laneIndex;
    this.targetX = x;
  }

  update(dt: number, worldSpeed: number): void {
    if (worldSpeed === 0) return;

    this.y += worldSpeed * this.speedFactor * dt;
    this.waddleTime += dt;

    if (this.canSwitchLanes) {
      this.switchCheckTimer += dt;
      if (this.switchCheckTimer >= this.nextSwitchCheck) {
        this.switchCheckTimer = 0;
        this.nextSwitchCheck = 2 + Math.random() * 2.5;

        if (Math.random() < 0.35) {
          const direction = Math.random() < 0.5 ? -1 : 1;
          const candidateLane = this.laneIndex + direction;
          if (candidateLane >= 0 && candidateLane <= 2) {
            this.laneIndex = candidateLane;
            this.targetX = this.laneX[this.laneIndex];
          }
        }
      }
    }
    this.x += (this.targetX - this.x) * 0.05;
  }

  isOffScreen(canvasHeight: number): boolean {
    return this.y - this.height > canvasHeight;
  }

  getBounds(): Bounds {
    const groundY = this.y + 4;
    const hitRadiusX = this.width * 0.35;
    const hitRadiusY = 12;
    return {
      left: this.x - hitRadiusX,
      right: this.x + hitRadiusX,
      top: groundY - hitRadiusY,
      bottom: groundY + hitRadiusY,
    };
  }

  draw(ctx: CanvasRenderingContext2D): void {
    const screenX = perspectiveX(this.x, this.y, PLAYER_ROW_Y);
    const scale = perspectiveScale(this.y, PLAYER_ROW_Y, 0.05);
    const waddleAngle = Math.sin(this.waddleTime * 7) * 0.22;
    const waddleSway = Math.sin(this.waddleTime * 7) * 3;

    ctx.save();
    ctx.translate(screenX + waddleSway, this.y);
    ctx.scale(scale, scale);
    ctx.translate(0, -this.height / 2);
    ctx.rotate(waddleAngle);

    ctx.fillStyle = "rgba(0,0,0,0.25)";
    ctx.beginPath();
    ctx.ellipse(
      0,
      this.height / 2 + 4,
      this.width * 0.35,
      6,
      0,
      0,
      Math.PI * 2
    );
    ctx.fill();

    const bodyGradient = ctx.createLinearGradient(
      0,
      -this.height / 2,
      0,
      this.height / 2
    );
    bodyGradient.addColorStop(0, "#ffffff");
    bodyGradient.addColorStop(1, "#d8d8ce");
    ctx.fillStyle = bodyGradient;
    ctx.beginPath();
    ctx.ellipse(0, 0, this.width / 2, this.height / 2, 0, 0, Math.PI * 2);
    ctx.fill();

    ctx.strokeStyle = "rgba(0,0,0,0.12)";
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(-this.width / 5, 0, this.height / 3, 0.3, Math.PI - 0.3);
    ctx.stroke();

    ctx.fillStyle = "#2b2b2b";
    ctx.beginPath();
    ctx.ellipse(0, -this.height / 2 - 8, 8, 14, 0, 0, Math.PI * 2);
    ctx.fill();

    ctx.fillStyle = "#f5a623";
    ctx.beginPath();
    ctx.moveTo(6, -this.height / 2 - 8);
    ctx.lineTo(18, -this.height / 2 - 5);
    ctx.lineTo(6, -this.height / 2 - 2);
    ctx.closePath();
    ctx.fill();

    ctx.restore();
  }
}

// ------------------------------------------------------------
// COFFEE
// ------------------------------------------------------------
class CoffeePowerUp {
  width = 30;
  height = 34;
  private bobTime = Math.random() * 10;

  constructor(
    public x: number,
    public y: number,
    private speedFactor: number
  ) {}

  update(dt: number, worldSpeed: number): void {
    if (worldSpeed === 0) return;
    this.y += worldSpeed * this.speedFactor * dt;
    this.bobTime += dt;
  }

  isOffScreen(canvasHeight: number): boolean {
    return this.y - this.height > canvasHeight;
  }

  getBounds(): Bounds {
    const groundY = this.y;
    const hitRadiusX = 15;
    const hitRadiusY = 12;
    return {
      left: this.x - hitRadiusX,
      right: this.x + hitRadiusX,
      top: groundY - hitRadiusY,
      bottom: groundY + hitRadiusY,
    };
  }

  draw(ctx: CanvasRenderingContext2D): void {
    const screenX = perspectiveX(this.x, this.y, PLAYER_ROW_Y);
    const scale = perspectiveScale(this.y, PLAYER_ROW_Y, 0.05);
    const bob = Math.sin(this.bobTime * 4) * 3;

    ctx.save();
    ctx.translate(screenX, this.y + bob);
    ctx.scale(scale, scale);
    ctx.translate(0, -12);

    const glow = ctx.createRadialGradient(0, 0, 2, 0, 0, 26);
    glow.addColorStop(0, "rgba(255,209,102,0.45)");
    glow.addColorStop(1, "rgba(255,209,102,0)");
    ctx.fillStyle = glow;
    ctx.fillRect(-26, -26, 52, 52);

    ctx.fillStyle = "#fff8ec";
    ctx.beginPath();
    ctx.moveTo(-10, -10);
    ctx.lineTo(10, -10);
    ctx.lineTo(7, 12);
    ctx.lineTo(-7, 12);
    ctx.closePath();
    ctx.fill();

    ctx.fillStyle = "#6f4a2f";
    ctx.fillRect(-9, -10, 18, 4);

    ctx.strokeStyle = "#fff8ec";
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.arc(12, -2, 6, -Math.PI / 2, Math.PI / 2);
    ctx.stroke();

    ctx.strokeStyle = "rgba(255,255,255,0.55)";
    ctx.lineWidth = 2;
    for (const dx of [-4, 4]) {
      ctx.beginPath();
      ctx.moveTo(dx, -14);
      ctx.quadraticCurveTo(
        dx + 4,
        -20 - Math.sin(this.bobTime * 3 + dx) * 2,
        dx,
        -26
      );
      ctx.stroke();
    }

    ctx.restore();
  }
}

// ------------------------------------------------------------
// MAIN ENGINE COMPONENT
// ------------------------------------------------------------
interface GooseRunEngineProps {
  onGameOver: (finalDistance: number) => void;
  difficulty: Difficulty;
}

function GooseRunEngine({ onGameOver, difficulty }: GooseRunEngineProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const distanceElRef = useRef<HTMLSpanElement | null>(null);
  const boostRef = useRef<HTMLSpanElement | null>(null);

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

    const LANE_X = [CANVAS_W * 0.25, CANVAS_W * 0.5, CANVAS_W * 0.75] as const;
    const SEASONS_LIST: Season[] = ["summer", "fall", "winter"];

    const mascotImg = new Image();
    mascotImg.src = "../../images/about-us.svg";

    const player = new Player(LANE_X, CANVAS_H, mascotImg);
    const background = new CampusBackground(CANVAS_W, CANVAS_H);

    let isDead = false;
    let deathTime = 0;

    function handleKeyDown(e: KeyboardEvent) {
      if (isDead) return;
      if (e.key === "ArrowLeft" || e.key.toLowerCase() === "a")
        player.moveLeft();
      else if (e.key === "ArrowRight" || e.key.toLowerCase() === "d")
        player.moveRight();
    }
    window.addEventListener("keydown", handleKeyDown);

    const settings = DIFFICULTY_SETTINGS[difficulty];

    let geese: Goose[] = [];
    let spawnTimer = 0;
    let spawnInterval = settings.spawnIntervalStart;

    let coffees: CoffeePowerUp[] = [];
    let coffeeSpawnTimer = 0;
    let coffeeSpawnInterval = 5 + Math.random() * 3;

    let sceneryItems: Scenery[] = [];
    let scenerySpawnTimer = 0;
    let scenerySpawnInterval = 0.2;

    let overlayParticles: OverlayParticle[] = [];
    let previousSeason: Season = "summer";

    function spawnGoose(forcedY?: number) {
      const laneIndex = Math.floor(Math.random() * 3);
      const x = LANE_X[laneIndex];
      const speedFactor =
        settings.gooseSpeedFactorBase +
        (Math.random() * 2 - 1) * settings.gooseSpeedFactorVariance;
      const spawnY = forcedY !== undefined ? forcedY : HORIZON_Y;
      geese.push(
        new Goose(
          x,
          spawnY,
          speedFactor,
          laneIndex,
          LANE_X,
          settings.geeseCanSwitchLanes
        )
      );
    }

    function spawnCoffee(forcedY?: number) {
      const laneIndex = Math.floor(Math.random() * 3);
      const spawnY = forcedY !== undefined ? forcedY : HORIZON_Y;
      coffees.push(new CoffeePowerUp(LANE_X[laneIndex], spawnY, 1));
    }

    function spawnScenery(forcedY?: number, overrideSeason?: Season) {
      const y = forcedY !== undefined ? forcedY : HORIZON_Y;
      const currentSeason = overrideSeason || SEASONS_LIST[0];

      if (Math.random() < 0.7) {
        let typeLeft: SceneryType = Math.random() < 0.2 ? "lamppost" : "tree";

        if (currentSeason === "winter" && typeLeft === "tree") {
          if (Math.random() < 0.15) typeLeft = "snowman";
          else if (Math.random() < 0.08) typeLeft = "candy_cane";
        } else if (currentSeason === "summer" && typeLeft === "tree") {
          if (Math.random() < 0.35) typeLeft = "flower";
        }

        const xPos = -20 - Math.random() * 400;
        sceneryItems.push(new Scenery(xPos, y, typeLeft));
      }

      if (Math.random() < 0.7) {
        let typeRight: SceneryType = Math.random() < 0.2 ? "lamppost" : "tree";

        if (currentSeason === "winter" && typeRight === "tree") {
          if (Math.random() < 0.15) typeRight = "snowman";
          else if (Math.random() < 0.08) typeRight = "candy_cane";
        } else if (currentSeason === "summer" && typeRight === "tree") {
          if (Math.random() < 0.35) typeRight = "flower";
        }

        const xPos = CANVAS_W + 20 + Math.random() * 400;
        sceneryItems.push(new Scenery(xPos, y, typeRight));
      }
    }

    const SPEED_BOOST_DURATION = 4;
    const SPEED_BOOST_MULTIPLIER = 1.6;
    let speedBoostRemaining = 0;

    let lastTime: number | null = null;
    let distance = 0;
    let animationFrameId = 0;

    if (distanceElRef.current) distanceElRef.current.textContent = "0m";
    if (boostRef.current) boostRef.current.textContent = "";

    function loop(timestampMs: number) {
      if (lastTime === null) lastTime = timestampMs;
      let dt = (timestampMs - lastTime) / 1000;
      lastTime = timestampMs;

      if (document.hidden) {
        animationFrameId = requestAnimationFrame(loop);
        return;
      }

      if (dt > 0.1) dt = 0.016;

      const currentSeason = SEASONS_LIST[Math.floor(distance / 150) % 3];

      if (currentSeason !== previousSeason) {
        for (const p of overlayParticles) p.startFade();
        previousSeason = currentSeason;
      }

      if (isDead) {
        deathTime += dt;
      } else {
        speedBoostRemaining = Math.max(0, speedBoostRemaining - dt);
      }

      const isBoosted = !isDead && speedBoostRemaining > 0;
      const speedMultiplier = isBoosted ? SPEED_BOOST_MULTIPLIER : 1;
      player.isBoosted = isBoosted;

      if (!isDead) {
        player.update(dt);
      }

      const dynamicBaseSpeed = Math.min(
        settings.baseRunSpeed + distance * 0.15,
        settings.maxRunSpeed
      );

      const worldSpeed = isDead ? 0 : dynamicBaseSpeed * speedMultiplier;
      background.update(dt, worldSpeed);

      if (!isDead) {
        distance += worldSpeed * dt * 0.05;
      }

      if (distanceElRef.current)
        distanceElRef.current.textContent = `${Math.floor(distance)}m`;
      if (boostRef.current)
        boostRef.current.textContent = isBoosted
          ? `☕️ ${speedBoostRemaining.toFixed(1)}s`
          : "";

      if (!isDead && currentSeason === "fall" && Math.random() < 0.015) {
        overlayParticles.push(new OverlayParticle(CANVAS_W, "leaf"));
      } else if (
        !isDead &&
        currentSeason === "winter" &&
        Math.random() < 0.25
      ) {
        overlayParticles.push(new OverlayParticle(CANVAS_W, "snow"));
      }

      if (!isDead) {
        spawnTimer += dt;
        spawnInterval = Math.max(
          settings.spawnIntervalFloor,
          settings.spawnIntervalStart - distance * 0.002
        );
        if (spawnTimer >= spawnInterval) {
          spawnTimer = 0;
          spawnGoose();
        }

        coffeeSpawnTimer += dt;
        if (coffeeSpawnTimer >= coffeeSpawnInterval) {
          coffeeSpawnTimer = 0;
          coffeeSpawnInterval = 5 + Math.random() * 3;
          spawnCoffee();
        }

        scenerySpawnTimer += dt;
        if (scenerySpawnTimer >= scenerySpawnInterval / speedMultiplier) {
          scenerySpawnTimer = 0;
          scenerySpawnInterval = 0.15 + Math.random() * 0.3;
          spawnScenery(undefined, currentSeason);
        }
      }

      for (const goose of geese) goose.update(dt, worldSpeed);
      geese = geese.filter((g) => !g.isOffScreen(CANVAS_H));

      for (const coffee of coffees) coffee.update(dt, worldSpeed);
      coffees = coffees.filter((c) => !c.isOffScreen(CANVAS_H));

      for (const scene of sceneryItems) scene.update(dt, worldSpeed);
      sceneryItems = sceneryItems.filter((s) => !s.isOffScreen(CANVAS_H));

      for (const p of overlayParticles) p.update(dt);
      overlayParticles = overlayParticles.filter(
        (p) => p.y < CANVAS_H + 20 && p.fadeTimer < 2.0
      );

      if (!isDead) {
        const playerBounds = player.getBounds();
        for (const goose of geese) {
          if (isColliding(playerBounds, goose.getBounds())) {
            isDead = true;
            onGameOver(distance);
            break;
          }
        }
      }

      if (!isDead) {
        coffees = coffees.filter((coffee) => {
          const collected = isColliding(player.getBounds(), coffee.getBounds());
          if (collected) speedBoostRemaining = SPEED_BOOST_DURATION;
          return !collected;
        });
      }

      ctx!.clearRect(0, 0, CANVAS_W, CANVAS_H);
      background.draw(ctx!, currentSeason);

      const renderables = [
        ...coffees.map((c) => ({
          y: c.y,
          draw: (ctx: CanvasRenderingContext2D) => c.draw(ctx),
        })),
        ...geese.map((g) => ({
          y: g.y,
          draw: (ctx: CanvasRenderingContext2D) => g.draw(ctx),
        })),
        ...sceneryItems.map((s) => ({
          y: s.y,
          draw: (ctx: CanvasRenderingContext2D) => s.draw(ctx, currentSeason),
        })),
        {
          y: player.y,
          draw: (ctx: CanvasRenderingContext2D) =>
            player.draw(ctx, isDead, deathTime),
        },
      ];

      renderables.sort((a, b) => a.y - b.y);
      renderables.forEach((r) => r.draw(ctx!));

      for (const p of overlayParticles) p.draw(ctx!);

      if (isBoosted && !isDead) {
        const pulse = Math.abs(Math.sin(speedBoostRemaining * 6));
        const alpha = 0.2 + pulse * 0.4;

        const screenGlow = ctx!.createRadialGradient(
          CANVAS_W / 2,
          CANVAS_H / 2,
          CANVAS_W * 0.3,
          CANVAS_W / 2,
          CANVAS_H / 2,
          CANVAS_H * 0.8
        );
        screenGlow.addColorStop(0, "rgba(255, 209, 102, 0)");
        screenGlow.addColorStop(1, `rgba(255, 209, 102, ${alpha})`);

        ctx!.fillStyle = screenGlow;
        ctx!.fillRect(0, 0, CANVAS_W, CANVAS_H);

        if (speedBoostRemaining > SPEED_BOOST_DURATION - 2) {
          ctx!.save();
          ctx!.textAlign = "center";
          ctx!.textBaseline = "middle";
          ctx!.font = "italic 900 42px 'Poppins', sans-serif";

          const timeActive = SPEED_BOOST_DURATION - speedBoostRemaining;
          const textScale = Math.min(1, timeActive * 5);

          ctx!.translate(CANVAS_W / 2, CANVAS_H / 2 - 60);
          ctx!.scale(textScale, textScale);

          const grad = ctx!.createLinearGradient(-100, 0, 100, 0);
          grad.addColorStop(0, "#ff007a");
          grad.addColorStop(0.5, "#ffea00");
          grad.addColorStop(1, "#00e5ff");

          ctx!.fillStyle = grad;
          ctx!.lineWidth = 2;
          ctx!.strokeStyle = "#000";

          ctx!.shadowColor = "rgba(0,0,0,0.8)";
          ctx!.shadowBlur = 12;
          ctx!.shadowOffsetY = 4;

          ctx!.fillText("COFFEE RUSH!", 0, 0);
          ctx!.strokeText("COFFEE RUSH!", 0, 0);

          ctx!.restore();
        }
      }

      animationFrameId = requestAnimationFrame(loop);
    }

    animationFrameId = requestAnimationFrame(loop);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      cancelAnimationFrame(animationFrameId);
    };
  }, [onGameOver, difficulty]);

  return (
    <>
      <canvas
        ref={canvasRef}
        width={CANVAS_W}
        height={CANVAS_H}
        className={styles.canvas}
      />
      <div className={styles.hud}>
        <span ref={distanceElRef}>0m</span>
        <span ref={boostRef}></span>
      </div>
    </>
  );
}

const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];

export function GooseRun() {
  const [resetKey, setResetKey] = useState(0);
  const [difficulty, setDifficulty] = useState<Difficulty>("medium");
  const [isGameOver, setIsGameOver] = useState(false);
  const [finalDistance, setFinalDistance] = useState(0);

  const handleGameOver = useCallback((distance: number) => {
    setFinalDistance(distance);
    setIsGameOver(true);
  }, []);

  function handleRestart() {
    setIsGameOver(false);
    setResetKey((k) => k + 1);
  }

  function handleSelectDifficulty(next: Difficulty) {
    setDifficulty(next);
    setIsGameOver(false);
    setResetKey((k) => k + 1);
  }

  return (
    <section className={styles.game}>
      <div className={styles.boardWrap}>
        <GooseRunEngine
          key={`${resetKey}-${difficulty}`}
          onGameOver={handleGameOver}
          difficulty={difficulty}
        />

        {isGameOver && (
          <div className={styles.gameOverOverlay}>
            <p className={styles.gameOverTitle}>Honked out!</p>
            <p className={styles.gameOverDistance}>
              {Math.floor(finalDistance)}m to the exam
            </p>
            <button className={styles.retryButton} onClick={handleRestart}>
              Try Again
            </button>
          </div>
        )}
      </div>

      <aside className={styles.sidebar}>
        <div className={styles.panel}>
          <p className={styles.score}>Goose Run</p>

          <div
            className={styles.difficultyRow}
            role="group"
            aria-label="Difficulty"
          >
            {DIFFICULTIES.map((level) => (
              <button
                key={level}
                type="button"
                className={
                  level === difficulty
                    ? `${styles.difficultyButton} ${styles.difficultyButtonActive}`
                    : styles.difficultyButton
                }
                onClick={() => handleSelectDifficulty(level)}
                aria-pressed={level === difficulty}
                disabled={level === difficulty}
              >
                {level[0].toUpperCase() + level.slice(1)}
              </button>
            ))}
          </div>

          <p className={styles.status}>
            Dodge the geese on your way to your final exam.
            <br />
            <br />
            <kbd>←</kbd> / <kbd>A</kbd> and <kbd>→</kbd> / <kbd>D</kbd> to
            switch lanes.
            {difficulty === "hard" && (
              <>
                <br />
                <br />
                Watch out, geese can now change lanes!
              </>
            )}
          </p>
        </div>
      </aside>
    </section>
  );
}
