Skip to content
VibeCodeBench
Back to the app

The code

Night Courier by Gemini 4 Argon

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)92.4 KB · 2,914 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Sunset Fish Courier — Cat Pilot Flying Game</title>
<style>
  * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
  }
  html, body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: #1a0f24;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    touch-action: none;
  }
  #game-canvas {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    display: block;
    cursor: crosshair;
  }

  /* HUD Layout */
  #hud {
    position: fixed;
    inset: 0;
    pointer-events: none;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 12px 16px 18px;
    z-index: 10;
  }

  .top-bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }

  .hud-group {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
  }

  .hud-card {
    background: rgba(24, 14, 32, 0.76);
    border: 2px solid rgba(255, 190, 105, 0.55);
    border-radius: 16px;
    padding: 8px 14px;
    color: #fff6e8;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.18);
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
    display: flex;
    align-items: center;
    gap: 10px;
    min-width: 120px;
  }

  .hud-icon {
    width: 32px;
    height: 32px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 162, 66, 0.22);
    border-radius: 10px;
    font-size: 18px;
  }

  .hud-label {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: #ffc98b;
    font-weight: 700;
  }

  .hud-value {
    font-size: 22px;
    font-weight: 800;
    line-height: 1.1;
    color: #ffffff;
    font-variant-numeric: tabular-nums;
    transition: transform 0.18s ease;
  }

  .hud-value.pulse {
    transform: scale(1.22);
    color: #ffe066;
  }

  .sunset-card {
    min-width: 170px;
  }

  .sunset-bar-wrap {
    width: 105px;
    height: 10px;
    background: rgba(255, 255, 255, 0.14);
    border-radius: 999px;
    overflow: hidden;
    margin-top: 4px;
    border: 1px solid rgba(255, 200, 130, 0.35);
  }

  .sunset-bar-fill {
    height: 100%;
    width: 100%;
    background: linear-gradient(90deg, #ff5e4d 0%, #ffad42 60%, #ffe680 100%);
    border-radius: 999px;
    transition: width 0.2s linear;
  }

  .sound-btn {
    pointer-events: auto;
    background: rgba(24, 14, 32, 0.78);
    border: 2px solid rgba(255, 190, 105, 0.55);
    color: #fff6e8;
    width: 48px;
    height: 48px;
    border-radius: 16px;
    font-size: 20px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
    transition: transform 0.12s ease, background 0.15s ease;
  }
  .sound-btn:active {
    transform: scale(0.93);
  }

  /* Demo Banner & Toast Messages */
  .center-hud {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    pointer-events: none;
  }

  #demo-banner {
    display: none;
    background: linear-gradient(135deg, rgba(255, 130, 46, 0.92), rgba(214, 58, 92, 0.92));
    color: #fff;
    padding: 8px 18px;
    border-radius: 999px;
    font-weight: 800;
    font-size: 13px;
    letter-spacing: 0.04em;
    border: 2px solid rgba(255, 238, 190, 0.85);
    box-shadow: 0 6px 22px rgba(0, 0, 0, 0.4);
    text-align: center;
    animation: demoPulse 1.8s infinite ease-in-out;
  }
  @keyframes demoPulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.04); }
  }

  #toast-msg {
    background: rgba(20, 14, 30, 0.82);
    border: 1.5px solid rgba(255, 208, 120, 0.75);
    color: #ffefc6;
    padding: 8px 18px;
    border-radius: 999px;
    font-weight: 700;
    font-size: 14px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35);
    opacity: 0;
    transform: translateY(-8px);
    transition: opacity 0.25s ease, transform 0.25s ease;
    text-align: center;
    max-width: 92vw;
  }
  #toast-msg.visible {
    opacity: 1;
    transform: translateY(0);
  }

  /* Bottom Camera Buttons Bar */
  .bottom-bar {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }

  .steer-hint {
    color: rgba(255, 240, 214, 0.88);
    font-size: 12px;
    font-weight: 600;
    text-shadow: 0 2px 6px rgba(0, 0, 0, 0.75);
    background: rgba(20, 12, 28, 0.5);
    padding: 4px 12px;
    border-radius: 999px;
  }

  .camera-bar {
    pointer-events: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: rgba(20, 12, 30, 0.82);
    padding: 6px;
    border-radius: 20px;
    border: 2px solid rgba(255, 186, 100, 0.5);
    box-shadow: 0 8px 26px rgba(0, 0, 0, 0.45);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    max-width: 100%;
  }

  .cam-btn {
    appearance: none;
    border: 2px solid transparent;
    background: rgba(255, 255, 255, 0.08);
    color: #ffe7c7;
    padding: 11px 16px;
    min-height: 48px;
    border-radius: 14px;
    font-size: 14px;
    font-weight: 800;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 7px;
    transition: background 0.15s ease, transform 0.1s ease, border-color 0.15s ease;
    white-space: nowrap;
  }
  .cam-btn:active {
    transform: scale(0.95);
  }
  .cam-btn.active {
    background: linear-gradient(135deg, #ff9933 0%, #e8532e 100%);
    color: #ffffff;
    border-color: #ffe5a3;
    box-shadow: 0 4px 14px rgba(232, 83, 46, 0.55);
  }

  /* Directional Ring Indicator on screen edges */
  #ring-pointer {
    position: fixed;
    width: 44px;
    height: 44px;
    margin-left: -22px;
    margin-top: -22px;
    pointer-events: none;
    z-index: 9;
    display: none;
    align-items: center;
    justify-content: center;
    filter: drop-shadow(0 2px 8px rgba(0,0,0,0.6));
  }

  /* Steering Reticle */
  #reticle {
    position: fixed;
    width: 34px;
    height: 34px;
    margin-left: -17px;
    margin-top: -17px;
    border: 2px solid rgba(255, 224, 140, 0.65);
    border-radius: 50%;
    pointer-events: none;
    z-index: 8;
    display: none;
    box-shadow: 0 0 12px rgba(255, 175, 70, 0.45);
  }
  #reticle::after {
    content: "";
    position: absolute;
    left: 50%;
    top: 50%;
    width: 6px;
    height: 6px;
    margin-left: -3px;
    margin-top: -3px;
    background: #ffd166;
    border-radius: 50%;
  }

  /* End Game Modal */
  #end-modal {
    position: fixed;
    inset: 0;
    background: rgba(14, 8, 24, 0.78);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    z-index: 30;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }
  #end-modal.open {
    display: flex;
  }

  .modal-card {
    background: linear-gradient(165deg, #2b1838 0%, #191026 100%);
    border: 3px solid #ffb35c;
    border-radius: 26px;
    padding: 26px 24px;
    max-width: 420px;
    width: 100%;
    color: #fff6e8;
    text-align: center;
    box-shadow: 0 20px 55px rgba(0, 0, 0, 0.65);
    animation: popIn 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
  }
  @keyframes popIn {
    from { transform: scale(0.86); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
  }

  .modal-badge {
    width: 68px;
    height: 68px;
    margin: 0 auto 12px;
    border-radius: 22px;
    background: rgba(255, 164, 72, 0.2);
    border: 2px solid rgba(255, 195, 115, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36px;
  }

  .modal-title {
    font-size: 26px;
    font-weight: 900;
    color: #ffd584;
    margin-bottom: 6px;
  }

  .modal-sub {
    font-size: 14px;
    color: #e6cbb0;
    margin-bottom: 18px;
    line-height: 1.45;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    margin-bottom: 20px;
  }

  .stat-box {
    background: rgba(255, 255, 255, 0.06);
    border: 1px solid rgba(255, 198, 130, 0.3);
    border-radius: 14px;
    padding: 10px 8px;
  }
  .stat-box .lbl {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.07em;
    color: #ffc685;
    font-weight: 700;
  }
  .stat-box .val {
    font-size: 22px;
    font-weight: 800;
    color: #ffffff;
    margin-top: 2px;
  }

  .play-again-btn {
    appearance: none;
    width: 100%;
    min-height: 56px;
    border: 2px solid #ffe9ad;
    border-radius: 16px;
    background: linear-gradient(135deg, #ff9e36 0%, #e84e2c 100%);
    color: #ffffff;
    font-size: 18px;
    font-weight: 900;
    letter-spacing: 0.03em;
    cursor: pointer;
    box-shadow: 0 8px 24px rgba(232, 78, 44, 0.55);
    transition: transform 0.12s ease;
  }
  .play-again-btn:active {
    transform: scale(0.96);
  }

  @media (max-width: 600px) {
    #hud {
      padding: 10px 10px 14px;
    }
    .hud-card {
      padding: 6px 10px;
      min-width: 96px;
      border-radius: 13px;
    }
    .hud-icon {
      width: 26px;
      height: 26px;
      font-size: 15px;
    }
    .hud-value {
      font-size: 18px;
    }
    .sunset-card {
      min-width: 135px;
    }
    .sunset-bar-wrap {
      width: 78px;
    }
    .cam-btn {
      padding: 10px 11px;
      font-size: 12.5px;
      min-height: 46px;
    }
  }
</style>
</head>
<body>

<canvas id="game-canvas"></canvas>

<div id="reticle"></div>

<div id="ring-pointer" aria-hidden="true">
  <svg width="44" height="44" viewBox="0 0 44 44">
    <circle cx="22" cy="22" r="16" fill="rgba(26,16,38,0.8)" stroke="#ffbe55" stroke-width="2.5"/>
    <path id="ring-pointer-arrow" d="M22 4 L30 16 L14 16 Z" fill="#ffe066"/>
    <circle cx="22" cy="22" r="6" fill="none" stroke="#5ce1e6" stroke-width="2"/>
  </svg>
</div>

<div id="hud">
  <div class="top-bar">
    <div class="hud-group">
      <div class="hud-card" aria-label="Score">
        <div class="hud-icon">⭐</div>
        <div>
          <div class="hud-label">Score</div>
          <div class="hud-value" id="score-val">0</div>
        </div>
      </div>

      <div class="hud-card" aria-label="Crates Left">
        <div class="hud-icon">🐟</div>
        <div>
          <div class="hud-label">Crates Left</div>
          <div class="hud-value" id="crates-val">8</div>
        </div>
      </div>

      <div class="hud-card sunset-card" aria-label="Sunset Daylight Remaining">
        <div class="hud-icon" id="sun-icon">🌅</div>
        <div>
          <div class="hud-label">Before Night <span id="time-val" style="color:#fff;margin-left:4px;">1:30</span></div>
          <div class="sunset-bar-wrap">
            <div class="sunset-bar-fill" id="sunset-bar"></div>
          </div>
        </div>
      </div>
    </div>

    <button class="sound-btn" id="sound-btn" title="Toggle Sound" aria-label="Toggle Sound">🔊</button>
  </div>

  <div class="center-hud">
    <div id="demo-banner">DEMO FLIGHT — Touch or Click Anywhere to Steer</div>
    <div id="toast-msg">Fly through glowing rings to drop fish crates to waiting cats!</div>
  </div>

  <div class="bottom-bar">
    <div class="steer-hint" id="steer-hint">Move mouse or drag one finger to steer through the glowing rings</div>
    <div class="camera-bar" role="group" aria-label="Camera View">
      <button class="cam-btn active" id="cam-behind" data-cam="behind">
        <span>✈️</span><span>Behind Plane</span>
      </button>
      <button class="cam-btn" id="cam-cockpit" data-cam="cockpit">
        <span>🐱</span><span>Inside Cockpit</span>
      </button>
      <button class="cam-btn" id="cam-above" data-cam="above">
        <span>🦅</span><span>From Above</span>
      </button>
    </div>
  </div>
</div>

<div id="end-modal" role="dialog" aria-modal="true" aria-labelledby="modal-title">
  <div class="modal-card">
    <div class="modal-badge" id="modal-badge">🐟</div>
    <div class="modal-title" id="modal-title">All Fish Delivered!</div>
    <div class="modal-sub" id="modal-sub">Every lakeside cat got their sunset fish dinner before night fell!</div>
    <div class="stats-grid">
      <div class="stat-box">
        <div class="lbl">Final Score</div>
        <div class="val" id="end-score">0</div>
      </div>
      <div class="stat-box">
        <div class="lbl">Crates Left</div>
        <div class="val" id="end-crates-left">0</div>
      </div>
      <div class="stat-box">
        <div class="lbl">Delivered</div>
        <div class="val" id="end-delivered">8 / 8</div>
      </div>
      <div class="stat-box">
        <div class="lbl">Best Score</div>
        <div class="val" id="end-best">0</div>
      </div>
    </div>
    <button class="play-again-btn" id="play-again-btn">Play Again</button>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function () {
  "use strict";

  // --- Safe Math & Storage Helpers ---
  function clamp(v, min, max) {
    return v < min ? min : (v > max ? max : v);
  }
  function lerp(a, b, t) {
    return a + (b - a) * t;
  }
  function damp(a, b, lambda, dt) {
    return lerp(a, b, 1 - Math.exp(-lambda * dt));
  }

  function loadBestScore() {
    try {
      const val = parseInt(localStorage.getItem("sunset_cat_courier_best") || "0", 10);
      return isNaN(val) ? 0 : val;
    } catch (e) {
      return 0;
    }
  }
  function saveBestScore(score) {
    try {
      const prev = loadBestScore();
      if (score > prev) {
        localStorage.setItem("sunset_cat_courier_best", String(score));
        return score;
      }
      return prev;
    } catch (e) {
      return score;
    }
  }

  // --- Synthesized Web Audio System ---
  const Sound = {
    ctx: null,
    muted: false,
    propGain: null,
    propOsc1: null,
    propOsc2: null,
    started: false,

    init: function () {
      if (this.started) return;
      try {
        const AudioCtx = window.AudioContext || window.webkitAudioContext;
        if (!AudioCtx) return;
        this.ctx = new AudioCtx();

        // Warm low propeller purr
        const filter = this.ctx.createBiquadFilter();
        filter.type = "lowpass";
        filter.frequency.value = 145;

        this.propGain = this.ctx.createGain();
        this.propGain.gain.value = this.muted ? 0 : 0.04;

        this.propOsc1 = this.ctx.createOscillator();
        this.propOsc1.type = "sawtooth";
        this.propOsc1.frequency.value = 54;

        this.propOsc2 = this.ctx.createOscillator();
        this.propOsc2.type = "triangle";
        this.propOsc2.frequency.value = 108;

        this.propOsc1.connect(filter);
        this.propOsc2.connect(filter);
        filter.connect(this.propGain);
        this.propGain.connect(this.ctx.destination);

        this.propOsc1.start();
        this.propOsc2.start();
        this.started = true;
      } catch (e) {}
    },

    resume: function () {
      try {
        if (!this.started) this.init();
        if (this.ctx && this.ctx.state === "suspended") {
          this.ctx.resume();
        }
      } catch (e) {}
    },

    updateProp: function (speedFactor) {
      if (!this.started || !this.ctx) return;
      try {
        const now = this.ctx.currentTime;
        const targetGain = this.muted ? 0 : 0.038;
        this.propGain.gain.setTargetAtTime(targetGain, now, 0.08);
        this.propOsc1.frequency.setTargetAtTime(50 + speedFactor * 16, now, 0.08);
        this.propOsc2.frequency.setTargetAtTime(100 + speedFactor * 32, now, 0.08);
      } catch (e) {}
    },

    playRingChime: function () {
      if (this.muted) return;
      this.resume();
      if (!this.ctx) return;
      try {
        const notes = [523.25, 659.25, 783.99, 1046.5];
        notes.forEach((freq, idx) => {
          const osc = this.ctx.createOscillator();
          const gain = this.ctx.createGain();
          osc.type = "triangle";
          osc.frequency.value = freq;
          const t0 = this.ctx.currentTime + idx * 0.065;
          gain.gain.setValueAtTime(0.001, t0);
          gain.gain.linearRampToValueAtTime(0.11, t0 + 0.02);
          gain.gain.exponentialRampToValueAtTime(0.001, t0 + 0.42);
          osc.connect(gain);
          gain.connect(this.ctx.destination);
          osc.start(t0);
          osc.stop(t0 + 0.45);
        });
      } catch (e) {}
    },

    playCatLanding: function () {
      if (this.muted) return;
      this.resume();
      if (!this.ctx) return;
      try {
        const t0 = this.ctx.currentTime;
        // Cute cat meow pitch envelope
        const osc = this.ctx.createOscillator();
        const gain = this.ctx.createGain();
        osc.type = "sine";
        osc.frequency.setValueAtTime(520, t0);
        osc.frequency.exponentialRampToValueAtTime(860, t0 + 0.14);
        osc.frequency.exponentialRampToValueAtTime(480, t0 + 0.36);

        gain.gain.setValueAtTime(0.001, t0);
        gain.gain.linearRampToValueAtTime(0.12, t0 + 0.05);
        gain.gain.exponentialRampToValueAtTime(0.001, t0 + 0.38);

        osc.connect(gain);
        gain.connect(this.ctx.destination);
        osc.start(t0);
        osc.stop(t0 + 0.4);
      } catch (e) {}
    },

    playFanfare: function (victory) {
      if (this.muted) return;
      this.resume();
      if (!this.ctx) return;
      try {
        const notes = victory
          ? [523.25, 659.25, 783.99, 1046.5, 1318.5]
          : [440, 392, 349.23, 329.63];
        notes.forEach((freq, i) => {
          const osc = this.ctx.createOscillator();
          const gain = this.ctx.createGain();
          osc.type = "triangle";
          osc.frequency.value = freq;
          const t0 = this.ctx.currentTime + i * 0.11;
          gain.gain.setValueAtTime(0.001, t0);
          gain.gain.linearRampToValueAtTime(0.12, t0 + 0.03);
          gain.gain.exponentialRampToValueAtTime(0.001, t0 + 0.55);
          osc.connect(gain);
          gain.connect(this.ctx.destination);
          osc.start(t0);
          osc.stop(t0 + 0.58);
        });
      } catch (e) {}
    }
  };

  // --- UI References ---
  const canvas = document.getElementById("game-canvas");
  const scoreEl = document.getElementById("score-val");
  const cratesEl = document.getElementById("crates-val");
  const timeEl = document.getElementById("time-val");
  const sunsetBarEl = document.getElementById("sunset-bar");
  const sunIconEl = document.getElementById("sun-icon");
  const toastEl = document.getElementById("toast-msg");
  const demoBannerEl = document.getElementById("demo-banner");
  const reticleEl = document.getElementById("reticle");
  const ringPointerEl = document.getElementById("ring-pointer");
  const ringPointerArrow = document.getElementById("ring-pointer-arrow");
  const endModalEl = document.getElementById("end-modal");
  const modalBadgeEl = document.getElementById("modal-badge");
  const modalTitleEl = document.getElementById("modal-title");
  const modalSubEl = document.getElementById("modal-sub");
  const endScoreEl = document.getElementById("end-score");
  const endCratesLeftEl = document.getElementById("end-crates-left");
  const endDeliveredEl = document.getElementById("end-delivered");
  const endBestEl = document.getElementById("end-best");
  const playAgainBtn = document.getElementById("play-again-btn");
  const soundBtn = document.getElementById("sound-btn");
  const camButtons = [
    document.getElementById("cam-behind"),
    document.getElementById("cam-cockpit"),
    document.getElementById("cam-above")
  ];

  let toastTimer = null;
  function showToast(text, durationMs) {
    toastEl.textContent = text;
    toastEl.classList.add("visible");
    if (toastTimer) clearTimeout(toastTimer);
    toastTimer = setTimeout(() => {
      toastEl.classList.remove("visible");
    }, durationMs || 3200);
  }

  // --- Three.js Scene Setup ---
  const renderer = new THREE.WebGLRenderer({
    canvas: canvas,
    antialias: true,
    powerPreference: "high-performance"
  });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.outputEncoding = THREE.sRGBEncoding;

  const scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0xd87b56, 0.0014);

  const camera = new THREE.PerspectiveCamera(
    60,
    window.innerWidth / window.innerHeight,
    0.4,
    1400
  );

  // Planar Reflection Camera & RenderTarget for Lake Reflections
  const reflectRT = new THREE.WebGLRenderTarget(512, 512, {
    minFilter: THREE.LinearFilter,
    magFilter: THREE.LinearFilter,
    format: THREE.RGBAFormat
  });
  const reflectCamera = camera.clone();
  const reflectMatrix = new THREE.Matrix4();

  // --- Lighting (Warm Sunset to Twilight Progression) ---
  const hemiLight = new THREE.HemisphereLight(0xffb56b, 0x3d4e5d, 0.85);
  hemiLight.position.set(0, 120, 0);
  scene.add(hemiLight);

  const sunLight = new THREE.DirectionalLight(0xff9b42, 1.35);
  sunLight.position.set(-220, 95, -280);
  sunLight.castShadow = true;
  sunLight.shadow.mapSize.width = 1024;
  sunLight.shadow.mapSize.height = 1024;
  sunLight.shadow.camera.near = 20;
  sunLight.shadow.camera.far = 750;
  const dShadow = 210;
  sunLight.shadow.camera.left = -dShadow;
  sunLight.shadow.camera.right = dShadow;
  sunLight.shadow.camera.top = dShadow;
  sunLight.shadow.camera.bottom = -dShadow;
  scene.add(sunLight);

  const warmFillLight = new THREE.DirectionalLight(0xff6b4a, 0.45);
  warmFillLight.position.set(150, 40, 200);
  scene.add(warmFillLight);

  // --- Custom Sunset & Twilight Sky Dome Shader ---
  const skyUniforms = {
    uSunDir: { value: new THREE.Vector3(-0.58, 0.22, -0.78).normalize() },
    uNightFactor: { value: 0.0 },
    uTime: { value: 0.0 }
  };

  const skyGeo = new THREE.SphereGeometry(900, 36, 24);
  const skyMat = new THREE.ShaderMaterial({
    side: THREE.BackSide,
    depthWrite: false,
    uniforms: skyUniforms,
    vertexShader: `
      varying vec3 vWorldDir;
      void main() {
        vec4 wp = modelMatrix * vec4(position, 1.0);
        vWorldDir = normalize(wp.xyz);
        gl_Position = projectionMatrix * viewMatrix * wp;
      }
    `,
    fragmentShader: `
      uniform vec3 uSunDir;
      uniform float uNightFactor;
      uniform float uTime;
      varying vec3 vWorldDir;

      float hash(vec3 p) {
        p = fract(p * 0.3183099 + 0.1);
        p *= 17.0;
        return fract(p.x * p.y * p.z * (p.x + p.y + p.z));
      }

      void main() {
        vec3 dir = normalize(vWorldDir);
        float y = clamp(dir.y, 0.0, 1.0);

        // Sunset palette vs night palette
        vec3 zenithSunset = vec3(0.20, 0.14, 0.38);
        vec3 midSunset    = vec3(0.76, 0.31, 0.36);
        vec3 horizSunset  = vec3(1.00, 0.65, 0.30);

        vec3 zenithNight  = vec3(0.03, 0.04, 0.11);
        vec3 midNight     = vec3(0.08, 0.10, 0.24);
        vec3 horizNight   = vec3(0.20, 0.16, 0.32);

        vec3 zenith = mix(zenithSunset, zenithNight, uNightFactor);
        vec3 mid    = mix(midSunset, midNight, uNightFactor);
        vec3 horiz  = mix(horizSunset, horizNight, uNightFactor);

        vec3 col = mix(horiz, mid, smoothstep(0.0, 0.26, y));
        col = mix(col, zenith, smoothstep(0.22, 0.85, y));

        // Warm sunset directional glow & sun disc
        float sunAmt = max(dot(dir, uSunDir), 0.0);
        vec3 sunGlowCol = mix(vec3(1.0, 0.58, 0.22), vec3(0.85, 0.25, 0.32), uNightFactor);
        col += sunGlowCol * pow(sunAmt, 5.0) * (0.65 * (1.0 - uNightFactor * 0.75));
        col += vec3(1.0, 0.88, 0.62) * pow(sunAmt, 36.0) * (0.9 * (1.0 - uNightFactor * 0.85));

        // Crispy sun disc
        float sunDisc = smoothstep(0.9968, 0.9985, sunAmt);
        col = mix(col, vec3(1.0, 0.96, 0.84), sunDisc * (1.0 - uNightFactor * 0.8));

        // Twinkling stars emerge as twilight deepens
        if (y > 0.05 && uNightFactor > 0.15) {
          vec3 starCell = floor(dir * 260.0);
          float h = hash(starCell);
          if (h > 0.992) {
            float twinkle = 0.65 + 0.35 * sin(uTime * 3.5 + h * 100.0);
            float starAlpha = smoothstep(0.15, 0.85, uNightFactor) * smoothstep(0.05, 0.35, y);
            col += vec3(0.95, 0.96, 1.0) * twinkle * starAlpha;
          }
        }

        gl_FragColor = vec4(col, 1.0);
      }
    `
  });
  const skyMesh = new THREE.Mesh(skyGeo, skyMat);
  scene.add(skyMesh);

  // --- Lake Water Surface with Real-Time Planar Reflections & Sunset Ripples ---
  const waterUniforms = {
    uReflectTex: { value: reflectRT.texture },
    uReflectMatrix: { value: reflectMatrix },
    uTime: { value: 0.0 },
    uSunDir: { value: skyUniforms.uSunDir.value },
    uNightFactor: { value: 0.0 },
    uCameraPos: { value: new THREE.Vector3() }
  };

  const waterGeo = new THREE.CircleGeometry(560, 64);
  waterGeo.rotateX(-Math.PI / 2);

  const waterMat = new THREE.ShaderMaterial({
    uniforms: waterUniforms,
    vertexShader: `
      uniform mat4 uReflectMatrix;
      varying vec4 vReflectCoord;
      varying vec3 vWorldPos;
      void main() {
        vec4 worldPosition = modelMatrix * vec4(position, 1.0);
        vWorldPos = worldPosition.xyz;
        vReflectCoord = uReflectMatrix * worldPosition;
        gl_Position = projectionMatrix * viewMatrix * worldPosition;
      }
    `,
    fragmentShader: `
      uniform sampler2D uReflectTex;
      uniform float uTime;
      uniform vec3 uSunDir;
      uniform float uNightFactor;
      uniform vec3 uCameraPos;

      varying vec4 vReflectCoord;
      varying vec3 vWorldPos;

      void main() {
        // Multi-layered procedural lake ripples
        vec2 p = vWorldPos.xz * 0.14;
        float w1 = sin(p.x * 1.7 + uTime * 1.8) * cos(p.y * 1.5 + uTime * 1.4);
        float w2 = sin((p.x + p.y) * 2.9 - uTime * 2.3) * 0.5;
        float w3 = cos(p.x * 4.3 - p.y * 3.8 + uTime * 2.9) * 0.25;
        vec2 ripple = vec2(w1 + w2, w2 + w3) * 0.022;

        vec3 N = normalize(vec3(ripple.x * 3.4, 1.0, ripple.y * 3.4));
        vec3 V = normalize(uCameraPos - vWorldPos);
        float NoV = clamp(dot(N, V), 0.0, 1.0);
        float fresnel = mix(0.28, 0.92, pow(1.0 - NoV, 3.0));

        // Sample planar reflection texture with ripple distortion
        vec3 reflCol = mix(vec3(0.88, 0.48, 0.30), vec3(0.10, 0.12, 0.25), uNightFactor);
        if (vReflectCoord.w > 0.0) {
          vec2 projUV = (vReflectCoord.xy / vReflectCoord.w) * 0.5 + 0.5;
          vec2 sampleUV = clamp(projUV + ripple * 0.85, 0.004, 0.996);
          vec3 texCol = texture2D(uReflectTex, sampleUV).rgb;
          float edgeFade = smoothstep(0.0, 0.08, projUV.x) * smoothstep(1.0, 0.92, projUV.x) *
                           smoothstep(0.0, 0.08, projUV.y) * smoothstep(1.0, 0.92, projUV.y);
          reflCol = mix(reflCol, texCol, edgeFade);
        }

        // Deep lake water base tint
        vec3 deepWater = mix(vec3(0.09, 0.24, 0.32), vec3(0.03, 0.07, 0.14), uNightFactor);
        vec3 waterCol = mix(deepWater, reflCol, fresnel);

        // Sparkling golden sunset reflection path on the water
        vec3 R = reflect(-V, N);
        float sunSpec = max(dot(R, normalize(uSunDir)), 0.0);
        vec3 specTint = mix(vec3(1.0, 0.72, 0.34), vec3(0.55, 0.45, 0.85), uNightFactor);
        waterCol += specTint * (pow(sunSpec, 28.0) * 0.55 + pow(sunSpec, 140.0) * 1.15) * (1.0 - uNightFactor * 0.65);

        gl_FragColor = vec4(waterCol, 1.0);
      }
    `
  });

  const waterMesh = new THREE.Mesh(waterGeo, waterMat);
  waterMesh.position.y = 0;
  scene.add(waterMesh);

  // --- Procedural Terrain: Lake Basin, Rolling Hills & Islands (All y >= 0) ---
  function getShoreRadius(angle) {
    return 145 +
      16 * Math.sin(angle * 2.0 + 0.4) +
      11 * Math.cos(angle * 3.0 - 0.8) +
      7 * Math.sin(angle * 5.0);
  }

  function getTerrainHeight(x, z) {
    const r = Math.hypot(x, z);
    const angle = Math.atan2(z, x);

    // Two scenic islands inside the lake
    const dIsland1 = Math.hypot(x - 115, z - 10);
    if (dIsland1 < 26) {
      const t = 1 - dIsland1 / 26;
      return Math.max(0, t * t * 7.5);
    }
    const dIsland2 = Math.hypot(x + 110, z + 15);
    if (dIsland2 < 25) {
      const t = 1 - dIsland2 / 25;
      return Math.max(0, t * t * 7.0);
    }

    const shore = getShoreRadius(angle);
    if (r <= shore) return 0;

    const distFromShore = r - shore;
    const gentleSlope = Math.min(1, distFromShore / 55);
    const hillWave =
      Math.sin(x * 0.018 + z * 0.014) * 16 +
      Math.cos(x * 0.027 - z * 0.022) * 12 +
      Math.sin(angle * 6.0) * 8;

    const ridge = Math.pow(clamp(distFromShore / 260, 0, 1.4), 1.55) * 88;
    const h = gentleSlope * 9 + ridge + gentleSlope * Math.max(-4, hillWave);
    return Math.max(0, h);
  }

  function buildHillsAndIslands() {
    const group = new THREE.Group();

    // Radial surrounding hills mesh
    const radialSegs = 52;
    const angularSegs = 108;
    const minR = 115;
    const maxR = 540;

    const positions = [];
    const colors = [];
    const indices = [];

    const cSand = new THREE.Color(0xe6c387);
    const cGrassLow = new THREE.Color(0x5e8a45);
    const cGrassHigh = new THREE.Color(0x889242);
    const cAutumnHill = new THREE.Color(0xa6693d);
    const cPeak = new THREE.Color(0x7c545b);
    const tmpCol = new THREE.Color();

    for (let i = 0; i <= radialSegs; i++) {
      const v = i / radialSegs;
      const r = lerp(minR, maxR, Math.pow(v, 1.15));
      for (let j = 0; j <= angularSegs; j++) {
        const theta = (j / angularSegs) * Math.PI * 2;
        const x = Math.cos(theta) * r;
        const z = Math.sin(theta) * r;
        const y = getTerrainHeight(x, z);

        positions.push(x, y, z);

        if (y < 0.35) {
          tmpCol.copy(cSand);
        } else if (y < 3.0) {
          tmpCol.copy(cSand).lerp(cGrassLow, (y - 0.35) / 2.65);
        } else if (y < 22.0) {
          tmpCol.copy(cGrassLow).lerp(cGrassHigh, (y - 3.0) / 19.0);
        } else if (y < 52.0) {
          tmpCol.copy(cGrassHigh).lerp(cAutumnHill, (y - 22.0) / 30.0);
        } else {
          tmpCol.copy(cAutumnHill).lerp(cPeak, clamp((y - 52.0) / 45.0, 0, 1));
        }
        colors.push(tmpCol.r, tmpCol.g, tmpCol.b);
      }
    }

    const row = angularSegs + 1;
    for (let i = 0; i < radialSegs; i++) {
      for (let j = 0; j < angularSegs; j++) {
        const a = i * row + j;
        const b = a + row;
        const c = a + 1;
        const d = b + 1;
        indices.push(a, b, c);
        indices.push(c, b, d);
      }
    }

    const geo = new THREE.BufferGeometry();
    geo.setIndex(indices);
    geo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
    geo.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
    geo.computeVertexNormals();

    const mat = new THREE.MeshLambertMaterial({
      vertexColors: true
    });
    const terrainMesh = new THREE.Mesh(geo, mat);
    terrainMesh.receiveShadow = true;
    terrainMesh.castShadow = true;
    group.add(terrainMesh);

    // Build the two scenic lake islands
    function makeIsland(cx, cz, radius, peakH) {
      const iGeo = new THREE.ConeGeometry(radius, peakH, 24, 4, true);
      iGeo.translate(0, peakH * 0.5, 0);
      const pos = iGeo.attributes.position;
      const iCols = [];
      for (let k = 0; k < pos.count; k++) {
        const vx = pos.getX(k);
        const vy = pos.getY(k);
        const vz = pos.getZ(k);
        const ang = Math.atan2(vz, vx);
        const wobble = 1 + 0.12 * Math.sin(ang * 3 + cx) + 0.08 * Math.cos(ang * 5);
        const smoothY = Math.max(0, Math.sin((vy / peakH) * (Math.PI * 0.5)) * peakH);
        pos.setXYZ(k, vx * wobble, smoothY, vz * wobble);
        if (smoothY < 1.6) {
          tmpCol.copy(cSand);
        } else {
          tmpCol.copy(cGrassLow).lerp(cGrassHigh, clamp((smoothY - 1.6) / peakH, 0, 1));
        }
        iCols.push(tmpCol.r, tmpCol.g, tmpCol.b);
      }
      iGeo.setAttribute("color", new THREE.Float32BufferAttribute(iCols, 3));
      iGeo.computeVertexNormals();
      const mesh = new THREE.Mesh(iGeo, mat);
      mesh.position.set(cx, 0, cz);
      mesh.receiveShadow = true;
      mesh.castShadow = true;
      group.add(mesh);
    }

    makeIsland(115, 10, 25, 7.2);
    makeIsland(-110, -15, 24, 6.8);

    return group;
  }

  scene.add(buildHillsAndIslands());

  // --- Shared Materials for Town, Docks, Trees & Cats ---
  const townWindowMat = new THREE.MeshBasicMaterial({ color: 0xffcc55 });
  const lanternGlowMat = new THREE.MeshBasicMaterial({ color: 0xffaa33 });
  const timberDarkMat = new THREE.MeshLambertMaterial({ color: 0x6b442a });
  const timberLightMat = new THREE.MeshLambertMaterial({ color: 0x9c663b });
  const wallCreamMat = new THREE.MeshLambertMaterial({ color: 0xf4e4c8 });
  const wallPeachMat = new THREE.MeshLambertMaterial({ color: 0xebbfa0 });
  const roofRedMat = new THREE.MeshLambertMaterial({ color: 0xb84634 });
  const roofSlateMat = new THREE.MeshLambertMaterial({ color: 0x455268 });

  const animatedStructures = {
    windmillBlades: null,
    lighthouseBeam: null,
    boats: []
  };

  // Helper to build a wooden dock with lanterns & optional moored boat
  function createDock(x, z, rotY) {
    const g = new THREE.Group();
    g.position.set(x, 0, z);
    g.rotation.y = rotY;

    // Main pier deck
    const deck = new THREE.Mesh(new THREE.BoxGeometry(8.5, 0.5, 18), timberLightMat);
    deck.position.set(0, 1.55, 0);
    deck.castShadow = true;
    deck.receiveShadow = true;
    g.add(deck);

    // Support pilings (clamped to y >= 0 so nothing extends below water level)
    const postGeo = new THREE.CylinderGeometry(0.38, 0.38, 2.6, 8);
    const postCoords = [
      [-3.7, -7.5], [3.7, -7.5],
      [-3.7, -2.5], [3.7, -2.5],
      [-3.7,  2.5], [3.7,  2.5],
      [-3.7,  7.5], [3.7,  7.5]
    ];
    postCoords.forEach(([px, pz]) => {
      const post = new THREE.Mesh(postGeo, timberDarkMat);
      post.position.set(px, 1.3, pz);
      post.castShadow = true;
      g.add(post);
    });

    // Hanging lantern pole at dock end
    const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.16, 0.2, 4.5, 8), timberDarkMat);
    pole.position.set(3.5, 3.8, 7.2);
    g.add(pole);

    const arm = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.18, 0.18), timberDarkMat);
    arm.position.set(2.9, 5.9, 7.2);
    g.add(arm);

    const lantern = new THREE.Mesh(new THREE.SphereGeometry(0.45, 10, 10), lanternGlowMat);
    lantern.position.set(2.3, 5.4, 7.2);
    g.add(lantern);

    // Moored little wooden rowboat beside the dock
    const boat = new THREE.Group();
    const hull = new THREE.Mesh(new THREE.BoxGeometry(2.6, 0.75, 5.2), roofRedMat);
    hull.position.y = 0.38;
    const seat = new THREE.Mesh(new THREE.BoxGeometry(2.2, 0.2, 1.0), timberLightMat);
    seat.position.y = 0.72;
    boat.add(hull, seat);
    boat.position.set(-6.2, 0.05, 2.0);
    g.add(boat);
    animatedStructures.boats.push(boat);

    scene.add(g);
    return g;
  }

  // Helper to build a rooftop delivery building with terrace pad & glowing windows
  function createDeliveryBuilding(x, z, deckY, type) {
    const baseH = Math.max(0, getTerrainHeight(x, z));
    const wallH = Math.max(4.5, deckY - baseH - 0.3);

    const g = new THREE.Group();
    g.position.set(x, baseH, z);

    // Main building body
    const bodyW = type === "tavern" ? 13 : 11;
    const bodyD = type === "tavern" ? 11 : 10;
    const body = new THREE.Mesh(
      new THREE.BoxGeometry(bodyW, wallH, bodyD),
      type === "windmill" ? wallPeachMat : wallCreamMat
    );
    body.position.y = wallH * 0.5;
    body.castShadow = true;
    body.receiveShadow = true;
    g.add(body);

    // Side pitched roof wings + central flat rooftop delivery terrace
    const terrace = new THREE.Mesh(
      new THREE.BoxGeometry(9.2, 0.5, 8.6),
      timberLightMat
    );
    terrace.position.y = wallH + 0.1;
    terrace.receiveShadow = true;
    terrace.castShadow = true;
    g.add(terrace);

    // Cozy glowing windows around building
    const winGeo = new THREE.PlaneGeometry(1.5, 1.9);
    for (let side = 0; side < 4; side++) {
      const winGroup = new THREE.Group();
      winGroup.rotation.y = side * (Math.PI / 2);
      const dist = (side % 2 === 0 ? bodyD : bodyW) * 0.5 + 0.06;
      for (let wx = -2.4; wx <= 2.4; wx += 4.8) {
        const wMesh = new THREE.Mesh(winGeo, townWindowMat);
        wMesh.position.set(wx, wallH * 0.52, dist);
        winGroup.add(wMesh);
      }
      g.add(winGroup);
    }

    // Special architectural landmarks
    if (type === "windmill") {
      const tower = new THREE.Mesh(new THREE.CylinderGeometry(2.1, 2.9, 9.5, 10), wallCreamMat);
      tower.position.set(-4.8, wallH + 3.2, -3.5);
      tower.castShadow = true;
      g.add(tower);

      const cap = new THREE.Mesh(new THREE.ConeGeometry(2.4, 2.5, 10), roofRedMat);
      cap.position.set(-4.8, wallH + 9.0, -3.5);
      g.add(cap);

      const bladesGroup = new THREE.Group();
      bladesGroup.position.set(-4.8, wallH + 6.5, -1.2);
      for (let b = 0; b < 4; b++) {
        const arm = new THREE.Mesh(new THREE.BoxGeometry(0.85, 7.2, 0.15), timberLightMat);
        arm.position.y = 3.4;
        const pivot = new THREE.Group();
        pivot.rotation.z = (b * Math.PI) / 2;
        pivot.add(arm);
        bladesGroup.add(pivot);
      }
      g.add(bladesGroup);
      animatedStructures.windmillBlades = bladesGroup;
    } else if (type === "lighthouse") {
      const tower = new THREE.Mesh(new THREE.CylinderGeometry(1.7, 2.5, 13, 12), wallCreamMat);
      tower.position.set(-5.0, wallH + 4.5, -3.5);
      tower.castShadow = true;
      g.add(tower);

      const lanternRoom = new THREE.Mesh(new THREE.CylinderGeometry(1.5, 1.5, 2.2, 10), lanternGlowMat);
      lanternRoom.position.set(-5.0, wallH + 11.8, -3.5);
      g.add(lanternRoom);

      const dome = new THREE.Mesh(new THREE.ConeGeometry(1.9, 2.0, 10), roofRedMat);
      dome.position.set(-5.0, wallH + 13.7, -3.5);
      g.add(dome);
    } else {
      // Chimney on rooftop corner
      const chimney = new THREE.Mesh(new THREE.BoxGeometry(1.3, 3.2, 1.3), roofRedMat);
      chimney.position.set(-3.4, wallH + 1.4, -3.2);
      g.add(chimney);
    }

    scene.add(g);
    return g;
  }

  // Build background lakeside cottages and trees for atmosphere
  function populateBackgroundTownAndTrees() {
    const townGroup = new THREE.Group();

    // 18 background cottages nestled along the lake shores
    const cottageAngles = [
      -1.35, -1.18, -0.95, -0.55, -0.38, -0.22,
      0.24, 0.42, 0.62, 0.96, 1.15, 1.42,
      1.78, 1.98, 2.22, 2.65, 2.88, -2.55
    ];

    cottageAngles.forEach((ang, idx) => {
      const r = getShoreRadius(ang) + 14 + (idx % 3) * 14;
      const cx = Math.cos(ang) * r;
      const cz = Math.sin(ang) * r;
      const cy = getTerrainHeight(cx, cz);

      const house = new THREE.Group();
      house.position.set(cx, cy, cz);
      house.rotation.y = -ang + Math.PI * 0.5;

      const w = 5.5 + (idx % 3) * 1.2;
      const h = 4.2 + (idx % 2) * 1.4;
      const d = 5.0 + (idx % 2) * 1.2;

      const walls = new THREE.Mesh(
        new THREE.BoxGeometry(w, h, d),
        idx % 2 === 0 ? wallCreamMat : wallPeachMat
      );
      walls.position.y = h * 0.5;
      walls.castShadow = true;
      walls.receiveShadow = true;
      house.add(walls);

      const roof = new THREE.Mesh(
        new THREE.ConeGeometry(Math.max(w, d) * 0.78, 3.2, 4),
        idx % 3 === 0 ? roofSlateMat : roofRedMat
      );
      roof.position.y = h + 1.6;
      roof.rotation.y = Math.PI * 0.25;
      roof.castShadow = true;
      house.add(roof);

      const win = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.3), townWindowMat);
      win.position.set(0, h * 0.52, d * 0.5 + 0.05);
      house.add(win);

      townGroup.add(house);
    });

    // Trees around hills & islands
    const pineMat1 = new THREE.MeshLambertMaterial({ color: 0x3b6e3c });
    const pineMat2 = new THREE.MeshLambertMaterial({ color: 0x5c7d35 });
    const autumnMat1 = new THREE.MeshLambertMaterial({ color: 0xd9722b });
    const autumnMat2 = new THREE.MeshLambertMaterial({ color: 0xe69f35 });
    const treeMats = [pineMat1, pineMat2, autumnMat1, autumnMat2];

    const trunkGeo = new THREE.CylinderGeometry(0.32, 0.48, 2.2, 6);
    const coneGeo = new THREE.ConeGeometry(2.4, 5.6, 7);
    const puffGeo = new THREE.DodecahedronGeometry(2.3, 1);

    for (let i = 0; i < 135; i++) {
      const ang = (i * 2.39996) % (Math.PI * 2);
      const band = i % 10 === 0 ? 0 : 1;
      let tx, tz;
      if (band === 0) {
        // Island trees
        const isl = i % 20 === 0 ? [115, 10] : [-110, -15];
        const ir = 6 + (i % 7) * 1.8;
        tx = isl[0] + Math.cos(ang) * ir;
        tz = isl[1] + Math.sin(ang) * ir;
      } else {
        const sr = getShoreRadius(ang) + 20 + (i % 11) * 16;
        tx = Math.cos(ang) * sr;
        tz = Math.sin(ang) * sr;
      }
      // Keep clear of the 8 delivery spots
      if (Math.hypot(tx - 95, tz + 95) < 16) continue;
      if (Math.hypot(tx - 85, tz - 110) < 16) continue;
      if (Math.hypot(tx + 105, tz - 85) < 16) continue;
      if (Math.hypot(tx + 75, tz + 105) < 16) continue;

      const ty = getTerrainHeight(tx, tz);
      if (ty < 1.2) continue;

      const tGroup = new THREE.Group();
      const s = 0.85 + (i % 5) * 0.16;
      tGroup.position.set(tx, ty, tz);
      tGroup.scale.set(s, s, s);

      const trunk = new THREE.Mesh(trunkGeo, timberDarkMat);
      trunk.position.y = 1.1;
      tGroup.add(trunk);

      const mat = treeMats[i % treeMats.length];
      if (i % 3 !== 0) {
        const c1 = new THREE.Mesh(coneGeo, mat);
        c1.position.y = 4.2;
        c1.castShadow = true;
        tGroup.add(c1);
      } else {
        const p1 = new THREE.Mesh(puffGeo, mat);
        p1.position.y = 3.8;
        p1.castShadow = true;
        tGroup.add(p1);
      }
      townGroup.add(tGroup);
    }

    scene.add(townGroup);
  }

  populateBackgroundTownAndTrees();

  // --- Fluffy Sunset Clouds ---
  const clouds = [];
  const cloudMat = new THREE.MeshLambertMaterial({
    color: 0xffe4c4,
    emissive: 0x7a3430,
    emissiveIntensity: 0.35
  });

  function buildClouds() {
    const puffGeo = new THREE.DodecahedronGeometry(1, 1);
    for (let i = 0; i < 18; i++) {
      const cGroup = new THREE.Group();
      const angle = (i / 18) * Math.PI * 2 + (i % 3) * 0.2;
      const dist = 120 + (i % 4) * 75;
      const alt = 70 + (i % 5) * 9;

      const numPuffs = 4 + (i % 3);
      for (let p = 0; p < numPuffs; p++) {
        const puff = new THREE.Mesh(puffGeo, cloudMat);
        const rx = (p - (numPuffs - 1) * 0.5) * 7.2;
        const ry = Math.sin(p * 1.4) * 2.2;
        const rz = Math.cos(p * 2.1) * 3.0;
        const sx = 6.5 + (p % 2) * 2.5;
        const sy = 3.8 + (p % 3) * 1.1;
        const sz = 5.5 + (p % 2) * 1.8;
        puff.position.set(rx, ry, rz);
        puff.scale.set(sx, sy, sz);
        cGroup.add(puff);
      }

      cGroup.position.set(Math.cos(angle) * dist, alt, Math.sin(angle) * dist);
      cGroup.rotation.y = -angle;
      scene.add(cGroup);
      clouds.push({
        mesh: cGroup,
        angle: angle,
        dist: dist,
        alt: alt,
        speed: 0.012 + (i % 4) * 0.004
      });
    }
  }
  buildClouds();

  // --- Procedural Fish Crate Texture ---
  function createFishCrateTexture() {
    const c = document.createElement("canvas");
    c.width = 128;
    c.height = 128;
    const ctx = c.getContext("2d");

    // Wooden crate background
    ctx.fillStyle = "#c98b4b";
    ctx.fillRect(0, 0, 128, 128);

    // Plank lines
    ctx.strokeStyle = "#8a5625";
    ctx.lineWidth = 4;
    for (let y = 32; y < 128; y += 32) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(128, y);
      ctx.stroke();
    }

    // Outer frame border
    ctx.strokeStyle = "#73441b";
    ctx.lineWidth = 14;
    ctx.strokeRect(7, 7, 114, 114);

    // Cute stenciled blue/silver fish icon in center
    ctx.fillStyle = "#2b6f9e";
    ctx.beginPath();
    ctx.ellipse(58, 64, 28, 15, 0, 0, Math.PI * 2);
    ctx.fill();

    // Fish tail
    ctx.beginPath();
    ctx.moveTo(82, 64);
    ctx.lineTo(103, 47);
    ctx.lineTo(103, 81);
    ctx.closePath();
    ctx.fill();

    // Fish eye
    ctx.fillStyle = "#fff8e7";
    ctx.beginPath();
    ctx.arc(43, 60, 4, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "#142738";
    ctx.beginPath();
    ctx.arc(42, 60, 2, 0, Math.PI * 2);
    ctx.fill();

    const tex = new THREE.CanvasTexture(c);
    tex.encoding = THREE.sRGBEncoding;
    return tex;
  }

  const fishCrateTex = createFishCrateTexture();
  const fishCrateMat = new THREE.MeshLambertMaterial({ map: fishCrateTex });

  // --- Waiting Cats on Rooftops and Docks ---
  function createWaitingCat(furColorHex) {
    const catGroup = new THREE.Group();

    // Landing target pad under cat
    const padMat = new THREE.MeshLambertMaterial({ color: 0xffd166 });
    const padInnerMat = new THREE.MeshLambertMaterial({ color: 0xe85d35 });
    const pad = new THREE.Mesh(new THREE.CylinderGeometry(2.8, 3.0, 0.24, 20), padMat);
    pad.position.y = 0.12;
    catGroup.add(pad);

    const padInner = new THREE.Mesh(new THREE.CylinderGeometry(1.7, 1.7, 0.28, 16), padInnerMat);
    padInner.position.y = 0.14;
    catGroup.add(padInner);

    // The Cat Model (positioned slightly to one side of the landing pad so the crate lands right next to it!)
    const cat = new THREE.Group();
    cat.position.set(1.35, 0.24, 0);

    const furMat = new THREE.MeshLambertMaterial({ color: furColorHex });
    const whiteMat = new THREE.MeshLambertMaterial({ color: 0xfff5e6 });
    const pinkMat = new THREE.MeshLambertMaterial({ color: 0xff94a2 });
    const darkMat = new THREE.MeshBasicMaterial({ color: 0x1e1624 });

    // Body
    const body = new THREE.Mesh(new THREE.CylinderGeometry(0.48, 0.58, 1.25, 12), furMat);
    body.position.y = 0.65;
    cat.add(body);

    // Chest patch
    const chest = new THREE.Mesh(new THREE.SphereGeometry(0.38, 10, 10), whiteMat);
    chest.position.set(0, 0.72, 0.26);
    cat.add(chest);

    // Head
    const head = new THREE.Mesh(new THREE.SphereGeometry(0.55, 14, 14), furMat);
    head.position.set(0, 1.55, 0.1);
    cat.add(head);

    // Ears
    const earGeo = new THREE.ConeGeometry(0.24, 0.48, 4);
    const leftEar = new THREE.Mesh(earGeo, furMat);
    leftEar.position.set(-0.32, 2.04, 0.08);
    leftEar.rotation.z = 0.25;
    const rightEar = new THREE.Mesh(earGeo, furMat);
    rightEar.position.set(0.32, 2.04, 0.08);
    rightEar.rotation.z = -0.25;
    cat.add(leftEar, rightEar);

    // Eyes & Nose (looking up eagerly at the sky!)
    const eyeGeo = new THREE.SphereGeometry(0.08, 8, 8);
    const eyeL = new THREE.Mesh(eyeGeo, darkMat);
    eyeL.position.set(-0.2, 1.68, 0.56);
    const eyeR = new THREE.Mesh(eyeGeo, darkMat);
    eyeR.position.set(0.2, 1.68, 0.56);
    const nose = new THREE.Mesh(new THREE.SphereGeometry(0.07, 8, 8), pinkMat);
    nose.position.set(0, 1.58, 0.63);
    cat.add(eyeL, eyeR, nose);

    // Waving front paws
    const pawGeo = new THREE.CylinderGeometry(0.13, 0.13, 0.65, 8);
    const leftPaw = new THREE.Mesh(pawGeo, furMat);
    leftPaw.position.set(-0.55, 1.15, 0.25);
    leftPaw.rotation.z = 0.8;
    const rightPaw = new THREE.Mesh(pawGeo, furMat);
    rightPaw.position.set(0.55, 1.15, 0.25);
    rightPaw.rotation.z = -0.8;
    cat.add(leftPaw, rightPaw);

    // Swishing tail
    const tail = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.13, 1.1, 8), furMat);
    tail.position.set(0, 0.65, -0.58);
    tail.rotation.x = -0.7;
    cat.add(tail);

    catGroup.add(cat);

    return {
      group: catGroup,
      catMesh: cat,
      leftPaw: leftPaw,
      rightPaw: rightPaw,
      tail: tail,
      delivered: false,
      happyTimer: 0
    };
  }

  // --- 8 Delivery Spots: 4 Docks & 4 Rooftops around the Lake ---
  const DELIVERY_SITES = [
    {
      name: "North Harbor Dock",
      kind: "dock",
      x: 0, z: -118,
      dockRot: 0,
      landingY: 1.8,
      ringY: 26,
      ringDir: new THREE.Vector3(1, 0, 0),
      catColor: 0xf28b30
    },
    {
      name: "Boathouse Rooftop",
      kind: "rooftop",
      bType: "boathouse",
      x: 96, z: -96,
      landingY: 11.5,
      ringY: 32,
      ringDir: new THREE.Vector3(0.7, 0, 0.7).normalize(),
      catColor: 0x454955
    },
    {
      name: "East Island Dock",
      kind: "dock",
      x: 115, z: 27,
      dockRot: Math.PI * 0.5,
      landingY: 1.8,
      ringY: 25,
      ringDir: new THREE.Vector3(0, 0, 1),
      catColor: 0xe6a15c
    },
    {
      name: "Hillside Tavern Rooftop",
      kind: "rooftop",
      bType: "tavern",
      x: 86, z: 112,
      landingY: 16.5,
      ringY: 36,
      ringDir: new THREE.Vector3(-0.7, 0, 0.7).normalize(),
      catColor: 0xd96b38
    },
    {
      name: "South Ferry Dock",
      kind: "dock",
      x: -8, z: 124,
      dockRot: Math.PI,
      landingY: 1.8,
      ringY: 26,
      ringDir: new THREE.Vector3(-1, 0, 0),
      catColor: 0x8c7b70
    },
    {
      name: "Windmill Bakery Rooftop",
      kind: "rooftop",
      bType: "windmill",
      x: -104, z: 86,
      landingY: 15.0,
      ringY: 34,
      ringDir: new THREE.Vector3(-0.7, 0, -0.7).normalize(),
      catColor: 0xf09c42
    },
    {
      name: "West Island Lantern Dock",
      kind: "dock",
      x: -110, z: -32,
      dockRot: -Math.PI * 0.5,
      landingY: 1.8,
      ringY: 25,
      ringDir: new THREE.Vector3(0, 0, -1),
      catColor: 0x3b3d45
    },
    {
      name: "Lighthouse Keeper's Rooftop",
      kind: "rooftop",
      bType: "lighthouse",
      x: -78, z: -104,
      landingY: 15.5,
      ringY: 34,
      ringDir: new THREE.Vector3(0.7, 0, -0.7).normalize(),
      catColor: 0xe87a2e
    }
  ];

  // Build structures, waiting cats, and glowing sky rings for all 8 sites
  const deliveryObjects = [];

  const ringOuterMat = new THREE.MeshBasicMaterial({ color: 0xffd04d });
  const ringInnerMat = new THREE.MeshBasicMaterial({ color: 0x5ce1e6 });
  const ringPortalMat = new THREE.MeshBasicMaterial({
    color: 0xffe484,
    transparent: true,
    opacity: 0.17,
    side: THREE.DoubleSide,
    depthWrite: false
  });
  const beamMat = new THREE.MeshBasicMaterial({
    color: 0xffc857,
    transparent: true,
    opacity: 0.14,
    depthWrite: false
  });

  DELIVERY_SITES.forEach((site, idx) => {
    if (site.kind === "dock") {
      createDock(site.x, site.z, site.dockRot);
    } else {
      const groundH = getTerrainHeight(site.x, site.z);
      site.landingY = Math.max(site.landingY, groundH + 6.5);
      site.ringY = Math.max(site.ringY, site.landingY + 18);
      createDeliveryBuilding(site.x, site.z, site.landingY, site.bType);
    }

    // Place waiting cat on the dock or rooftop
    const catObj = createWaitingCat(site.catColor);
    catObj.group.position.set(site.x, site.landingY, site.z);
    scene.add(catObj.group);

    // Build Glowing Ring in the sky above the cat
    const ringGroup = new THREE.Group();
    ringGroup.position.set(site.x, site.ringY, site.z);

    // Orient ring perpendicular to flight path around lake
    const lookTarget = new THREE.Vector3(site.x, site.ringY, site.z).add(site.ringDir);
    ringGroup.lookAt(lookTarget);

    const outerTorus = new THREE.Mesh(new THREE.TorusGeometry(6.8, 0.46, 14, 42), ringOuterMat);
    ringGroup.add(outerTorus);

    const innerStarRing = new THREE.Mesh(new THREE.TorusGeometry(5.5, 0.2, 10, 6), ringInnerMat);
    ringGroup.add(innerStarRing);

    const portalDisc = new THREE.Mesh(new THREE.CircleGeometry(6.3, 32), ringPortalMat);
    ringGroup.add(portalDisc);

    // 6 orbiting sparkle gems around ring perimeter
    const orbsGroup = new THREE.Group();
    const orbGeo = new THREE.OctahedronGeometry(0.45, 0);
    for (let k = 0; k < 6; k++) {
      const a = (k / 6) * Math.PI * 2;
      const orb = new THREE.Mesh(orbGeo, k % 2 === 0 ? ringInnerMat : ringOuterMat);
      orb.position.set(Math.cos(a) * 6.8, Math.sin(a) * 6.8, 0);
      orbsGroup.add(orb);
    }
    ringGroup.add(orbsGroup);

    scene.add(ringGroup);

    // Vertical beacon column connecting the glowing ring down to the waiting cat
    const beamH = site.ringY - site.landingY - 6.8;
    const beamGeo = new THREE.CylinderGeometry(0.45, 1.7, beamH, 14, 1, true);
    const beamMesh = new THREE.Mesh(beamGeo, beamMat);
    beamMesh.position.set(site.x, site.landingY + beamH * 0.5, site.z);
    scene.add(beamMesh);

    deliveryObjects.push({
      index: idx,
      site: site,
      catObj: catObj,
      ringGroup: ringGroup,
      innerStarRing: innerStarRing,
      orbsGroup: orbsGroup,
      beamMesh: beamMesh,
      active: true,
      deliveredMesh: null
    });
  });

  // --- Build the Orange Cat Pilot & Little Propeller Plane ---
  const planeGroup = new THREE.Group();
  scene.add(planeGroup);

  const planeParts = {
    propeller: null,
    scarfSegments: [],
    catHead: null,
    yoke: null,
    compassNeedle: null,
    altNeedle: null,
    sunsetNeedle: null,
    bellyCrate: null
  };

  function buildCatPlane() {
    const creamMat = new THREE.MeshLambertMaterial({ color: 0xfff1d0 });
    const coralMat = new THREE.MeshLambertMaterial({ color: 0xe8532e });
    const yellowMat = new THREE.MeshLambertMaterial({ color: 0xffbe3d });
    const woodMat = new THREE.MeshLambertMaterial({ color: 0x704224 });
    const darkMetalMat = new THREE.MeshLambertMaterial({ color: 0x2c303b });
    const orangeCatMat = new THREE.MeshLambertMaterial({ color: 0xf47b20 });
    const tabbyStripeMat = new THREE.MeshLambertMaterial({ color: 0xc8520a });
    const whiteFurMat = new THREE.MeshLambertMaterial({ color: 0xfff7eb });
    const pinkNoseMat = new THREE.MeshLambertMaterial({ color: 0xff8da1 });
    const goggleLensMat = new THREE.MeshBasicMaterial({ color: 0x68e8f8 });
    const scarfMat = new THREE.MeshLambertMaterial({ color: 0xd9383a });

    // Note: Plane local forward is +Z
    // Fuselage main body
    const fuselage = new THREE.Mesh(new THREE.BoxGeometry(1.75, 1.55, 4.4), creamMat);
    fuselage.position.set(0, 0, -0.2);
    fuselage.castShadow = true;
    planeGroup.add(fuselage);

    // Coral-red engine cowling nose
    const nose = new THREE.Mesh(new THREE.CylinderGeometry(0.75, 0.92, 1.35, 16), coralMat);
    nose.rotation.x = Math.PI * 0.5;
    nose.position.set(0, 0.02, 2.45);
    nose.castShadow = true;
    planeGroup.add(nose);

    // Tapered rear tail boom
    const tailBoom = new THREE.Mesh(new THREE.CylinderGeometry(0.32, 0.78, 2.9, 12), creamMat);
    tailBoom.rotation.x = -Math.PI * 0.5;
    tailBoom.position.set(0, 0.08, -3.5);
    tailBoom.castShadow = true;
    planeGroup.add(tailBoom);

    // Vertical tail fin & horizontal stabilizer
    const vFin = new THREE.Mesh(new THREE.BoxGeometry(0.18, 1.45, 1.35), coralMat);
    vFin.position.set(0, 0.85, -4.45);
    const hStab = new THREE.Mesh(new THREE.BoxGeometry(3.4, 0.14, 1.05), yellowMat);
    hStab.position.set(0, 0.25, -4.4);
    planeGroup.add(vFin, hStab);

    // Lower Wing & Upper Biplane Wing
    const lowerWing = new THREE.Mesh(new THREE.BoxGeometry(9.6, 0.18, 1.75), creamMat);
    lowerWing.position.set(0, -0.45, 0.55);
    lowerWing.castShadow = true;
    planeGroup.add(lowerWing);

    const lowerTips = new THREE.Mesh(new THREE.BoxGeometry(9.75, 0.16, 0.45), coralMat);
    lowerTips.position.set(0, -0.45, 1.22);
    planeGroup.add(lowerTips);

    const upperWing = new THREE.Mesh(new THREE.BoxGeometry(9.8, 0.18, 1.8), yellowMat);
    upperWing.position.set(0, 1.72, 0.65);
    upperWing.castShadow = true;
    planeGroup.add(upperWing);

    // Biplane Wooden Wing Struts
    const strutGeo = new THREE.CylinderGeometry(0.06, 0.06, 2.15, 6);
    [-3.4, -1.65, 1.65, 3.4].forEach((sx) => {
      const s1 = new THREE.Mesh(strutGeo, woodMat);
      s1.position.set(sx, 0.63, 1.0);
      const s2 = new THREE.Mesh(strutGeo, woodMat);
      s2.position.set(sx, 0.63, 0.2);
      planeGroup.add(s1, s2);
    });

    // Twin Seaplane Pontoon Floats
    const floatGeo = new THREE.CylinderGeometry(0.32, 0.28, 3.6, 12);
    floatGeo.rotateX(Math.PI * 0.5);
    [-1.4, 1.4].forEach((fx) => {
      const pontoon = new THREE.Mesh(floatGeo, coralMat);
      pontoon.position.set(fx, -1.35, 0.5);
      const leg1 = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.06, 0.95, 6), darkMetalMat);
      leg1.position.set(fx, -0.9, 1.1);
      const leg2 = leg1.clone();
      leg2.position.set(fx, -0.9, -0.2);
      planeGroup.add(pontoon, leg1, leg2);
    });

    // Front Spinning Propeller + Blur Disc
    const propGroup = new THREE.Group();
    propGroup.position.set(0, 0.02, 3.22);

    const spinner = new THREE.Mesh(new THREE.ConeGeometry(0.28, 0.45, 12), yellowMat);
    spinner.rotation.x = Math.PI * 0.5;
    spinner.position.z = 0.12;
    propGroup.add(spinner);

    const blade1 = new THREE.Mesh(new THREE.BoxGeometry(2.7, 0.24, 0.06), woodMat);
    const blade2 = new THREE.Mesh(new THREE.BoxGeometry(0.24, 2.7, 0.06), woodMat);
    propGroup.add(blade1, blade2);

    const blurDisc = new THREE.Mesh(
      new THREE.CircleGeometry(1.38, 24),
      new THREE.MeshBasicMaterial({
        color: 0xffe8c2,
        transparent: true,
        opacity: 0.18,
        side: THREE.DoubleSide,
        depthWrite: false
      })
    );
    blurDisc.position.z = 0.03;
    propGroup.add(blurDisc);
    planeGroup.add(propGroup);
    planeParts.propeller = propGroup;

    // Cockpit Coaming, Dashboard & Working Gauges (for Inside Cockpit camera!)
    const dashPanel = new THREE.Mesh(new THREE.BoxGeometry(1.48, 0.62, 0.18), woodMat);
    dashPanel.position.set(0, 0.78, 1.15);
    planeGroup.add(dashPanel);

    // Windshield frame
    const glassMat = new THREE.MeshBasicMaterial({
      color: 0xd9f7ff,
      transparent: true,
      opacity: 0.24,
      side: THREE.DoubleSide,
      depthWrite: false
    });
    const windshield = new THREE.Mesh(new THREE.PlaneGeometry(1.36, 0.62), glassMat);
    windshield.position.set(0, 1.24, 1.18);
    windshield.rotation.x = -0.35;
    planeGroup.add(windshield);

    // Three Working Cockpit Dials (facing -Z toward the cockpit camera)
    const dialFaceMat = new THREE.MeshBasicMaterial({ color: 0x1e1829 });
    const needleMat = new THREE.MeshBasicMaterial({ color: 0xffd166 });
    const ringNeedleMat = new THREE.MeshBasicMaterial({ color: 0x5ce1e6 });

    function makeGauge(gx) {
      const g = new THREE.Group();
      g.position.set(gx, 0.85, 1.04);
      const face = new THREE.Mesh(new THREE.CircleGeometry(0.21, 16), dialFaceMat);
      face.rotation.y = Math.PI;
      const rim = new THREE.Mesh(new THREE.RingGeometry(0.19, 0.23, 16), yellowMat);
      rim.rotation.y = Math.PI;
      rim.position.z = -0.005;
      g.add(face, rim);
      return g;
    }

    // Left Gauge: Altimeter
    const altGauge = makeGauge(-0.46);
    const altNeedle = new THREE.Mesh(new THREE.BoxGeometry(0.035, 0.15, 0.02), needleMat);
    altNeedle.position.set(0, 0.05, -0.01);
    const altPivot = new THREE.Group();
    altPivot.add(altNeedle);
    altGauge.add(altPivot);
    planeGroup.add(altGauge);
    planeParts.altNeedle = altPivot;

    // Center Gauge: Glowing Ring Finder Compass
    const compGauge = makeGauge(0);
    const compNeedle = new THREE.Mesh(new THREE.ConeGeometry(0.055, 0.17, 4), ringNeedleMat);
    compNeedle.position.set(0, 0.05, -0.01);
    const compPivot = new THREE.Group();
    compPivot.add(compNeedle);
    compGauge.add(compPivot);
    planeGroup.add(compGauge);
    planeParts.compassNeedle = compPivot;

    // Right Gauge: Sunset Daylight Clock
    const sunGauge = makeGauge(0.46);
    const sunNeedle = new THREE.Mesh(new THREE.BoxGeometry(0.035, 0.15, 0.02), coralMat);
    sunNeedle.position.set(0, 0.05, -0.01);
    const sunPivot = new THREE.Group();
    sunPivot.add(sunNeedle);
    sunGauge.add(sunPivot);
    planeGroup.add(sunGauge);
    planeParts.sunsetNeedle = sunPivot;

    // Cockpit Steering Yoke & Cat Paws
    const yokeGroup = new THREE.Group();
    yokeGroup.position.set(0, 0.64, 0.88);
    const yokeBar = new THREE.Mesh(new THREE.BoxGeometry(0.56, 0.07, 0.07), darkMetalMat);
    const pawL = new THREE.Mesh(new THREE.SphereGeometry(0.13, 10, 10), orangeCatMat);
    pawL.position.set(-0.24, 0.04, -0.04);
    const pawR = new THREE.Mesh(new THREE.SphereGeometry(0.13, 10, 10), orangeCatMat);
    pawR.position.set(0.24, 0.04, -0.04);
    yokeGroup.add(yokeBar, pawL, pawR);
    planeGroup.add(yokeGroup);
    planeParts.yoke = yokeGroup;

    // --- The Orange Cat Pilot in the Cockpit ---
    const catPilot = new THREE.Group();
    catPilot.position.set(0, 0.55, 0.18);

    // Torso
    const torso = new THREE.Mesh(new THREE.CylinderGeometry(0.42, 0.5, 0.85, 12), orangeCatMat);
    torso.position.y = 0.2;
    catPilot.add(torso);

    // Head Pivot (turns slightly with steering!)
    const headGroup = new THREE.Group();
    headGroup.position.set(0, 0.85, 0.05);

    const head = new THREE.Mesh(new THREE.SphereGeometry(0.52, 16, 16), orangeCatMat);
    headGroup.add(head);

    // Tabby forehead stripes
    const stripe = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.25, 0.5), tabbyStripeMat);
    stripe.position.set(0, 0.34, 0.18);
    headGroup.add(stripe);

    // White chubby cheeks / muzzle
    const cheekL = new THREE.Mesh(new THREE.SphereGeometry(0.21, 10, 10), whiteFurMat);
    cheekL.position.set(-0.16, -0.08, 0.41);
    const cheekR = new THREE.Mesh(new THREE.SphereGeometry(0.21, 10, 10), whiteFurMat);
    cheekR.position.set(0.16, -0.08, 0.41);
    const nosePink = new THREE.Mesh(new THREE.SphereGeometry(0.075, 8, 8), pinkNoseMat);
    nosePink.position.set(0, 0.0, 0.54);
    headGroup.add(cheekL, cheekR, nosePink);

    // Orange Cat Ears with Pink Insides
    const earOuterGeo = new THREE.ConeGeometry(0.24, 0.48, 4);
    const earInnerGeo = new THREE.ConeGeometry(0.13, 0.32, 4);

    const earL = new THREE.Group();
    earL.position.set(-0.34, 0.48, -0.02);
    earL.rotation.z = 0.26;
    earL.rotation.y = Math.PI * 0.25;
    const earLOut = new THREE.Mesh(earOuterGeo, orangeCatMat);
    const earLIn = new THREE.Mesh(earInnerGeo, pinkNoseMat);
    earLIn.position.set(0.03, -0.02, 0.05);
    earL.add(earLOut, earLIn);

    const earR = new THREE.Group();
    earR.position.set(0.34, 0.48, -0.02);
    earR.rotation.z = -0.26;
    earR.rotation.y = Math.PI * 0.25;
    const earROut = new THREE.Mesh(earOuterGeo, orangeCatMat);
    const earRIn = new THREE.Mesh(earInnerGeo, pinkNoseMat);
    earRIn.position.set(-0.03, -0.02, 0.05);
    earR.add(earROut, earRIn);

    headGroup.add(earL, earR);

    // Aviator Goggles on Cat's Forehead
    const strap = new THREE.Mesh(new THREE.CylinderGeometry(0.535, 0.535, 0.14, 16, 1, true), darkMetalMat);
    strap.position.y = 0.18;
    headGroup.add(strap);

    [-0.19, 0.19].forEach((gx) => {
      const rim = new THREE.Mesh(new THREE.CylinderGeometry(0.16, 0.16, 0.14, 12), yellowMat);
      rim.rotation.x = Math.PI * 0.5;
      rim.position.set(gx, 0.2, 0.47);
      const lens = new THREE.Mesh(new THREE.CircleGeometry(0.12, 12), goggleLensMat);
      lens.position.set(gx, 0.2, 0.55);
      headGroup.add(rim, lens);
    });

    catPilot.add(headGroup);
    planeParts.catHead = headGroup;

    // Fluttering Red Pilot Scarf trailing behind the cat
    const scarfRoot = new THREE.Group();
    scarfRoot.position.set(0, 0.52, -0.28);
    for (let s = 0; s < 5; s++) {
      const seg = new THREE.Mesh(new THREE.BoxGeometry(0.34 - s * 0.03, 0.08, 0.46), scarfMat);
      seg.position.set(0, 0, -s * 0.38);
      scarfRoot.add(seg);
      planeParts.scarfSegments.push(seg);
    }
    catPilot.add(scarfRoot);
    planeGroup.add(catPilot);

    // Attached Fish Crate under plane's belly ready to drop
    const bellyCrate = new THREE.Mesh(new THREE.BoxGeometry(1.4, 1.1, 1.4), fishCrateMat);
    bellyCrate.position.set(0, -1.15, 0.2);
    planeGroup.add(bellyCrate);
    planeParts.bellyCrate = bellyCrate;
  }

  buildCatPlane();

  // --- Falling Parachute Crates & Sparkle Particles ---
  const fallingCrates = [];
  const particles = [];

  const chuteMat1 = new THREE.MeshLambertMaterial({ color: 0xfff3d6, side: THREE.DoubleSide });
  const chuteMat2 = new THREE.MeshLambertMaterial({ color: 0xff6b3d, side: THREE.DoubleSide });
  const cordMat = new THREE.LineBasicMaterial({ color: 0xfff0d0 });

  function spawnParachuteCrate(startPos, deliveryObj) {
    const group = new THREE.Group();
    group.position.copy(startPos);

    // Wooden Fish Crate
    const crateMesh = new THREE.Mesh(new THREE.BoxGeometry(2.1, 1.8, 2.1), fishCrateMat);
    crateMesh.castShadow = true;
    group.add(crateMesh);

    // Parachute Canopy & Suspension Lines
    const chuteGroup = new THREE.Group();
    chuteGroup.position.y = 4.4;

    const segs = 8;
    for (let i = 0; i < segs; i++) {
      const phiStart = (i / segs) * Math.PI * 2;
      const phiLen = (1 / segs) * Math.PI * 2;
      const domeGeo = new THREE.SphereGeometry(3.2, 4, 8, phiStart, phiLen, 0, Math.PI * 0.52);
      const panel = new THREE.Mesh(domeGeo, i % 2 === 0 ? chuteMat1 : chuteMat2);
      chuteGroup.add(panel);
    }

    // 4 Parachute suspension cords
    const cordPts = [
      new THREE.Vector3(-2.6, -0.2, -2.6), new THREE.Vector3(-0.8, -3.6, -0.8),
      new THREE.Vector3( 2.6, -0.2, -2.6), new THREE.Vector3( 0.8, -3.6, -0.8),
      new THREE.Vector3(-2.6, -0.2,  2.6), new THREE.Vector3(-0.8, -3.6,  0.8),
      new THREE.Vector3( 2.6, -0.2,  2.6), new THREE.Vector3( 0.8, -3.6,  0.8)
    ];
    const cordGeo = new THREE.BufferGeometry().setFromPoints(cordPts);
    const cords = new THREE.LineSegments(cordGeo, cordMat);
    chuteGroup.add(cords);

    group.add(chuteGroup);
    scene.add(group);

    const targetPos = new THREE.Vector3(
      deliveryObj.site.x - 0.85,
      deliveryObj.site.landingY + 0.9,
      deliveryObj.site.z
    );

    fallingCrates.push({
      group: group,
      chuteGroup: chuteGroup,
      startPos: startPos.clone(),
      targetPos: targetPos,
      deliveryObj: deliveryObj,
      progress: 0,
      duration: 3.1,
      swaySeed: Math.random() * 10
    });
  }

  function spawnRingBurst(pos, colorHex) {
    const geo = new THREE.OctahedronGeometry(0.42, 0);
    const mat = new THREE.MeshBasicMaterial({ color: colorHex || 0xffe066 });
    for (let i = 0; i < 20; i++) {
      const m = new THREE.Mesh(geo, mat);
      m.position.copy(pos);
      const ang = (i / 20) * Math.PI * 2;
      const spd = 8 + Math.random() * 12;
      const vel = new THREE.Vector3(
        Math.cos(ang) * spd,
        (Math.random() - 0.3) * spd,
        Math.sin(ang) * spd
      );
      scene.add(m);
      particles.push({
        mesh: m,
        vel: vel,
        life: 0.95
      });
    }
  }

  // --- Demo Mode Closed Spline Curve around the 8 Glowing Rings ---
  const demoWaypoints = DELIVERY_SITES.map((s) => new THREE.Vector3(s.x, s.ringY, s.z));
  const demoCurve = new THREE.CatmullRomCurve3(demoWaypoints, true, "catmullrom", 0.5);

  // --- Game State & Controls ---
  const TOTAL_CRATES = DELIVERY_SITES.length;
  const TOTAL_DAYLIGHT_SECONDS = 90.0;

  let score = 0;
  let cratesLeft = TOTAL_CRATES;
  let timeRemaining = TOTAL_DAYLIGHT_SECONDS;
  let gameEnded = false;

  // Plane Flight Kinematics
  const planeState = {
    pos: new THREE.Vector3(-42, 26, -118),
    heading: Math.PI * 0.5, // radians, 0 = +Z, PI/2 = +X
    pitch: 0,
    roll: 0,
    speed: 41.0,
    targetAlt: 28.0
  };

  // Steering Input State
  const input = {
    steerX: 0, // -1 (left) to +1 (right)
    steerY: 0, // -1 (down) to +1 (up)
    isDraggingTouch: false,
    touchAnchorX: 0,
    touchAnchorY: 0,
    hasMouseMoved: false
  };

  // Camera Modes: 'behind', 'cockpit', 'above'
  let cameraMode = "behind";
  const smoothCamPos = new THREE.Vector3();
  const smoothCamLook = new THREE.Vector3();
  let camInitialized = false;

  // Demo Mode State (#demo)
  let isDemoMode = window.location.hash.toLowerCase() === "#demo";
  let demoElapsed = 0;

  function setCameraMode(mode, silent) {
    cameraMode = mode;
    camButtons.forEach((btn) => {
      btn.classList.toggle("active", btn.getAttribute("data-cam") === mode);
    });
    if (!silent) {
      const labels = {
        behind: "Camera: Behind the Plane",
        cockpit: "Camera: Inside the Cockpit",
        above: "Camera: From Above"
      };
      showToast(labels[mode] || "", 1800);
    }
  }

  function updateHUD(pulseScore) {
    scoreEl.textContent = String(score);
    cratesEl.textContent = String(cratesLeft);
    if (pulseScore) {
      scoreEl.classList.add("pulse");
      cratesEl.classList.add("pulse");
      setTimeout(() => {
        scoreEl.classList.remove("pulse");
        cratesEl.classList.remove("pulse");
      }, 220);
    }

    const secs = Math.max(0, Math.ceil(timeRemaining));
    const m = Math.floor(secs / 60);
    const s = secs % 60;
    timeEl.textContent = m + ":" + (s < 10 ? "0" + s : s);

    const pct = clamp((timeRemaining / TOTAL_DAYLIGHT_SECONDS) * 100, 0, 100);
    sunsetBarEl.style.width = pct.toFixed(1) + "%";
    sunIconEl.textContent = pct > 25 ? "🌅" : "🌙";
  }

  function resetGame(keepDemo) {
    score = 0;
    cratesLeft = TOTAL_CRATES;
    timeRemaining = TOTAL_DAYLIGHT_SECONDS;
    gameEnded = false;
    endModalEl.classList.remove("open");

    // Start positioned cleanly behind the first glowing ring (North Harbor Dock)
    planeState.pos.set(-48, 26, -118);
    planeState.heading = Math.PI * 0.5;
    planeState.pitch = 0;
    planeState.roll = 0;
    planeState.targetAlt = 26;

    input.steerX = 0;
    input.steerY = 0;

    if (planeParts.bellyCrate) {
      planeParts.bellyCrate.visible = true;
    }

    // Clear falling crates & delivered static crates
    while (fallingCrates.length > 0) {
      const fc = fallingCrates.pop();
      scene.remove(fc.group);
    }

    deliveryObjects.forEach((d) => {
      d.active = true;
      d.ringGroup.visible = true;
      d.beamMesh.visible = true;
      d.catObj.delivered = false;
      d.catObj.happyTimer = 0;
      if (d.deliveredMesh) {
        scene.remove(d.deliveredMesh);
        d.deliveredMesh = null;
      }
    });

    if (!keepDemo) {
      isDemoMode = false;
      demoBannerEl.style.display = "none";
    } else {
      demoElapsed = 0;
      demoBannerEl.style.display = "block";
    }

    camInitialized = false;
    updateHUD(false);
  }

  function endDemoAndPlay() {
    if (!isDemoMode) return;
    isDemoMode = false;
    demoBannerEl.style.display = "none";
    try {
      if (window.location.hash.toLowerCase() === "#demo") {
        history.replaceState(null, "", window.location.pathname + window.location.search);
      }
    } catch (e) {}
    setCameraMode("behind", true);
    resetGame(false);
    showToast("You have the controls! Fly through the glowing rings!", 3200);
  }

  window.addEventListener("hashchange", () => {
    if (window.location.hash.toLowerCase() === "#demo") {
      isDemoMode = true;
      resetGame(true);
    }
  });

  // --- Input Event Listeners (Mouse Pointer & 1-Finger Touch Drag) ---
  function updateReticleDisplay(clientX, clientY, visible) {
    if (!visible || isDemoMode || gameEnded) {
      reticleEl.style.display = "none";
      return;
    }
    reticleEl.style.display = "block";
    reticleEl.style.left = clientX + "px";
    reticleEl.style.top = clientY + "px";
  }

  // Mouse pointer following on desktop
  window.addEventListener("mousemove", (e) => {
    if (isDemoMode || gameEnded || input.isDraggingTouch) return;
    const nx = (e.clientX / window.innerWidth) * 2 - 1;
    const ny = -((e.clientY / window.innerHeight) * 2 - 1);

    // Soft center deadzone
    const dead = 0.04;
    const sx = Math.abs(nx) < dead ? 0 : (nx - Math.sign(nx) * dead) / (1 - dead);
    const sy = Math.abs(ny) < dead ? 0 : (ny - Math.sign(ny) * dead) / (1 - dead);

    input.steerX = clamp(sx * 1.25, -1, 1);
    input.steerY = clamp(sy * 1.25, -1, 1);
    input.hasMouseMoved = true;
    updateReticleDisplay(e.clientX, e.clientY, true);
  });

  window.addEventListener("mousedown", (e) => {
    Sound.resume();
    if (isDemoMode) {
      endDemoAndPlay();
    }
  });

  // 1-Finger Touch Drag on phones & tablets
  canvas.addEventListener("touchstart", (e) => {
    Sound.resume();
    if (isDemoMode) {
      endDemoAndPlay();
    }
    if (e.touches.length > 0) {
      const t = e.touches[0];
      input.isDraggingTouch = true;
      const spanX = window.innerWidth * 0.34;
      const spanY = window.innerHeight * 0.30;
      input.touchAnchorX = t.clientX - input.steerX * spanX;
      input.touchAnchorY = t.clientY + input.steerY * spanY;
      updateReticleDisplay(t.clientX, t.clientY, true);
    }
  }, { passive: true });

  canvas.addEventListener("touchmove", (e) => {
    if (!input.isDraggingTouch || e.touches.length === 0) return;
    const t = e.touches[0];
    const spanX = window.innerWidth * 0.34;
    const spanY = window.innerHeight * 0.30;
    input.steerX = clamp((t.clientX - input.touchAnchorX) / spanX, -1, 1);
    input.steerY = clamp(-(t.clientY - input.touchAnchorY) / spanY, -1, 1);
    updateReticleDisplay(t.clientX, t.clientY, true);
  }, { passive: true });

  function handleTouchEnd() {
    input.isDraggingTouch = false;
    updateReticleDisplay(0, 0, false);
  }
  canvas.addEventListener("touchend", handleTouchEnd, { passive: true });
  canvas.addEventListener("touchcancel", handleTouchEnd, { passive: true });

  // Camera Buttons
  camButtons.forEach((btn) => {
    btn.addEventListener("click", (e) => {
      e.stopPropagation();
      Sound.resume();
      const mode = btn.getAttribute("data-cam");
      if (isDemoMode) {
        endDemoAndPlay();
      }
      setCameraMode(mode, false);
    });
  });

  // Sound Mute Toggle
  soundBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    Sound.muted = !Sound.muted;
    if (!Sound.muted) Sound.resume();
    soundBtn.textContent = Sound.muted ? "🔇" : "🔊";
  });

  // Play Again Button
  playAgainBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    Sound.resume();
    resetGame(false);
    showToast("New sunset flight started! Deliver all 8 fish crates!", 3000);
  });

  // --- Trigger End of Round ---
  function finishRound(victory) {
    if (gameEnded) return;
    gameEnded = true;
    updateReticleDisplay(0, 0, false);
    ringPointerEl.style.display = "none";

    if (victory) {
      const timeBonus = Math.round(timeRemaining * 10);
      score += timeBonus;
      updateHUD(true);
    }

    const best = saveBestScore(score);
    Sound.playFanfare(victory);

    modalBadgeEl.textContent = victory ? "🐱🐟" : "🌙✈️";
    modalTitleEl.textContent = victory ? "All Fish Delivered!" : "Night Has Fallen!";
    modalSubEl.textContent = victory
      ? "Purr-fect flying! Every cat on the docks and rooftops got their fish crate before dark!"
      : "The stars came out over Lake Town! See if you can deliver every crate before sunset ends.";

    endScoreEl.textContent = String(score);
    endCratesLeftEl.textContent = String(cratesLeft);
    endDeliveredEl.textContent = (TOTAL_CRATES - cratesLeft) + " / " + TOTAL_CRATES;
    endBestEl.textContent = String(best);

    endModalEl.classList.add("open");
  }

  // --- Ring Trigger & Parachute Crate Drop ---
  function triggerRingDelivery(dObj, distToCenter) {
    if (!dObj.active) return;
    dObj.active = false;
    dObj.ringGroup.visible = false;
    dObj.beamMesh.visible = false;

    cratesLeft = Math.max(0, cratesLeft - 1);
    const centerBonus = Math.max(0, Math.round((1 - clamp(distToCenter / 8.5, 0, 1)) * 50));
    const pts = 100 + centerBonus;
    score += pts;
    updateHUD(true);

    if (cratesLeft === 0 && planeParts.bellyCrate) {
      planeParts.bellyCrate.visible = false;
    }

    Sound.playRingChime();
    spawnRingBurst(dObj.ringGroup.position, 0xffe066);

    const dropPos = planeState.pos.clone();
    dropPos.y -= 1.2;
    spawnParachuteCrate(dropPos, dObj);

    showToast(
      "+" + pts + " pts! Fish crate floating down to " + dObj.site.name + "!",
      2600
    );

    if (!isDemoMode && cratesLeft === 0) {
      setTimeout(() => {
        finishRound(true);
      }, 1800);
    }
  }

  // --- Update Sunset-to-Night Lighting & Atmosphere ---
  const cSunGold = new THREE.Color(0xff9b42);
  const cSunDusk = new THREE.Color(0xc93b5b);
  const cSunNight = new THREE.Color(0x3a4d8f);

  const cFogSunset = new THREE.Color(0xd87b56);
  const cFogDusk = new THREE.Color(0x52315c);
  const cFogNight = new THREE.Color(0x0d1226);

  function updateAtmosphere(nightFactor, elapsedSec) {
    skyUniforms.uNightFactor.value = nightFactor;
    skyUniforms.uTime.value = elapsedSec;
    waterUniforms.uNightFactor.value = nightFactor;
    waterUniforms.uTime.value = elapsedSec;

    // Lower the sun gradually toward the horizon as night approaches
    const sunElev = lerp(0.24, -0.04, nightFactor);
    skyUniforms.uSunDir.value.set(-0.58, sunElev, -0.78).normalize();
    sunLight.position.copy(skyUniforms.uSunDir.value).multiplyScalar(340);
    sunLight.position.y = Math.max(25, sunLight.position.y);

    if (nightFactor < 0.5) {
      const t = nightFactor * 2;
      sunLight.color.copy(cSunGold).lerp(cSunDusk, t);
      scene.fog.color.copy(cFogSunset).lerp(cFogDusk, t);
    } else {
      const t = (nightFactor - 0.5) * 2;
      sunLight.color.copy(cSunDusk).lerp(cSunNight, t);
      scene.fog.color.copy(cFogDusk).lerp(cFogNight, t);
    }

    sunLight.intensity = lerp(1.38, 0.38, nightFactor);
    hemiLight.intensity = lerp(0.88, 0.35, nightFactor);
    cloudMat.emissiveIntensity = lerp(0.38, 0.08, nightFactor);
  }

  // --- Update HUD On-Screen Ring Finder Arrow ---
  const projVec = new THREE.Vector3();
  function updateRingPointer(nearestObj) {
    if (!nearestObj || isDemoMode || gameEnded) {
      ringPointerEl.style.display = "none";
      return;
    }

    projVec.copy(nearestObj.ringGroup.position);
    projVec.project(camera);

    const isBehind = projVec.z > 1.0;
    const ndcX = isBehind ? -projVec.x : projVec.x;
    const ndcY = isBehind ? -projVec.y : projVec.y;

    // Show edge pointer only when nearest ring is near or outside screen edges
    if (!isBehind && Math.abs(ndcX) < 0.78 && Math.abs(ndcY) < 0.72) {
      ringPointerEl.style.display = "none";
      return;
    }

    const angle = Math.atan2(ndcY, ndcX);
    const padX = window.innerWidth * 0.41;
    const padY = window.innerHeight * 0.36;
    const sx = window.innerWidth * 0.5 + Math.cos(angle) * padX;
    const sy = window.innerHeight * 0.5 - Math.sin(angle) * padY;

    ringPointerEl.style.display = "flex";
    ringPointerEl.style.left = clamp(sx, 34, window.innerWidth - 34) + "px";
    ringPointerEl.style.top = clamp(sy, 72, window.innerHeight - 85) + "px";

    const rotDeg = 90 - (angle * 180) / Math.PI;
    ringPointerArrow.setAttribute("transform", "rotate(" + rotDeg + " 22 22)");
  }

  // --- Main Animation Loop ---
  let lastTime = performance.now();
  let totalElapsed = 0;

  if (isDemoMode) {
    resetGame(true);
  } else {
    resetGame(false);
    showToast("Fly through the glowing rings to drop fish crates to waiting cats!", 4000);
  }

  function animate(now) {
    requestAnimationFrame(animate);

    const dt = Math.min((now - lastTime) * 0.001, 0.05);
    lastTime = now;
    totalElapsed += dt;

    // 1. Update Demo Mode OR Player Flight Controls
    if (isDemoMode) {
      demoElapsed += dt;
      const loopDuration = 20.0;
      if (demoElapsed >= loopDuration) {
        demoElapsed -= loopDuration;
        // Refresh all rings seamlessly for continuous 20s hands-free loop
        cratesLeft = TOTAL_CRATES;
        if (planeParts.bellyCrate) planeParts.bellyCrate.visible = true;
        deliveryObjects.forEach((d) => {
          d.active = true;
          d.ringGroup.visible = true;
          d.beamMesh.visible = true;
        });
      }

      // Cycle through all 3 cameras automatically during the 20s demo loop
      if (demoElapsed < 7.5) {
        if (cameraMode !== "behind") setCameraMode("behind", true);
      } else if (demoElapsed < 14.0) {
        if (cameraMode !== "cockpit") setCameraMode("cockpit", true);
      } else {
        if (cameraMode !== "above") setCameraMode("above", true);
      }

      const u = (demoElapsed / loopDuration) % 1.0;
      const uNext = ((demoElapsed + 0.08) / loopDuration) % 1.0;
      const pt = demoCurve.getPointAt(u);
      const ptNext = demoCurve.getPointAt(uNext);
      const tangent = ptNext.clone().sub(pt).normalize();

      const prevHeading = planeState.heading;
      planeState.pos.copy(pt);
      planeState.heading = Math.atan2(tangent.x, tangent.z);

      let dHeading = planeState.heading - prevHeading;
      while (dHeading > Math.PI) dHeading -= Math.PI * 2;
      while (dHeading < -Math.PI) dHeading += Math.PI * 2;

      planeState.roll = damp(planeState.roll, clamp(-dHeading / Math.max(dt, 0.008) * 0.35, -0.65, 0.65), 6, dt);
      planeState.pitch = damp(planeState.pitch, clamp(-tangent.y * 0.65, -0.35, 0.35), 6, dt);

      // Oscillate sunset softly during demo
      timeRemaining = TOTAL_DAYLIGHT_SECONDS * (0.72 - 0.35 * Math.sin(u * Math.PI * 2));
      updateHUD(false);
    } else if (!gameEnded) {
      // Countdown sunset timer
      timeRemaining = Math.max(0, timeRemaining - dt);
      updateHUD(false);
      if (timeRemaining <= 0) {
        finishRound(false);
      }

      // When touch finger is lifted on mobile, gently level out turn
      if (!input.isDraggingTouch && !input.hasMouseMoved) {
        input.steerX = damp(input.steerX, 0, 3.5, dt);
        input.steerY = damp(input.steerY, 0, 2.0, dt);
      } else if (!input.isDraggingTouch && "ontouchstart" in window) {
        input.steerX = damp(input.steerX, 0, 3.5, dt);
        input.steerY = damp(input.steerY, 0, 1.5, dt);
      }

      // Steer yaw & bank
      const turnRate = -input.steerX * 1.48;
      planeState.heading += turnRate * dt;
      const targetRoll = -input.steerX * 0.72;
      planeState.roll = damp(planeState.roll, targetRoll, 7.0, dt);

      // Base target altitude from vertical pointer/finger drag
      let desiredAlt = clamp(29.5 + input.steerY * 15.0, 15.0, 48.0);

      // Gentle magnetic ring altitude assist when flying toward a nearby active ring
      const fwdX = Math.sin(planeState.heading);
      const fwdZ = Math.cos(planeState.heading);
      let bestAssistDist = 68;
      deliveryObjects.forEach((d) => {
        if (!d.active) return;
        const dx = d.site.x - planeState.pos.x;
        const dz = d.site.z - planeState.pos.z;
        const hDist = Math.hypot(dx, dz);
        if (hDist < bestAssistDist && hDist > 2) {
          const dot = (dx * fwdX + dz * fwdZ) / hDist;
          if (dot > 0.76) {
            bestAssistDist = hDist;
            const blend = (1 - hDist / 68) * 0.55;
            desiredAlt = lerp(desiredAlt, d.site.ringY, blend);
          }
        }
      });

      // Ensure plane always stays safely above hills & buildings
      const groundBeneath = getTerrainHeight(planeState.pos.x, planeState.pos.z);
      desiredAlt = Math.max(desiredAlt, groundBeneath + 11.5);

      planeState.targetAlt = damp(planeState.targetAlt, desiredAlt, 3.8, dt);
      const vy = (planeState.targetAlt - planeState.pos.y) * 2.5;
      planeState.pos.y += vy * dt;

      const targetPitch = clamp(-vy * 0.028, -0.38, 0.38);
      planeState.pitch = damp(planeState.pitch, targetPitch, 6.5, dt);

      // Move plane forward
      planeState.pos.x += Math.sin(planeState.heading) * planeState.speed * dt;
      planeState.pos.z += Math.cos(planeState.heading) * planeState.speed * dt;

      // Soft boundary turnback if flying too far outside the lake basin
      const distFromCenter = Math.hypot(planeState.pos.x, planeState.pos.z);
      if (distFromCenter > 215) {
        const toCenterHeading = Math.atan2(-planeState.pos.x, -planeState.pos.z);
        let diff = toCenterHeading - planeState.heading;
        while (diff > Math.PI) diff -= Math.PI * 2;
        while (diff < -Math.PI) diff += Math.PI * 2;
        planeState.heading += diff * dt * 1.4;
      }
    }

    // Apply transform to planeGroup
    planeGroup.position.copy(planeState.pos);
    planeGroup.rotation.order = "YXZ";
    planeGroup.rotation.y = planeState.heading;
    planeGroup.rotation.x = planeState.pitch;
    planeGroup.rotation.z = planeState.roll;

    // Animate plane details (propeller, cat head, scarf, cockpit gauges)
    if (planeParts.propeller) {
      planeParts.propeller.rotation.z += dt * 38;
    }
    if (planeParts.catHead) {
      planeParts.catHead.rotation.y = damp(planeParts.catHead.rotation.y, -input.steerX * 0.42, 8, dt);
      planeParts.catHead.rotation.z = damp(planeParts.catHead.rotation.z, -planeState.roll * 0.3, 8, dt);
    }
    if (planeParts.yoke) {
      planeParts.yoke.rotation.z = planeState.roll * 0.6;
    }
    planeParts.scarfSegments.forEach((seg, idx) => {
      seg.position.x = Math.sin(totalElapsed * 14 - idx * 0.9) * (0.045 * (idx + 1));
      seg.position.y = Math.cos(totalElapsed * 11 - idx * 0.7) * (0.03 * (idx + 1));
    });

    Sound.updateProp(Math.abs(input.steerX) + Math.abs(input.steerY));

    // 2. Check Glowing Ring Fly-Throughs & Find Nearest Active Ring
    let nearestRing = null;
    let nearestDistSq = Infinity;

    deliveryObjects.forEach((d) => {
      // Animate waiting cat on rooftop or dock
      const cat = d.catObj;
      if (!cat.delivered) {
        // Wave paws at plane and look toward plane
        cat.leftPaw.rotation.z = 0.8 + Math.sin(totalElapsed * 7 + d.index) * 0.45;
        cat.rightPaw.rotation.z = -0.8 - Math.cos(totalElapsed * 7 + d.index) * 0.45;
        cat.tail.rotation.z = Math.sin(totalElapsed * 5 + d.index) * 0.4;
        const angleToPlane = Math.atan2(
          planeState.pos.x - d.site.x,
          planeState.pos.z - d.site.z
        );
        cat.catMesh.rotation.y = angleToPlane;
      } else {
        // Happy cat jump dance after receiving fish crate!
        cat.happyTimer += dt;
        cat.catMesh.position.y = 0.24 + Math.abs(Math.sin(cat.happyTimer * 7)) * 0.75;
        cat.catMesh.rotation.y += dt * 3.5;
        cat.tail.rotation.z = Math.sin(totalElapsed * 10) * 0.6;
      }

      if (!d.active) return;

      // Rotate inner star ring & orbiting sparkles
      d.innerStarRing.rotation.z = totalElapsed * 1.4;
      d.orbsGroup.rotation.z = -totalElapsed * 1.1;
      const pulse = 1 + Math.sin(totalElapsed * 3.5 + d.index) * 0.06;
      d.ringGroup.scale.set(pulse, pulse, pulse);

      const dSq = planeState.pos.distanceToSquared(d.ringGroup.position);
      if (dSq < nearestDistSq) {
        nearestDistSq = dSq;
        nearestRing = d;
      }

      // Generous fly-through trigger radius (9.2 units)
      if (!gameEnded && dSq < 9.2 * 9.2) {
        triggerRingDelivery(d, Math.sqrt(dSq));
      }
    });

    // Update Cockpit Gauges & Screen Edge Ring Pointer
    if (planeParts.altNeedle) {
      const altRatio = clamp((planeState.pos.y - 12) / 40, 0, 1);
      planeParts.altNeedle.rotation.z = (altRatio - 0.5) * 2.4;
    }
    if (planeParts.sunsetNeedle) {
      const sunRatio = clamp(1 - timeRemaining / TOTAL_DAYLIGHT_SECONDS, 0, 1);
      planeParts.sunsetNeedle.rotation.z = (sunRatio - 0.5) * 2.4;
    }
    if (planeParts.compassNeedle && nearestRing) {
      const toRingAngle = Math.atan2(
        nearestRing.site.x - planeState.pos.x,
        nearestRing.site.z - planeState.pos.z
      );
      const relAngle = toRingAngle - planeState.heading;
      planeParts.compassNeedle.rotation.z = relAngle;
    }
    updateRingPointer(nearestRing);

    // 3. Update Parachute Crates Floating Down to Waiting Cats
    for (let i = fallingCrates.length - 1; i >= 0; i--) {
      const fc = fallingCrates[i];
      fc.progress += dt / fc.duration;
      const t = clamp(fc.progress, 0, 1);

      // Smooth horizontal glide + steady parachute descent
      const horizT = 1 - Math.pow(1 - t, 2.2);
      fc.group.position.x = lerp(fc.startPos.x, fc.targetPos.x, horizT);
      fc.group.position.z = lerp(fc.startPos.z, fc.targetPos.z, horizT);
      fc.group.position.y = lerp(fc.startPos.y, fc.targetPos.y, t);

      // Gentle pendulum parachute sway in the breeze
      const sway = Math.sin(totalElapsed * 4.2 + fc.swaySeed) * 0.22 * (1 - t * 0.7);
      fc.group.rotation.z = sway;
      fc.group.rotation.x = Math.cos(totalElapsed * 3.4 + fc.swaySeed) * 0.16 * (1 - t * 0.7);

      if (t >= 1) {
        // Crate has landed at the waiting cat on the rooftop or dock!
        Sound.playCatLanding();
        spawnRingBurst(fc.targetPos, 0xff9e44);

        // Detach parachute and leave the delivered fish crate beside the happy cat
        fc.group.remove(fc.chuteGroup);
        fc.group.rotation.set(0, fc.swaySeed, 0);
        fc.group.position.copy(fc.targetPos);
        fc.deliveryObj.deliveredMesh = fc.group;
        fc.deliveryObj.catObj.delivered = true;

        fallingCrates.splice(i, 1);
      }
    }

    // 4. Update Burst Particles, Drifting Clouds & Town Animations
    for (let i = particles.length - 1; i >= 0; i--) {
      const p = particles[i];
      p.life -= dt;
      if (p.life <= 0) {
        scene.remove(p.mesh);
        particles.splice(i, 1);
      } else {
        p.mesh.position.addScaledVector(p.vel, dt);
        p.mesh.scale.setScalar(p.life);
        p.mesh.rotation.x += dt * 5;
        p.mesh.rotation.y += dt * 5;
      }
    }

    clouds.forEach((c) => {
      c.angle += c.speed * dt;
      c.mesh.position.x = Math.cos(c.angle) * c.dist;
      c.mesh.position.z = Math.sin(c.angle) * c.dist;
      c.mesh.rotation.y = -c.angle;
    });

    if (animatedStructures.windmillBlades) {
      animatedStructures.windmillBlades.rotation.z -= dt * 0.85;
    }
    animatedStructures.boats.forEach((b, idx) => {
      b.position.y = 0.05 + Math.sin(totalElapsed * 2.4 + idx) * 0.08;
      b.rotation.z = Math.sin(totalElapsed * 1.9 + idx) * 0.05;
    });

    // 5. Sunset to Nightfall Atmosphere Update
    const nightFactor = clamp(1 - timeRemaining / TOTAL_DAYLIGHT_SECONDS, 0, 1);
    updateAtmosphere(nightFactor, totalElapsed);

    // 6. Update Camera Position & Target for the 3 Camera Modes
    const desiredPos = new THREE.Vector3();
    const desiredLook = new THREE.Vector3();

    if (cameraMode === "cockpit") {
      // Inside the Cockpit: looking right over the orange cat pilot's ears & dashboard gauges!
      const localEye = new THREE.Vector3(0, 1.48, -0.38);
      const localLook = new THREE.Vector3(0, 1.15, 22.0);
      planeGroup.localToWorld(localEye);
      planeGroup.localToWorld(localLook);

      camera.position.copy(localEye);
      camera.up.set(0, 1, 0);
      camera.lookAt(localLook);
      smoothCamPos.copy(localEye);
      smoothCamLook.copy(localLook);
    } else if (cameraMode === "above") {
      // From Above: High bird's-eye view over the plane, glowing rings, and lake reflections
      const backX = Math.sin(planeState.heading);
      const backZ = Math.cos(planeState.heading);
      desiredPos.set(
        planeState.pos.x - backX * 22,
        planeState.pos.y + 62,
        planeState.pos.z - backZ * 22
      );
      desiredLook.set(
        planeState.pos.x + backX * 14,
        planeState.pos.y - 4,
        planeState.pos.z + backZ * 14
      );

      if (!camInitialized) {
        smoothCamPos.copy(desiredPos);
        smoothCamLook.copy(desiredLook);
        camInitialized = true;
      } else {
        smoothCamPos.lerp(desiredPos, 1 - Math.exp(-7 * dt));
        smoothCamLook.lerp(desiredLook, 1 - Math.exp(-9 * dt));
      }
      camera.position.copy(smoothCamPos);
      camera.up.set(0, 1, 0);
      camera.lookAt(smoothCamLook);
    } else {
      // Behind the Plane: Classic warm chase camera
      const fwdX = Math.sin(planeState.heading);
      const fwdZ = Math.cos(planeState.heading);
      desiredPos.set(
        planeState.pos.x - fwdX * 15.5,
        Math.max(4.5, planeState.pos.y + 4.6 - planeState.pitch * 6.0),
        planeState.pos.z - fwdZ * 15.5
      );
      desiredLook.set(
        planeState.pos.x + fwdX * 16.0,
        planeState.pos.y + 0.8,
        planeState.pos.z + fwdZ * 16.0
      );

      if (!camInitialized) {
        smoothCamPos.copy(desiredPos);
        smoothCamLook.copy(desiredLook);
        camInitialized = true;
      } else {
        smoothCamPos.lerp(desiredPos, 1 - Math.exp(-8.5 * dt));
        smoothCamLook.lerp(desiredLook, 1 - Math.exp(-11 * dt));
      }
      camera.position.copy(smoothCamPos);
      camera.up.set(0, 1, 0);
      camera.lookAt(smoothCamLook);
    }

    camera.updateMatrixWorld(true);
    waterUniforms.uCameraPos.value.copy(camera.position);

    // 7. Render Real-Time Planar Water Reflection Pass
    reflectCamera.aspect = camera.aspect;
    reflectCamera.fov = Math.min(105, camera.fov + 14);
    reflectCamera.updateProjectionMatrix();

    reflectCamera.position.set(
      camera.position.x,
      -Math.max(1.5, camera.position.y),
      camera.position.z
    );
    const reflTarget = new THREE.Vector3(
      smoothCamLook.x,
      -smoothCamLook.y,
      smoothCamLook.z
    );
    reflectCamera.up.set(0, 1, 0);
    reflectCamera.lookAt(reflTarget);
    reflectCamera.updateMatrixWorld(true);

    reflectMatrix.multiplyMatrices(
      reflectCamera.projectionMatrix,
      reflectCamera.matrixWorldInverse
    );

    waterMesh.visible = false;
    renderer.setRenderTarget(reflectRT);
    renderer.render(scene, reflectCamera);
    renderer.setRenderTarget(null);
    waterMesh.visible = true;

    // 8. Render Main Scene
    renderer.render(scene, camera);
  }

  requestAnimationFrame(animate);

  // --- Responsive Resize Handler ---
  window.addEventListener("resize", () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  });
})();
</script>
</body>
</html>