Skip to content
VibeCodeBench
Back to the app

The code

Cat Island 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.)109.5 KB · 2,859 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>Whiskerhaven — Floating Cat Island</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;
      font-family: "Courier New", Courier, monospace, system-ui;
      background: #6cc8f5;
      touch-action: none;
    }

    #sky-backdrop {
      position: fixed;
      inset: 0;
      z-index: 0;
      background: linear-gradient(180deg, #4da6e8 0%, #8ed6ff 58%, #cdefff 100%);
      transition: background 1.2s ease;
    }

    #canvas-container {
      position: fixed;
      inset: 0;
      z-index: 1;
      touch-action: none;
    }

    canvas {
      display: block;
      width: 100%;
      height: 100%;
      image-rendering: pixelated;
    }

    /* Pixel-art UI styling */
    .ui-layer {
      position: fixed;
      inset: 0;
      z-index: 10;
      pointer-events: none;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 12px;
    }

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

    .brand-badge {
      pointer-events: auto;
      background: rgba(28, 24, 42, 0.86);
      color: #fff7e6;
      border: 3px solid #fff7e6;
      box-shadow: 0 4px 0 rgba(0, 0, 0, 0.45);
      padding: 8px 12px;
      display: flex;
      flex-direction: column;
      gap: 3px;
      max-width: 310px;
    }

    .brand-title {
      font-size: 16px;
      font-weight: 900;
      letter-spacing: 0.5px;
      color: #ffd166;
      display: flex;
      align-items: center;
      gap: 6px;
      text-shadow: 2px 2px 0 #000;
    }

    .brand-sub {
      font-size: 11px;
      font-weight: 700;
      color: #e0d6c3;
      line-height: 1.3;
    }

    .time-controls {
      pointer-events: auto;
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }

    .pixel-btn {
      pointer-events: auto;
      appearance: none;
      border: 3px solid #231f2e;
      background: #fff4db;
      color: #231f2e;
      font-family: inherit;
      font-size: 14px;
      font-weight: 900;
      padding: 10px 15px;
      min-height: 46px;
      cursor: pointer;
      box-shadow: 0 4px 0 #231f2e;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      transition: transform 0.08s ease, background 0.15s ease;
      touch-action: manipulation;
    }

    .pixel-btn:active {
      transform: translateY(3px);
      box-shadow: 0 1px 0 #231f2e;
    }

    .pixel-btn.active {
      background: #ffd166;
      border-color: #181422;
      color: #181422;
      box-shadow: 0 4px 0 #c97b1e;
    }

    .pixel-btn.night-btn.active {
      background: #6c63ff;
      color: #ffffff;
      border-color: #ffffff;
      box-shadow: 0 4px 0 #2a2475;
    }

    .pixel-btn.sunset-btn.active {
      background: #ff7b54;
      color: #ffffff;
      border-color: #2b1410;
      box-shadow: 0 4px 0 #9e3316;
    }

    .bottom-bar {
      display: flex;
      flex-wrap: wrap;
      align-items: flex-end;
      justify-content: space-between;
      gap: 10px;
      width: 100%;
    }

    .cat-card {
      pointer-events: auto;
      background: rgba(28, 24, 42, 0.9);
      color: #fff7e6;
      border: 3px solid #ffd166;
      box-shadow: 0 4px 0 rgba(0, 0, 0, 0.5);
      padding: 10px 14px;
      min-width: 260px;
      max-width: 390px;
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .cat-card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 8px;
    }

    .cat-name-row {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .cat-swatch {
      width: 18px;
      height: 18px;
      border: 2px solid #fff;
      display: inline-block;
      flex-shrink: 0;
    }

    .cat-name {
      font-size: 16px;
      font-weight: 900;
      color: #ffd166;
      text-shadow: 2px 2px 0 #000;
    }

    .cat-role {
      font-size: 11px;
      font-weight: 700;
      background: #3d3459;
      color: #ffeaac;
      padding: 2px 6px;
      border: 1px solid #8a7cb8;
    }

    .cat-status {
      font-size: 13px;
      font-weight: 700;
      color: #a8f0c6;
      background: rgba(0, 0, 0, 0.35);
      padding: 6px 8px;
      border-left: 4px solid #ffd166;
    }

    .cat-card-actions {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
    }

    .small-btn {
      font-size: 12px;
      padding: 7px 10px;
      min-height: 38px;
    }

    .quick-nav {
      pointer-events: auto;
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
      align-items: center;
    }

    .demo-banner {
      position: fixed;
      top: 76px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 20;
      background: rgba(255, 209, 102, 0.96);
      color: #1c182a;
      border: 3px solid #1c182a;
      box-shadow: 0 4px 0 rgba(0,0,0,0.4);
      padding: 7px 14px;
      font-size: 13px;
      font-weight: 900;
      text-align: center;
      pointer-events: none;
      display: none;
    }

    .demo-banner.visible {
      display: block;
    }

    /* Floating 2D thought bubble over followed cat */
    #cat-label-float {
      position: fixed;
      z-index: 5;
      pointer-events: none;
      transform: translate(-50%, -100%);
      background: rgba(24, 20, 36, 0.88);
      color: #fff7e6;
      border: 2px solid #ffd166;
      padding: 4px 8px;
      font-size: 12px;
      font-weight: 900;
      white-space: nowrap;
      box-shadow: 0 3px 0 rgba(0,0,0,0.45);
      display: none;
    }

    @media (max-width: 640px) {
      .brand-badge {
        max-width: 100%;
        padding: 6px 10px;
      }
      .brand-title {
        font-size: 14px;
      }
      .brand-sub {
        font-size: 10px;
      }
      .pixel-btn {
        font-size: 13px;
        padding: 8px 11px;
        min-height: 42px;
      }
      .cat-card {
        min-width: 0;
        width: 100%;
        max-width: 100%;
      }
      .bottom-bar {
        flex-direction: column-reverse;
        align-items: stretch;
      }
      .quick-nav {
        justify-content: flex-end;
      }
    }
  </style>
</head>
<body>
  <div id="sky-backdrop"></div>
  <div id="canvas-container"></div>

  <div id="cat-label-float"></div>
  <div id="demo-banner" class="demo-banner">🎬 AUTO DEMO TOUR — Touch or click anywhere to take control</div>

  <div class="ui-layer">
    <div class="top-bar">
      <div class="brand-badge">
        <div class="brand-title">🐾 WHISKERHAVEN ISLAND</div>
        <div class="brand-sub">Drag to spin • Pinch/Scroll to zoom • Tap any cat to follow</div>
      </div>

      <div class="time-controls" role="group" aria-label="Time of Day">
        <button id="btn-day" class="pixel-btn active" type="button">☀️ Day</button>
        <button id="btn-sunset" class="pixel-btn sunset-btn" type="button">🌅 Sunset</button>
        <button id="btn-night" class="pixel-btn night-btn" type="button">🌙 Night</button>
      </div>
    </div>

    <div class="bottom-bar">
      <div class="cat-card" id="cat-inspector">
        <div class="cat-card-header">
          <div class="cat-name-row">
            <span class="cat-swatch" id="cat-swatch" style="background:#f58220;"></span>
            <span class="cat-name" id="cat-name">Island Overview</span>
          </div>
          <span class="cat-role" id="cat-role">13 Cats Active</span>
        </div>
        <div class="cat-status" id="cat-status">Tap any cat on the island (or use the buttons below) to follow them!</div>
        <div class="cat-card-actions">
          <button id="btn-mayor" class="pixel-btn small-btn" type="button">🎩 Follow Mayor</button>
          <button id="btn-next-cat" class="pixel-btn small-btn" type="button">🐾 Next Cat ▶</button>
          <button id="btn-unfollow" class="pixel-btn small-btn" type="button" style="display:none;">🗺️ Island View</button>
        </div>
      </div>

      <div class="quick-nav">
        <button id="btn-zoom-in" class="pixel-btn small-btn" type="button" aria-label="Zoom In">+ Zoom</button>
        <button id="btn-zoom-out" class="pixel-btn small-btn" type="button" aria-label="Zoom Out">- Zoom</button>
      </div>
    </div>
  </div>

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

      // ============================================================
      // 1. PROCEDURAL PIXEL-ART TEXTURE FACTORY
      // ============================================================
      function makePixelTexture(w, h, drawFn, repeatX, repeatY) {
        var canvas = document.createElement('canvas');
        canvas.width = w;
        canvas.height = h;
        var ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = false;
        drawFn(ctx, w, h);

        var tex = new THREE.CanvasTexture(canvas);
        tex.magFilter = THREE.NearestFilter;
        tex.minFilter = THREE.NearestFilter;
        tex.generateMipmaps = false;
        if (repeatX || repeatY) {
          tex.wrapS = THREE.RepeatWrapping;
          tex.wrapT = THREE.RepeatWrapping;
          tex.repeat.set(repeatX || 1, repeatY || 1);
        }
        tex.needsUpdate = true;
        return tex;
      }

      // Deterministic pseudo-random helper for textures
      var seedVal = 1337;
      function pRand() {
        seedVal = (seedVal * 16807) % 2147483647;
        return (seedVal - 1) / 2147483646;
      }

      var Textures = {
        grassTop: makePixelTexture(32, 32, function (ctx, w, h) {
          ctx.fillStyle = '#5eb84d';
          ctx.fillRect(0, 0, w, h);
          var shades = ['#51a642', '#6bc959', '#77d463', '#49993b'];
          for (var y = 0; y < h; y += 2) {
            for (var x = 0; x < w; x += 2) {
              if (pRand() < 0.48) {
                ctx.fillStyle = shades[Math.floor(pRand() * shades.length)];
                ctx.fillRect(x, y, 2, 2);
              }
            }
          }
        }, 6, 6),

        parkGrass: makePixelTexture(32, 32, function (ctx, w, h) {
          ctx.fillStyle = '#6bd158';
          ctx.fillRect(0, 0, w, h);
          var shades = ['#5ec24c', '#7ee06c', '#98ed87', '#ffd166', '#ff85a1'];
          for (var y = 0; y < h; y += 2) {
            for (var x = 0; x < w; x += 2) {
              var r = pRand();
              if (r < 0.35) {
                ctx.fillStyle = shades[Math.floor(pRand() * 3)];
                ctx.fillRect(x, y, 2, 2);
              } else if (r < 0.41) {
                ctx.fillStyle = shades[3 + Math.floor(pRand() * 2)];
                ctx.fillRect(x, y, 2, 2);
              }
            }
          }
        }, 3, 3),

        cliffRock: makePixelTexture(32, 32, function (ctx, w, h) {
          ctx.fillStyle = '#736559';
          ctx.fillRect(0, 0, w, h);
          var cols = ['#63554a', '#857668', '#54473d', '#918274'];
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = cols[(y / 4) % cols.length];
            ctx.fillRect(0, y, w, 4);
            for (var x = 0; x < w; x += 4) {
              if (pRand() < 0.55) {
                ctx.fillStyle = cols[Math.floor(pRand() * cols.length)];
                ctx.fillRect(x, y, 4, 4);
              }
            }
          }
        }, 4, 3),

        cobble: makePixelTexture(32, 32, function (ctx, w, h) {
          ctx.fillStyle = '#8b8378';
          ctx.fillRect(0, 0, w, h);
          var stones = ['#b8b0a4', '#a39b8f', '#c7bfb5', '#968e83'];
          for (var y = 0; y < h; y += 8) {
            var offset = (y % 16 === 0) ? 0 : 4;
            for (var x = 0; x < w; x += 8) {
              ctx.fillStyle = stones[Math.floor(pRand() * stones.length)];
              ctx.fillRect((x + offset) % w, y + 1, 6, 6);
              ctx.fillStyle = '#d6cfc7';
              ctx.fillRect((x + offset) % w, y + 1, 6, 1);
            }
          }
        }, 5, 5),

        woodPlank: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#a86b3c';
          ctx.fillRect(0, 0, w, h);
          var planks = ['#b87948', '#965d30', '#c28351', '#875229'];
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = planks[(y / 4) % planks.length];
            ctx.fillRect(0, y, w, 3);
            ctx.fillStyle = '#5e3617';
            ctx.fillRect(0, y + 3, w, 1);
            ctx.fillRect(((y * 3) % 12) + 2, y + 1, 1, 1);
          }
        }, 2, 2),

        sunDeckWood: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#d4945a';
          ctx.fillRect(0, 0, w, h);
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = (y % 8 === 0) ? '#e0a269' : '#c9884f';
            ctx.fillRect(0, y, w, 3);
            ctx.fillStyle = '#8f592c';
            ctx.fillRect(0, y + 3, w, 1);
          }
        }, 2, 2),

        creamWall: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#f5ead6';
          ctx.fillRect(0, 0, w, h);
          for (var y = 0; y < h; y += 2) {
            for (var x = 0; x < w; x += 2) {
              if (pRand() < 0.25) {
                ctx.fillStyle = '#eadbc3';
                ctx.fillRect(x, y, 2, 2);
              }
            }
          }
          ctx.fillStyle = '#734829';
          ctx.fillRect(0, 0, w, 2);
          ctx.fillRect(0, h - 2, w, 2);
          ctx.fillRect(0, 0, 2, h);
          ctx.fillRect(w - 2, 0, 2, h);
        }, 2, 2),

        mintWall: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#bfe8d5';
          ctx.fillRect(0, 0, w, h);
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = '#a8d9c3';
            ctx.fillRect(0, y + 3, w, 1);
          }
        }, 2, 2),

        coralWall: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#f5b5a6';
          ctx.fillRect(0, 0, w, h);
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = '#e39e8d';
            ctx.fillRect(0, y + 3, w, 1);
          }
        }, 2, 2),

        roofRed: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#c44938';
          ctx.fillRect(0, 0, w, h);
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = (y % 8 === 0) ? '#d65847' : '#b33f2f';
            ctx.fillRect(0, y, w, 3);
            ctx.fillStyle = '#872a1e';
            ctx.fillRect(0, y + 3, w, 1);
          }
        }, 2, 2),

        roofBlue: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#476899';
          ctx.fillRect(0, 0, w, h);
          for (var y = 0; y < h; y += 4) {
            ctx.fillStyle = (y % 8 === 0) ? '#5679ad' : '#3d5c8a';
            ctx.fillRect(0, y, w, 3);
            ctx.fillStyle = '#294063';
            ctx.fillRect(0, y + 3, w, 1);
          }
        }, 2, 2),

        awningRedWhite: makePixelTexture(16, 16, function (ctx, w, h) {
          for (var x = 0; x < w; x += 4) {
            ctx.fillStyle = ((x / 4) % 2 === 0) ? '#e63946' : '#fff8eb';
            ctx.fillRect(x, 0, 4, h);
            ctx.fillStyle = ((x / 4) % 2 === 0) ? '#b8232e' : '#e0d6c5';
            ctx.fillRect(x, h - 3, 4, 3);
          }
        }, 2, 1),

        awningBlueWhite: makePixelTexture(16, 16, function (ctx, w, h) {
          for (var x = 0; x < w; x += 4) {
            ctx.fillStyle = ((x / 4) % 2 === 0) ? '#2b82d9' : '#fff8eb';
            ctx.fillRect(x, 0, 4, h);
            ctx.fillStyle = ((x / 4) % 2 === 0) ? '#1c5ea3' : '#e0d6c5';
            ctx.fillRect(x, h - 3, 4, 3);
          }
        }, 2, 1),

        awningOrangeWhite: makePixelTexture(16, 16, function (ctx, w, h) {
          for (var x = 0; x < w; x += 4) {
            ctx.fillStyle = ((x / 4) % 2 === 0) ? '#f77f00' : '#fff8eb';
            ctx.fillRect(x, 0, 4, h);
            ctx.fillStyle = ((x / 4) % 2 === 0) ? '#c96200' : '#e0d6c5';
            ctx.fillRect(x, h - 3, 4, 3);
          }
        }, 2, 1),

        waterTex: makePixelTexture(32, 32, function (ctx, w, h) {
          ctx.fillStyle = '#2bb3d6';
          ctx.fillRect(0, 0, w, h);
          var waves = ['#39c5e8', '#1f9ec0', '#7ae6ff'];
          for (var y = 0; y < h; y += 4) {
            for (var x = 0; x < w; x += 4) {
              var r = pRand();
              if (r < 0.35) {
                ctx.fillStyle = waves[0];
                ctx.fillRect(x, y, 4, 2);
              } else if (r < 0.48) {
                ctx.fillStyle = waves[2];
                ctx.fillRect(x, y, 4, 1);
              }
            }
          }
        }, 2, 2),

        yarnPink: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#eb4888';
          ctx.fillRect(0, 0, w, h);
          var cols = ['#ff6ba5', '#c72c69', '#ff94be'];
          for (var y = 0; y < h; y += 2) {
            ctx.fillStyle = cols[(y / 2) % cols.length];
            ctx.fillRect(0, y, w, 1);
          }
          for (var x = 0; x < w; x += 4) {
            ctx.fillStyle = '#ad1f57';
            ctx.fillRect(x, (x * 2) % h, 2, 6);
          }
        }, 2, 2),

        yarnCyan: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#25b8cc';
          ctx.fillRect(0, 0, w, h);
          var cols = ['#49d7eb', '#188fa1', '#85f0ff'];
          for (var y = 0; y < h; y += 2) {
            ctx.fillStyle = cols[(y / 2) % cols.length];
            ctx.fillRect(0, y, w, 1);
          }
          for (var x = 0; x < w; x += 4) {
            ctx.fillStyle = '#11707d';
            ctx.fillRect(x, (x * 2) % h, 2, 6);
          }
        }, 2, 2),

        yarnGold: makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = '#f5b727';
          ctx.fillRect(0, 0, w, h);
          var cols = ['#ffd25a', '#cc8e08', '#ffe494'];
          for (var y = 0; y < h; y += 2) {
            ctx.fillStyle = cols[(y / 2) % cols.length];
            ctx.fillRect(0, y, w, 1);
          }
          for (var x = 0; x < w; x += 4) {
            ctx.fillStyle = '#9e6c00';
            ctx.fillRect(x, (x * 2) % h, 2, 6);
          }
        }, 2, 2)
      };

      // Glow sprite texture for lanterns & windows at night
      function createGlowTexture() {
        var canvas = document.createElement('canvas');
        canvas.width = 64;
        canvas.height = 64;
        var ctx = canvas.getContext('2d');
        var grad = ctx.createRadialGradient(32, 32, 2, 32, 32, 32);
        grad.addColorStop(0, 'rgba(255, 240, 175, 1.0)');
        grad.addColorStop(0.35, 'rgba(255, 185, 70, 0.65)');
        grad.addColorStop(0.7, 'rgba(255, 130, 30, 0.2)');
        grad.addColorStop(1, 'rgba(255, 110, 20, 0.0)');
        ctx.fillStyle = grad;
        ctx.fillRect(0, 0, 64, 64);
        var tex = new THREE.CanvasTexture(canvas);
        return tex;
      }
      var glowSpriteTex = createGlowTexture();

      // Dynamic floating icon / Zzz sprite textures
      function createIconSpriteTexture(type) {
        var canvas = document.createElement('canvas');
        canvas.width = 32;
        canvas.height = 32;
        var ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = false;

        // Pixel badge background
        ctx.fillStyle = 'rgba(24, 20, 38, 0.85)';
        ctx.fillRect(3, 4, 26, 22);
        ctx.fillStyle = '#ffd166';
        ctx.fillRect(3, 3, 26, 2);
        ctx.fillRect(3, 25, 26, 2);
        ctx.fillRect(2, 4, 2, 22);
        ctx.fillRect(28, 4, 2, 22);
        ctx.fillRect(14, 27, 4, 3);

        if (type === 'fish') {
          // Pixel blue/silver fish
          ctx.fillStyle = '#5ce1e6';
          ctx.fillRect(8, 12, 12, 6);
          ctx.fillRect(10, 10, 8, 10);
          ctx.fillStyle = '#38b6ff';
          ctx.fillRect(20, 11, 4, 8);
          ctx.fillRect(22, 9, 3, 4);
          ctx.fillRect(22, 17, 3, 4);
          ctx.fillStyle = '#111';
          ctx.fillRect(10, 13, 2, 2);
        } else if (type === 'butterfly') {
          ctx.fillStyle = '#ff66c4';
          ctx.fillRect(7, 8, 7, 7);
          ctx.fillRect(18, 8, 7, 7);
          ctx.fillStyle = '#ffde59';
          ctx.fillRect(8, 15, 6, 5);
          ctx.fillRect(18, 15, 6, 5);
          ctx.fillStyle = '#fff';
          ctx.fillRect(15, 9, 2, 11);
        } else if (type === 'zzz') {
          ctx.fillStyle = '#a3e4ff';
          // Big Z
          ctx.fillRect(7, 8, 8, 2);
          ctx.fillRect(12, 10, 2, 2);
          ctx.fillRect(10, 12, 2, 2);
          ctx.fillRect(8, 14, 2, 2);
          ctx.fillRect(7, 16, 8, 2);
          // Small z
          ctx.fillStyle = '#ffd166';
          ctx.fillRect(18, 13, 6, 2);
          ctx.fillRect(21, 15, 2, 2);
          ctx.fillRect(19, 17, 2, 2);
          ctx.fillRect(18, 19, 6, 2);
        } else if (type === 'stretch') {
          ctx.fillStyle = '#ffde59';
          ctx.fillRect(15, 7, 2, 16);
          ctx.fillRect(8, 14, 16, 2);
          ctx.fillRect(11, 10, 10, 10);
          ctx.fillStyle = '#fff';
          ctx.fillRect(13, 12, 6, 6);
        }

        var tex = new THREE.CanvasTexture(canvas);
        tex.magFilter = THREE.NearestFilter;
        tex.minFilter = THREE.NearestFilter;
        tex.generateMipmaps = false;
        return tex;
      }

      var BubbleTextures = {
        fish: createIconSpriteTexture('fish'),
        butterfly: createIconSpriteTexture('butterfly'),
        zzz: createIconSpriteTexture('zzz'),
        stretch: createIconSpriteTexture('stretch')
      };

      // ============================================================
      // 2. THREE.JS SCENE, CAMERA & RENDERER SETUP
      // ============================================================
      var container = document.getElementById('canvas-container');
      var scene = new THREE.Scene();
      scene.fog = new THREE.FogExp2(0x8ed6ff, 0.0085);

      var camera = new THREE.PerspectiveCamera(44, window.innerWidth / window.innerHeight, 0.5, 220);

      var renderer = new THREE.WebGLRenderer({ antialias: false, alpha: true, powerPreference: 'high-performance' });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
      renderer.shadowMap.enabled = true;
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;
      container.appendChild(renderer.domElement);

      // Root group for the whole world
      var worldGroup = new THREE.Group();
      scene.add(worldGroup);

      // ============================================================
      // 3. LIGHTING & DAY / SUNSET / NIGHT SYSTEM
      // ============================================================
      var ambientLight = new THREE.AmbientLight(0xd9f0ff, 0.68);
      scene.add(ambientLight);

      var hemiLight = new THREE.HemisphereLight(0xffffff, 0x5d8254, 0.45);
      hemiLight.position.set(0, 30, 0);
      scene.add(hemiLight);

      var dirLight = new THREE.DirectionalLight(0xfff5d6, 1.05);
      dirLight.position.set(20, 32, 16);
      dirLight.castShadow = true;
      dirLight.shadow.mapSize.width = 1024;
      dirLight.shadow.mapSize.height = 1024;
      dirLight.shadow.camera.near = 5;
      dirLight.shadow.camera.far = 85;
      var dBound = 19;
      dirLight.shadow.camera.left = -dBound;
      dirLight.shadow.camera.right = dBound;
      dirLight.shadow.camera.top = dBound;
      dirLight.shadow.camera.bottom = -dBound;
      dirLight.shadow.bias = -0.0012;
      scene.add(dirLight);

      // Dynamic night/sunset glow registries
      var windowMaterials = [];
      var lanternCoreMaterials = [];
      var glowSprites = [];
      var townPointLights = [];
      var sunbeamMeshes = [];

      // Starfield & Moon for night
      var skyGroup = new THREE.Group();
      scene.add(skyGroup);

      var starMeshes = [];
      var starMat = new THREE.MeshBasicMaterial({ color: 0xfff8d6, transparent: true, opacity: 0 });
      var starGeo = new THREE.BoxGeometry(0.32, 0.32, 0.32);
      for (var s = 0; s < 110; s++) {
        var star = new THREE.Mesh(starGeo, starMat);
        var sTheta = pRand() * Math.PI * 2;
        var sPhi = 0.15 + pRand() * 1.15;
        var sRad = 65 + pRand() * 20;
        star.position.set(
          Math.cos(sTheta) * Math.sin(sPhi) * sRad,
          Math.cos(sPhi) * sRad + 8,
          Math.sin(sTheta) * Math.sin(sPhi) * sRad
        );
        skyGroup.add(star);
        starMeshes.push(star);
      }

      // Chunky voxel crescent moon
      var moonGroup = new THREE.Group();
      var moonMat = new THREE.MeshBasicMaterial({ color: 0xfff3a1, transparent: true, opacity: 0 });
      var m1 = new THREE.Mesh(new THREE.BoxGeometry(3.5, 3.5, 1.2), moonMat);
      moonGroup.add(m1);
      moonGroup.position.set(-34, 28, -38);
      skyGroup.add(moonGroup);

      // Shared Window Material (updates dynamically between Day/Sunset/Night)
      var sharedWindowMat = new THREE.MeshLambertMaterial({
        color: 0x7ec8e3,
        emissive: 0x112233,
        emissiveIntensity: 0.2
      });
      windowMaterials.push(sharedWindowMat);

      var sharedLanternGlassMat = new THREE.MeshBasicMaterial({
        color: 0xfff1c2
      });
      lanternCoreMaterials.push(sharedLanternGlassMat);

      function addPointLightCluster(x, y, z, colorHex, maxIntensity, distance) {
        var pl = new THREE.PointLight(colorHex, 0, distance || 11);
        pl.position.set(x, y, z);
        worldGroup.add(pl);
        townPointLights.push({ light: pl, maxIntensity: maxIntensity || 1.25 });
      }

      // Place key town night lights
      addPointLightCluster(-5.5, 2.6, -4.0, 0xffaa33, 1.35, 13); // Fish Market
      addPointLightCluster(0, 2.8, 0, 0xffb84d, 1.2, 13);        // Central Plaza
      addPointLightCluster(5.2, 2.5, 5.2, 0xffaa33, 1.3, 12);    // Pond Bridge
      addPointLightCluster(5.2, 3.0, -5.5, 0xffb347, 1.35, 13);  // Town Hall
      addPointLightCluster(7.8, 2.4, -1.0, 0xffaa33, 1.1, 10);   // Mint Cottage
      addPointLightCluster(-7.8, 2.4, 1.8, 0xffaa33, 1.1, 10);   // Coral Cottage
      addPointLightCluster(-5.2, 2.5, 5.5, 0xffaa44, 0.9, 11);   // Yarn Park

      // Helper to create a street/hanging lantern
      function createLantern(x, y, z, isHanging) {
        var lGroup = new THREE.Group();
        lGroup.position.set(x, y, z);

        var ironMat = new THREE.MeshLambertMaterial({ color: 0x2c2838 });
        if (!isHanging) {
          var post = new THREE.Mesh(new THREE.BoxGeometry(0.18, 1.5, 0.18), ironMat);
          post.position.y = 0.75;
          post.castShadow = true;
          lGroup.add(post);

          var base = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.16, 0.34), ironMat);
          base.position.y = 0.08;
          lGroup.add(base);
        } else {
          var chain = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.35, 0.08), ironMat);
          chain.position.y = 0.35;
          lGroup.add(chain);
        }

        var housingY = isHanging ? 0 : 1.62;
        var capBot = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.08, 0.42), ironMat);
        capBot.position.y = housingY - 0.18;
        lGroup.add(capBot);

        var glass = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.34, 0.32), sharedLanternGlassMat);
        glass.position.y = housingY;
        lGroup.add(glass);

        var capTop = new THREE.Mesh(new THREE.BoxGeometry(0.48, 0.12, 0.48), ironMat);
        capTop.position.y = housingY + 0.2;
        lGroup.add(capTop);

        var spriteMat = new THREE.SpriteMaterial({
          map: glowSpriteTex,
          color: 0xffb74d,
          transparent: true,
          opacity: 0.0,
          blending: THREE.AdditiveBlending,
          depthWrite: false
        });
        var glowSprite = new THREE.Sprite(spriteMat);
        glowSprite.position.y = housingY;
        glowSprite.scale.set(1.9, 1.9, 1.9);
        lGroup.add(glowSprite);
        glowSprites.push({ sprite: glowSprite, baseScale: 2.0 });

        worldGroup.add(lGroup);
        return lGroup;
      }

      // Helper to add a glowing window to a building
      function createWindow(w, h, x, y, z, rotY) {
        var winGroup = new THREE.Group();
        winGroup.position.set(x, y, z);
        if (rotY) winGroup.rotation.y = rotY;

        var frameMat = new THREE.MeshLambertMaterial({ color: 0x4f331d });
        var frame = new THREE.Mesh(new THREE.BoxGeometry(w + 0.14, h + 0.14, 0.1), frameMat);
        winGroup.add(frame);

        var pane = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.13), sharedWindowMat);
        winGroup.add(pane);

        var barH = new THREE.Mesh(new THREE.BoxGeometry(w + 0.04, 0.07, 0.15), frameMat);
        var barV = new THREE.Mesh(new THREE.BoxGeometry(0.07, h + 0.04, 0.15), frameMat);
        winGroup.add(barH, barV);

        var sill = new THREE.Mesh(new THREE.BoxGeometry(w + 0.24, 0.1, 0.22), frameMat);
        sill.position.set(0, -h * 0.5 - 0.05, 0.05);
        winGroup.add(sill);

        // Soft night glow halo on window
        var spriteMat = new THREE.SpriteMaterial({
          map: glowSpriteTex,
          color: 0xffcc55,
          transparent: true,
          opacity: 0.0,
          blending: THREE.AdditiveBlending,
          depthWrite: false
        });
        var wGlow = new THREE.Sprite(spriteMat);
        wGlow.position.set(0, 0, 0.16);
        wGlow.scale.set(w * 2.1, h * 2.1, 1);
        winGroup.add(wGlow);
        glowSprites.push({ sprite: wGlow, baseScale: Math.max(w, h) * 2.1 });

        return winGroup;
      }

      // ============================================================
      // 4. FLOATING ISLAND TERRAIN & UNDERSIDE CLIFFS
      // ============================================================
      function buildFloatingIsland() {
        var islandGroup = new THREE.Group();

        var grassMat = new THREE.MeshLambertMaterial({ map: Textures.grassTop });
        var cliffMat = new THREE.MeshLambertMaterial({ map: Textures.cliffRock });
        var dirtMat = new THREE.MeshLambertMaterial({ color: 0x8c6239 });
        var cobbleMat = new THREE.MeshLambertMaterial({ map: Textures.cobble });
        var parkMat = new THREE.MeshLambertMaterial({ map: Textures.parkGrass });

        // Top grassy island deck (built in quadrants around the pond at x:[2.0, 8.6], z:[2.2, 8.8])
        // Main top deck thickness: y from -1.0 to 0.0
        var deckBlocks = [
          // West & North-West main slab
          { x: -5.2, y: -0.5, z: 0.0, w: 14.4, h: 1.0, d: 24.0 },
          // North-East slab (north of pond)
          { x: 6.6, y: -0.5, z: -4.9, w: 9.2, h: 1.0, d: 14.2 },
          // Far East strip (east of pond)
          { x: 9.9, y: -0.5, z: 5.5, w: 2.6, h: 1.0, d: 6.6 },
          // South-East lip (south of pond, with gap for waterfall channel)
          { x: 3.3, y: -0.5, z: 10.4, w: 2.6, h: 1.0, d: 3.2 },
          { x: 8.4, y: -0.5, z: 10.4, w: 5.6, h: 1.0, d: 3.2 },
          // Pond floor slab
          { x: 5.3, y: -1.1, z: 6.5, w: 6.8, h: 0.6, d: 9.0 },
          // Outer chunky border extensions to give an organic pixel island silhouette
          { x: 0.0, y: -0.55, z: -12.6, w: 16.0, h: 0.9, d: 1.4 },
          { x: -12.9, y: -0.55, z: -0.5, w: 1.4, h: 0.9, d: 17.0 },
          { x: 11.7, y: -0.55, z: -1.5, w: 1.2, h: 0.9, d: 15.0 },
          { x: -4.5, y: -0.55, z: 12.6, w: 13.0, h: 0.9, d: 1.4 }
        ];

        for (var i = 0; i < deckBlocks.length; i++) {
          var b = deckBlocks[i];
          var mesh = new THREE.Mesh(new THREE.BoxGeometry(b.w, b.h, b.d), grassMat);
          mesh.position.set(b.x, b.y, b.z);
          mesh.receiveShadow = true;
          mesh.castShadow = true;
          islandGroup.add(mesh);
        }

        // Cobblestone Central Plaza & connecting town walkways
        var plaza = new THREE.Mesh(new THREE.BoxGeometry(6.8, 0.06, 6.8), cobbleMat);
        plaza.position.set(0, 0.02, -0.4);
        plaza.receiveShadow = true;
        islandGroup.add(plaza);

        // Paths connecting Market, Town Hall, Park, and Pond Bridge
        var paths = [
          { x: -4.2, z: -2.4, w: 4.5, d: 2.2 }, // To Fish Market
          { x: 4.2, z: -3.2, w: 3.6, d: 2.4 },  // To Town Hall
          { x: -3.8, z: 3.4, w: 2.4, d: 4.2 },  // To Yarn Park
          { x: 1.2, z: 5.2, w: 2.6, d: 2.2 }    // To Pond Bridge
        ];
        for (var p = 0; p < paths.length; p++) {
          var pm = new THREE.Mesh(new THREE.BoxGeometry(paths[p].w, 0.05, paths[p].d), cobbleMat);
          pm.position.set(paths[p].x, 0.015, paths[p].z);
          pm.receiveShadow = true;
          islandGroup.add(pm);
        }

        // Park lawn pad in South-West
        var parkPad = new THREE.Mesh(new THREE.BoxGeometry(8.6, 0.05, 8.2), parkMat);
        parkPad.position.set(-5.8, 0.015, 6.2);
        parkPad.receiveShadow = true;
        islandGroup.add(parkPad);

        // Central Plaza Cat Fountain / Statue
        var fountainGroup = new THREE.Group();
        fountainGroup.position.set(0, 0.05, -0.4);
        var stoneMat = new THREE.MeshLambertMaterial({ color: 0xc2bab0 });
        var goldMat = new THREE.MeshLambertMaterial({ color: 0xffc83b });

        var fRim = new THREE.Mesh(new THREE.BoxGeometry(2.1, 0.38, 2.1), stoneMat);
        fRim.position.y = 0.19;
        fRim.castShadow = true;
        fRim.receiveShadow = true;
        fountainGroup.add(fRim);

        var fWater = new THREE.Mesh(new THREE.BoxGeometry(1.7, 0.42, 1.7), new THREE.MeshLambertMaterial({ map: Textures.waterTex }));
        fWater.position.y = 0.2;
        fountainGroup.add(fWater);

        var fPedestal = new THREE.Mesh(new THREE.BoxGeometry(0.65, 0.9, 0.65), stoneMat);
        fPedestal.position.y = 0.45;
        fPedestal.castShadow = true;
        fountainGroup.add(fPedestal);

        // Golden Pixel Cat Statue atop fountain
        var statueBody = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.5, 0.45), goldMat);
        statueBody.position.y = 1.12;
        statueBody.castShadow = true;
        var statueHead = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.36, 0.42), goldMat);
        statueHead.position.y = 1.52;
        var statueEarL = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.16, 0.12), goldMat);
        statueEarL.position.set(-0.13, 1.76, 0);
        var statueEarR = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.16, 0.12), goldMat);
        statueEarR.position.set(0.13, 1.76, 0);
        fountainGroup.add(statueBody, statueHead, statueEarL, statueEarR);
        islandGroup.add(fountainGroup);

        // Stepped Chunky Voxel Cliff Underside tapering down into the sky
        var cliffLayers = [
          { y: -1.8, w: 22.5, d: 22.5, h: 1.6, x: -0.4, z: 0 },
          { y: -3.3, w: 18.8, d: 18.8, h: 1.6, x: 0.3, z: -0.3 },
          { y: -4.8, w: 14.6, d: 15.0, h: 1.6, x: -0.5, z: 0.4 },
          { y: -6.3, w: 10.6, d: 10.4, h: 1.6, x: 0.2, z: -0.2 },
          { y: -7.8, w: 6.8,  d: 6.6,  h: 1.6, x: -0.2, z: 0.2 },
          { y: -9.3, w: 3.6,  d: 3.8,  h: 1.6, x: 0.1, z: -0.1 },
          { y: -10.7, w: 1.6, d: 1.6,  h: 1.4, x: 0, z: 0 }
        ];

        for (var c = 0; c < cliffLayers.length; c++) {
          var cl = cliffLayers[c];
          var cMesh = new THREE.Mesh(new THREE.BoxGeometry(cl.w, cl.h, cl.d), c === 0 ? dirtMat : cliffMat);
          cMesh.position.set(cl.x, cl.y, cl.z);
          cMesh.castShadow = true;
          cMesh.receiveShadow = true;
          islandGroup.add(cMesh);
        }

        // Hanging rock spires & green pixel vines on cliff edges
        var vineMat = new THREE.MeshLambertMaterial({ color: 0x459939 });
        var vineCoords = [
          [-11.8, -1.6, -4.0, 2.4], [-11.8, -1.4, -3.5, 1.6],
          [10.8, -1.7, -5.0, 2.6],  [-7.5, -1.8, 11.8, 2.8],
          [9.5, -1.6, 9.5, 2.2],    [-11.5, -1.5, 5.5, 2.0]
        ];
        for (var v = 0; v < vineCoords.length; v++) {
          var vc = vineCoords[v];
          var vine = new THREE.Mesh(new THREE.BoxGeometry(0.35, vc[3], 0.35), vineMat);
          vine.position.set(vc[0], vc[1], vc[2]);
          islandGroup.add(vine);
        }

        // 3 Small Floating Satellite Mini-Islets around the main island
        var islets = [
          { x: -16.5, y: -2.2, z: -7.5, s: 2.2 },
          { x: 15.8,  y: -3.4, z: 6.5,  s: 2.5 },
          { x: -14.2, y: -4.2, z: 12.5, s: 1.9 }
        ];
        for (var m = 0; m < islets.length; m++) {
          var isl = islets[m];
          var ig = new THREE.Group();
          ig.position.set(isl.x, isl.y, isl.z);
          var iTop = new THREE.Mesh(new THREE.BoxGeometry(isl.s, 0.6, isl.s), grassMat);
          var iMid = new THREE.Mesh(new THREE.BoxGeometry(isl.s * 0.75, 1.0, isl.s * 0.75), cliffMat);
          iMid.position.y = -0.8;
          var iTip = new THREE.Mesh(new THREE.BoxGeometry(isl.s * 0.4, 0.9, isl.s * 0.4), cliffMat);
          iTip.position.y = -1.7;
          ig.add(iTop, iMid, iTip);
          islandGroup.add(ig);
        }

        worldGroup.add(islandGroup);
      }

      // ============================================================
      // 5. ZONE 1: FISH MARKET WITH STRIPED AWNINGS
      // ============================================================
      function createPixelFishMesh(colorHex, scale) {
        var fg = new THREE.Group();
        var s = scale || 1;
        var bodyMat = new THREE.MeshLambertMaterial({ color: colorHex });
        var bellyMat = new THREE.MeshLambertMaterial({ color: 0xe8f4f8 });
        var body = new THREE.Mesh(new THREE.BoxGeometry(0.42 * s, 0.14 * s, 0.22 * s), bodyMat);
        var belly = new THREE.Mesh(new THREE.BoxGeometry(0.32 * s, 0.15 * s, 0.12 * s), bellyMat);
        belly.position.z = 0.05 * s;
        var tail = new THREE.Mesh(new THREE.BoxGeometry(0.16 * s, 0.12 * s, 0.26 * s), bodyMat);
        tail.position.x = -0.26 * s;
        fg.add(body, belly, tail);
        return fg;
      }

      function buildMarketStall(x, z, rotY, awningTexture, fishColors) {
        var stall = new THREE.Group();
        stall.position.set(x, 0, z);
        stall.rotation.y = rotY;

        var woodMat = new THREE.MeshLambertMaterial({ map: Textures.woodPlank });
        var iceMat = new THREE.MeshLambertMaterial({ color: 0xd9f7ff });
        var awningMat = new THREE.MeshLambertMaterial({ map: awningTexture });

        // Counter base
        var counter = new THREE.Mesh(new THREE.BoxGeometry(2.7, 0.95, 1.35), woodMat);
        counter.position.y = 0.475;
        counter.castShadow = true;
        counter.receiveShadow = true;
        stall.add(counter);

        // Ice bed on top of counter
        var iceBed = new THREE.Mesh(new THREE.BoxGeometry(2.4, 0.14, 1.08), iceMat);
        iceBed.position.y = 0.98;
        stall.add(iceBed);

        // Display fish on ice
        for (var f = 0; f < 5; f++) {
          var fish = createPixelFishMesh(fishColors[f % fishColors.length], 0.95);
          fish.position.set(-0.85 + f * 0.42, 1.1, (f % 2 === 0) ? -0.12 : 0.14);
          fish.rotation.y = (f % 2 === 0) ? 0.35 : -0.25;
          stall.add(fish);
        }

        // 4 Wooden corner posts supporting the striped awning
        var postOffsets = [
          [-1.22, -0.55], [1.22, -0.55],
          [-1.22,  0.55], [1.22,  0.55]
        ];
        for (var p = 0; p < postOffsets.length; p++) {
          var post = new THREE.Mesh(new THREE.BoxGeometry(0.16, 2.25, 0.16), woodMat);
          post.position.set(postOffsets[p][0], 1.125, postOffsets[p][1]);
          post.castShadow = true;
          stall.add(post);
        }

        // Slanted Striped Awning Roof + front scalloped valance
        var awningGroup = new THREE.Group();
        awningGroup.position.set(0, 2.28, 0.08);
        awningGroup.rotation.x = 0.22;

        var awningTop = new THREE.Mesh(new THREE.BoxGeometry(3.05, 0.18, 1.85), awningMat);
        awningTop.castShadow = true;
        awningGroup.add(awningTop);

        // Front striped valance fringe
        var valance = new THREE.Mesh(new THREE.BoxGeometry(3.05, 0.28, 0.12), awningMat);
        valance.position.set(0, -0.16, 0.88);
        awningGroup.add(valance);

        stall.add(awningGroup);

        // Wooden fish barrel beside stall
        var barrel = new THREE.Mesh(new THREE.BoxGeometry(0.65, 0.78, 0.65), woodMat);
        barrel.position.set(1.72, 0.39, 0.15);
        barrel.castShadow = true;
        stall.add(barrel);

        var barrelIce = new THREE.Mesh(new THREE.BoxGeometry(0.52, 0.1, 0.52), iceMat);
        barrelIce.position.set(1.72, 0.8, 0.15);
        stall.add(barrelIce);

        var uprightFish = createPixelFishMesh(0x45b6fe, 1.0);
        uprightFish.position.set(1.72, 0.96, 0.15);
        uprightFish.rotation.z = 0.9;
        stall.add(uprightFish);

        worldGroup.add(stall);
      }

      function buildFishMarketZone() {
        // 3 Stalls with bright striped awnings
        buildMarketStall(-7.8, -3.2, 0.25, Textures.awningRedWhite, [0x38b6ff, 0xff758f, 0x5ce1e6]);
        buildMarketStall(-3.8, -6.5, -0.2, Textures.awningBlueWhite, [0xff8c42, 0x4cc9f0, 0x72efdd]);
        buildMarketStall(-3.8, -2.5, 0.72, Textures.awningOrangeWhite, [0x48bfe3, 0xff6b6b, 0xffd166]);

        // Hanging lanterns under market awnings
        createLantern(-7.8, 2.0, -2.5, true);
        createLantern(-3.8, 2.0, -5.8, true);
        createLantern(-3.3, 2.0, -2.0, true);

        // Main Fishmonger Shop Building behind stalls (with flat sunny rooftop deck!)
        var shopGroup = new THREE.Group();
        shopGroup.position.set(-7.6, 0, -7.4);

        var wallMat = new THREE.MeshLambertMaterial({ map: Textures.creamWall });
        var woodMat = new THREE.MeshLambertMaterial({ map: Textures.woodPlank });
        var deckMat = new THREE.MeshLambertMaterial({ map: Textures.sunDeckWood });
        var awningMat = new THREE.MeshLambertMaterial({ map: Textures.awningRedWhite });

        var body = new THREE.Mesh(new THREE.BoxGeometry(4.4, 3.1, 3.4), wallMat);
        body.position.y = 1.55;
        body.castShadow = true;
        body.receiveShadow = true;
        shopGroup.add(body);

        // Sunny Rooftop Deck for cats to nap in the sun
        var roofDeck = new THREE.Mesh(new THREE.BoxGeometry(4.7, 0.22, 3.7), deckMat);
        roofDeck.position.y = 3.21;
        roofDeck.castShadow = true;
        roofDeck.receiveShadow = true;
        shopGroup.add(roofDeck);

        // Low rooftop railing posts
        var railMat = new THREE.MeshLambertMaterial({ color: 0x6e4221 });
        var rBack = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.35, 0.16), railMat);
        rBack.position.set(0, 3.45, -1.75);
        var rLeft = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.35, 3.6), railMat);
        rLeft.position.set(-2.25, 3.45, 0);
        shopGroup.add(rBack, rLeft);

        // Cozy rooftop sun-cushion
        var cushion = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.14, 1.1), new THREE.MeshLambertMaterial({ color: 0xff6b8b }));
        cushion.position.set(-0.6, 3.38, -0.3);
        shopGroup.add(cushion);

        // Striped Porch Awning over shop front door
        var frontAwning = new THREE.Mesh(new THREE.BoxGeometry(4.2, 0.18, 1.1), awningMat);
        frontAwning.position.set(0, 2.15, 2.1);
        frontAwning.rotation.x = 0.25;
        frontAwning.castShadow = true;
        shopGroup.add(frontAwning);

        // Giant 3D Pixel Fish Signboard on roof edge
        var signBoard = new THREE.Mesh(new THREE.BoxGeometry(2.2, 0.75, 0.18), woodMat);
        signBoard.position.set(0.6, 3.75, 1.72);
        shopGroup.add(signBoard);
        var bigFishSign = createPixelFishMesh(0x38b6ff, 1.9);
        bigFishSign.position.set(0.6, 3.75, 1.85);
        shopGroup.add(bigFishSign);

        // Glowing shop windows
        shopGroup.add(createWindow(0.95, 0.9, -1.2, 1.45, 1.71, 0));
        shopGroup.add(createWindow(0.95, 0.9,  1.2, 1.45, 1.71, 0));
        shopGroup.add(createWindow(0.9,  0.9,  2.21, 1.5, 0, Math.PI / 2));

        // Wooden cat ladder on side so cats can climb to the roof
        for (var s = 0; s < 7; s++) {
          var rung = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.1, 0.65), railMat);
          rung.position.set(2.3, 0.4 + s * 0.45, 0.8);
          shopGroup.add(rung);
        }

        worldGroup.add(shopGroup);
      }

      // ============================================================
      // 6. ZONE 2: TOWN BUILDINGS & SUNNY ROOFTOPS WHERE CATS NAP
      // ============================================================
      function buildTownBuildings() {
        var creamMat = new THREE.MeshLambertMaterial({ map: Textures.creamWall });
        var mintMat = new THREE.MeshLambertMaterial({ map: Textures.mintWall });
        var coralMat = new THREE.MeshLambertMaterial({ map: Textures.coralWall });
        var roofRedMat = new THREE.MeshLambertMaterial({ map: Textures.roofRed });
        var roofBlueMat = new THREE.MeshLambertMaterial({ map: Textures.roofBlue });
        var deckMat = new THREE.MeshLambertMaterial({ map: Textures.sunDeckWood });
        var timberMat = new THREE.MeshLambertMaterial({ color: 0x5c381c });

        // 1. TOWN HALL & BAKERY (North-East: x=5.4, z=-6.5)
        var hall = new THREE.Group();
        hall.position.set(5.4, 0, -6.5);

        var hallBase = new THREE.Mesh(new THREE.BoxGeometry(4.8, 3.6, 3.8), creamMat);
        hallBase.position.y = 1.8;
        hallBase.castShadow = true;
        hallBase.receiveShadow = true;
        hall.add(hallBase);

        // Sunny wooden rooftop terrace on Town Hall (y = 3.72)
        var hallDeck = new THREE.Mesh(new THREE.BoxGeometry(5.1, 0.24, 4.1), deckMat);
        hallDeck.position.y = 3.72;
        hallDeck.castShadow = true;
        hallDeck.receiveShadow = true;
        hall.add(hallDeck);

        // Cute bell/clock gable tower on the back corner of Town Hall roof
        var tower = new THREE.Mesh(new THREE.BoxGeometry(1.7, 1.5, 1.5), roofRedMat);
        tower.position.set(1.4, 4.55, -1.0);
        tower.castShadow = true;
        hall.add(tower);

        // Cat-eared Gold Emblem on Town Hall front
        var emblem = new THREE.Mesh(new THREE.BoxGeometry(0.7, 0.65, 0.16), new THREE.MeshLambertMaterial({ color: 0xffc83b }));
        emblem.position.set(0, 3.1, 1.95);
        hall.add(emblem);

        // Rooftop sun-nap cushion on Town Hall sundeck
        var hallCushion = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.15, 1.2), new THREE.MeshLambertMaterial({ color: 0x4ecdc4 }));
        hallCushion.position.set(-0.9, 3.9, 0.3);
        hall.add(hallCushion);

        // Door & Glowing Windows on Town Hall
        var door = new THREE.Mesh(new THREE.BoxGeometry(0.95, 1.55, 0.15), timberMat);
        door.position.set(0, 0.78, 1.92);
        hall.add(door);

        hall.add(createWindow(1.05, 1.0, -1.45, 1.4, 1.91, 0));
        hall.add(createWindow(1.05, 1.0,  1.45, 1.4, 1.91, 0));
        hall.add(createWindow(0.95, 0.85, -1.45, 2.75, 1.91, 0));
        hall.add(createWindow(0.95, 0.85,  1.45, 2.75, 1.91, 0));
        hall.add(createWindow(1.0,  1.0, -2.41, 1.6, 0, Math.PI / 2));
        hall.add(createWindow(1.0,  1.0,  2.41, 1.6, 0, Math.PI / 2));

        worldGroup.add(hall);

        // 2. MINT COTTAGE (East: x=8.4, z=-1.0)
        var mintHouse = new THREE.Group();
        mintHouse.position.set(8.4, 0, -1.0);

        var mBody = new THREE.Mesh(new THREE.BoxGeometry(3.4, 2.7, 3.2), mintMat);
        mBody.position.y = 1.35;
        mBody.castShadow = true;
        mBody.receiveShadow = true;
        mintHouse.add(mBody);

        // Stepped pixel roof with flat sunny top pad (y = 2.95)
        var mRoof1 = new THREE.Mesh(new THREE.BoxGeometry(3.8, 0.3, 3.6), roofBlueMat);
        mRoof1.position.y = 2.85;
        mRoof1.castShadow = true;
        mRoof1.receiveShadow = true;
        mintHouse.add(mRoof1);

        var mRoofSunPad = new THREE.Mesh(new THREE.BoxGeometry(2.8, 0.18, 2.6), deckMat);
        mRoofSunPad.position.y = 3.08;
        mRoofSunPad.receiveShadow = true;
        mintHouse.add(mRoofSunPad);

        var mCushion = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.12, 1.1), new THREE.MeshLambertMaterial({ color: 0xffbe0b }));
        mCushion.position.set(0, 3.2, 0);
        mintHouse.add(mCushion);

        mintHouse.add(createWindow(0.9, 0.9, -1.71, 1.45, -0.6, Math.PI / 2));
        mintHouse.add(createWindow(0.9, 0.9, -1.71, 1.45,  0.7, Math.PI / 2));
        mintHouse.add(createWindow(0.95, 0.9, 0, 1.45, 1.61, 0));

        worldGroup.add(mintHouse);

        // 3. CORAL COTTAGE (West: x=-8.8, z=2.0)
        var coralHouse = new THREE.Group();
        coralHouse.position.set(-8.8, 0, 2.0);

        var cBody = new THREE.Mesh(new THREE.BoxGeometry(3.2, 2.6, 3.0), coralMat);
        cBody.position.y = 1.3;
        cBody.castShadow = true;
        cBody.receiveShadow = true;
        coralHouse.add(cBody);

        var cRoof1 = new THREE.Mesh(new THREE.BoxGeometry(3.6, 0.28, 3.4), roofRedMat);
        cRoof1.position.y = 2.74;
        cRoof1.castShadow = true;
        cRoof1.receiveShadow = true;
        coralHouse.add(cRoof1);

        var cRoofSunPad = new THREE.Mesh(new THREE.BoxGeometry(2.6, 0.18, 2.4), deckMat);
        cRoofSunPad.position.y = 2.96;
        cRoofSunPad.receiveShadow = true;
        coralHouse.add(cRoofSunPad);

        coralHouse.add(createWindow(0.88, 0.88, 1.61, 1.4, -0.5, Math.PI / 2));
        coralHouse.add(createWindow(0.88, 0.88, 1.61, 1.4,  0.6, Math.PI / 2));
        coralHouse.add(createWindow(0.9,  0.88, 0, 1.4, 1.51, 0));

        worldGroup.add(coralHouse);

        // Subtle golden sunbeam volumes over the sunny rooftops (visible during Day/Sunset)
        var beamMat = new THREE.MeshBasicMaterial({
          color: 0xfff3a8,
          transparent: true,
          opacity: 0.11,
          depthWrite: false
        });
        var rooftopBeamCoords = [
          [-8.0, 4.4, -7.6],
          [4.6,  4.8, -6.2],
          [8.4,  4.3, -1.0]
        ];
        for (var b = 0; b < rooftopBeamCoords.length; b++) {
          var bc = rooftopBeamCoords[b];
          var beam = new THREE.Mesh(new THREE.CylinderGeometry(0.9, 1.55, 2.6, 8), beamMat);
          beam.position.set(bc[0], bc[1], bc[2]);
          beam.rotation.z = -0.22;
          worldGroup.add(beam);
          sunbeamMeshes.push(beam);
        }

        // Street Lanterns around the plaza and paths
        createLantern(-2.8, 0, -0.8, false);
        createLantern( 2.8, 0, -2.5, false);
        createLantern( 6.4, 0, -3.8, false);
        createLantern(-6.5, 0,  1.8, false);
        createLantern(-2.2, 0,  3.2, false);
      }

      // ============================================================
      // 7. ZONE 3: PARK WITH GIANT BALLS OF YARN & TREES
      // ============================================================
      var giantYarnBalls = [];

      function createGiantYarnBall(x, z, radius, texture, strandColorHex) {
        var yGroup = new THREE.Group();
        yGroup.position.set(x, radius * 0.92, z);

        var mat = new THREE.MeshLambertMaterial({ map: texture });
        // Chunky voxelized yarn ball (overlapping orthogonal boxes + core sphere)
        var core = new THREE.Mesh(new THREE.BoxGeometry(radius * 1.55, radius * 1.55, radius * 1.55), mat);
        core.castShadow = true;
        core.receiveShadow = true;
        yGroup.add(core);

        var bandX = new THREE.Mesh(new THREE.BoxGeometry(radius * 1.82, radius * 1.18, radius * 1.18), mat);
        var bandY = new THREE.Mesh(new THREE.BoxGeometry(radius * 1.18, radius * 1.82, radius * 1.18), mat);
        var bandZ = new THREE.Mesh(new THREE.BoxGeometry(radius * 1.18, radius * 1.18, radius * 1.82), mat);
        bandX.castShadow = true;
        bandY.castShadow = true;
        bandZ.castShadow = true;
        yGroup.add(bandX, bandY, bandZ);

        // Diagonal wound yarn bands
        var wrap1 = new THREE.Mesh(new THREE.BoxGeometry(radius * 1.65, radius * 0.65, radius * 1.45), mat);
        wrap1.rotation.set(0.4, 0.5, 0.3);
        yGroup.add(wrap1);

        worldGroup.add(yGroup);

        // Trailing yarn thread unspooled onto the park grass
        var strandMat = new THREE.MeshLambertMaterial({ color: strandColorHex });
        for (var s = 0; s < 5; s++) {
          var seg = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.1, 0.14), strandMat);
          seg.position.set(x + 0.7 + s * 0.36, 0.07, z + Math.sin(s * 1.2) * 0.35);
          seg.rotation.y = Math.cos(s) * 0.5;
          worldGroup.add(seg);
        }

        giantYarnBalls.push({
          mesh: yGroup,
          x: x,
          z: z,
          radius: radius,
          baseY: radius * 0.92,
          phase: pRand() * Math.PI * 2
        });
      }

      function createVoxelTree(x, z, trunkH, crownColor1, crownColor2) {
        var tGroup = new THREE.Group();
        tGroup.position.set(x, 0, z);

        var trunkMat = new THREE.MeshLambertMaterial({ color: 0x6e472b });
        var leaf1 = new THREE.MeshLambertMaterial({ color: crownColor1 });
        var leaf2 = new THREE.MeshLambertMaterial({ color: crownColor2 });

        var trunk = new THREE.Mesh(new THREE.BoxGeometry(0.7, trunkH, 0.7), trunkMat);
        trunk.position.y = trunkH * 0.5;
        trunk.castShadow = true;
        tGroup.add(trunk);

        var c1 = new THREE.Mesh(new THREE.BoxGeometry(2.5, 1.5, 2.5), leaf1);
        c1.position.y = trunkH + 0.5;
        c1.castShadow = true;
        var c2 = new THREE.Mesh(new THREE.BoxGeometry(1.9, 1.2, 1.9), leaf2);
        c2.position.y = trunkH + 1.45;
        c2.castShadow = true;
        var c3 = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.8, 1.1), leaf1);
        c3.position.y = trunkH + 2.15;
        c3.castShadow = true;
        tGroup.add(c1, c2, c3);

        worldGroup.add(tGroup);
      }

      function buildYarnParkZone() {
        // 3 Giant Balls of Yarn in the Park
        createGiantYarnBall(-6.2, 5.4, 1.12, Textures.yarnPink, 0xff6ba5);
        createGiantYarnBall(-3.7, 6.8, 0.92, Textures.yarnCyan, 0x49d7eb);
        createGiantYarnBall(-6.6, 7.9, 0.82, Textures.yarnGold, 0xffd25a);

        // Voxel Trees framing the park & island
        createVoxelTree(-10.2, 6.5, 1.8, 0xff8fab, 0xffb3c6); // Cherry blossom tree
        createVoxelTree(-2.2,  9.6, 1.6, 0x52b788, 0x74c69d); // Lush green oak
        createVoxelTree(10.2, -7.8, 1.9, 0x52b788, 0x74c69d);
        createVoxelTree(-10.4, -3.2, 1.7, 0xff8fab, 0xffb3c6);

        // Wooden Park Bench
        var bench = new THREE.Group();
        bench.position.set(-8.6, 0, 4.6);
        bench.rotation.y = 0.45;
        var bMat = new THREE.MeshLambertMaterial({ map: Textures.woodPlank });
        var seat = new THREE.Mesh(new THREE.BoxGeometry(1.9, 0.14, 0.65), bMat);
        seat.position.y = 0.42;
        seat.castShadow = true;
        var back = new THREE.Mesh(new THREE.BoxGeometry(1.9, 0.5, 0.12), bMat);
        back.position.set(0, 0.72, -0.28);
        back.castShadow = true;
        var leg1 = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.42, 0.55), bMat);
        leg1.position.set(-0.75, 0.21, 0);
        var leg2 = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.42, 0.55), bMat);
        leg2.position.set(0.75, 0.21, 0);
        bench.add(seat, back, leg1, leg2);
        worldGroup.add(bench);

        // Cat Scratching Post Tower in the Park
        var tower = new THREE.Group();
        tower.position.set(-8.8, 0, 8.6);
        var sisalMat = new THREE.MeshLambertMaterial({ color: 0xd9b98b });
        var plushMat = new THREE.MeshLambertMaterial({ color: 0x9b5de5 });
        var tBase = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.18, 1.3), plushMat);
        tBase.position.y = 0.09;
        var tPole = new THREE.Mesh(new THREE.BoxGeometry(0.36, 1.6, 0.36), sisalMat);
        tPole.position.y = 0.9;
        tPole.castShadow = true;
        var tTop = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.18, 1.0), plushMat);
        tTop.position.y = 1.75;
        tTop.castShadow = true;
        tower.add(tBase, tPole, tTop);
        worldGroup.add(tower);
      }

      // ============================================================
      // 8. ZONE 4: POND WITH SMALL BRIDGE, KOI & WATERFALL
      // ============================================================
      var pondKoiList = [];
      var waterfallDrops = [];
      var waterMesh = null;

      // Bridge constants (used by cat height solver too)
      var BRIDGE_X_MIN = 1.2;
      var BRIDGE_X_MAX = 9.2;
      var BRIDGE_Z_MIN = 4.1;
      var BRIDGE_Z_MAX = 6.3;

      function getBridgeHeightAt(x) {
        var t = (x - BRIDGE_X_MIN) / (BRIDGE_X_MAX - BRIDGE_X_MIN);
        t = Math.max(0, Math.min(1, t));
        return Math.sin(t * Math.PI) * 1.05;
      }

      function buildPondAndBridgeZone() {
        var pondGroup = new THREE.Group();

        // Translucent Pixel-Art Pond Water Surface at y = -0.28
        var waterMat = new THREE.MeshLambertMaterial({
          map: Textures.waterTex,
          transparent: true,
          opacity: 0.88
        });
        waterMesh = new THREE.Mesh(new THREE.BoxGeometry(6.6, 0.45, 9.8), waterMat);
        waterMesh.position.set(5.3, -0.52, 7.0);
        waterMesh.receiveShadow = true;
        pondGroup.add(waterMesh);

        // Stone rim blocks around pond banks
        var stoneMat = new THREE.MeshLambertMaterial({ color: 0x8f887d });
        var rimCoords = [
          [1.9, 0.08, 3.0, 0.45, 1.5], [1.9, 0.08, 7.6, 0.45, 2.4],
          [8.65, 0.08, 3.0, 0.45, 1.5], [8.65, 0.08, 7.6, 0.45, 2.4],
          [5.3, 0.08, 2.1, 6.6, 0.45]
        ];
        for (var r = 0; r < rimCoords.length; r++) {
          var rc = rimCoords[r];
          var rim = new THREE.Mesh(new THREE.BoxGeometry(rc[3], 0.22, rc[4]), stoneMat);
          rim.position.set(rc[0], rc[1], rc[2]);
          rim.receiveShadow = true;
          pondGroup.add(rim);
        }

        // Voxel Lily Pads & Pink Lotus Flowers
        var lilyMat = new THREE.MeshLambertMaterial({ color: 0x4ad66d });
        var lotusMat = new THREE.MeshLambertMaterial({ color: 0xff70a6 });
        var lilies = [
          [3.4, 3.1], [6.8, 3.3], [3.6, 7.3], [7.0, 7.5], [5.1, 8.2]
        ];
        for (var l = 0; l < lilies.length; l++) {
          var pad = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.08, 0.75), lilyMat);
          pad.position.set(lilies[l][0], -0.26, lilies[l][1]);
          pondGroup.add(pad);
          if (l % 2 === 0) {
            var flower = new THREE.Mesh(new THREE.BoxGeometry(0.28, 0.2, 0.28), lotusMat);
            flower.position.set(lilies[l][0], -0.15, lilies[l][1]);
            pondGroup.add(flower);
          }
        }

        // Swimming Pixel Koi Fish in the Pond
        var koiColors = [0xff6b35, 0xffbe0b, 0xff595e, 0xffffff];
        for (var k = 0; k < 5; k++) {
          var koi = createPixelFishMesh(koiColors[k % koiColors.length], 0.78);
          var cx = (k < 2) ? 4.8 : 5.5;
          var cz = (k < 2) ? 3.2 : 7.4;
          pondGroup.add(koi);
          pondKoiList.push({
            mesh: koi,
            cx: cx,
            cz: cz,
            rx: 1.2 + (k % 2) * 0.5,
            rz: 0.55 + (k % 2) * 0.25,
            angle: k * 1.4,
            speed: 0.9 + (k % 3) * 0.25
          });
        }

        // SMALL ARCHED WOODEN BRIDGE OVER THE POND
        var bridgeGroup = new THREE.Group();
        var plankMat = new THREE.MeshLambertMaterial({ map: Textures.woodPlank });
        var postMat = new THREE.MeshLambertMaterial({ color: 0xb83b2b });
        var railMat = new THREE.MeshLambertMaterial({ color: 0x7a4924 });

        var numPlanks = 15;
        var spanLen = BRIDGE_X_MAX - BRIDGE_X_MIN;
        var stepX = spanLen / numPlanks;

        for (var i = 0; i <= numPlanks; i++) {
          var px = BRIDGE_X_MIN + i * stepX;
          var py = getBridgeHeightAt(px);
          var plank = new THREE.Mesh(new THREE.BoxGeometry(stepX * 0.96, 0.16, 2.2), plankMat);
          plank.position.set(px, py, 5.2);

          // Tilt plank along arch tangent
          var nextY = getBridgeHeightAt(Math.min(BRIDGE_X_MAX, px + 0.2));
          var prevY = getBridgeHeightAt(Math.max(BRIDGE_X_MIN, px - 0.2));
          plank.rotation.z = Math.atan2(nextY - prevY, 0.4);
          plank.castShadow = true;
          plank.receiveShadow = true;
          bridgeGroup.add(plank);

          // Bridge posts along both sides
          if (i % 3 === 0) {
            for (var side = -1; side <= 1; side += 2) {
              var bPost = new THREE.Mesh(new THREE.BoxGeometry(0.18, 0.78, 0.18), postMat);
              bPost.position.set(px, py + 0.39, 5.2 + side * 1.02);
              bPost.castShadow = true;
              bridgeGroup.add(bPost);
            }
          }
        }

        // Curved handrail segments connecting bridge posts
        for (var rStep = 0; rStep < 5; rStep++) {
          var xA = BRIDGE_X_MIN + rStep * (spanLen / 5);
          var xB = BRIDGE_X_MIN + (rStep + 1) * (spanLen / 5);
          var yA = getBridgeHeightAt(xA) + 0.72;
          var yB = getBridgeHeightAt(xB) + 0.72;
          var midX = (xA + xB) * 0.5;
          var midY = (yA + yB) * 0.5;
          var segLen = Math.hypot(xB - xA, yB - yA);
          var ang = Math.atan2(yB - yA, xB - xA);

          for (var sSide = -1; sSide <= 1; sSide += 2) {
            var rail = new THREE.Mesh(new THREE.BoxGeometry(segLen + 0.1, 0.12, 0.12), railMat);
            rail.position.set(midX, midY, 5.2 + sSide * 1.02);
            rail.rotation.z = ang;
            bridgeGroup.add(rail);
          }
        }

        pondGroup.add(bridgeGroup);

        // Bridge entrance lanterns (glow at night!)
        createLantern(1.4, -0.5, 3.9, false);
        createLantern(1.4, -0.5, 6.5, false);
        createLantern(9.0, -0.5, 3.9, false);
        createLantern(9.0, -0.5, 6.5, false);

        // Cascading Pixel Waterfall at the Southern Cliff Edge of the Pond (x=5.3, z=11.9)
        var dropGeo = new THREE.BoxGeometry(0.45, 0.55, 0.35);
        var dropMat = new THREE.MeshBasicMaterial({ color: 0x7ae6ff, transparent: true, opacity: 0.85 });
        for (var w = 0; w < 18; w++) {
          var drop = new THREE.Mesh(dropGeo, dropMat);
          drop.position.set(4.5 + (w % 4) * 0.48, -0.4 - (w / 18) * 9.5, 11.95 + (w % 2) * 0.15);
          pondGroup.add(drop);
          waterfallDrops.push({
            mesh: drop,
            speed: 3.6 + (w % 3) * 0.6,
            xOffset: 4.5 + (w % 4) * 0.48
          });
        }

        worldGroup.add(pondGroup);
      }

      // ============================================================
      // 9. BUTTERFLIES IN THE PARK & MEADOW
      // ============================================================
      var butterflies = [];

      function buildButterflies() {
        var bColors = [0xff66c4, 0xffde59, 0x5ce1e6, 0xff9f1c, 0xc77dff];
        for (var i = 0; i < 5; i++) {
          var bGroup = new THREE.Group();
          var wingMat = new THREE.MeshBasicMaterial({ color: bColors[i], side: THREE.DoubleSide });

          var leftWingPivot = new THREE.Group();
          var lw = new THREE.Mesh(new THREE.BoxGeometry(0.24, 0.04, 0.28), wingMat);
          lw.position.x = -0.13;
          leftWingPivot.add(lw);

          var rightWingPivot = new THREE.Group();
          var rw = new THREE.Mesh(new THREE.BoxGeometry(0.24, 0.04, 0.28), wingMat);
          rw.position.x = 0.13;
          rightWingPivot.add(rw);

          bGroup.add(leftWingPivot, rightWingPivot);
          worldGroup.add(bGroup);

          butterflies.push({
            group: bGroup,
            leftWing: leftWingPivot,
            rightWing: rightWingPivot,
            cx: -4.8 + (i % 3) * 2.2,
            cz: 4.2 + Math.floor(i / 2) * 2.1,
            radius: 1.5 + (i % 2) * 0.8,
            angle: i * 1.3,
            speed: 1.2 + (i % 3) * 0.25,
            phase: i * 2.1
          });
        }
      }

      // ============================================================
      // 10. DRIFTING CLOUDS BELOW THE ISLAND
      // ============================================================
      var clouds = [];
      var cloudMaterial = new THREE.MeshLambertMaterial({
        color: 0xffffff,
        transparent: true,
        opacity: 0.92
      });

      function buildDriftingClouds() {
        for (var i = 0; i < 18; i++) {
          var cGroup = new THREE.Group();
          var baseW = 3.2 + (i % 4) * 1.1;
          var baseD = 2.2 + (i % 3) * 0.8;
          var baseH = 0.9 + (i % 2) * 0.35;

          var mainPuff = new THREE.Mesh(new THREE.BoxGeometry(baseW, baseH, baseD), cloudMaterial);
          var topPuff = new THREE.Mesh(new THREE.BoxGeometry(baseW * 0.65, baseH * 0.85, baseD * 0.72), cloudMaterial);
          topPuff.position.set((i % 2 === 0 ? -0.3 : 0.3), baseH * 0.65, 0);
          var sidePuff = new THREE.Mesh(new THREE.BoxGeometry(baseW * 0.55, baseH * 0.7, baseD * 0.65), cloudMaterial);
          sidePuff.position.set(baseW * 0.45, -0.1, 0.2);

          cGroup.add(mainPuff, topPuff, sidePuff);

          var cx = -38 + (i / 18) * 76 + (pRand() - 0.5) * 4;
          var cy = -4.8 - (i % 5) * 2.1;
          var cz = -28 + ((i * 7) % 18) * 3.3;

          cGroup.position.set(cx, cy, cz);
          worldGroup.add(cGroup);

          clouds.push({
            mesh: cGroup,
            speed: 1.1 + (i % 4) * 0.38,
            baseY: cy,
            phase: i * 0.9
          });
        }
      }

      // ============================================================
      // 11. CAT GENERATOR & AUTONOMOUS AI BEHAVIORS (13 CATS)
      // ============================================================
      var cats = [];
      var catHitMeshes = [];

      function createCatFaceTexture(furHex, accentHex, eyeHex, isSleeping) {
        return makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = furHex;
          ctx.fillRect(0, 0, w, h);

          // Forehead tabby stripes / markings
          ctx.fillStyle = accentHex;
          ctx.fillRect(4, 1, 2, 3);
          ctx.fillRect(7, 1, 2, 4);
          ctx.fillRect(10, 1, 2, 3);

          // Muzzle / cheeks
          ctx.fillStyle = '#fff9f0';
          ctx.fillRect(4, 10, 8, 4);

          if (isSleeping) {
            // Closed happy sleeping eyes
            ctx.fillStyle = '#241c24';
            ctx.fillRect(2, 7, 4, 2);
            ctx.fillRect(10, 7, 4, 2);
          } else {
            // Big cute pixel eyes
            ctx.fillStyle = '#18141c';
            ctx.fillRect(2, 6, 4, 4);
            ctx.fillRect(10, 6, 4, 4);
            ctx.fillStyle = eyeHex;
            ctx.fillRect(3, 6, 3, 3);
            ctx.fillRect(11, 6, 3, 3);
            // Eye shine pixel
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(2, 6, 2, 2);
            ctx.fillRect(10, 6, 2, 2);
          }

          // Pink triangle pixel nose
          ctx.fillStyle = '#ff7b9c';
          ctx.fillRect(7, 10, 2, 2);

          // Whiskers
          ctx.fillStyle = '#d9d2c9';
          ctx.fillRect(0, 10, 3, 1);
          ctx.fillRect(0, 12, 3, 1);
          ctx.fillRect(13, 10, 3, 1);
          ctx.fillRect(13, 12, 3, 1);
        });
      }

      function createCatFurTexture(furHex, accentHex) {
        return makePixelTexture(16, 16, function (ctx, w, h) {
          ctx.fillStyle = furHex;
          ctx.fillRect(0, 0, w, h);
          ctx.fillStyle = accentHex;
          for (var y = 2; y < h; y += 4) {
            ctx.fillRect(2, y, 12, 2);
          }
        });
      }

      // Ground height & obstacle check for ground-walking cats
      function getTerrainHeight(x, z) {
        if (x >= BRIDGE_X_MIN && x <= BRIDGE_X_MAX && z >= BRIDGE_Z_MIN && z <= BRIDGE_Z_MAX) {
          return getBridgeHeightAt(x);
        }
        return 0;
      }

      function isPositionBlocked(x, z) {
        // Keep within island bounds
        if (x < -10.8 || x > 10.2 || z < -10.5 || z > 10.2) return true;
        // Fish Shop building
        if (x > -10.2 && x < -5.1 && z > -9.5 && z < -5.3) return true;
        // Market Stall counters
        if (x > -9.4 && x < -6.2 && z > -4.2 && z < -2.2) return true;
        if (x > -5.4 && x < -2.2 && z > -7.5 && z < -5.5) return true;
        if (x > -5.1 && x < -2.4 && z > -3.5 && z < -1.5) return true;
        // Town Hall building
        if (x > 2.7 && x < 8.1 && z > -8.8 && z < -4.2) return true;
        // Mint Cottage
        if (x > 6.4 && x < 10.4 && z > -2.9 && z < 0.9) return true;
        // Coral Cottage
        if (x > -10.6 && x < -6.9 && z > 0.2 && z < 3.8) return true;
        // Central Fountain
        if (Math.hypot(x - 0, z + 0.4) < 1.45) return true;
        // Giant Yarn Balls
        for (var y = 0; y < giantYarnBalls.length; y++) {
          var yb = giantYarnBalls[y];
          if (Math.hypot(x - yb.x, z - yb.z) < yb.radius + 0.42) return true;
        }
        // Pond Water (except when crossing on the Small Bridge!)
        var inPondBox = (x > 1.7 && x < 8.8 && z > 2.0 && z < 11.2);
        var onBridge = (x >= BRIDGE_X_MIN + 0.1 && x <= BRIDGE_X_MAX - 0.1 && z >= BRIDGE_Z_MIN + 0.25 && z <= BRIDGE_Z_MAX - 0.25);
        if (inPondBox && !onBridge) return true;

        return false;
      }

      function pickRandomTownTarget() {
        var presets = [
          { x: -1.8, z: -1.6 },
          { x: 1.8,  z: 1.4 },
          { x: 5.2,  z: 5.2 },  // Center of small pond bridge!
          { x: 2.8,  z: 5.2 },  // West end of pond bridge
          { x: 7.4,  z: 5.2 },  // East end of pond bridge
          { x: -4.5, z: 3.8 },  // Park entrance
          { x: -7.5, z: -1.2 }, // Front of Fish Market Stall 1
          { x: -2.2, z: -4.6 }, // Front of Fish Market Stall 2
          { x: 3.5,  z: -3.2 }, // Town Hall square
          { x: -1.5, z: 6.2 }   // Meadow near pond & park
        ];
        if (Math.random() < 0.6) {
          var pt = presets[Math.floor(Math.random() * presets.length)];
          return { x: pt.x + (Math.random() - 0.5) * 0.6, z: pt.z + (Math.random() - 0.5) * 0.6 };
        }
        for (var tries = 0; tries < 25; tries++) {
          var rx = -9.2 + Math.random() * 18.4;
          var rz = -8.8 + Math.random() * 17.6;
          if (!isPositionBlocked(rx, rz)) {
            return { x: rx, z: rz };
          }
        }
        return { x: 0, z: 2.0 };
      }

      var CAT_PROFILES = [
        { name: 'Mayor Barnaby', role: '🎩 Town Mayor', fur: '#f58220', accent: '#c95b0c', eye: '#70e000', isMayor: true, startX: 0.2, startZ: -2.4, initState: 'SHOPPING' },
        { name: 'Mochi', role: '🐟 Fish Connoisseur', fur: '#f4f1ea', accent: '#d9cfc1', eye: '#38b6ff', startX: -7.4, startZ: -1.5, initState: 'SHOPPING' },
        { name: 'Cleo', role: '🦋 Butterfly Chaser', fur: '#34343f', accent: '#1b1b22', eye: '#ffd166', startX: -4.6, startZ: 4.5, initState: 'CHASING' },
        { name: 'Biscuit', role: '🧶 Yarn Explorer', fur: '#e6b88a', accent: '#7a4b2a', eye: '#4cc9f0', startX: -4.8, startZ: 6.0, initState: 'CHASING' },
        { name: 'Pepper', role: '🌉 Bridge Watcher', fur: '#7d8597', accent: '#5c677d', eye: '#80ed99', startX: 5.2, startZ: 5.2, initState: 'STRETCHING' },
        { name: 'Nori', role: '🐟 Market Regular', fur: '#2b2d42', accent: '#ffffff', eye: '#ffbe0b', startX: -3.5, startZ: -4.8, initState: 'SHOPPING' },
        { name: 'Ginger', role: '🦋 Park Sprinter', fur: '#ff9f1c', accent: '#e07a00', eye: '#52b788', startX: -2.8, startZ: 5.8, initState: 'WALKING' },
        { name: 'Tofu', role: '💤 Plaza Lounger', fur: '#fff8e8', accent: '#f77f00', eye: '#48cae4', startX: 2.2, startZ: -2.0, initState: 'SLEEPING' },
        { name: 'Miso', role: '🧘 Stretch Master', fur: '#b5838d', accent: '#6d6875', eye: '#ffd166', startX: 1.8, startZ: 2.2, initState: 'STRETCHING' },
        { name: 'Socks', role: '🐾 Town Patroller', fur: '#8d5524', accent: '#5c3310', eye: '#70e000', startX: -2.0, startZ: 1.2, initState: 'WALKING' },
        // 3 Rooftop Sun-Napping Cats!
        { name: 'Sunny', role: '☀️ Rooftop Napper', fur: '#ffbe0b', accent: '#fb5607', eye: '#38b6ff', isRooftop: true, roofY: 3.98, startX: 4.5, startZ: -6.2, minX: 3.7, maxX: 5.9, minZ: -7.5, maxZ: -5.2, initState: 'SLEEPING' },
        { name: 'Cloudy', role: '☀️ Rooftop Dreamer', fur: '#e5e5e5', accent: '#adb5bd', eye: '#4cc9f0', isRooftop: true, roofY: 3.45, startX: -8.2, startZ: -7.7, minX: -9.1, maxX: -6.4, minZ: -8.4, maxZ: -6.4, initState: 'SLEEPING' },
        { name: 'Pumpkin', role: '☀️ Sundeck Napper', fur: '#f77f00', accent: '#d62828', eye: '#9ef01a', isRooftop: true, roofY: 3.26, startX: 8.4, startZ: -1.0, minX: 7.6, maxX: 9.2, minZ: -1.7, maxZ: -0.3, initState: 'SLEEPING' }
      ];

      function buildCats() {
        for (var i = 0; i < CAT_PROFILES.length; i++) {
          var prof = CAT_PROFILES[i];
          var root = new THREE.Group();

          var furTex = createCatFurTexture(prof.fur, prof.accent);
          var faceAwakeTex = createCatFaceTexture(prof.fur, prof.accent, prof.eye, false);
          var faceSleepTex = createCatFaceTexture(prof.fur, prof.accent, prof.eye, true);

          var furMat = new THREE.MeshLambertMaterial({ map: furTex });
          var pawMat = new THREE.MeshLambertMaterial({ color: 0xfff8f0 });
          var earInnerMat = new THREE.MeshLambertMaterial({ color: 0xff8fab });
          var faceMat = new THREE.MeshLambertMaterial({ map: faceAwakeTex });

          // Articulated hierarchy so cats can walk, stretch, pounce, and curl up to sleep
          var rig = new THREE.Group();
          root.add(rig);

          // Torso
          var bodyMesh = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.34, 0.66), furMat);
          bodyMesh.position.set(0, 0.34, 0);
          bodyMesh.castShadow = true;
          rig.add(bodyMesh);

          // Head pivot
          var headGroup = new THREE.Group();
          headGroup.position.set(0, 0.56, 0.34);
          rig.add(headGroup);

          var headMaterials = [furMat, furMat, furMat, furMat, faceMat, furMat];
          var headMesh = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.38, 0.40), headMaterials);
          headMesh.castShadow = true;
          headGroup.add(headMesh);

          // Pointy voxel ears
          var earL = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.15, 0.1), furMat);
          earL.position.set(-0.14, 0.25, -0.02);
          var earLIn = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.09, 0.04), earInnerMat);
          earLIn.position.set(-0.14, 0.24, 0.04);

          var earR = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.15, 0.1), furMat);
          earR.position.set(0.14, 0.25, -0.02);
          var earRIn = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.09, 0.04), earInnerMat);
          earRIn.position.set(0.14, 0.24, 0.04);
          headGroup.add(earL, earLIn, earR, earRIn);

          // MAYOR BARNABY'S TINY TOP HAT & GOLD MAYOR COLLAR!
          if (prof.isMayor) {
            var hatGroup = new THREE.Group();
            hatGroup.position.set(0, 0.22, 0.02);
            hatGroup.rotation.z = -0.08;

            var hatBlackMat = new THREE.MeshLambertMaterial({ color: 0x1e1b29 });
            var hatRibbonMat = new THREE.MeshLambertMaterial({ color: 0xe63946 });
            var hatGoldMat = new THREE.MeshLambertMaterial({ color: 0xffd166 });

            var brim = new THREE.Mesh(new THREE.BoxGeometry(0.36, 0.05, 0.36), hatBlackMat);
            var crown = new THREE.Mesh(new THREE.BoxGeometry(0.24, 0.26, 0.24), hatBlackMat);
            crown.position.y = 0.15;
            var ribbon = new THREE.Mesh(new THREE.BoxGeometry(0.25, 0.06, 0.25), hatRibbonMat);
            ribbon.position.y = 0.06;
            var buckle = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.07, 0.26), hatGoldMat);
            buckle.position.y = 0.06;

            hatGroup.add(brim, crown, ribbon, buckle);
            headGroup.add(hatGroup);

            // Tiny gold mayor medallion on chest
            var medal = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.14, 0.06), hatGoldMat);
            medal.position.set(0, 0.34, 0.35);
            rig.add(medal);
          }

          // 4 Articulated Legs
          var legGeo = new THREE.BoxGeometry(0.12, 0.24, 0.12);
          var legFL = new THREE.Mesh(legGeo, pawMat);
          legFL.position.set(-0.13, 0.12, 0.22);
          var legFR = new THREE.Mesh(legGeo, pawMat);
          legFR.position.set(0.13, 0.12, 0.22);
          var legBL = new THREE.Mesh(legGeo, pawMat);
          legBL.position.set(-0.13, 0.12, -0.22);
          var legBR = new THREE.Mesh(legGeo, pawMat);
          legBR.position.set(0.13, 0.12, -0.22);
          rig.add(legFL, legFR, legBL, legBR);

          // Expressive Pivoting Tail
          var tailPivot = new THREE.Group();
          tailPivot.position.set(0, 0.42, -0.32);
          var tailSeg1 = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.36, 0.1), furMat);
          tailSeg1.position.set(0, 0.16, -0.06);
          tailSeg1.rotation.x = -0.55;
          tailPivot.add(tailSeg1);
          rig.add(tailPivot);

          // Floating Activity Thought Bubble Sprite above cat
          var bubbleMat = new THREE.SpriteMaterial({
            map: BubbleTextures.zzz,
            transparent: true,
            opacity: 0
          });
          var bubbleSprite = new THREE.Sprite(bubbleMat);
          bubbleSprite.position.set(0, 1.25, 0);
          bubbleSprite.scale.set(0.65, 0.65, 1);
          root.add(bubbleSprite);

          // Generous Invisible Hitbox for effortless touch/mouse tapping
          var hitBox = new THREE.Mesh(
            new THREE.BoxGeometry(1.25, 1.35, 1.25),
            new THREE.MeshBasicMaterial({ visible: false })
          );
          hitBox.position.y = 0.55;
          hitBox.userData.catIndex = i;
          root.add(hitBox);
          catHitMeshes.push(hitBox);

          var initY = prof.isRooftop ? prof.roofY : getTerrainHeight(prof.startX, prof.startZ);
          root.position.set(prof.startX, initY, prof.startZ);
          worldGroup.add(root);

          var catObj = {
            index: i,
            profile: prof,
            root: root,
            rig: rig,
            bodyMesh: bodyMesh,
            headGroup: headGroup,
            faceMat: faceMat,
            faceAwakeTex: faceAwakeTex,
            faceSleepTex: faceSleepTex,
            legs: [legFL, legFR, legBL, legBR],
            tailPivot: tailPivot,
            bubbleSprite: bubbleSprite,
            state: prof.initState || 'WALKING',
            stateTimer: 3 + Math.random() * 5,
            targetX: prof.startX,
            targetZ: prof.startZ,
            butterflyTarget: i % butterflies.length,
            marketStallIndex: i % 3,
            walkCycle: Math.random() * Math.PI * 2,
            speed: prof.isMayor ? 1.55 : (1.35 + Math.random() * 0.45)
          };

          setCatBehavior(catObj, prof.initState || 'WALKING');
          cats.push(catObj);
        }
      }

      var MARKET_SHOP_SPOTS = [
        { x: -7.5, z: -1.4, lookX: -7.8, lookZ: -3.2 },
        { x: -3.6, z: -4.7, lookX: -3.8, lookZ: -6.5 },
        { x: -2.4, z: -1.6, lookX: -3.8, lookZ: -2.5 }
      ];

      function getCatStatusText(cat) {
        switch (cat.state) {
          case 'SHOPPING':
            return '🐟 Shopping for fresh fish at the market';
          case 'CHASING':
            return '🦋 Chasing a butterfly in the park!';
          case 'STRETCHING':
            return '🧘 Doing a big sunny cat stretch';
          case 'SLEEPING':
            return cat.profile.isRooftop
              ? '💤 Curled up napping on a sunny rooftop'
              : '💤 Curled up fast asleep';
          default:
            return cat.profile.isMayor
              ? '🎩 Patrolling Whiskerhaven town'
              : '🐾 Strolling around the island';
        }
      }

      function setCatBehavior(cat, newState) {
        cat.state = newState;
        var prof = cat.profile;

        if (prof.isRooftop) {
          // Rooftop cats alternate between napping in the sun, stretching, and taking a few steps on their sundeck
          if (newState === 'SLEEPING') {
            cat.stateTimer = 6.5 + Math.random() * 6.0;
            cat.faceMat.map = cat.faceSleepTex;
            cat.bubbleSprite.material.map = BubbleTextures.zzz;
            cat.bubbleSprite.material.opacity = 0.95;
          } else if (newState === 'STRETCHING') {
            cat.stateTimer = 3.2;
            cat.faceMat.map = cat.faceAwakeTex;
            cat.bubbleSprite.material.map = BubbleTextures.stretch;
            cat.bubbleSprite.material.opacity = 0.9;
          } else {
            cat.state = 'WALKING';
            cat.stateTimer = 2.8 + Math.random() * 2.0;
            cat.faceMat.map = cat.faceAwakeTex;
            cat.bubbleSprite.material.opacity = 0;
            cat.targetX = prof.minX + Math.random() * (prof.maxX - prof.minX);
            cat.targetZ = prof.minZ + Math.random() * (prof.maxZ - prof.minZ);
          }
          cat.faceMat.needsUpdate = true;
          return;
        }

        // Ground cats cycle through SHOPPING, CHASING butterflies, STRETCHING, SLEEPING, and WALKING
        if (newState === 'SHOPPING') {
          cat.marketStallIndex = Math.floor(Math.random() * MARKET_SHOP_SPOTS.length);
          var spot = MARKET_SHOP_SPOTS[cat.marketStallIndex];
          cat.targetX = spot.x + (Math.random() - 0.5) * 0.8;
          cat.targetZ = spot.z + (Math.random() - 0.5) * 0.6;
          cat.stateTimer = 7.0 + Math.random() * 4.5;
          cat.faceMat.map = cat.faceAwakeTex;
          cat.bubbleSprite.material.map = BubbleTextures.fish;
          cat.bubbleSprite.material.opacity = 0.95;
        } else if (newState === 'CHASING') {
          cat.butterflyTarget = Math.floor(Math.random() * butterflies.length);
          cat.stateTimer = 6.5 + Math.random() * 4.5;
          cat.faceMat.map = cat.faceAwakeTex;
          cat.bubbleSprite.material.map = BubbleTextures.butterfly;
          cat.bubbleSprite.material.opacity = 0.95;
        } else if (newState === 'STRETCHING') {
          cat.stateTimer = 3.4;
          cat.faceMat.map = cat.faceAwakeTex;
          cat.bubbleSprite.material.map = BubbleTextures.stretch;
          cat.bubbleSprite.material.opacity = 0.92;
        } else if (newState === 'SLEEPING') {
          cat.stateTimer = 6.5 + Math.random() * 5.0;
          cat.faceMat.map = cat.faceSleepTex;
          cat.bubbleSprite.material.map = BubbleTextures.zzz;
          cat.bubbleSprite.material.opacity = 0.95;
        } else {
          cat.state = 'WALKING';
          var pt = pickRandomTownTarget();
          cat.targetX = pt.x;
          cat.targetZ = pt.z;
          cat.stateTimer = 5.0 + Math.random() * 4.5;
          cat.faceMat.map = cat.faceAwakeTex;
          cat.bubbleSprite.material.opacity = 0;
        }
        cat.faceMat.needsUpdate = true;
      }

      function chooseNextGroundBehavior(cat) {
        if (cat.state === 'WALKING') {
          var r = Math.random();
          if (r < 0.28) return 'SHOPPING';
          if (r < 0.55) return 'CHASING';
          if (r < 0.78) return 'STRETCHING';
          return 'SLEEPING';
        }
        if (cat.state === 'STRETCHING') {
          return (Math.random() < 0.45) ? 'SLEEPING' : 'WALKING';
        }
        return 'WALKING';
      }

      function resetCatPose(cat) {
        cat.rig.position.set(0, 0, 0);
        cat.rig.rotation.set(0, 0, 0);
        cat.bodyMesh.position.set(0, 0.34, 0);
        cat.bodyMesh.rotation.set(0, 0, 0);
        cat.headGroup.position.set(0, 0.56, 0.34);
        cat.headGroup.rotation.set(0, 0, 0);
        for (var l = 0; l < 4; l++) {
          cat.legs[l].rotation.set(0, 0, 0);
          cat.legs[l].scale.set(1, 1, 1);
        }
        cat.tailPivot.rotation.set(0, 0, 0);
      }

      function moveCatToward(cat, destX, destZ, speedMult, dt, elapsed) {
        var pos = cat.root.position;
        var dx = destX - pos.x;
        var dz = destZ - pos.z;
        var dist = Math.hypot(dx, dz);

        if (dist > 0.18) {
          var step = Math.min(dist, cat.speed * speedMult * dt);
          var nx = pos.x + (dx / dist) * step;
          var nz = pos.z + (dz / dist) * step;

          if (!cat.profile.isRooftop && isPositionBlocked(nx, nz)) {
            // Try sliding along X or Z or pick a fresh unobstructed target
            if (!isPositionBlocked(nx, pos.z)) {
              pos.x = nx;
            } else if (!isPositionBlocked(pos.x, nz)) {
              pos.z = nz;
            } else {
              var alt = pickRandomTownTarget();
              cat.targetX = alt.x;
              cat.targetZ = alt.z;
            }
          } else {
            pos.x = nx;
            pos.z = nz;
          }

          pos.y = cat.profile.isRooftop ? cat.profile.roofY : getTerrainHeight(pos.x, pos.z);

          // Smooth heading rotation
          var desiredYaw = Math.atan2(dx, dz);
          var diff = desiredYaw - cat.root.rotation.y;
          while (diff > Math.PI) diff -= Math.PI * 2;
          while (diff < -Math.PI) diff += Math.PI * 2;
          cat.root.rotation.y += diff * Math.min(1, dt * 8);

          // Walk cycle leg & tail animation
          cat.walkCycle += dt * 11 * speedMult;
          var swing = Math.sin(cat.walkCycle) * 0.55;
          cat.legs[0].rotation.x = swing;
          cat.legs[1].rotation.x = -swing;
          cat.legs[2].rotation.x = -swing;
          cat.legs[3].rotation.x = swing;
          cat.rig.position.y = Math.abs(Math.cos(cat.walkCycle)) * 0.05;
          cat.tailPivot.rotation.z = Math.sin(elapsed * 4 + cat.index) * 0.28;
          return false; // not arrived yet
        }
        return true; // arrived
      }

      function updateCats(dt, elapsed) {
        for (var i = 0; i < cats.length; i++) {
          var cat = cats[i];
          cat.stateTimer -= dt;

          // Float thought bubble gently
          cat.bubbleSprite.position.y = 1.22 + Math.sin(elapsed * 3.5 + i) * 0.08;

          if (cat.stateTimer <= 0) {
            resetCatPose(cat);
            if (cat.profile.isRooftop) {
              var nextRoof = (cat.state === 'SLEEPING') ? 'STRETCHING' : (cat.state === 'STRETCHING' ? 'WALKING' : 'SLEEPING');
              setCatBehavior(cat, nextRoof);
            } else {
              setCatBehavior(cat, chooseNextGroundBehavior(cat));
            }
          }

          if (cat.state === 'WALKING') {
            resetCatPose(cat);
            var arrived = moveCatToward(cat, cat.targetX, cat.targetZ, 1.0, dt, elapsed);
            if (arrived) {
              cat.headGroup.rotation.y = Math.sin(elapsed * 2.2 + i) * 0.25;
              cat.tailPivot.rotation.z = Math.sin(elapsed * 3 + i) * 0.25;
            }
          } else if (cat.state === 'SHOPPING') {
            resetCatPose(cat);
            var spot = MARKET_SHOP_SPOTS[cat.marketStallIndex];
            var atStall = moveCatToward(cat, cat.targetX, cat.targetZ, 1.05, dt, elapsed);
            if (atStall) {
              // Face the market counter, look up at fish, hop excitedly
              var lookYaw = Math.atan2(spot.lookX - cat.root.position.x, spot.lookZ - cat.root.position.z);
              cat.root.rotation.y = lookYaw;
              cat.headGroup.rotation.x = -0.28 + Math.sin(elapsed * 5 + i) * 0.1;
              cat.headGroup.rotation.y = Math.sin(elapsed * 3.2 + i) * 0.22;
              cat.rig.position.y = Math.max(0, Math.sin(elapsed * 6.5 + i)) * 0.12;
              cat.tailPivot.rotation.z = Math.sin(elapsed * 8 + i) * 0.35;
            }
          } else if (cat.state === 'CHASING') {
            resetCatPose(cat);
            var bfly = butterflies[cat.butterflyTarget];
            var bx = bfly.group.position.x;
            var bz = bfly.group.position.z;
            moveCatToward(cat, bx, bz, 1.45, dt, elapsed);
            // Playful pounce leap every couple seconds
            var pounceWave = Math.sin(elapsed * 5.5 + i);
            if (pounceWave > 0.45) {
              cat.rig.position.y = (pounceWave - 0.45) * 0.55;
              cat.rig.rotation.x = -0.28;
              cat.legs[0].rotation.x = -0.8;
              cat.legs[1].rotation.x = -0.8;
            }
            cat.headGroup.rotation.x = -0.25;
            cat.tailPivot.rotation.z = Math.sin(elapsed * 10 + i) * 0.45;
          } else if (cat.state === 'STRETCHING') {
            resetCatPose(cat);
            // Classic front-paw bow stretch followed by back arch
            var phase = 1.0 - (cat.stateTimer / 3.4);
            if (phase < 0.65) {
              // Front bow ("big stretch!")
              cat.bodyMesh.rotation.x = 0.38;
              cat.bodyMesh.position.y = 0.27;
              cat.headGroup.position.set(0, 0.38, 0.42);
              cat.legs[0].rotation.x = -0.75;
              cat.legs[1].rotation.x = -0.75;
              cat.tailPivot.rotation.x = 0.35;
            } else {
              // Arch back upward
              cat.bodyMesh.rotation.x = -0.22;
              cat.bodyMesh.position.y = 0.39;
              cat.headGroup.position.set(0, 0.52, 0.32);
            }
            cat.tailPivot.rotation.z = Math.sin(elapsed * 4) * 0.2;
          } else if (cat.state === 'SLEEPING') {
            resetCatPose(cat);
            // Curl up into a cozy sleeping ball on the ground or sunny rooftop
            cat.rig.position.y = -0.13;
            cat.bodyMesh.rotation.y = 0.25;
            cat.headGroup.position.set(0.14, 0.36, 0.22);
            cat.headGroup.rotation.set(0.25, -0.55, 0.15);
            for (var l = 0; l < 4; l++) {
              cat.legs[l].scale.y = 0.35;
            }
            cat.tailPivot.rotation.set(0.6, 0.85, 0.4);
            // Gentle breathing motion
            var breath = 1.0 + Math.sin(elapsed * 2.4 + i) * 0.04;
            cat.bodyMesh.scale.set(breath, breath, 1.0);
          }
        }
      }

      // ============================================================
      // 12. SELECTION RING & CAMERA CONTROLLER (SPIN, ZOOM, FOLLOW)
      // ============================================================
      var followedCatIndex = -1;

      var selectionRing = new THREE.Group();
      var ringMat = new THREE.MeshBasicMaterial({ color: 0xffd166 });
      for (var rSeg = 0; rSeg < 8; rSeg++) {
        var rAngle = (rSeg / 8) * Math.PI * 2;
        var rBox = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.06, 0.08), ringMat);
        rBox.position.set(Math.cos(rAngle) * 0.55, 0.05, Math.sin(rAngle) * 0.55);
        rBox.rotation.y = -rAngle;
        selectionRing.add(rBox);
      }
      selectionRing.visible = false;
      worldGroup.add(selectionRing);

      // Camera spherical coordinates
      var camState = {
        theta: 0.68,
        phi: 1.02,
        radius: 26.0,
        targetTheta: 0.68,
        targetPhi: 1.02,
        targetRadius: 26.0,
        lookAt: new THREE.Vector3(0, 1.0, 0),
        desiredLookAt: new THREE.Vector3(0, 1.0, 0)
      };

      var catNameEl = document.getElementById('cat-name');
      var catRoleEl = document.getElementById('cat-role');
      var catStatusEl = document.getElementById('cat-status');
      var catSwatchEl = document.getElementById('cat-swatch');
      var btnUnfollowEl = document.getElementById('btn-unfollow');
      var floatLabelEl = document.getElementById('cat-label-float');

      function selectCatToFollow(index) {
        followedCatIndex = index;
        if (index >= 0 && index < cats.length) {
          var cat = cats[index];
          selectionRing.visible = true;
          camState.targetRadius = Math.min(camState.targetRadius, 15.5);
          catNameEl.textContent = cat.profile.name;
          catRoleEl.textContent = cat.profile.role;
          catSwatchEl.style.background = cat.profile.fur;
          catStatusEl.textContent = getCatStatusText(cat);
          btnUnfollowEl.style.display = 'inline-flex';
          floatLabelEl.style.display = 'block';
        } else {
          followedCatIndex = -1;
          selectionRing.visible = false;
          camState.desiredLookAt.set(0, 1.0, 0);
          camState.targetRadius = 26.0;
          catNameEl.textContent = 'Island Overview';
          catRoleEl.textContent = '13 Cats Active';
          catSwatchEl.style.background = '#f58220';
          catStatusEl.textContent = 'Tap any cat on the island (or use the buttons below) to follow them!';
          btnUnfollowEl.style.display = 'none';
          floatLabelEl.style.display = 'none';
        }
      }

      // Pointer & Touch gesture handling (Drag to spin, Pinch/Scroll to zoom, Tap cat to follow)
      var activePointers = {};
      var isDragging = false;
      var pointerDownPos = { x: 0, y: 0 };
      var lastDragPos = { x: 0, y: 0 };
      var prevPinchDist = 0;

      var raycaster = new THREE.Raycaster();
      var ndcMouse = new THREE.Vector2();

      function getActivePointerList() {
        var list = [];
        for (var k in activePointers) {
          if (Object.prototype.hasOwnProperty.call(activePointers, k)) {
            list.push(activePointers[k]);
          }
        }
        return list;
      }

      function handleTapAt(clientX, clientY) {
        var rect = renderer.domElement.getBoundingClientRect();
        ndcMouse.x = ((clientX - rect.left) / rect.width) * 2 - 1;
        ndcMouse.y = -((clientY - rect.top) / rect.height) * 2 + 1;

        raycaster.setFromCamera(ndcMouse, camera);
        var hits = raycaster.intersectObjects(catHitMeshes, false);
        if (hits.length > 0) {
          var hitCatIdx = hits[0].object.userData.catIndex;
          if (typeof hitCatIdx === 'number') {
            selectCatToFollow(hitCatIdx);
          }
        }
      }

      var domCanvas = renderer.domElement;

      domCanvas.addEventListener('pointerdown', function (e) {
        if (e.isTrusted) stopDemoMode();
        activePointers[e.pointerId] = { id: e.pointerId, x: e.clientX, y: e.clientY };
        var pts = getActivePointerList();
        if (pts.length === 1) {
          isDragging = false;
          pointerDownPos.x = e.clientX;
          pointerDownPos.y = e.clientY;
          lastDragPos.x = e.clientX;
          lastDragPos.y = e.clientY;
        } else if (pts.length === 2) {
          isDragging = true;
          prevPinchDist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
        }
      });

      window.addEventListener('pointermove', function (e) {
        if (!activePointers[e.pointerId]) return;
        activePointers[e.pointerId].x = e.clientX;
        activePointers[e.pointerId].y = e.clientY;

        var pts = getActivePointerList();
        if (pts.length === 1) {
          var dx = e.clientX - lastDragPos.x;
          var dy = e.clientY - lastDragPos.y;
          if (Math.hypot(e.clientX - pointerDownPos.x, e.clientY - pointerDownPos.y) > 6) {
            isDragging = true;
          }
          if (isDragging) {
            camState.targetTheta -= dx * 0.0085;
            camState.targetPhi = Math.max(0.38, Math.min(1.42, camState.targetPhi - dy * 0.0065));
          }
          lastDragPos.x = e.clientX;
          lastDragPos.y = e.clientY;
        } else if (pts.length === 2) {
          var dist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
          if (prevPinchDist > 0) {
            var deltaPinch = prevPinchDist - dist;
            camState.targetRadius = Math.max(9.0, Math.min(44.0, camState.targetRadius + deltaPinch * 0.08));
          }
          prevPinchDist = dist;
        }
      });

      function onPointerEnd(e) {
        if (!activePointers[e.pointerId]) return;
        var wasTap = !isDragging && Math.hypot(e.clientX - pointerDownPos.x, e.clientY - pointerDownPos.y) <= 8;
        delete activePointers[e.pointerId];
        prevPinchDist = 0;
        if (wasTap && getActivePointerList().length === 0) {
          handleTapAt(e.clientX, e.clientY);
        }
      }

      window.addEventListener('pointerup', onPointerEnd);
      window.addEventListener('pointercancel', onPointerEnd);

      domCanvas.addEventListener('wheel', function (e) {
        if (e.isTrusted) stopDemoMode();
        e.preventDefault();
        var zoomStep = e.deltaY * 0.02;
        camState.targetRadius = Math.max(9.0, Math.min(44.0, camState.targetRadius + zoomStep));
      }, { passive: false });

      // ============================================================
      // 13. DAY / SUNSET / NIGHT PRESETS & SMOOTH TRANSITIONS
      // ============================================================
      var TIME_PRESETS = {
        day: {
          skyGradient: 'linear-gradient(180deg, #4da6e8 0%, #8ed6ff 58%, #cdefff 100%)',
          fogColor: new THREE.Color(0x8ed6ff),
          ambientColor: new THREE.Color(0xd9f0ff),
          ambientIntensity: 0.7,
          hemiSky: new THREE.Color(0xffffff),
          hemiGround: new THREE.Color(0x5d8254),
          hemiIntensity: 0.45,
          dirColor: new THREE.Color(0xfff5d6),
          dirIntensity: 1.08,
          dirPos: new THREE.Vector3(20, 32, 16),
          cloudColor: new THREE.Color(0xffffff),
          windowColor: new THREE.Color(0x7ec8e3),
          windowEmissive: new THREE.Color(0x112233),
          lanternColor: new THREE.Color(0xdde8f0),
          glowOpacity: 0.0,
          pointLightFactor: 0.0,
          starOpacity: 0.0,
          sunbeamOpacity: 0.12
        },
        sunset: {
          skyGradient: 'linear-gradient(180deg, #3b245e 0%, #c94b4b 42%, #ff9b54 78%, #ffd166 100%)',
          fogColor: new THREE.Color(0xf28d63),
          ambientColor: new THREE.Color(0xffbfa3),
          ambientIntensity: 0.56,
          hemiSky: new THREE.Color(0xff9e66),
          hemiGround: new THREE.Color(0x472d4c),
          hemiIntensity: 0.4,
          dirColor: new THREE.Color(0xff7733),
          dirIntensity: 0.98,
          dirPos: new THREE.Vector3(-28, 13, 18),
          cloudColor: new THREE.Color(0xffb59e),
          windowColor: new THREE.Color(0xffcf70),
          windowEmissive: new THREE.Color(0x994d00),
          lanternColor: new THREE.Color(0xffe082),
          glowOpacity: 0.52,
          pointLightFactor: 0.55,
          starOpacity: 0.25,
          sunbeamOpacity: 0.16
        },
        night: {
          skyGradient: 'linear-gradient(180deg, #070a1c 0%, #141c3d 52%, #23305e 100%)',
          fogColor: new THREE.Color(0x141c3d),
          ambientColor: new THREE.Color(0x3a4e8c),
          ambientIntensity: 0.42,
          hemiSky: new THREE.Color(0x4a64ad),
          hemiGround: new THREE.Color(0x141829),
          hemiIntensity: 0.3,
          dirColor: new THREE.Color(0x88aaff),
          dirIntensity: 0.35,
          dirPos: new THREE.Vector3(-20, 28, -20),
          cloudColor: new THREE.Color(0x526494),
          windowColor: new THREE.Color(0xffe57f),
          windowEmissive: new THREE.Color(0xffaa22),
          lanternColor: new THREE.Color(0xffea85),
          glowOpacity: 0.96,
          pointLightFactor: 1.0,
          starOpacity: 0.95,
          sunbeamOpacity: 0.0
        }
      };

      var currentMode = 'day';
      var activePreset = TIME_PRESETS.day;

      var btnDay = document.getElementById('btn-day');
      var btnSunset = document.getElementById('btn-sunset');
      var btnNight = document.getElementById('btn-night');
      var skyBackdrop = document.getElementById('sky-backdrop');

      function setTimeOfDay(mode) {
        if (!TIME_PRESETS[mode]) return;
        currentMode = mode;
        activePreset = TIME_PRESETS[mode];
        skyBackdrop.style.background = activePreset.skyGradient;

        btnDay.classList.toggle('active', mode === 'day');
        btnSunset.classList.toggle('active', mode === 'sunset');
        btnNight.classList.toggle('active', mode === 'night');
      }

      btnDay.addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        setTimeOfDay('day');
      });
      btnSunset.addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        setTimeOfDay('sunset');
      });
      btnNight.addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        setTimeOfDay('night');
      });

      // Inspector & Zoom Buttons
      document.getElementById('btn-mayor').addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        selectCatToFollow(0);
      });
      document.getElementById('btn-next-cat').addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        var nextIdx = (followedCatIndex + 1) % cats.length;
        selectCatToFollow(nextIdx);
      });
      document.getElementById('btn-unfollow').addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        selectCatToFollow(-1);
      });
      document.getElementById('btn-zoom-in').addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        camState.targetRadius = Math.max(9.0, camState.targetRadius - 3.5);
      });
      document.getElementById('btn-zoom-out').addEventListener('click', function (e) {
        if (e.isTrusted) stopDemoMode();
        camState.targetRadius = Math.min(44.0, camState.targetRadius + 3.5);
      });

      // ============================================================
      // 14. HANDS-FREE 20-SECOND #DEMO LOOP
      // ============================================================
      var demoActive = false;
      var demoStartTime = 0;
      var demoStage = -1;
      var demoBannerEl = document.getElementById('demo-banner');

      function startDemoMode() {
        demoActive = true;
        demoStartTime = performance.now() * 0.001;
        demoStage = -1;
        demoBannerEl.classList.add('visible');
      }

      function stopDemoMode() {
        if (!demoActive) return;
        demoActive = false;
        demoBannerEl.classList.remove('visible');
      }

      function updateDemoLoop(nowSec, dt) {
        if (!demoActive) return;
        var loopT = (nowSec - demoStartTime) % 20.0;

        // 20-second choreographed tour across all features
        if (loopT < 4.0) {
          if (demoStage !== 0) {
            demoStage = 0;
            setTimeOfDay('day');
            selectCatToFollow(-1);
            camState.targetRadius = 26.0;
            camState.targetPhi = 1.02;
          }
          camState.targetTheta += dt * 0.42;
        } else if (loopT < 8.5) {
          if (demoStage !== 1) {
            demoStage = 1;
            setTimeOfDay('day');
            selectCatToFollow(0); // Follow Mayor Barnaby with his tiny top hat!
            camState.targetRadius = 13.5;
            camState.targetPhi = 1.05;
          }
          camState.targetTheta += dt * 0.35;
        } else if (loopT < 13.0) {
          if (demoStage !== 2) {
            demoStage = 2;
            setTimeOfDay('sunset');
            selectCatToFollow(2); // Follow butterfly-chasing cat in the Yarn Park
            camState.targetRadius = 14.5;
            camState.targetPhi = 1.0;
          }
          camState.targetTheta += dt * 0.38;
        } else if (loopT < 16.5) {
          if (demoStage !== 3) {
            demoStage = 3;
            setTimeOfDay('night');
            selectCatToFollow(10); // Follow Sunny sleeping on the Town Hall rooftop
            camState.targetRadius = 14.0;
            camState.targetPhi = 0.96;
          }
          camState.targetTheta += dt * 0.35;
        } else {
          if (demoStage !== 4) {
            demoStage = 4;
            setTimeOfDay('night');
            selectCatToFollow(-1); // Full glowing night island overview
            camState.targetRadius = 24.5;
            camState.targetPhi = 1.04;
          }
          camState.targetTheta += dt * 0.45;
        }
      }

      // ============================================================
      // 15. INITIALIZE WORLD & START ANIMATION LOOP
      // ============================================================
      buildFloatingIsland();
      buildFishMarketZone();
      buildTownBuildings();
      buildYarnParkZone();
      buildPondAndBridgeZone();
      buildButterflies();
      buildDriftingClouds();
      buildCats();

      if (window.location.hash && window.location.hash.toLowerCase() === '#demo') {
        startDemoMode();
      }

      window.addEventListener('resize', function () {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      });

      var prevTime = performance.now() * 0.001;
      var hudUpdateCounter = 0;
      var tempProjVec = new THREE.Vector3();

      function animate() {
        requestAnimationFrame(animate);

        var now = performance.now() * 0.001;
        var dt = Math.min(0.05, Math.max(0.001, now - prevTime));
        prevTime = now;

        // 1. Update #demo autopilot if active
        updateDemoLoop(now, dt);

        // 2. Smoothly interpolate Day / Sunset / Night lighting & glowing windows/lanterns
        var lerpFactor = Math.min(1, dt * 2.6);
        scene.fog.color.lerp(activePreset.fogColor, lerpFactor);
        ambientLight.color.lerp(activePreset.ambientColor, lerpFactor);
        ambientLight.intensity += (activePreset.ambientIntensity - ambientLight.intensity) * lerpFactor;
        hemiLight.color.lerp(activePreset.hemiSky, lerpFactor);
        hemiLight.groundColor.lerp(activePreset.hemiGround, lerpFactor);
        hemiLight.intensity += (activePreset.hemiIntensity - hemiLight.intensity) * lerpFactor;
        dirLight.color.lerp(activePreset.dirColor, lerpFactor);
        dirLight.intensity += (activePreset.dirIntensity - dirLight.intensity) * lerpFactor;
        dirLight.position.lerp(activePreset.dirPos, lerpFactor);
        cloudMaterial.color.lerp(activePreset.cloudColor, lerpFactor);

        sharedWindowMat.color.lerp(activePreset.windowColor, lerpFactor);
        sharedWindowMat.emissive.lerp(activePreset.windowEmissive, lerpFactor);
        sharedLanternGlassMat.color.lerp(activePreset.lanternColor, lerpFactor);

        // Flickering warm glow sprites on windows & lanterns at sunset/night
        for (var g = 0; g < glowSprites.length; g++) {
          var gs = glowSprites[g];
          var flicker = 1.0 + Math.sin(now * 6.0 + g * 1.7) * 0.07;
          var targetOp = activePreset.glowOpacity * flicker;
          gs.sprite.material.opacity += (targetOp - gs.sprite.material.opacity) * lerpFactor;
          var sc = gs.baseScale * flicker;
          gs.sprite.scale.set(sc, sc, 1);
        }

        // Town point lights for night illumination
        for (var pl = 0; pl < townPointLights.length; pl++) {
          var tLight = townPointLights[pl];
          var targetInt = tLight.maxIntensity * activePreset.pointLightFactor;
          tLight.light.intensity += (targetInt - tLight.light.intensity) * lerpFactor;
        }

        // Stars & Moon at night
        starMat.opacity += (activePreset.starOpacity - starMat.opacity) * lerpFactor;
        moonMat.opacity = starMat.opacity;

        // Daytime rooftop sunbeams
        for (var sb = 0; sb < sunbeamMeshes.length; sb++) {
          var curOp = sunbeamMeshes[sb].material.opacity;
          sunbeamMeshes[sb].material.opacity = curOp + (activePreset.sunbeamOpacity - curOp) * lerpFactor;
        }

        // 3. Drift clouds below the island
        for (var c = 0; c < clouds.length; c++) {
          var cl = clouds[c];
          cl.mesh.position.x += cl.speed * dt;
          if (cl.mesh.position.x > 40) {
            cl.mesh.position.x = -40;
          }
          cl.mesh.position.y = cl.baseY + Math.sin(now * 0.9 + cl.phase) * 0.25;
        }

        // 4. Animate fluttering butterflies
        for (var b = 0; b < butterflies.length; b++) {
          var bf = butterflies[b];
          bf.angle += bf.speed * dt;
          var bx = bf.cx + Math.cos(bf.angle) * bf.radius + Math.sin(now * 1.7 + bf.phase) * 0.6;
          var bz = bf.cz + Math.sin(bf.angle * 1.3) * bf.radius;
          var by = 0.85 + Math.abs(Math.sin(now * 3.2 + bf.phase)) * 0.65;

          var prevX = bf.group.position.x;
          var prevZ = bf.group.position.z;
          bf.group.position.set(bx, by, bz);
          bf.group.rotation.y = Math.atan2(bx - prevX, bz - prevZ);

          var flap = Math.sin(now * 24 + bf.phase) * 0.85;
          bf.leftWing.rotation.z = flap;
          bf.rightWing.rotation.z = -flap;
        }

        // 5. Animate swimming koi & cascading waterfall drops
        for (var k = 0; k < pondKoiList.length; k++) {
          var koi = pondKoiList[k];
          koi.angle += koi.speed * dt;
          var kx = koi.cx + Math.cos(koi.angle) * koi.rx;
          var kz = koi.cz + Math.sin(koi.angle) * koi.rz;
          var prevKX = koi.mesh.position.x;
          var prevKZ = koi.mesh.position.z;
          koi.mesh.position.set(kx, -0.32, kz);
          koi.mesh.rotation.y = Math.atan2(kx - prevKX, kz - prevKZ) - Math.PI * 0.5;
        }

        for (var w = 0; w < waterfallDrops.length; w++) {
          var wd = waterfallDrops[w];
          wd.mesh.position.y -= wd.speed * dt;
          if (wd.mesh.position.y < -10.0) {
            wd.mesh.position.y = -0.35;
          }
        }

        // Gentle wobble on Giant Yarn Balls
        for (var y = 0; y < giantYarnBalls.length; y++) {
          var yb = giantYarnBalls[y];
          yb.mesh.rotation.z = Math.sin(now * 1.6 + yb.phase) * 0.04;
          yb.mesh.rotation.x = Math.cos(now * 1.3 + yb.phase) * 0.04;
        }

        // 6. Update all 13 autonomous cats
        updateCats(dt, now);

        // 7. Update camera target & selection ring if following a cat
        if (followedCatIndex >= 0 && followedCatIndex < cats.length) {
          var fCat = cats[followedCatIndex];
          camState.desiredLookAt.set(
            fCat.root.position.x,
            fCat.root.position.y + 0.55,
            fCat.root.position.z
          );
          selectionRing.position.copy(fCat.root.position);
          selectionRing.rotation.y = now * 1.8;

          hudUpdateCounter++;
          if (hudUpdateCounter % 15 === 0) {
            catStatusEl.textContent = getCatStatusText(fCat);
          }

          // Project 2D floating name tag above followed cat
          tempProjVec.set(fCat.root.position.x, fCat.root.position.y + 1.65, fCat.root.position.z);
          tempProjVec.project(camera);
          if (tempProjVec.z < 1) {
            var screenX = (tempProjVec.x * 0.5 + 0.5) * window.innerWidth;
            var screenY = (-tempProjVec.y * 0.5 + 0.5) * window.innerHeight;
            floatLabelEl.style.left = screenX + 'px';
            floatLabelEl.style.top = screenY + 'px';
            floatLabelEl.textContent = (fCat.profile.isMayor ? '🎩 ' : '🐾 ') + fCat.profile.name;
          }
        }

        // Smoothly interpolate camera spherical coordinates
        var camSmooth = Math.min(1, dt * 7.5);
        camState.theta += (camState.targetTheta - camState.theta) * camSmooth;
        camState.phi += (camState.targetPhi - camState.phi) * camSmooth;
        camState.radius += (camState.targetRadius - camState.radius) * camSmooth;
        camState.lookAt.lerp(camState.desiredLookAt, camSmooth);

        var sinPhi = Math.sin(camState.phi);
        camera.position.set(
          camState.lookAt.x + camState.radius * sinPhi * Math.sin(camState.theta),
          camState.lookAt.y + camState.radius * Math.cos(camState.phi),
          camState.lookAt.z + camState.radius * sinPhi * Math.cos(camState.theta)
        );
        camera.lookAt(camState.lookAt);

        renderer.render(scene, camera);
      }

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