Skip to content
VibeCodeBench
Back to the app

The code

Lantern Cats 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.)82.0 KB · 2,352 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>Festival Night — Paper-Lantern Cats</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: #070b1a;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    color: #fff5e4;
    touch-action: none;
  }
  #canvas-container {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    touch-action: none;
  }
  canvas {
    display: block;
    width: 100%;
    height: 100%;
    touch-action: none;
  }
  .hud-top {
    position: fixed;
    top: 16px;
    left: 16px;
    right: 16px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    pointer-events: none;
    z-index: 20;
    gap: 12px;
  }
  .title-card {
    background: rgba(10, 15, 34, 0.72);
    border: 1px solid rgba(255, 190, 110, 0.32);
    border-radius: 18px;
    padding: 10px 16px;
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);
    max-width: min(360px, 60vw);
  }
  .title-card h1 {
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 0.03em;
    color: #ffd79a;
    margin-bottom: 3px;
    text-shadow: 0 0 12px rgba(255, 155, 50, 0.5);
  }
  .title-card p {
    font-size: 12.5px;
    line-height: 1.35;
    color: rgba(255, 240, 220, 0.85);
  }
  .controls-group {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 10px;
    pointer-events: auto;
  }
  .big-btn {
    appearance: none;
    border: 1.5px solid rgba(255, 200, 130, 0.55);
    background: rgba(16, 23, 48, 0.84);
    color: #fff2db;
    min-height: 52px;
    min-width: 156px;
    padding: 10px 20px;
    border-radius: 26px;
    font-size: 15px;
    font-weight: 600;
    letter-spacing: 0.02em;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    box-shadow: 0 6px 22px rgba(0, 0, 0, 0.5), inset 0 0 14px rgba(255, 170, 70, 0.15);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    transition: transform 0.12s ease, background 0.2s ease, border-color 0.2s ease;
    touch-action: manipulation;
  }
  .big-btn:active {
    transform: scale(0.95);
    background: rgba(35, 48, 88, 0.92);
  }
  .big-btn.muted {
    border-color: rgba(180, 195, 220, 0.35);
    color: rgba(215, 225, 240, 0.78);
    box-shadow: 0 6px 22px rgba(0, 0, 0, 0.45);
  }
  .btn-icon {
    width: 22px;
    height: 22px;
    display: inline-block;
    flex-shrink: 0;
  }
  .status-banner {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(12, 18, 40, 0.78);
    border: 1px solid rgba(255, 200, 125, 0.38);
    border-radius: 999px;
    padding: 10px 22px;
    font-size: 14px;
    font-weight: 500;
    color: #ffe8c2;
    pointer-events: none;
    z-index: 20;
    white-space: nowrap;
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
    display: flex;
    align-items: center;
    gap: 9px;
    transition: opacity 0.25s ease, border-color 0.25s ease;
  }
  .status-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #ff942e;
    box-shadow: 0 0 10px #ff942e;
    flex-shrink: 0;
  }
  #demo-cursor {
    position: fixed;
    width: 44px;
    height: 44px;
    margin-left: -22px;
    margin-top: -22px;
    border-radius: 50%;
    border: 2.5px solid rgba(255, 220, 150, 0.92);
    background: radial-gradient(circle, rgba(255, 200, 110, 0.55) 0%, rgba(255, 140, 40, 0.12) 70%, transparent 100%);
    box-shadow: 0 0 20px rgba(255, 180, 75, 0.85);
    pointer-events: none;
    z-index: 18;
    display: none;
  }
  @media (max-width: 600px) {
    .title-card {
      padding: 8px 12px;
      max-width: 54vw;
    }
    .title-card h1 {
      font-size: 14px;
    }
    .title-card p {
      font-size: 11px;
    }
    .big-btn {
      min-height: 48px;
      min-width: 138px;
      padding: 8px 16px;
      font-size: 14px;
    }
    .status-banner {
      font-size: 12.5px;
      padding: 8px 16px;
      bottom: 14px;
    }
  }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</head>
<body>

<div id="canvas-container"></div>
<div id="demo-cursor"></div>

<div class="hud-top">
  <div class="title-card">
    <h1>Lantern Cat Festival</h1>
    <p>Touch or drag anywhere to call the nearest paper-lantern cat.</p>
  </div>
  <div class="controls-group">
    <button id="mute-btn" class="big-btn" type="button" aria-label="Toggle melody mute">
      <svg id="icon-sound-on" class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
        <path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
        <path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
      </svg>
      <svg id="icon-sound-off" class="btn-icon" style="display:none;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
        <line x1="23" y1="9" x2="17" y2="15"></line>
        <line x1="17" y1="9" x2="23" y2="15"></line>
      </svg>
      <span id="mute-label">Melody: ON</span>
    </button>
  </div>
</div>

<div id="status-banner" class="status-banner">
  <span id="status-dot" class="status-dot"></span>
  <span id="status-text">Weaving over the festival town &amp; river</span>
</div>

<script>
(function () {
  'use strict';

  // --- Utility Helpers ---
  function clamp(v, min, max) {
    return v < min ? min : (v > max ? max : v);
  }
  function lerp(a, b, t) {
    return a + (b - a) * t;
  }

  // --- Storage Helper (Rule 3: wrapped in try/catch) ---
  function getStoredMute() {
    try {
      return window.localStorage.getItem('lantern_cats_muted') === '1';
    } catch (e) {
      return false;
    }
  }
  function setStoredMute(val) {
    try {
      window.localStorage.setItem('lantern_cats_muted', val ? '1' : '0');
    } catch (e) {
      // Ignore storage restrictions in sandboxed iframe
    }
  }

  // --- Procedural Web Audio Festival Melody Synthesizer ---
  class FestivalMelody {
    constructor() {
      this.ctx = null;
      this.masterGain = null;
      this.delayL = null;
      this.delayR = null;
      this.isMuted = getStoredMute();
      this.isRunning = false;
      this.stepIndex = 0;
      this.nextNoteTime = 0;
      this.timerId = null;

      // D Major / B Minor Japanese Yo-Pentatonic Festival Melody
      // Frequencies in Hz
      this.notes = {
        D3: 146.83, E3: 164.81, Fs3: 185.00, A3: 220.00, B3: 246.94,
        D4: 293.66, E4: 329.63, Fs4: 369.99, A4: 440.00, B4: 493.88,
        D5: 587.33, E5: 659.25, Fs5: 739.99, A5: 880.00, B5: 987.77
      };

      // 32-step gentle cycling festival phrase (step = 0.42s)
      this.sequence = [
        { koto: 'A4', pad: 'D3', chime: null },
        { koto: 'B4', pad: null, chime: null },
        { koto: 'D5', pad: null, chime: 'A5' },
        { koto: null, pad: null, chime: null },
        { koto: 'Fs5', pad: 'B3', chime: null },
        { koto: 'E5', pad: null, chime: null },
        { koto: 'D5', pad: null, chime: null },
        { koto: 'B4', pad: null, chime: null },

        { koto: 'A4', pad: 'E3', chime: 'Fs5' },
        { koto: 'Fs4', pad: null, chime: null },
        { koto: 'E4', pad: null, chime: null },
        { koto: 'Fs4', pad: null, chime: null },
        { koto: 'A4', pad: 'A3', chime: null },
        { koto: null, pad: null, chime: 'E5' },
        { koto: 'B4', pad: null, chime: null },
        { koto: null, pad: null, chime: null },

        { koto: 'D5', pad: 'D3', chime: null },
        { koto: 'E5', pad: null, chime: null },
        { koto: 'Fs5', pad: null, chime: 'A5' },
        { koto: 'A5', pad: null, chime: null },
        { koto: 'Fs5', pad: 'Fs3', chime: null },
        { koto: 'E5', pad: null, chime: null },
        { koto: 'D5', pad: null, chime: null },
        { koto: null, pad: null, chime: null },

        { koto: 'B4', pad: 'B3', chime: 'D5' },
        { koto: 'D5', pad: null, chime: null },
        { koto: 'B4', pad: null, chime: null },
        { koto: 'A4', pad: null, chime: null },
        { koto: 'Fs4', pad: 'A3', chime: null },
        { koto: 'E4', pad: null, chime: null },
        { koto: 'D4', pad: 'D3', chime: 'A5' },
        { koto: null, pad: null, chime: null }
      ];
    }

    initContext() {
      if (this.ctx) return;
      const AudioCtx = window.AudioContext || window.webkitAudioContext;
      if (!AudioCtx) return;

      try {
        this.ctx = new AudioCtx();
        this.masterGain = this.ctx.createGain();
        this.masterGain.gain.value = this.isMuted ? 0.0 : 0.34;
        this.masterGain.connect(this.ctx.destination);

        // Soft stereo echo network for warm night-air ambience
        this.delayL = this.ctx.createDelay(1.0);
        this.delayR = this.ctx.createDelay(1.0);
        this.delayL.delayTime.value = 0.36;
        this.delayR.delayTime.value = 0.52;

        const fbL = this.ctx.createGain();
        const fbR = this.ctx.createGain();
        fbL.gain.value = 0.28;
        fbR.gain.value = 0.26;

        const toneFilter = this.ctx.createBiquadFilter();
        toneFilter.type = 'lowpass';
        toneFilter.frequency.value = 1350;

        this.delayL.connect(fbL);
        fbL.connect(toneFilter);
        toneFilter.connect(this.delayR);
        this.delayR.connect(fbR);
        fbR.connect(this.delayL);

        const wetGain = this.ctx.createGain();
        wetGain.gain.value = 0.38;
        this.delayL.connect(wetGain);
        this.delayR.connect(wetGain);
        wetGain.connect(this.masterGain);

        this.reverbInput = this.ctx.createGain();
        this.reverbInput.gain.value = 1.0;
        this.reverbInput.connect(this.delayL);

        this.nextNoteTime = this.ctx.currentTime + 0.08;
        this.isRunning = true;
        this.timerId = window.setInterval(() => this.scheduler(), 80);
      } catch (e) {
        // Web Audio unavailable
      }
    }

    ensureResumed() {
      if (!this.ctx) {
        this.initContext();
      }
      if (this.ctx && this.ctx.state === 'suspended' && !this.isMuted) {
        this.ctx.resume().catch(() => {});
      }
    }

    setMuted(muted) {
      this.isMuted = muted;
      setStoredMute(muted);
      if (!this.ctx && !muted) {
        this.initContext();
      }
      if (!this.ctx) return;

      const now = this.ctx.currentTime;
      this.masterGain.gain.cancelScheduledValues(now);
      this.masterGain.gain.setValueAtTime(this.masterGain.gain.value, now);
      if (muted) {
        this.masterGain.gain.linearRampToValueAtTime(0.0001, now + 0.18);
      } else {
        if (this.ctx.state === 'suspended') {
          this.ctx.resume().catch(() => {});
        }
        this.masterGain.gain.linearRampToValueAtTime(0.34, now + 0.25);
      }
    }

    scheduler() {
      if (!this.ctx || this.ctx.state !== 'running') return;
      while (this.nextNoteTime < this.ctx.currentTime + 0.25) {
        const step = this.sequence[this.stepIndex % this.sequence.length];
        if (!this.isMuted) {
          if (step.koto && this.notes[step.koto]) {
            this.playKoto(this.notes[step.koto], this.nextNoteTime);
          }
          if (step.pad && this.notes[step.pad]) {
            this.playBambooPad(this.notes[step.pad], this.nextNoteTime);
          }
          if (step.chime && this.notes[step.chime]) {
            this.playLanternChime(this.notes[step.chime], this.nextNoteTime + 0.12);
          }
        }
        this.nextNoteTime += 0.44;
        this.stepIndex++;
      }
    }

    playKoto(freq, time) {
      const ctx = this.ctx;
      const osc1 = ctx.createOscillator();
      const osc2 = ctx.createOscillator();
      osc1.type = 'triangle';
      osc2.type = 'sine';
      osc1.frequency.setValueAtTime(freq, time);
      osc2.frequency.setValueAtTime(freq * 2.0, time);

      const filter = ctx.createBiquadFilter();
      filter.type = 'lowpass';
      filter.frequency.setValueAtTime(2100, time);
      filter.frequency.exponentialRampToValueAtTime(520, time + 1.4);

      const gain = ctx.createGain();
      gain.gain.setValueAtTime(0.0001, time);
      gain.gain.linearRampToValueAtTime(0.24, time + 0.02);
      gain.gain.exponentialRampToValueAtTime(0.0008, time + 1.65);

      const overtoneGain = ctx.createGain();
      overtoneGain.gain.setValueAtTime(0.07, time);
      overtoneGain.gain.exponentialRampToValueAtTime(0.0005, time + 0.55);

      osc1.connect(filter);
      osc2.connect(overtoneGain);
      overtoneGain.connect(filter);
      filter.connect(gain);
      gain.connect(this.masterGain);
      gain.connect(this.reverbInput);

      osc1.start(time);
      osc2.start(time);
      osc1.stop(time + 1.7);
      osc2.stop(time + 1.7);
    }

    playBambooPad(freq, time) {
      const ctx = this.ctx;
      const osc = ctx.createOscillator();
      const sub = ctx.createOscillator();
      osc.type = 'sine';
      sub.type = 'triangle';
      osc.frequency.setValueAtTime(freq, time);
      sub.frequency.setValueAtTime(freq * 1.5, time); // gentle fifth harmonic

      const filter = ctx.createBiquadFilter();
      filter.type = 'lowpass';
      filter.frequency.setValueAtTime(620, time);

      const gain = ctx.createGain();
      gain.gain.setValueAtTime(0.0001, time);
      gain.gain.linearRampToValueAtTime(0.11, time + 0.55);
      gain.gain.linearRampToValueAtTime(0.08, time + 1.4);
      gain.gain.exponentialRampToValueAtTime(0.0008, time + 2.4);

      const subGain = ctx.createGain();
      subGain.gain.value = 0.25;

      osc.connect(filter);
      sub.connect(subGain);
      subGain.connect(filter);
      filter.connect(gain);
      gain.connect(this.masterGain);
      gain.connect(this.reverbInput);

      osc.start(time);
      sub.start(time);
      osc.stop(time + 2.45);
      sub.stop(time + 2.45);
    }

    playLanternChime(freq, time) {
      const ctx = this.ctx;
      const osc = ctx.createOscillator();
      osc.type = 'sine';
      osc.frequency.setValueAtTime(freq, time);

      const gain = ctx.createGain();
      gain.gain.setValueAtTime(0.0001, time);
      gain.gain.linearRampToValueAtTime(0.075, time + 0.015);
      gain.gain.exponentialRampToValueAtTime(0.0005, time + 1.9);

      osc.connect(gain);
      gain.connect(this.masterGain);
      gain.connect(this.reverbInput);

      osc.start(time);
      osc.stop(time + 1.95);
    }
  }

  const melody = new FestivalMelody();
  const muteBtn = document.getElementById('mute-btn');
  const muteLabel = document.getElementById('mute-label');
  const iconSoundOn = document.getElementById('icon-sound-on');
  const iconSoundOff = document.getElementById('icon-sound-off');

  function updateMuteUI() {
    if (melody.isMuted) {
      muteBtn.classList.add('muted');
      muteLabel.textContent = 'Melody: MUTED';
      iconSoundOn.style.display = 'none';
      iconSoundOff.style.display = 'inline-block';
    } else {
      muteBtn.classList.remove('muted');
      muteLabel.textContent = 'Melody: ON';
      iconSoundOn.style.display = 'inline-block';
      iconSoundOff.style.display = 'none';
    }
  }
  updateMuteUI();

  muteBtn.addEventListener('pointerdown', function (e) {
    e.stopPropagation();
  });
  muteBtn.addEventListener('click', function (e) {
    e.stopPropagation();
    melody.setMuted(!melody.isMuted);
    updateMuteUI();
  });

  // Try starting audio immediately; browsers requiring gesture will resume on first pointerdown
  if (!melody.isMuted) {
    melody.initContext();
  }

  // --- Procedural Canvas Textures ---
  function createLanternTexture(primaryHex, ribHex, coreHex) {
    const canvas = document.createElement('canvas');
    canvas.width = 256;
    canvas.height = 256;
    const ctx = canvas.getContext('2d');

    // Warm inner candle radial gradient
    const grad = ctx.createLinearGradient(0, 0, 0, 256);
    grad.addColorStop(0.0, ribHex);
    grad.addColorStop(0.18, primaryHex);
    grad.addColorStop(0.5, coreHex);
    grad.addColorStop(0.82, primaryHex);
    grad.addColorStop(1.0, ribHex);
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, 256, 256);

    // Subtle paper grain fibers
    ctx.fillStyle = 'rgba(255, 255, 255, 0.06)';
    for (let i = 0; i < 450; i++) {
      const x = (i * 73) % 256;
      const y = (i * 137) % 256;
      ctx.fillRect(x, y, 8, 1.5);
    }

    // Horizontal bamboo lantern ribs
    const numRibs = 9;
    for (let i = 0; i <= numRibs; i++) {
      const y = (i / numRibs) * 256;
      ctx.fillStyle = 'rgba(20, 10, 5, 0.36)';
      ctx.fillRect(0, y - 2, 256, 4);
      ctx.fillStyle = 'rgba(255, 255, 240, 0.18)';
      ctx.fillRect(0, y + 2, 256, 2);
    }

    // Vertical seam creases
    for (let j = 0; j < 8; j++) {
      const x = (j / 8) * 256;
      ctx.fillStyle = 'rgba(15, 10, 8, 0.14)';
      ctx.fillRect(x, 0, 2, 256);
    }

    const tex = new THREE.CanvasTexture(canvas);
    tex.wrapS = THREE.RepeatWrapping;
    tex.wrapT = THREE.ClampToEdgeWrapping;
    return tex;
  }

  function createGlowTexture() {
    const canvas = document.createElement('canvas');
    canvas.width = 128;
    canvas.height = 128;
    const ctx = canvas.getContext('2d');
    const grad = ctx.createRadialGradient(64, 64, 2, 64, 64, 62);
    grad.addColorStop(0.0, 'rgba(255, 255, 245, 1.0)');
    grad.addColorStop(0.28, 'rgba(255, 225, 165, 0.75)');
    grad.addColorStop(0.65, 'rgba(255, 160, 70, 0.22)');
    grad.addColorStop(1.0, 'rgba(255, 120, 30, 0.0)');
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, 128, 128);
    return new THREE.CanvasTexture(canvas);
  }

  function createHouseWallTexture() {
    const canvas = document.createElement('canvas');
    canvas.width = 256;
    canvas.height = 256;
    const ctx = canvas.getContext('2d');

    // Dark timber plaster background
    ctx.fillStyle = '#1b1622';
    ctx.fillRect(0, 0, 256, 256);

    // Timber frame beams
    ctx.fillStyle = '#0f0c14';
    for (let x = 0; x <= 256; x += 64) {
      ctx.fillRect(x - 4, 0, 8, 256);
    }
    for (let y = 0; y <= 256; y += 128) {
      ctx.fillRect(0, y - 5, 256, 10);
    }

    // Glowing shoji screen windows
    for (let row = 0; row < 2; row++) {
      for (let col = 0; col < 4; col++) {
        const wx = col * 64 + 12;
        const wy = row * 128 + 26;
        const ww = 40;
        const wh = 76;

        // Determine if window is lit
        const isLit = ((row * 5 + col * 3) % 4) !== 0;
        if (isLit) {
          const wGrad = ctx.createLinearGradient(wx, wy, wx, wy + wh);
          wGrad.addColorStop(0, '#' ? '#ffb347' : '#ffb347');
          wGrad.addColorStop(0.5, '#ffd885');
          wGrad.addColorStop(1, '#ff9838');
          ctx.fillStyle = wGrad;
          ctx.fillRect(wx, wy, ww, wh);

          // Shoji lattice mullions
          ctx.fillStyle = '#241710';
          ctx.fillRect(wx + ww * 0.5 - 1.5, wy, 3, wh);
          ctx.fillRect(wx, wy + wh * 0.33, ww, 2.5);
          ctx.fillRect(wx, wy + wh * 0.66, ww, 2.5);
        } else {
          ctx.fillStyle = '#252131';
          ctx.fillRect(wx, wy, ww, wh);
        }
      }
    }

    const tex = new THREE.CanvasTexture(canvas);
    tex.wrapS = THREE.RepeatWrapping;
    tex.wrapT = THREE.RepeatWrapping;
    return tex;
  }

  function createRoofTileTexture() {
    const canvas = document.createElement('canvas');
    canvas.width = 128;
    canvas.height = 128;
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#182036';
    ctx.fillRect(0, 0, 128, 128);
    for (let x = 0; x < 128; x += 16) {
      ctx.fillStyle = '#232e4a';
      ctx.fillRect(x, 0, 7, 128);
      ctx.fillStyle = '#0e1322';
      ctx.fillRect(x + 7, 0, 3, 128);
    }
    for (let y = 0; y < 128; y += 24) {
      ctx.fillStyle = 'rgba(8, 12, 22, 0.55)';
      ctx.fillRect(0, y, 128, 3);
    }
    const tex = new THREE.CanvasTexture(canvas);
    tex.wrapS = THREE.RepeatWrapping;
    tex.wrapT = THREE.RepeatWrapping;
    tex.repeat.set(3, 2);
    return tex;
  }

  // --- Scene, Camera, Renderer & Planar River Reflection ---
  const container = document.getElementById('canvas-container');
  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0x060a18);
  scene.fog = new THREE.FogExp2(0x080d20, 0.0085);

  const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.5, 320);
  camera.position.set(0, 13, 38);
  const cameraTarget = new THREE.Vector3(0, 7, 0);

  // Reflection camera for real-time planar river reflection across y = 0
  const reflectionCamera = camera.clone();
  const reflectedTarget = new THREE.Vector3();

  const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.18;
  container.appendChild(renderer.domElement);

  const reflScale = 0.65;
  let reflectionRT = new THREE.WebGLRenderTarget(
    Math.max(256, Math.floor(window.innerWidth * reflScale)),
    Math.max(256, Math.floor(window.innerHeight * reflScale)),
    {
      minFilter: THREE.LinearFilter,
      magFilter: THREE.LinearFilter,
      format: THREE.RGBAFormat
    }
  );

  // --- Lighting ---
  const hemiLight = new THREE.HemisphereLight(0x3a5288, 0x1a1324, 0.75);
  scene.add(hemiLight);

  const moonDirLight = new THREE.DirectionalLight(0x9bb8ff, 0.65);
  moonDirLight.position.set(-40, 65, -70);
  scene.add(moonDirLight);

  const townWarmAmbient = new THREE.PointLight(0xff9238, 1.3, 95, 1.6);
  townWarmAmbient.position.set(0, 12, 0);
  scene.add(townWarmAmbient);

  // --- Night Sky, Full Moon, Stars & Distant Mountains ---
  const glowTex = createGlowTexture();

  // Moon & Halo
  const moonGroup = new THREE.Group();
  moonGroup.position.set(-34, 52, -115);
  const moonMesh = new THREE.Mesh(
    new THREE.SphereGeometry(7.2, 24, 24),
    new THREE.MeshBasicMaterial({ color: 0xfff3d6 })
  );
  moonGroup.add(moonMesh);

  const moonHalo = new THREE.Sprite(
    new THREE.SpriteMaterial({
      map: glowTex,
      color: 0xffd896,
      transparent: true,
      opacity: 0.65,
      blending: THREE.AdditiveBlending,
      depthWrite: false
    })
  );
  moonHalo.scale.set(42, 42, 1);
  moonGroup.add(moonHalo);
  scene.add(moonGroup);

  // Starfield (only above horizon y > 6 so reflection is clean)
  const starCount = 380;
  const starPos = new Float32Array(starCount * 3);
  for (let i = 0; i < starCount; i++) {
    const theta = (i * 1.6180339) * Math.PI * 2;
    const y = 18 + (i % 70) * 1.4;
    const r = 115 + (i % 35) * 2.5;
    starPos[i * 3] = Math.cos(theta) * r;
    starPos[i * 3 + 1] = y;
    starPos[i * 3 + 2] = Math.sin(theta) * r - 20;
  }
  const starGeo = new THREE.BufferGeometry();
  starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3));
  const starMat = new THREE.PointsMaterial({
    color: 0xdce8ff,
    size: 0.9,
    transparent: true,
    opacity: 0.8
  });
  scene.add(new THREE.Points(starGeo, starMat));

  // Distant Mountain Silhouettes
  const mountainMat = new THREE.MeshLambertMaterial({ color: 0x0b1228 });
  for (let i = 0; i < 14; i++) {
    const angle = (i / 14) * Math.PI * 2;
    const dist = 128 + (i % 3) * 12;
    const mx = Math.cos(angle) * dist;
    const mz = Math.sin(angle) * dist;
    if (Math.abs(mx) < 22 && mz > 0) continue; // Keep camera south river corridor open
    const mh = 26 + (i * 17) % 22;
    const mr = 28 + (i * 13) % 18;
    const cone = new THREE.Mesh(new THREE.ConeGeometry(mr, mh, 7), mountainMat);
    cone.position.set(mx, mh * 0.5, mz);
    scene.add(cone);
  }

  // --- The Reflective River (y = 0) ---
  const riverWidth = 26;
  const riverLength = 240;
  const riverUniforms = {
    tReflection: { value: reflectionRT.texture },
    uTime: { value: 0 },
    uCameraPos: { value: new THREE.Vector3() },
    uFogColor: { value: new THREE.Color(0x080d20) },
    uFogDensity: { value: 0.0085 }
  };

  const riverMaterial = new THREE.ShaderMaterial({
    uniforms: riverUniforms,
    vertexShader: `
      varying vec4 vClipPos;
      varying vec3 vWorldPos;
      varying vec2 vUv;
      void main() {
        vUv = uv;
        vec4 worldPosition = modelMatrix * vec4(position, 1.0);
        vWorldPos = worldPosition.xyz;
        vClipPos = projectionMatrix * viewMatrix * worldPosition;
        gl_Position = vClipPos;
      }
    `,
    fragmentShader: `
      uniform sampler2D tReflection;
      uniform float uTime;
      uniform vec3 uCameraPos;
      uniform vec3 uFogColor;
      uniform float uFogDensity;
      varying vec4 vClipPos;
      varying vec3 vWorldPos;
      varying vec2 vUv;

      void main() {
        vec2 ndc = (vClipPos.xy / vClipPos.w) * 0.5 + 0.5;
        // Planar mirror at y=0 flips Y in clip space
        vec2 reflUV = vec2(ndc.x, 1.0 - ndc.y);

        // Multi-layered gentle river current & ripple distortion
        float wave1 = sin(vWorldPos.z * 0.65 + uTime * 2.2 + vWorldPos.x * 0.4) * 0.007;
        float wave2 = cos(vWorldPos.x * 1.35 - uTime * 1.8 + vWorldPos.z * 0.9) * 0.005;
        float wave3 = sin((vWorldPos.x + vWorldPos.z) * 2.4 + uTime * 3.1) * 0.003;
        vec2 ripple = vec2(wave1 + wave3, wave2 + wave3 * 0.8);

        vec2 sampleUV = clamp(reflUV + ripple, 0.002, 0.998);
        // Subtle horizontal blur for water shimmer
        vec3 reflCol = texture2D(tReflection, sampleUV).rgb * 0.55
                     + texture2D(tReflection, clamp(sampleUV + vec2(0.0035, 0.0), 0.002, 0.998)).rgb * 0.225
                     + texture2D(tReflection, clamp(sampleUV - vec2(0.0035, 0.0), 0.002, 0.998)).rgb * 0.225;

        // Fresnel effect
        vec3 viewDir = normalize(uCameraPos - vWorldPos);
        float fresnel = pow(1.0 - max(dot(viewDir, vec3(0.0, 1.0, 0.0)), 0.0), 2.2);
        fresnel = clamp(0.38 + fresnel * 0.58, 0.38, 0.95);

        vec3 deepWater = vec3(0.025, 0.055, 0.125);
        // Subtle water surface sparkle bands
        float shimmer = smoothstep(0.92, 0.99, sin(vWorldPos.z * 2.5 + uTime * 3.5) * cos(vWorldPos.x * 1.9 - uTime * 2.2));
        vec3 waterCol = mix(deepWater, reflCol * 1.22, fresnel) + vec3(1.0, 0.72, 0.38) * shimmer * 0.08;

        // darken edges slightly near stone banks
        float bankEdge = smoothstep(0.0, 0.12, vUv.x) * smoothstep(1.0, 0.88, vUv.x);
        waterCol *= (0.72 + 0.28 * bankEdge);

        // Exp2 distance fog matching scene
        float dist = length(uCameraPos - vWorldPos);
        float fogFactor = 1.0 - exp(-uFogDensity * uFogDensity * dist * dist);
        waterCol = mix(waterCol, uFogColor, clamp(fogFactor, 0.0, 1.0));

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

  const riverMesh = new THREE.Mesh(new THREE.PlaneGeometry(riverWidth, riverLength, 1, 1), riverMaterial);
  riverMesh.rotation.x = -Math.PI / 2;
  riverMesh.position.y = 0;
  scene.add(riverMesh);

  // --- Riverbanks & Stone Promenades (all y >= 0 for clean planar reflection) ---
  const stoneMat = new THREE.MeshStandardMaterial({ color: 0x26293a, roughness: 0.85 });
  const groundMat = new THREE.MeshStandardMaterial({ color: 0x161928, roughness: 0.92 });

  const leftBank = new THREE.Mesh(new THREE.BoxGeometry(90, 1.8, riverLength), groundMat);
  leftBank.position.set(-13 - 45, 0.9, 0);
  scene.add(leftBank);

  const rightBank = new THREE.Mesh(new THREE.BoxGeometry(90, 1.8, riverLength), groundMat);
  rightBank.position.set(13 + 45, 0.9, 0);
  scene.add(rightBank);

  const leftQuay = new THREE.Mesh(new THREE.BoxGeometry(1.4, 2.1, riverLength), stoneMat);
  leftQuay.position.set(-13.2, 1.05, 0);
  scene.add(leftQuay);

  const rightQuay = new THREE.Mesh(new THREE.BoxGeometry(1.4, 2.1, riverLength), stoneMat);
  rightQuay.position.set(13.2, 1.05, 0);
  scene.add(rightQuay);

  // --- Obstacles Registry (Houses, Pagodas, Bridges) ---
  // Used so the two lantern cats weave around/over houses and NEVER pass through them
  const obstacles = [];
  const roofAnchors = []; // Anchors for hanging strings of lights

  const wallTex = createHouseWallTexture();
  const roofTex = createRoofTileTexture();

  const houseWallMat = new THREE.MeshStandardMaterial({
    map: wallTex,
    emissive: new THREE.Color(0xff9c38),
    emissiveMap: wallTex,
    emissiveIntensity: 0.78,
    roughness: 0.7
  });

  const darkWoodMat = new THREE.MeshStandardMaterial({
    color: 0x231615,
    roughness: 0.8
  });

  const roofMat = new THREE.MeshStandardMaterial({
    map: roofTex,
    color: 0x222c46,
    roughness: 0.55,
    metalness: 0.15
  });

  const redTrimMat = new THREE.MeshStandardMaterial({
    color: 0x9e251b,
    roughness: 0.5
  });

  const eaveLanternMat = new THREE.MeshBasicMaterial({ color: 0xffaa3b });
  const eaveLanternGeo = new THREE.SphereGeometry(0.26, 8, 8);

  function addHouse(x, z, w, d, wallH, tiers, isTower) {
    const baseY = 1.8;
    const houseGroup = new THREE.Group();
    houseGroup.position.set(x, baseY, z);

    // Stone plinth
    const plinth = new THREE.Mesh(new THREE.BoxGeometry(w + 0.6, 0.6, d + 0.6), stoneMat);
    plinth.position.y = 0.3;
    houseGroup.add(plinth);

    let curY = 0.6;
    let curW = w;
    let curD = d;
    let tierH = wallH / tiers;

    for (let t = 0; t < tiers; t++) {
      // Timber & Shoji Walls
      const bodyMesh = new THREE.Mesh(new THREE.BoxGeometry(curW, tierH, curD), houseWallMat);
      bodyMesh.position.y = curY + tierH * 0.5;
      houseGroup.add(bodyMesh);

      // Red balcony rail on upper tiers
      if (t > 0) {
        const rail = new THREE.Mesh(new THREE.BoxGeometry(curW + 0.9, 0.35, curD + 0.9), redTrimMat);
        rail.position.y = curY + 0.2;
        houseGroup.add(rail);
      }

      // Overhanging Pitched Pyramid/Gable Roof
      const roofOverhang = 1.35;
      const roofRadius = Math.hypot(curW + roofOverhang, curD + roofOverhang) * 0.54;
      const roofPeakH = (t === tiers - 1) ? (isTower ? 3.2 : 2.3) : 1.7;
      const roofCone = new THREE.Mesh(new THREE.ConeGeometry(roofRadius, roofPeakH, 4), roofMat);
      roofCone.rotation.y = Math.PI * 0.25;
      roofCone.scale.set((curW + roofOverhang) / (roofRadius * 1.414), 1, (curD + roofOverhang) / (roofRadius * 1.414));
      roofCone.position.y = curY + tierH + roofPeakH * 0.48;
      houseGroup.add(roofCone);

      // Eave trim
      const eaveTrim = new THREE.Mesh(
        new THREE.BoxGeometry(curW + roofOverhang * 1.05, 0.22, curD + roofOverhang * 1.05),
        redTrimMat
      );
      eaveTrim.position.y = curY + tierH + 0.08;
      houseGroup.add(eaveTrim);

      // Corner glowing mini-lanterns under the eaves
      const lx = (curW + roofOverhang * 0.85) * 0.5;
      const lz = (curD + roofOverhang * 0.85) * 0.5;
      const ly = curY + tierH - 0.25;
      const corners = [
        [lx, ly, lz], [-lx, ly, lz], [lx, ly, -lz], [-lx, ly, -lz]
      ];
      for (let c = 0; c < corners.length; c++) {
        const lMesh = new THREE.Mesh(eaveLanternGeo, eaveLanternMat);
        lMesh.scale.set(0.85, 1.25, 0.85);
        lMesh.position.set(corners[c][0], corners[c][1], corners[c][2]);
        houseGroup.add(lMesh);
      }

      curY += tierH + roofPeakH * 0.52;
      curW *= 0.82;
      curD *= 0.82;
    }

    // Golden finial spire on top of towers
    if (isTower) {
      const spire = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.22, 2.2, 8), eaveLanternMat);
      spire.position.y = curY + 1.1;
      houseGroup.add(spire);
      curY += 1.9;
    }

    scene.add(houseGroup);

    const totalTopY = baseY + curY + 0.4;
    const halfW = w * 0.5 + 0.85;
    const halfD = d * 0.5 + 0.85;

    obstacles.push({
      x: x,
      z: z,
      halfW: halfW,
      halfD: halfD,
      topY: totalTopY,
      isBridge: false
    });

    roofAnchors.push({
      x: x + (x < 0 ? halfW * 0.8 : -halfW * 0.8),
      y: Math.min(totalTopY - 1.0, baseY + wallH * 0.82),
      z: z,
      bank: x < 0 ? -1 : 1
    });
  }

  // Build the festival town along both banks with deliberate aerial avenues between houses
  const townLayout = [
    // Left Bank Front Row (x ~ -21 to -24)
    { x: -21, z: -48, w: 7.2, d: 7.2, h: 11.0, tiers: 3, tower: true },
    { x: -20, z: -33, w: 6.4, d: 7.5, h: 5.5,  tiers: 1, tower: false },
    { x: -22, z: -18, w: 7.5, d: 6.8, h: 8.2,  tiers: 2, tower: false },
    { x: -21, z: -2,  w: 7.6, d: 7.6, h: 12.2, tiers: 3, tower: true },
    { x: -20, z: 14,  w: 6.5, d: 7.2, h: 5.6,  tiers: 1, tower: false },
    { x: -22, z: 29,  w: 7.0, d: 7.0, h: 11.4, tiers: 3, tower: true },
    { x: -20, z: 45,  w: 6.8, d: 7.4, h: 7.6,  tiers: 2, tower: false },

    // Left Bank Second Row (x ~ -34 to -38)
    { x: -35, z: -40, w: 8.0, d: 7.5, h: 9.0,  tiers: 2, tower: false },
    { x: -34, z: -24, w: 7.6, d: 7.6, h: 12.5, tiers: 3, tower: true },
    { x: -36, z: -9,  w: 7.5, d: 8.2, h: 7.2,  tiers: 2, tower: false },
    { x: -34, z: 7,   w: 7.4, d: 7.4, h: 11.0, tiers: 3, tower: true },
    { x: -36, z: 22,  w: 8.0, d: 7.2, h: 6.4,  tiers: 1, tower: false },
    { x: -35, z: 38,  w: 7.8, d: 7.8, h: 11.8, tiers: 3, tower: true },

    // Right Bank Front Row (x ~ +20 to +23)
    { x: 21, z: -46, w: 7.0, d: 7.2, h: 8.0,  tiers: 2, tower: false },
    { x: 21, z: -31, w: 7.4, d: 7.4, h: 11.8, tiers: 3, tower: true },
    { x: 20, z: -15, w: 6.4, d: 7.0, h: 5.5,  tiers: 1, tower: false },
    { x: 22, z: 2,   w: 7.6, d: 7.6, h: 12.4, tiers: 3, tower: true },
    { x: 20, z: 18,  w: 6.5, d: 7.2, h: 7.6,  tiers: 2, tower: false },
    { x: 21, z: 33,  w: 7.4, d: 7.4, h: 11.2, tiers: 3, tower: true },
    { x: 20, z: 48,  w: 6.8, d: 6.8, h: 6.0,  tiers: 1, tower: false },

    // Right Bank Second Row (x ~ +34 to +38)
    { x: 35, z: -38, w: 7.8, d: 7.8, h: 11.5, tiers: 3, tower: true },
    { x: 36, z: -22, w: 7.5, d: 7.8, h: 7.5,  tiers: 2, tower: false },
    { x: 34, z: -6,  w: 7.6, d: 7.6, h: 11.8, tiers: 3, tower: true },
    { x: 36, z: 10,  w: 7.8, d: 7.2, h: 6.8,  tiers: 1, tower: false },
    { x: 34, z: 25,  w: 7.6, d: 7.6, h: 12.2, tiers: 3, tower: true },
    { x: 35, z: 41,  w: 8.0, d: 7.5, h: 8.4,  tiers: 2, tower: false }
  ];

  for (let i = 0; i < townLayout.length; i++) {
    const b = townLayout[i];
    addHouse(b.x, b.z, b.w, b.d, b.h, b.tiers, b.tower);
  }

  // --- Two Traditional Arched Festival Bridges Across the River ---
  function addBridge(zPos) {
    const bridgeGroup = new THREE.Group();
    bridgeGroup.position.set(0, 0, zPos);

    const segs = 11;
    const span = 27.0;
    for (let i = 0; i < segs; i++) {
      const u = (i + 0.5) / segs;
      const x = (u - 0.5) * span;
      const archY = 1.7 + Math.sin(u * Math.PI) * 2.3;
      const segLen = (span / segs) + 0.25;

      const plank = new THREE.Mesh(new THREE.BoxGeometry(segLen, 0.42, 4.6), darkWoodMat);
      plank.position.set(x, archY, 0);
      const slope = Math.cos(u * Math.PI) * (2.3 * Math.PI / span);
      plank.rotation.z = slope;
      bridgeGroup.add(plank);

      // Red bridge railings
      for (let side = -1; side <= 1; side += 2) {
        const rail = new THREE.Mesh(new THREE.BoxGeometry(segLen, 0.22, 0.22), redTrimMat);
        rail.position.set(x, archY + 0.95, side * 2.15);
        rail.rotation.z = slope;
        bridgeGroup.add(rail);

        const post = new THREE.Mesh(new THREE.BoxGeometry(0.24, 1.1, 0.24), redTrimMat);
        post.position.set(x, archY + 0.5, side * 2.15);
        bridgeGroup.add(post);

        if (i % 2 === 1) {
          const orb = new THREE.Mesh(eaveLanternGeo, eaveLanternMat);
          orb.position.set(x, archY + 1.25, side * 2.15);
          bridgeGroup.add(orb);
        }
      }
    }

    scene.add(bridgeGroup);

    // Bridge collision box so cats glide over the bridge arch
    obstacles.push({
      x: 0,
      z: zPos,
      halfW: 14.2,
      halfD: 2.8,
      topY: 5.2,
      isBridge: true
    });
  }

  addBridge(-22);
  addBridge(20);

  // --- Riverfront Lantern Poles ---
  for (let z = -44; z <= 44; z += 11) {
    if (Math.abs(z + 22) < 4 || Math.abs(z - 20) < 4) continue;
    for (let side = -1; side <= 1; side += 2) {
      const px = side * 14.3;
      const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.12, 0.16, 6.2, 6), darkWoodMat);
      pole.position.set(px, 4.9, z);
      scene.add(pole);

      const topLantern = new THREE.Mesh(new THREE.SphereGeometry(0.38, 10, 10), eaveLanternMat);
      topLantern.scale.set(0.9, 1.3, 0.9);
      topLantern.position.set(px, 8.1, z);
      scene.add(topLantern);
    }
  }

  // --- Strings of Lights Between Rooftops & Across the River ---
  const lightStrings = [];
  const cordMat = new THREE.LineBasicMaterial({ color: 0x3b2c28, transparent: true, opacity: 0.75 });
  const bulbGeo = new THREE.SphereGeometry(0.36, 10, 10);
  const bulbMats = [
    new THREE.MeshBasicMaterial({ color: 0xff5e2b }),
    new THREE.MeshBasicMaterial({ color: 0xffb838 }),
    new THREE.MeshBasicMaterial({ color: 0xffe484 }),
    new THREE.MeshBasicMaterial({ color: 0xff7744 })
  ];

  function createLightString(pA, pB, sag, numBulbs) {
    const pts = [];
    const segs = 18;
    for (let i = 0; i <= segs; i++) {
      const u = i / segs;
      const x = lerp(pA.x, pB.x, u);
      const z = lerp(pA.z, pB.z, u);
      const y = lerp(pA.y, pB.y, u) - 4 * sag * u * (1 - u);
      pts.push(new THREE.Vector3(x, y, z));
    }
    const lineGeo = new THREE.BufferGeometry().setFromPoints(pts);
    const line = new THREE.Line(lineGeo, cordMat);
    scene.add(line);

    const bulbs = [];
    for (let i = 1; i <= numBulbs; i++) {
      const u = i / (numBulbs + 1);
      const bx = lerp(pA.x, pB.x, u);
      const bz = lerp(pA.z, pB.z, u);
      const by = lerp(pA.y, pB.y, u) - 4 * sag * u * (1 - u) - 0.35;
      const mat = bulbMats[(i + lightStrings.length) % bulbMats.length];
      const mesh = new THREE.Mesh(bulbGeo, mat);
      mesh.scale.set(0.88, 1.28, 0.88);
      mesh.position.set(bx, by, bz);
      scene.add(mesh);
      bulbs.push({ mesh: mesh, basePos: new THREE.Vector3(bx, by, bz), u: u });
    }

    const midU = 0.5;
    const midY = lerp(pA.y, pB.y, midU) - sag;
    lightStrings.push({
      pA: pA,
      pB: pB,
      sag: sag,
      midY: midY,
      bulbs: bulbs
    });
  }

  // River-crossing festival light strings at varied heights so cats weave over & under them
  const stringPairs = [
    [new THREE.Vector3(-18, 13.5, -42), new THREE.Vector3(18, 13.0, -40), 2.2, 11],
    [new THREE.Vector3(-17, 10.5, -30), new THREE.Vector3(17, 12.2, -29), 1.9, 10],
    [new THREE.Vector3(-18, 11.8, -17), new THREE.Vector3(18, 10.8, -15), 2.0, 11],
    [new THREE.Vector3(-17, 14.5, -3),  new THREE.Vector3(17, 14.5, 1),   2.4, 12],
    [new THREE.Vector3(-18, 10.2, 12),  new THREE.Vector3(18, 11.2, 15),  1.8, 10],
    [new THREE.Vector3(-18, 13.8, 27),  new THREE.Vector3(18, 13.5, 30),  2.3, 11],
    [new THREE.Vector3(-17, 10.8, 41),  new THREE.Vector3(17, 10.5, 44),  1.8, 10],

    // Street-level & rooftop garlands along Left Bank
    [new THREE.Vector3(-21, 12.5, -47), new THREE.Vector3(-22, 10.5, -18), 1.8, 8],
    [new THREE.Vector3(-22, 10.5, -18), new THREE.Vector3(-21, 13.2, -2),  1.5, 7],
    [new THREE.Vector3(-21, 13.2, -2),  new THREE.Vector3(-22, 12.5, 29),  2.1, 9],
    [new THREE.Vector3(-21, 12.8, -2),  new THREE.Vector3(-34, 13.0, 7),   1.6, 7],
    [new THREE.Vector3(-22, 12.2, 29),  new THREE.Vector3(-35, 12.8, 38),  1.6, 7],

    // Street-level & rooftop garlands along Right Bank
    [new THREE.Vector3(21, 12.5, -31), new THREE.Vector3(22, 13.4, 2),   2.1, 9],
    [new THREE.Vector3(22, 13.4, 2),   new THREE.Vector3(21, 12.4, 33),  2.1, 9],
    [new THREE.Vector3(21, 12.5, -31), new THREE.Vector3(35, 12.5, -38), 1.5, 7],
    [new THREE.Vector3(22, 13.0, 2),   new THREE.Vector3(34, 12.8, -6),  1.5, 7],
    [new THREE.Vector3(21, 12.2, 33),  new THREE.Vector3(34, 13.0, 25),  1.5, 7]
  ];

  for (let i = 0; i < stringPairs.length; i++) {
    const sp = stringPairs[i];
    createLightString(sp[0], sp[1], sp[2], sp[3]);
  }

  // --- Hard 3D Obstacle & String Collision Resolution ---
  // Ensures no cat head, body segment, or tail ever passes through any house, roof, bridge, or light string
  function getFloorHeight(x, z) {
    if (Math.abs(x) < 12.5) {
      return 2.0; // Safe clearance above river water plane
    }
    return 3.2; // Safe clearance above bank promenades
  }

  function resolveObstacleCollision(pos, radius) {
    // 1. Floor clearance
    const minFloor = getFloorHeight(pos.x, pos.z) + radius;
    if (pos.y < minFloor) {
      pos.y = minFloor;
    }

    // 2. Houses, Pagodas & Bridges (smooth rounded-AABB Minkowski push-out)
    const pad = radius + 0.65;
    for (let i = 0; i < obstacles.length; i++) {
      const obs = obstacles[i];
      if (pos.y > obs.topY + pad) continue;
      if (Math.abs(pos.x - obs.x) > obs.halfW + pad) continue;
      if (Math.abs(pos.z - obs.z) > obs.halfD + pad) continue;

      if (obs.isBridge) {
        // Always fly over bridges
        if (pos.y < obs.topY + radius) {
          pos.y = obs.topY + radius;
        }
        continue;
      }

      // Closest point on solid building core box
      const cx = clamp(pos.x, obs.x - obs.halfW, obs.x + obs.halfW);
      const cy = clamp(pos.y, 0.0, obs.topY);
      const cz = clamp(pos.z, obs.z - obs.halfD, obs.z + obs.halfD);

      const dx = pos.x - cx;
      const dy = pos.y - cy;
      const dz = pos.z - cz;
      const distSq = dx * dx + dy * dy + dz * dz;

      if (distSq < pad * pad) {
        if (distSq > 0.0001) {
          const dist = Math.sqrt(distSq);
          const push = (pad - dist) / dist;
          pos.x += dx * push;
          pos.y += dy * push;
          pos.z += dz * push;
        } else {
          // Point is strictly inside core box: push out along nearest face (preferring roof top if high)
          const penLeft = (pos.x - (obs.x - obs.halfW)) + pad;
          const penRight = ((obs.x + obs.halfW) - pos.x) + pad;
          const penBack = (pos.z - (obs.z - obs.halfD)) + pad;
          const penFront = ((obs.z + obs.halfD) - pos.z) + pad;
          const penTop = (obs.topY - pos.y) + pad;

          const minPen = Math.min(penLeft, penRight, penBack, penFront, penTop * 0.85);
          if (minPen === penTop * 0.85) {
            pos.y = obs.topY + pad;
          } else if (minPen === penLeft) {
            pos.x = obs.x - obs.halfW - pad;
          } else if (minPen === penRight) {
            pos.x = obs.x + obs.halfW + pad;
          } else if (minPen === penBack) {
            pos.z = obs.z - obs.halfD - pad;
          } else {
            pos.z = obs.z + obs.halfD + pad;
          }
        }
      }
    }

    // 3. Gentle vertical clearance from light string cables so cats weave cleanly above or below them
    const stringClearance = radius + 0.55;
    for (let i = 0; i < lightStrings.length; i++) {
      const ls = lightStrings[i];
      const abx = ls.pB.x - ls.pA.x;
      const abz = ls.pB.z - ls.pA.z;
      const abLenSq = abx * abx + abz * abz;
      if (abLenSq < 0.01) continue;
      const u = clamp(((pos.x - ls.pA.x) * abx + (pos.z - ls.pA.z) * abz) / abLenSq, 0, 1);
      const sx = ls.pA.x + abx * u;
      const sz = ls.pA.z + abz * u;
      const horizDistSq = (pos.x - sx) * (pos.x - sx) + (pos.z - sz) * (pos.z - sz);
      if (horizDistSq < stringClearance * stringClearance) {
        const sy = lerp(ls.pA.y, ls.pB.y, u) - 4 * ls.sag * u * (1 - u) - 0.2;
        const dy = pos.y - sy;
        if (Math.abs(dy) < stringClearance) {
          pos.y = sy + (dy >= 0 ? stringClearance : -stringClearance);
        }
      }
    }
  }

  // Lookahead steering repulsion so flight paths curve gracefully around rooftops before reaching them
  function computeObstacleAvoidanceForce(pos, vel, outForce) {
    outForce.set(0, 0, 0);
    const lookPos = new THREE.Vector3().copy(pos).addScaledVector(vel, 0.85);
    const senseMargin = 4.2;

    for (let i = 0; i < obstacles.length; i++) {
      const obs = obstacles[i];
      if (obs.isBridge) {
        if (Math.abs(lookPos.z - obs.z) < obs.halfD + 3.5 && lookPos.y < obs.topY + 2.2) {
          outForce.y += 14.0;
        }
        continue;
      }
      const rx = obs.halfW + senseMargin;
      const rz = obs.halfD + senseMargin;
      const ry = obs.topY + 2.6;

      if (lookPos.y < ry && Math.abs(lookPos.x - obs.x) < rx && Math.abs(lookPos.z - obs.z) < rz) {
        const dx = lookPos.x - obs.x;
        const dz = lookPos.z - obs.z;
        const dist = Math.hypot(dx, dz) || 0.01;
        const maxR = Math.hypot(rx, rz);
        const strength = clamp((maxR - dist) / maxR, 0, 1) * 24.0;
        outForce.x += (dx / dist) * strength;
        outForce.z += (dz / dist) * strength;
        if (lookPos.y > obs.topY - 3.2) {
          outForce.y += strength * 0.75; // Swoop over rooftop if already near top
        }
      }
    }

    if (pos.y < 5.5) {
      outForce.y += (5.5 - pos.y) * 9.0;
    } else if (pos.y > 21.0) {
      outForce.y -= (pos.y - 21.0) * 6.0;
    }
    return outForce;
  }

  // --- Long Paper-Lantern Cat Class ---
  class LanternCat {
    constructor(config) {
      this.name = config.name;
      this.palette = config.palette;
      this.phaseOffset = config.phaseOffset || 0;

      this.headPos = config.startPos.clone();
      this.velocity = new THREE.Vector3(0, 0, 10);
      this.forward = new THREE.Vector3(0, 0, 1);
      this.turnRate = 0;

      // Ear & tail flick animation state
      this.earFlickTimer = 1.2 + this.phaseOffset;
      this.earFlickImpulseL = 0;
      this.earFlickImpulseR = 0;
      this.tailFlickTimer = 0.8 + this.phaseOffset * 0.5;
      this.tailFlickAmplitude = 0;

      const lanternTex = createLanternTexture(
        this.palette.primaryCss,
        this.palette.ribCss,
        this.palette.coreCss
      );

      this.lanternMat = new THREE.MeshStandardMaterial({
        map: lanternTex,
        color: this.palette.primaryHex,
        emissive: this.palette.emissiveHex,
        emissiveMap: lanternTex,
        emissiveIntensity: 1.05,
        roughness: 0.45,
        metalness: 0.05
      });

      this.innerCoreMat = new THREE.MeshBasicMaterial({
        color: this.palette.coreHex
      });

      this.rimMat = new THREE.MeshStandardMaterial({
        color: this.palette.rimHex,
        roughness: 0.4,
        metalness: 0.6
      });

      this.whiskerMat = new THREE.MeshBasicMaterial({
        color: this.palette.whiskerHex
      });

      // 1. Build Cat Head Group
      this.headGroup = new THREE.Group();
      this.headRadius = 1.15;

      const headDrum = new THREE.Mesh(new THREE.SphereGeometry(1.08, 20, 16), this.lanternMat);
      headDrum.scale.set(1.12, 0.96, 1.16);
      this.headGroup.add(headDrum);

      // Lantern top & bottom caps
      const capGeo = new THREE.CylinderGeometry(0.52, 0.52, 0.14, 14);
      const topCap = new THREE.Mesh(capGeo, this.rimMat);
      topCap.position.y = 0.98;
      this.headGroup.add(topCap);

      const botCap = new THREE.Mesh(capGeo, this.rimMat);
      botCap.position.y = -0.98;
      this.headGroup.add(botCap);

      // Glowing Muzzle Cheeks & Nose
      const cheekGeo = new THREE.SphereGeometry(0.36, 12, 10);
      const leftCheek = new THREE.Mesh(cheekGeo, this.lanternMat);
      leftCheek.position.set(0.32, -0.22, 1.05);
      leftCheek.scale.set(1.1, 0.85, 0.9);
      this.headGroup.add(leftCheek);

      const rightCheek = new THREE.Mesh(cheekGeo, this.lanternMat);
      rightCheek.position.set(-0.32, -0.22, 1.05);
      rightCheek.scale.set(1.1, 0.85, 0.9);
      this.headGroup.add(rightCheek);

      const noseMesh = new THREE.Mesh(
        new THREE.ConeGeometry(0.16, 0.2, 3),
        new THREE.MeshBasicMaterial({ color: this.palette.noseHex })
      );
      noseMesh.rotation.x = Math.PI * 0.5;
      noseMesh.rotation.z = Math.PI;
      noseMesh.position.set(0, -0.06, 1.34);
      this.headGroup.add(noseMesh);

      // Glowing Cat Eyes with vertical pupils
      const eyeMat = new THREE.MeshBasicMaterial({ color: this.palette.eyeHex });
      const pupilMat = new THREE.MeshBasicMaterial({ color: 0x120a18 });
      for (let side = -1; side <= 1; side += 2) {
        const eyeGroup = new THREE.Group();
        eyeGroup.position.set(side * 0.46, 0.18, 1.08);
        eyeGroup.rotation.y = side * 0.28;
        eyeGroup.rotation.z = -side * 0.16;

        const eyeBall = new THREE.Mesh(new THREE.SphereGeometry(0.24, 12, 10), eyeMat);
        eyeBall.scale.set(1.15, 0.82, 0.55);
        eyeGroup.add(eyeBall);

        const pupil = new THREE.Mesh(new THREE.BoxGeometry(0.07, 0.28, 0.16), pupilMat);
        pupil.position.z = 0.09;
        eyeGroup.add(pupil);

        this.headGroup.add(eyeGroup);
      }

      // Articulated Ears that Flick
      this.leftEarPivot = new THREE.Group();
      this.leftEarPivot.position.set(0.66, 0.78, 0.12);
      this.rightEarPivot = new THREE.Group();
      this.rightEarPivot.position.set(-0.66, 0.78, 0.12);

      const earOuterGeo = new THREE.ConeGeometry(0.44, 0.98, 12);
      earOuterGeo.translate(0, 0.45, 0);
      const earInnerGeo = new THREE.ConeGeometry(0.24, 0.68, 8);
      earInnerGeo.translate(0, 0.42, 0.14);

      const leftEarOuter = new THREE.Mesh(earOuterGeo, this.lanternMat);
      const leftEarInner = new THREE.Mesh(earInnerGeo, this.innerCoreMat);
      this.leftEarPivot.add(leftEarOuter, leftEarInner);

      const rightEarOuter = new THREE.Mesh(earOuterGeo, this.lanternMat);
      const rightEarInner = new THREE.Mesh(earInnerGeo, this.innerCoreMat);
      this.rightEarPivot.add(rightEarOuter, rightEarInner);

      this.headGroup.add(this.leftEarPivot, this.rightEarPivot);

      // 6 Long Glowing Whiskers (3 per side) that Flick
      this.whiskerPivots = [];
      for (let side = -1; side <= 1; side += 2) {
        for (let w = 0; w < 3; w++) {
          const wPivot = new THREE.Group();
          wPivot.position.set(side * 0.58, -0.14 + (w - 1) * 0.11, 1.02);

          const curve = new THREE.CatmullRomCurve3([
            new THREE.Vector3(0, 0, 0),
            new THREE.Vector3(side * 0.65, 0.06 + (w - 1) * 0.08, 0.12),
            new THREE.Vector3(side * 1.35, 0.02 + (w - 1) * 0.16, -0.06),
            new THREE.Vector3(side * 1.95, -0.12 + (w - 1) * 0.24, -0.25)
          ]);
          const tubeGeo = new THREE.TubeGeometry(curve, 10, 0.032, 5, false);
          const wMesh = new THREE.Mesh(tubeGeo, this.whiskerMat);
          wPivot.add(wMesh);

          const tipBead = new THREE.Mesh(new THREE.SphereGeometry(0.065, 6, 6), this.innerCoreMat);
          tipBead.position.set(side * 1.95, -0.12 + (w - 1) * 0.24, -0.25);
          wPivot.add(tipBead);

          this.headGroup.add(wPivot);
          this.whiskerPivots.push({
            pivot: wPivot,
            side: side,
            idx: w
          });
        }
      }

      // Head Halo & Dynamic PointLight illuminating town rooftops & river below
      const headHalo = new THREE.Sprite(
        new THREE.SpriteMaterial({
          map: glowTex,
          color: this.palette.coreHex,
          transparent: true,
          opacity: 0.6,
          blending: THREE.AdditiveBlending,
          depthWrite: false
        })
      );
      headHalo.scale.set(5.2, 5.2, 1);
      this.headGroup.add(headHalo);

      this.headLight = new THREE.PointLight(this.palette.lightHex, 2.2, 28, 1.6);
      this.headGroup.add(this.headLight);

      scene.add(this.headGroup);

      // 2. Build Long Chain of Glowing Paper Body Segments (18 segments) + Flicking Tail (8 segments)
      this.numBodySegments = 18;
      this.numTailSegments = 8;
      this.totalSegments = this.numBodySegments + this.numTailSegments;
      this.segments = [];

      const segSphereGeo = new THREE.SphereGeometry(1.0, 16, 12);
      const segRimGeo = new THREE.CylinderGeometry(0.46, 0.46, 0.12, 10);

      for (let i = 0; i < this.totalSegments; i++) {
        const isTail = i >= this.numBodySegments;
        let radius;
        if (!isTail) {
          const t = i / (this.numBodySegments - 1);
          // Graceful feline paper-lantern torso profile
          radius = 0.78 + Math.sin(t * Math.PI * 0.75) * 0.14 - t * 0.34;
        } else {
          const tt = (i - this.numBodySegments) / (this.numTailSegments - 1);
          // Tapered tail with a slightly puffed lantern brush tip
          radius = lerp(0.36, 0.17, tt) + (i === this.totalSegments - 1 ? 0.11 : 0);
        }

        const segGroup = new THREE.Group();
        const lanternMesh = new THREE.Mesh(segSphereGeo, this.lanternMat);
        if (!isTail) {
          lanternMesh.scale.set(radius * 0.96, radius * 0.92, radius * 1.12);
        } else {
          lanternMesh.scale.set(radius * 0.9, radius * 0.9, radius * 1.22);
        }
        segGroup.add(lanternMesh);

        if (!isTail) {
          const fRim = new THREE.Mesh(segRimGeo, this.rimMat);
          fRim.rotation.x = Math.PI * 0.5;
          fRim.scale.set(radius, 1, radius);
          fRim.position.z = radius * 0.98;
          segGroup.add(fRim);

          const bRim = new THREE.Mesh(segRimGeo, this.rimMat);
          bRim.rotation.x = Math.PI * 0.5;
          bRim.scale.set(radius, 1, radius);
          bRim.position.z = -radius * 0.98;
          segGroup.add(bRim);
        }

        // Attach a warm mid-body point light on segment 7
        if (i === 7) {
          this.midLight = new THREE.PointLight(this.palette.lightHex, 1.5, 22, 1.6);
          segGroup.add(this.midLight);
        }

        // Soft additive glow sprite every 3rd segment
        if (i % 3 === 0 || i === this.totalSegments - 1) {
          const segHalo = new THREE.Sprite(
            new THREE.SpriteMaterial({
              map: glowTex,
              color: this.palette.coreHex,
              transparent: true,
              opacity: 0.42,
              blending: THREE.AdditiveBlending,
              depthWrite: false
            })
          );
          const s = radius * 4.2;
          segHalo.scale.set(s, s, 1);
          segGroup.add(segHalo);
        }

        const initPos = this.headPos.clone().add(new THREE.Vector3(0, 0, -(i + 1) * 1.1));
        segGroup.position.copy(initPos);
        scene.add(segGroup);

        const prevRadius = i === 0 ? this.headRadius : this.segments[i - 1].radius;
        const spacing = (prevRadius + radius) * (isTail ? 0.92 : 0.86);

        this.segments.push({
          group: segGroup,
          pos: initPos,
          radius: radius,
          spacing: spacing,
          isTail: isTail
        });
      }

      // Reusable temp vectors
      this._desiredVel = new THREE.Vector3();
      this._avoidForce = new THREE.Vector3();
      this._up = new THREE.Vector3(0, 1, 0);
      this._right = new THREE.Vector3(1, 0, 0);
      this._tangent = new THREE.Vector3(0, 0, 1);
      this._lookMat = new THREE.Matrix4();
      this._targetQuat = new THREE.Quaternion();
    }

    steerHead(targetPos, dt, time, maxSpeed, otherCat) {
      // Vector toward target
      this._desiredVel.subVectors(targetPos, this.headPos);
      const dist = this._desiredVel.length();
      if (dist > 0.001) {
        this._desiredVel.divideScalar(dist);
      }
      const speed = clamp(dist * 2.4, 7.5, maxSpeed);
      this._desiredVel.multiplyScalar(speed);

      // Gentle vertical undulation of the head
      this._desiredVel.y += Math.sin(time * 3.8 + this.phaseOffset) * 2.1;

      // Obstacle avoidance steering force
      computeObstacleAvoidanceForce(this.headPos, this.velocity, this._avoidForce);
      this._desiredVel.addScaledVector(this._avoidForce, 1.0);

      // Mutual head repulsion so the two cats swirl around each other smoothly
      if (otherCat) {
        const dx = this.headPos.x - otherCat.headPos.x;
        const dy = this.headPos.y - otherCat.headPos.y;
        const dz = this.headPos.z - otherCat.headPos.z;
        const dSq = dx * dx + dy * dy + dz * dz;
        const minHeadSep = 5.4;
        if (dSq < minHeadSep * minHeadSep && dSq > 0.0001) {
          const d = Math.sqrt(dSq);
          const push = ((minHeadSep - d) / minHeadSep) * 18.0;
          this._desiredVel.x += (dx / d) * push;
          this._desiredVel.y += (dy / d) * push;
          this._desiredVel.z += (dz / d) * push;
        }
      }

      // Clamp total speed
      const prevForwardX = this.forward.x;
      const prevForwardZ = this.forward.z;

      this.velocity.lerp(this._desiredVel, clamp(dt * 3.8, 0, 1));
      const curSpeed = this.velocity.length();
      if (curSpeed > maxSpeed) {
        this.velocity.multiplyScalar(maxSpeed / curSpeed);
      } else if (curSpeed < 6.0) {
        this.velocity.normalize().multiplyScalar(6.0);
      }

      this.headPos.addScaledVector(this.velocity, dt);
      resolveObstacleCollision(this.headPos, this.headRadius);

      if (this.velocity.lengthSq() > 0.01) {
        this.forward.copy(this.velocity).normalize();
      }

      // Compute yaw turn rate for banking and whisker/ear flick triggers
      const crossY = prevForwardX * this.forward.z - prevForwardZ * this.forward.x;
      this.turnRate = lerp(this.turnRate, crossY / Math.max(dt, 0.008), 0.2);

      // Update Ear & Tail Flick Impulses
      this.earFlickTimer -= dt;
      if (this.earFlickTimer <= 0 || Math.abs(this.turnRate) > 1.8) {
        this.earFlickTimer = 1.1 + ((Math.sin(time * 7.3 + this.phaseOffset) * 0.5 + 0.5) * 1.6);
        this.earFlickImpulseL = 1.0;
        this.earFlickImpulseR = 0.85;
      }
      this.earFlickImpulseL *= Math.exp(-dt * 7.5);
      this.earFlickImpulseR *= Math.exp(-dt * 6.5);

      this.tailFlickTimer -= dt;
      if (this.tailFlickTimer <= 0) {
        this.tailFlickTimer = 1.4 + ((Math.cos(time * 5.1 + this.phaseOffset) * 0.5 + 0.5) * 1.4);
        this.tailFlickAmplitude = 1.0;
      }
      this.tailFlickAmplitude *= Math.exp(-dt * 2.8);
    }

    updateBodyWaveChain(dt, time) {
      // Propagate smooth waves down the chain of glowing paper segments
      let leaderPos = this.headPos;
      let prevTangent = this.forward;

      for (let i = 0; i < this.totalSegments; i++) {
        const seg = this.segments[i];

        // Local coordinate frame perpendicular to spine tangent
        this._right.crossVectors(prevTangent, this._up);
        if (this._right.lengthSq() < 0.001) {
          this._right.set(1, 0, 0);
        } else {
          this._right.normalize();
        }
        const localUp = this._tangent.crossVectors(this._right, prevTangent).normalize();

        // Smooth traveling wave along body + expressive flick on tail
        let lateralWave, verticalWave;
        if (!seg.isTail) {
          const wavePhase = time * 6.8 - i * 0.46 + this.phaseOffset;
          const envelope = Math.sin((i / this.numBodySegments) * Math.PI) * 0.85 + 0.25;
          lateralWave = Math.sin(wavePhase) * 0.16 * envelope;
          verticalWave = Math.cos(wavePhase * 0.85) * 0.13 * envelope;
        } else {
          const tailIdx = i - this.numBodySegments;
          const tailFactor = (tailIdx + 1) / this.numTailSegments;
          const flickWave = Math.sin(time * 12.5 - tailIdx * 0.72 + this.phaseOffset);
          const flickBoost = 1.0 + this.tailFlickAmplitude * 1.65 + clamp(Math.abs(this.turnRate) * 0.4, 0, 1.2);
          lateralWave = flickWave * 0.34 * tailFactor * flickBoost;
          // Feline upward tail curl + gentle bob
          verticalWave = 0.14 * tailFactor + Math.cos(time * 8.2 - tailIdx * 0.55) * 0.12 * tailFactor;
        }

        // Pull segment along spine with wave offset
        seg.pos.addScaledVector(this._right, lateralWave * dt * 16.0);
        seg.pos.addScaledVector(localUp, verticalWave * dt * 16.0);

        // Enforce segment spacing constraint
        const dx = seg.pos.x - leaderPos.x;
        const dy = seg.pos.y - leaderPos.y;
        const dz = seg.pos.z - leaderPos.z;
        const dist = Math.sqrt(dx * dx + dy * dy + dz * dz) || 0.001;
        const scale = seg.spacing / dist;
        seg.pos.x = leaderPos.x + dx * scale;
        seg.pos.y = leaderPos.y + dy * scale;
        seg.pos.z = leaderPos.z + dz * scale;

        // Hard collision resolution against buildings & river floor
        resolveObstacleCollision(seg.pos, seg.radius);

        // Re-project spacing after obstacle push
        const dx2 = seg.pos.x - leaderPos.x;
        const dy2 = seg.pos.y - leaderPos.y;
        const dz2 = seg.pos.z - leaderPos.z;
        const dist2 = Math.sqrt(dx2 * dx2 + dy2 * dy2 + dz2 * dz2) || 0.001;
        const scale2 = seg.spacing / dist2;
        seg.pos.x = leaderPos.x + dx2 * scale2;
        seg.pos.y = leaderPos.y + dy2 * scale2;
        seg.pos.z = leaderPos.z + dz2 * scale2;

        prevTangent = new THREE.Vector3(
          leaderPos.x - seg.pos.x,
          leaderPos.y - seg.pos.y,
          leaderPos.z - seg.pos.z
        ).normalize();
        leaderPos = seg.pos;
      }
    }

    applyTransforms(time) {
      // Orient Head Group
      this.headGroup.position.copy(this.headPos);
      const lookPoint = new THREE.Vector3().copy(this.headPos).add(this.forward);
      this._lookMat.lookAt(lookPoint, this.headPos, this._up);
      this._targetQuat.setFromRotationMatrix(this._lookMat);
      this.headGroup.quaternion.slerp(this._targetQuat, 0.28);
      // Roll bank into turns
      this.headGroup.rotateZ(clamp(-this.turnRate * 0.14, -0.45, 0.45));

      // Animate Flicking Ears
      const flickL = Math.sin(time * 32.0) * this.earFlickImpulseL * 0.52;
      const flickR = Math.cos(time * 29.0) * this.earFlickImpulseR * 0.52;
      this.leftEarPivot.rotation.z = -0.26 + flickL + Math.sin(time * 4.5 + this.phaseOffset) * 0.06;
      this.leftEarPivot.rotation.x = 0.12 + Math.abs(flickL) * 0.3;
      this.rightEarPivot.rotation.z = 0.26 - flickR - Math.cos(time * 4.8 + this.phaseOffset) * 0.06;
      this.rightEarPivot.rotation.x = 0.12 + Math.abs(flickR) * 0.3;

      // Animate Flicking Whiskers
      for (let i = 0; i < this.whiskerPivots.length; i++) {
        const wp = this.whiskerPivots[i];
        const twitch = Math.sin(time * 16.0 + wp.idx * 1.7 + wp.side) * (0.09 + this.earFlickImpulseL * 0.28);
        wp.pivot.rotation.y = -wp.side * 0.15 + twitch - clamp(this.turnRate * 0.08, -0.25, 0.25);
        wp.pivot.rotation.z = wp.side * twitch * 0.7;
      }

      // Orient All Body & Tail Lantern Segments along spine tangent
      let prevPos = this.headPos;
      for (let i = 0; i < this.totalSegments; i++) {
        const seg = this.segments[i];
        seg.group.position.copy(seg.pos);
        this._lookMat.lookAt(prevPos, seg.pos, this._up);
        seg.group.quaternion.setFromRotationMatrix(this._lookMat);
        prevPos = seg.pos;
      }
    }
  }

  // --- Instantiate the Two Paper-Lantern Cats (Orange & Silver Gray) ---
  const orangeCat = new LanternCat({
    name: 'Orange Cat',
    phaseOffset: 0.0,
    startPos: new THREE.Vector3(-8, 10, 12),
    palette: {
      primaryCss: '#ff7b1c',
      ribCss: '#b53408',
      coreCss: '#ffe27a',
      primaryHex: 0xff7b1c,
      emissiveHex: 0xff5500,
      coreHex: 0xffd66b,
      rimHex: 0x4a1e0b,
      whiskerHex: 0xffe082,
      eyeHex: 0xfff8b8,
      noseHex: 0xffb38a,
      lightHex: 0xff8524
    }
  });

  const silverCat = new LanternCat({
    name: 'Silver-Gray Cat',
    phaseOffset: 2.4,
    startPos: new THREE.Vector3(8, 11.5, 4),
    palette: {
      primaryCss: '#b8c7dc',
      ribCss: '#56657d',
      coreCss: '#f0f7ff',
      primaryHex: 0xc2d0e3,
      emissiveHex: 0x7e9cc4,
      coreHex: 0xeaf4ff,
      rimHex: 0x2c364a,
      whiskerHex: 0xe6f2ff,
      eyeHex: 0xb5f4ff,
      noseHex: 0xd4e4ff,
      lightHex: 0x9ec5ff
    }
  });

  const cats = [orangeCat, silverCat];

  // --- Pairwise Cat-to-Cat Segment Collision Solver ("never pass through each other") ---
  function resolveCatToCatCollisions(catA, catB) {
    const spheresA = [{ pos: catA.headPos, radius: catA.headRadius }];
    const spheresB = [{ pos: catB.headPos, radius: catB.headRadius }];
    for (let i = 0; i < catA.totalSegments; i++) {
      spheresA.push(catA.segments[i]);
      spheresB.push(catB.segments[i]);
    }

    for (let iter = 0; iter < 2; iter++) {
      for (let i = 0; i < spheresA.length; i++) {
        const sA = spheresA[i];
        for (let j = 0; j < spheresB.length; j++) {
          const sB = spheresB[j];
          const minDist = sA.radius + sB.radius + 0.45;
          const dx = sA.pos.x - sB.pos.x;
          const dy = sA.pos.y - sB.pos.y;
          const dz = sA.pos.z - sB.pos.z;
          const dSq = dx * dx + dy * dy + dz * dz;
          if (dSq < minDist * minDist) {
            const d = Math.sqrt(dSq) || 0.001;
            const overlap = (minDist - d) * 0.52;
            const nx = dx / d;
            const ny = dy / d;
            const nz = dz / d;
            sA.pos.x += nx * overlap;
            sA.pos.y += ny * overlap;
            sA.pos.z += nz * overlap;
            sB.pos.x -= nx * overlap;
            sB.pos.y -= ny * overlap;
            sB.pos.z -= nz * overlap;
          }
        }
      }

      // Re-verify obstacle clearance & chain spacing after separation
      for (let c = 0; c < 2; c++) {
        const cat = c === 0 ? catA : catB;
        resolveObstacleCollision(cat.headPos, cat.headRadius);
        let prev = cat.headPos;
        for (let k = 0; k < cat.totalSegments; k++) {
          const seg = cat.segments[k];
          resolveObstacleCollision(seg.pos, seg.radius);
          const dx = seg.pos.x - prev.x;
          const dy = seg.pos.y - prev.y;
          const dz = seg.pos.z - prev.z;
          const dist = Math.sqrt(dx * dx + dy * dy + dz * dz) || 0.001;
          const sc = seg.spacing / dist;
          seg.pos.x = prev.x + dx * sc;
          seg.pos.y = prev.y + dy * sc;
          seg.pos.z = prev.z + dz * sc;
          prev = seg.pos;
        }
      }
    }
  }

  // --- Aerial Weaving Slalom Course Between Strings of Lights & Rooftops ---
  const slalomWaypoints = [
    new THREE.Vector3(0, 8.8, 26),     // Skim above South Bridge & under high river string
    new THREE.Vector3(-14, 13.5, 19),  // Weave over left-bank light string into rooftop avenue
    new THREE.Vector3(-28, 11.2, 14),  // Thread between Left Bank Front & Second Row houses
    new THREE.Vector3(-15, 15.2, 2),   // Spiral around Left Center Pagoda spire
    new THREE.Vector3(0, 8.5, -9),     // Dive under central river lantern string
    new THREE.Vector3(15, 14.5, -16),  // Swoop up over right-bank strings
    new THREE.Vector3(28, 11.5, -23),  // Weave between Right Bank rooftops
    new THREE.Vector3(14, 13.8, -35),  // Curl around Right North Pagoda
    new THREE.Vector3(0, 8.8, -22),    // Glide over North Bridge
    new THREE.Vector3(-28, 11.5, -15), // Cross to Left Bank avenue
    new THREE.Vector3(-14, 12.8, 6),   // Weave along Left Riverfront lanterns
    new THREE.Vector3(16, 13.5, 16),   // Cross over river light garland to Right Bank
    new THREE.Vector3(28, 11.0, 20),   // Thread between Right South Pagoda and houses
    new THREE.Vector3(13, 12.2, 34)    // Return toward South Bridge
  ];
  const slalomCurve = new THREE.CatmullRomCurve3(slalomWaypoints, true, 'centripetal', 0.5);

  // --- Floating Sky Lanterns & Drifting Sparks ---
  const skyLanterns = [];
  const skyLanternGeo = new THREE.CylinderGeometry(0.32, 0.24, 0.72, 8);
  const skyLanternMats = [
    new THREE.MeshBasicMaterial({ color: 0xff9a3b }),
    new THREE.MeshBasicMaterial({ color: 0xffc45e }),
    new THREE.MeshBasicMaterial({ color: 0xff732e })
  ];

  for (let i = 0; i < 44; i++) {
    const mesh = new THREE.Mesh(skyLanternGeo, skyLanternMats[i % skyLanternMats.length]);
    const halo = new THREE.Sprite(
      new THREE.SpriteMaterial({
        map: glowTex,
        color: 0xffb354,
        transparent: true,
        opacity: 0.55,
        blending: THREE.AdditiveBlending,
        depthWrite: false
      })
    );
    halo.scale.set(2.3, 2.3, 1);
    mesh.add(halo);

    const side = (i % 2 === 0 ? -1 : 1);
    const x = side * (5 + (i * 7) % 36) + Math.sin(i) * 6;
    const z = -52 + (i * 19) % 104;
    const y = 3.0 + (i * 4.3) % 32;
    mesh.position.set(x, y, z);
    scene.add(mesh);

    skyLanterns.push({
      mesh: mesh,
      baseX: x,
      baseZ: z,
      speedY: 0.85 + (i % 7) * 0.14,
      phase: i * 1.13
    });
  }

  // Drifting Sparks (rising from the town & trailing gently behind the two lantern cats)
  const sparkCount = 320;
  const sparkPositions = new Float32Array(sparkCount * 3);
  const sparkVel = [];
  for (let i = 0; i < sparkCount; i++) {
    sparkPositions[i * 3] = ((i * 37) % 76) - 38;
    sparkPositions[i * 3 + 1] = 2 + ((i * 17) % 24);
    sparkPositions[i * 3 + 2] = ((i * 53) % 100) - 50;
    sparkVel.push({
      vx: (Math.sin(i * 2.1) * 0.8),
      vy: 0.7 + (i % 10) * 0.15,
      vz: (Math.cos(i * 1.7) * 0.8),
      phase: i * 0.7
    });
  }
  const sparkGeo = new THREE.BufferGeometry();
  sparkGeo.setAttribute('position', new THREE.BufferAttribute(sparkPositions, 3));
  const sparkMat = new THREE.PointsMaterial({
    map: glowTex,
    color: 0xffd480,
    size: 0.85,
    transparent: true,
    opacity: 0.88,
    blending: THREE.AdditiveBlending,
    depthWrite: false
  });
  const sparkPoints = new THREE.Points(sparkGeo, sparkMat);
  scene.add(sparkPoints);
  let nextCatSparkIdx = 0;

  // --- Touch / Drag Interaction Beacon & Raycasting ---
  const raycaster = new THREE.Raycaster();
  const pointerNDC = new THREE.Vector2();
  const interactionPlane = new THREE.Plane();
  const intersectPoint = new THREE.Vector3();

  let isPointerDown = false;
  let activeFollowCat = null;
  let followTimer = 0;
  const followTarget3D = new THREE.Vector3(0, 12, 0);

  // Visual 3D lantern-ring beacon showing where user is guiding the cat
  const beaconGroup = new THREE.Group();
  const beaconRing = new THREE.Mesh(
    new THREE.TorusGeometry(1.15, 0.06, 8, 28),
    new THREE.MeshBasicMaterial({ color: 0xffe299, transparent: true, opacity: 0.85 })
  );
  beaconGroup.add(beaconRing);
  const beaconSprite = new THREE.Sprite(
    new THREE.SpriteMaterial({
      map: glowTex,
      color: 0xffc65c,
      transparent: true,
      opacity: 0.75,
      blending: THREE.AdditiveBlending,
      depthWrite: false
    })
  );
  beaconSprite.scale.set(4.5, 4.5, 1);
  beaconGroup.add(beaconSprite);
  beaconGroup.visible = false;
  scene.add(beaconGroup);

  const statusText = document.getElementById('status-text');
  const statusDot = document.getElementById('status-dot');
  const demoCursor = document.getElementById('demo-cursor');

  function updateStatusBanner(text, dotColor) {
    statusText.textContent = text;
    statusDot.style.background = dotColor;
    statusDot.style.boxShadow = '0 0 10px ' + dotColor;
  }

  function projectScreenToFlightSpace(clientX, clientY, referencePos) {
    pointerNDC.x = (clientX / window.innerWidth) * 2 - 1;
    pointerNDC.y = -(clientY / window.innerHeight) * 2 + 1;
    raycaster.setFromCamera(pointerNDC, camera);

    const planeNormal = new THREE.Vector3().subVectors(camera.position, cameraTarget).normalize();
    planeNormal.y *= 0.35;
    planeNormal.normalize();
    interactionPlane.setFromNormalAndCoplanarPoint(planeNormal, referencePos);

    if (raycaster.ray.intersectPlane(interactionPlane, intersectPoint)) {
      followTarget3D.x = clamp(intersectPoint.x, -36, 36);
      followTarget3D.y = clamp(intersectPoint.y, 6.0, 20.5);
      followTarget3D.z = clamp(intersectPoint.z, -48, 48);
      resolveObstacleCollision(followTarget3D, 1.8);
    }
  }

  function selectNearestCatToScreen(clientX, clientY) {
    const nx = (clientX / window.innerWidth) * 2 - 1;
    const ny = -(clientY / window.innerHeight) * 2 + 1;

    let bestCat = orangeCat;
    let bestDist = Infinity;
    const proj = new THREE.Vector3();

    for (let i = 0; i < cats.length; i++) {
      proj.copy(cats[i].headPos).project(camera);
      const dx = proj.x - nx;
      const dy = proj.y - ny;
      const d = dx * dx + dy * dy;
      if (d < bestDist) {
        bestDist = d;
        bestCat = cats[i];
      }
    }
    return bestCat;
  }

  // --- Rule 5: #demo Hands-Free 20-Second Loop ---
  let isDemoMode = window.location.hash.toLowerCase() === '#demo';
  window.addEventListener('hashchange', function () {
    if (window.location.hash.toLowerCase() === '#demo') {
      isDemoMode = true;
    }
  });

  function stopDemoOnRealTouch(e) {
    if (isDemoMode && e && e.isTrusted) {
      isDemoMode = false;
      demoCursor.style.display = 'none';
    }
  }

  // Unified Pointer & Touch Handlers
  function onInputStart(clientX, clientY, e) {
    stopDemoOnRealTouch(e);
    melody.ensureResumed();

    isPointerDown = true;
    activeFollowCat = selectNearestCatToScreen(clientX, clientY);
    projectScreenToFlightSpace(clientX, clientY, activeFollowCat.headPos);
    followTimer = 5.5; // Cat keeps following for a while even after release
  }

  function onInputMove(clientX, clientY) {
    if (!isPointerDown || !activeFollowCat) return;
    projectScreenToFlightSpace(clientX, clientY, activeFollowCat.headPos);
    followTimer = 5.5;
  }

  function onInputEnd() {
    isPointerDown = false;
  }

  renderer.domElement.addEventListener('pointerdown', function (e) {
    onInputStart(e.clientX, e.clientY, e);
  });
  window.addEventListener('pointermove', function (e) {
    if (isPointerDown) {
      onInputMove(e.clientX, e.clientY);
    }
  });
  window.addEventListener('pointerup', onInputEnd);
  window.addEventListener('pointercancel', onInputEnd);

  // Fallback touch listeners for older mobile webviews
  renderer.domElement.addEventListener('touchstart', function (e) {
    if (e.touches && e.touches.length > 0) {
      onInputStart(e.touches[0].clientX, e.touches[0].clientY, e);
    }
  }, { passive: true });
  window.addEventListener('touchmove', function (e) {
    if (isPointerDown && e.touches && e.touches.length > 0) {
      onInputMove(e.touches[0].clientX, e.touches[0].clientY);
    }
  }, { passive: true });
  window.addEventListener('touchend', onInputEnd);

  // --- Window Resize Handling ---
  window.addEventListener('resize', function () {
    const w = window.innerWidth;
    const h = window.innerHeight;
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    reflectionCamera.aspect = w / h;
    reflectionCamera.updateProjectionMatrix();
    renderer.setSize(w, h);
    reflectionRT.setSize(
      Math.max(256, Math.floor(w * reflScale)),
      Math.max(256, Math.floor(h * reflScale))
    );
  });

  // --- Main Animation Loop ---
  const clock = new THREE.Clock();
  let totalTime = 0;
  const slalomPointA = new THREE.Vector3();
  const slalomPointB = new THREE.Vector3();
  const chaseTarget = new THREE.Vector3();
  const desiredCamPos = new THREE.Vector3();
  const desiredCamLook = new THREE.Vector3();

  function animate() {
    requestAnimationFrame(animate);

    const rawDt = clock.getDelta();
    const dt = Math.min(rawDt, 0.05);
    totalTime += dt;

    // 1. Handle #demo 20-Second Loop vs Interactive Mode
    if (isDemoMode) {
      const demoT = totalTime % 20.0;
      if (demoT >= 5.0 && demoT < 10.2) {
        // Demo Phase 2: Simulated finger drag guiding the Orange Cat
        activeFollowCat = orangeCat;
        followTimer = 1.5;
        const p = (demoT - 5.0) / 5.2;
        const sx = window.innerWidth * (0.5 + Math.sin(p * Math.PI * 2) * 0.26);
        const sy = window.innerHeight * (0.42 + Math.cos(p * Math.PI * 2) * 0.16);
        demoCursor.style.display = 'block';
        demoCursor.style.left = sx + 'px';
        demoCursor.style.top = sy + 'px';
        projectScreenToFlightSpace(sx, sy, orangeCat.headPos);
      } else if (demoT >= 14.8 && demoT < 19.2) {
        // Demo Phase 4: Simulated finger drag guiding the Silver-Gray Cat
        activeFollowCat = silverCat;
        followTimer = 1.5;
        const p = (demoT - 14.8) / 4.4;
        const sx = window.innerWidth * (0.5 - Math.sin(p * Math.PI * 2) * 0.25);
        const sy = window.innerHeight * (0.44 - Math.cos(p * Math.PI * 2) * 0.14);
        demoCursor.style.display = 'block';
        demoCursor.style.left = sx + 'px';
        demoCursor.style.top = sy + 'px';
        projectScreenToFlightSpace(sx, sy, silverCat.headPos);
      } else {
        demoCursor.style.display = 'none';
        followTimer = 0;
        activeFollowCat = null;
      }
    }

    // 2. Determine Cat Targets (Chasing Each Other & Weaving OR Following Finger)
    if (followTimer > 0 && activeFollowCat) {
      if (!isPointerDown && !isDemoMode) {
        followTimer -= dt;
        // Gently orbit the last touched point while timer winds down
        followTarget3D.x += Math.cos(totalTime * 2.2) * dt * 3.5;
        followTarget3D.z += Math.sin(totalTime * 2.2) * dt * 3.5;
        resolveObstacleCollision(followTarget3D, 1.8);
      }

      const otherCat = activeFollowCat === orangeCat ? silverCat : orangeCat;
      activeFollowCat.steerHead(followTarget3D, dt, totalTime, 15.5, otherCat);

      // The other cat playfully chases behind the user-guided cat
      chaseTarget.copy(activeFollowCat.segments[5].pos);
      chaseTarget.x += Math.sin(totalTime * 2.6) * 3.4;
      chaseTarget.y += Math.cos(totalTime * 2.1) * 1.6;
      resolveObstacleCollision(chaseTarget, 1.5);
      otherCat.steerHead(chaseTarget, dt, totalTime, 14.5, activeFollowCat);

      // Update 3D beacon ring & status banner
      beaconGroup.visible = true;
      beaconGroup.position.copy(followTarget3D);
      beaconGroup.lookAt(camera.position);
      const pulse = 1.0 + Math.sin(totalTime * 8.0) * 0.15;
      beaconRing.scale.set(pulse, pulse, 1);

      const dotCol = activeFollowCat === orangeCat ? '#ff8b28' : '#b8d4ff';
      const prefix = isDemoMode ? '[Demo] ' : '';
      updateStatusBanner(prefix + activeFollowCat.name + ' following your touch', dotCol);
    } else {
      beaconGroup.visible = false;

      // Autonomous Chase & Weaving Slalom: cats swap leader/chaser role every 10 seconds
      const cycle = Math.floor(totalTime / 10.0) % 2;
      const leader = cycle === 0 ? orangeCat : silverCat;
      const chaser = cycle === 0 ? silverCat : orangeCat;

      const uLead = (totalTime * 0.036) % 1.0;
      slalomCurve.getPointAt(uLead, slalomPointA);
      resolveObstacleCollision(slalomPointA, 1.6);

      leader.steerHead(slalomPointA, dt, totalTime, 13.8, chaser);

      // Chaser pursues the leader's mid-body while weaving through the slalom
      const uChase = (uLead - 0.045 + 1.0) % 1.0;
      slalomCurve.getPointAt(uChase, slalomPointB);
      chaseTarget.copy(leader.segments[4].pos).lerp(slalomPointB, 0.42);
      chaseTarget.x += Math.sin(totalTime * 2.4) * 3.2;
      chaseTarget.y += Math.cos(totalTime * 1.9) * 1.5;
      resolveObstacleCollision(chaseTarget, 1.6);

      chaser.steerHead(chaseTarget, dt, totalTime, 14.4, leader);

      if (isDemoMode) {
        updateStatusBanner('[Demo] Chasing & weaving through festival lights', '#ffb347');
      } else {
        updateStatusBanner(chaser.name + ' chasing ' + leader.name + ' over the rooftops', '#ff9e3d');
      }
    }

    // 3. Update Wave Spine Chains & Mutual Collision Solver
    orangeCat.updateBodyWaveChain(dt, totalTime);
    silverCat.updateBodyWaveChain(dt, totalTime);
    resolveCatToCatCollisions(orangeCat, silverCat);
    orangeCat.applyTransforms(totalTime);
    silverCat.applyTransforms(totalTime);

    // 4. Gently Sway Strings of Lights in the Night Breeze
    for (let i = 0; i < lightStrings.length; i++) {
      const ls = lightStrings[i];
      for (let j = 0; j < ls.bulbs.length; j++) {
        const b = ls.bulbs[j];
        const env = 4.0 * b.u * (1.0 - b.u);
        b.mesh.position.x = b.basePos.x + Math.sin(totalTime * 2.1 + i + j * 0.5) * 0.14 * env;
        b.mesh.position.z = b.basePos.z + Math.cos(totalTime * 1.8 + i * 0.7 + j * 0.4) * 0.14 * env;
      }
    }

    // 5. Animate Floating Sky Lanterns & Drifting Sparks
    for (let i = 0; i < skyLanterns.length; i++) {
      const sl = skyLanterns[i];
      sl.mesh.position.y += sl.speedY * dt;
      sl.mesh.position.x = sl.baseX + Math.sin(totalTime * 0.9 + sl.phase) * 1.8;
      sl.mesh.position.z = sl.baseZ + Math.cos(totalTime * 0.75 + sl.phase) * 1.8;
      sl.mesh.rotation.y = totalTime * 0.4 + sl.phase;
      if (sl.mesh.position.y > 38) {
        sl.mesh.position.y = 2.6;
      }
    }

    const posAttr = sparkGeo.getAttribute('position');
    const arr = posAttr.array;

    // Emit a couple of fresh sparks from the two cats' flicking tails each frame
    for (let c = 0; c < 2; c++) {
      const tailTip = cats[c].segments[cats[c].totalSegments - 1].pos;
      const idx = (nextCatSparkIdx % sparkCount) * 3;
      arr[idx] = tailTip.x + (Math.random() - 0.5) * 0.5;
      arr[idx + 1] = tailTip.y + (Math.random() - 0.5) * 0.5;
      arr[idx + 2] = tailTip.z + (Math.random() - 0.5) * 0.5;
      nextCatSparkIdx++;
    }

    for (let i = 0; i < sparkCount; i++) {
      const i3 = i * 3;
      const sv = sparkVel[i];
      arr[i3] += (sv.vx + Math.sin(totalTime * 1.5 + sv.phase) * 0.45) * dt;
      arr[i3 + 1] += sv.vy * dt;
      arr[i3 + 2] += (sv.vz + Math.cos(totalTime * 1.3 + sv.phase) * 0.45) * dt;
      if (arr[i3 + 1] > 28) {
        arr[i3] = ((i * 37) % 72) - 36;
        arr[i3 + 1] = 2.0;
        arr[i3 + 2] = ((i * 53) % 92) - 46;
      }
    }
    posAttr.needsUpdate = true;

    // 6. Slow Cinematic Film Camera Movement
    const midCatX = (orangeCat.headPos.x + silverCat.headPos.x) * 0.5;
    const midCatY = (orangeCat.headPos.y + silverCat.headPos.y) * 0.5;
    const midCatZ = (orangeCat.headPos.z + silverCat.headPos.z) * 0.5;

    const camAngle = Math.sin(totalTime * 0.11) * 0.55;
    const camDist = 31 + Math.cos(totalTime * 0.15) * 6;
    desiredCamPos.x = clamp(midCatX * 0.45 + Math.sin(camAngle) * 18, -19, 19);
    desiredCamPos.y = clamp(8.5 + Math.sin(totalTime * 0.18) * 3.8 + (midCatY - 10) * 0.25, 5.2, 17.5);
    desiredCamPos.z = clamp(midCatZ * 0.55 + camDist, -28, 48);
    resolveObstacleCollision(desiredCamPos, 1.8);

    camera.position.lerp(desiredCamPos, clamp(dt * 1.35, 0, 1));

    desiredCamLook.set(
      midCatX * 0.65,
      clamp(midCatY * 0.68 - 1.2, 3.5, 13.0),
      midCatZ * 0.72
    );
    cameraTarget.lerp(desiredCamLook, clamp(dt * 2.1, 0, 1));
    camera.lookAt(cameraTarget);

    // 7. Render Planar River Reflection Texture (y = 0 mirror plane)
    reflectionCamera.position.set(camera.position.x, -camera.position.y, camera.position.z);
    reflectedTarget.set(cameraTarget.x, -cameraTarget.y, cameraTarget.z);
    reflectionCamera.up.set(0, 1, 0);
    reflectionCamera.lookAt(reflectedTarget);

    riverMesh.visible = false;
    renderer.setRenderTarget(reflectionRT);
    renderer.render(scene, reflectionCamera);
    renderer.setRenderTarget(null);
    riverMesh.visible = true;

    // 8. Update River Shader Uniforms & Render Final Frame
    riverUniforms.uTime.value = totalTime;
    riverUniforms.uCameraPos.value.copy(camera.position);
    renderer.render(scene, camera);
  }

  animate();
})();
</script>
</body>
</html>