Skip to content
VibeCodeBench
Back to the app

The code

Cat Island by Gemini 4 Neon

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.)126.8 KB · 3,565 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/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, viewport-fit=cover">
<title>Cat Island — Chunky Pixel 3D</title>
<style>
  *, *::before, *::after {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
  }
  html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: #4da6ff;
    font-family: ui-monospace, 'Cascadia Mono', 'SFMono-Regular', Menlo, Consolas, monospace;
    user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
  }
  #canvas-wrap {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
  }
  #canvas-wrap canvas {
    display: block;
    width: 100%;
    height: 100%;
    touch-action: none;
    cursor: grab;
  }
  #canvas-wrap canvas:active {
    cursor: grabbing;
  }

  /* UI Overlay */
  #ui-overlay {
    position: fixed;
    inset: 0;
    pointer-events: none;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(14px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
    z-index: 10;
  }

  .top-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 10px;
  }

  .title-badge {
    background: rgba(28, 25, 42, 0.72);
    border: 2px solid rgba(255, 245, 224, 0.35);
    box-shadow: 0 4px 0 rgba(16, 14, 26, 0.45);
    border-radius: 10px;
    padding: 8px 12px;
    color: #fff8eb;
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
  }
  .title-badge h1 {
    margin: 0;
    font-size: 15px;
    font-weight: 800;
    letter-spacing: 0.04em;
    display: flex;
    align-items: center;
    gap: 6px;
    line-height: 1.2;
  }
  .title-badge p {
    margin: 3px 0 0;
    font-size: 11px;
    color: rgba(255, 243, 220, 0.78);
    line-height: 1.2;
  }

  .demo-badge {
    display: none;
    align-items: center;
    gap: 7px;
    background: rgba(255, 134, 71, 0.9);
    border: 2px solid #fff3d6;
    box-shadow: 0 4px 0 rgba(130, 48, 18, 0.6);
    border-radius: 10px;
    padding: 7px 11px;
    color: #fffdf7;
    font-size: 11px;
    font-weight: 800;
    letter-spacing: 0.05em;
    text-transform: uppercase;
  }
  .demo-badge.active {
    display: inline-flex;
  }
  .demo-dot {
    width: 8px;
    height: 8px;
    background: #fff9c4;
    border-radius: 2px;
    animation: pulseDot 1.1s infinite ease-in-out;
  }
  @keyframes pulseDot {
    0%, 100% { opacity: 1; transform: scale(1); }
    50% { opacity: 0.4; transform: scale(0.75); }
  }

  .bottom-stack {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }

  /* Follow Cat Pill */
  .follow-card {
    pointer-events: auto;
    display: none;
    align-items: center;
    gap: 10px;
    background: rgba(29, 25, 44, 0.84);
    border: 2px solid rgba(255, 228, 173, 0.65);
    box-shadow: 0 5px 0 rgba(14, 11, 24, 0.55), 0 8px 22px rgba(0, 0, 0, 0.28);
    border-radius: 12px;
    padding: 8px 10px 8px 12px;
    color: #fff9ee;
    max-width: min(94vw, 390px);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    animation: popIn 0.18s ease-out;
  }
  .follow-card.active {
    display: flex;
  }
  @keyframes popIn {
    from { opacity: 0; transform: translateY(8px) scale(0.96); }
    to { opacity: 1; transform: translateY(0) scale(1); }
  }
  .cat-swatch {
    width: 34px;
    height: 34px;
    border-radius: 8px;
    border: 2px solid rgba(255, 255, 255, 0.6);
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    position: relative;
    image-rendering: pixelated;
  }
  .cat-info {
    display: flex;
    flex-direction: column;
    min-width: 0;
    flex: 1;
  }
  .cat-name {
    font-size: 13px;
    font-weight: 800;
    color: #ffdf8e;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .cat-status {
    font-size: 11px;
    color: #e8e2f5;
    margin-top: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .unfollow-btn {
    pointer-events: auto;
    appearance: none;
    border: 2px solid rgba(255, 240, 210, 0.55);
    background: rgba(255, 255, 255, 0.14);
    color: #fff8ea;
    font-family: inherit;
    font-size: 12px;
    font-weight: 800;
    border-radius: 8px;
    min-height: 40px;
    min-width: 44px;
    padding: 0 12px;
    cursor: pointer;
    flex-shrink: 0;
    transition: transform 0.08s ease, background 0.15s ease;
  }
  .unfollow-btn:active {
    transform: translateY(2px);
    background: rgba(255, 255, 255, 0.28);
  }

  /* Time of Day Bar */
  .time-bar {
    pointer-events: auto;
    display: flex;
    align-items: center;
    gap: 8px;
    background: rgba(24, 21, 38, 0.74);
    border: 2px solid rgba(255, 245, 224, 0.35);
    box-shadow: 0 5px 0 rgba(12, 10, 20, 0.5), 0 10px 24px rgba(0, 0, 0, 0.25);
    border-radius: 14px;
    padding: 6px;
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
  }
  .time-btn {
    appearance: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    min-height: 46px;
    min-width: 96px;
    padding: 8px 14px;
    border-radius: 10px;
    border: 2px solid transparent;
    background: rgba(255, 255, 255, 0.09);
    color: #f3ecff;
    font-family: inherit;
    font-size: 13px;
    font-weight: 800;
    letter-spacing: 0.03em;
    cursor: pointer;
    box-shadow: 0 3px 0 rgba(0, 0, 0, 0.32);
    transition: transform 0.08s ease, background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
  }
  .time-btn:active {
    transform: translateY(2px);
    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.35);
  }
  .time-btn svg {
    width: 18px;
    height: 18px;
    flex-shrink: 0;
    shape-rendering: crispEdges;
  }
  .time-btn[data-mode="day"].active {
    background: #3aa0f2;
    border-color: #d9f3ff;
    color: #ffffff;
    box-shadow: 0 3px 0 #1f649e;
  }
  .time-btn[data-mode="sunset"].active {
    background: #eb6d44;
    border-color: #ffe3b8;
    color: #fffdf7;
    box-shadow: 0 3px 0 #99391d;
  }
  .time-btn[data-mode="night"].active {
    background: #32478f;
    border-color: #ffd97d;
    color: #fff7db;
    box-shadow: 0 3px 0 #18234d;
  }

  @media (max-width: 480px) {
    .title-badge h1 { font-size: 13px; }
    .title-badge p { font-size: 10px; }
    .time-bar { gap: 6px; padding: 5px; }
    .time-btn {
      min-width: 86px;
      min-height: 46px;
      padding: 8px 10px;
      font-size: 12px;
      gap: 5px;
    }
  }

  #fallback-msg {
    display: none;
    position: fixed;
    inset: 0;
    align-items: center;
    justify-content: center;
    background: #1c2438;
    color: #fff8e6;
    padding: 24px;
    text-align: center;
    z-index: 99;
  }
</style>
</head>
<body>
<div id="canvas-wrap"></div>

<div id="ui-overlay">
  <div class="top-row">
    <div class="title-badge">
      <h1>
        <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" style="shape-rendering:crispEdges">
          <rect x="2" y="2" width="3" height="4" fill="#ff9e44"/>
          <rect x="11" y="2" width="3" height="4" fill="#ff9e44"/>
          <rect x="2" y="5" width="12" height="9" fill="#ff9e44"/>
          <rect x="4" y="8" width="2" height="2" fill="#231c2b"/>
          <rect x="10" y="8" width="2" height="2" fill="#231c2b"/>
          <rect x="7" y="10" width="2" height="2" fill="#ff738f"/>
          <rect x="5" y="1" width="6" height="2" fill="#2a2d40"/>
          <rect x="6" y="0" width="4" height="2" fill="#ffd24a"/>
        </svg>
        CAT ISLAND
      </h1>
      <p>Drag to spin · Pinch/scroll to zoom · Tap a cat</p>
    </div>
    <div id="demo-badge" class="demo-badge">
      <span class="demo-dot"></span>
      <span>Demo · Touch to explore</span>
    </div>
  </div>

  <div class="bottom-stack">
    <div id="follow-card" class="follow-card" role="status" aria-live="polite">
      <div id="cat-swatch" class="cat-swatch"></div>
      <div class="cat-info">
        <div id="cat-name" class="cat-name">Mayor Marmalade</div>
        <div id="cat-status" class="cat-status">Strolling the square</div>
      </div>
      <button id="unfollow-btn" class="unfollow-btn" type="button" aria-label="Return to island view">Island ✕</button>
    </div>

    <div class="time-bar" role="group" aria-label="Time of day">
      <button class="time-btn active" type="button" data-mode="day" aria-pressed="true">
        <svg viewBox="0 0 16 16" aria-hidden="true">
          <rect x="7" y="1" width="2" height="2" fill="#ffe66d"/>
          <rect x="7" y="13" width="2" height="2" fill="#ffe66d"/>
          <rect x="1" y="7" width="2" height="2" fill="#ffe66d"/>
          <rect x="13" y="7" width="2" height="2" fill="#ffe66d"/>
          <rect x="3" y="3" width="2" height="2" fill="#ffd447"/>
          <rect x="11" y="3" width="2" height="2" fill="#ffd447"/>
          <rect x="3" y="11" width="2" height="2" fill="#ffd447"/>
          <rect x="11" y="11" width="2" height="2" fill="#ffd447"/>
          <rect x="5" y="5" width="6" height="6" fill="#fff28a"/>
          <rect x="6" y="6" width="4" height="4" fill="#ffcf33"/>
        </svg>
        <span>Day</span>
      </button>
      <button class="time-btn" type="button" data-mode="sunset" aria-pressed="false">
        <svg viewBox="0 0 16 16" aria-hidden="true">
          <rect x="1" y="11" width="14" height="2" fill="#ff9e64"/>
          <rect x="3" y="13" width="10" height="2" fill="#c95b7a"/>
          <rect x="5" y="6" width="6" height="5" fill="#ffd166"/>
          <rect x="4" y="8" width="8" height="3" fill="#ff8f4c"/>
          <rect x="7" y="2" width="2" height="2" fill="#ffe28a"/>
          <rect x="2" y="5" width="2" height="2" fill="#ffb86b"/>
          <rect x="12" y="5" width="2" height="2" fill="#ffb86b"/>
        </svg>
        <span>Sunset</span>
      </button>
      <button class="time-btn" type="button" data-mode="night" aria-pressed="false">
        <svg viewBox="0 0 16 16" aria-hidden="true">
          <rect x="5" y="2" width="5" height="2" fill="#ffe68c"/>
          <rect x="3" y="4" width="4" height="8" fill="#ffe68c"/>
          <rect x="5" y="12" width="6" height="2" fill="#ffe68c"/>
          <rect x="7" y="10" width="4" height="2" fill="#ffd25a"/>
          <rect x="11" y="3" width="2" height="2" fill="#ffffff"/>
          <rect x="12" y="7" width="2" height="2" fill="#b8d4ff"/>
        </svg>
        <span>Night</span>
      </button>
    </div>
  </div>
</div>

<div id="fallback-msg">
  <div>
    <h2>Cat Island needs WebGL &amp; Three.js</h2>
    <p>Please enable WebGL and allow loading Three.js from jsDelivr.</p>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(function() {
  'use strict';

  if (typeof THREE === 'undefined') {
    document.getElementById('fallback-msg').style.display = 'flex';
    return;
  }

  // =========================================================================
  // 1. DETERMINISTIC HELPERS & MATH
  // =========================================================================
  function mulberry32(seed) {
    let a = seed >>> 0;
    return function() {
      a |= 0;
      a = (a + 0x6D2B79F5) | 0;
      let t = Math.imul(a ^ (a >>> 15), 1 | a);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };
  }
  const rng = mulberry32(20260417);
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
  const lerp = (a, b, t) => a + (b - a) * t;
  const smoothstep = (e0, e1, x) => {
    const t = clamp((x - e0) / (e1 - e0), 0, 1);
    return t * t * (3 - 2 * t);
  };
  const dampFactor = (lambda, dt) => 1 - Math.exp(-lambda * dt);
  function hash2D(x, z) {
    const n = Math.sin(x * 127.1 + z * 311.7) * 43758.5453123;
    return n - Math.floor(n);
  }
  function shortestAngleDiff(current, target) {
    let d = (target - current) % (Math.PI * 2);
    if (d > Math.PI) d -= Math.PI * 2;
    if (d < -Math.PI) d += Math.PI * 2;
    return d;
  }

  // =========================================================================
  // 2. PROCEDURAL PIXEL-ART TEXTURE FACTORY
  // =========================================================================
  function createPixelTexture(size, drawFn, opts) {
    const c = document.createElement('canvas');
    c.width = size;
    c.height = size;
    const ctx = c.getContext('2d');
    ctx.imageSmoothingEnabled = false;
    drawFn(ctx, size);
    const tex = new THREE.CanvasTexture(c);
    tex.magFilter = THREE.NearestFilter;
    tex.minFilter = THREE.NearestFilter;
    tex.generateMipmaps = false;
    tex.encoding = THREE.sRGBEncoding;
    if (opts && opts.repeat) {
      tex.wrapS = THREE.RepeatWrapping;
      tex.wrapT = THREE.RepeatWrapping;
      tex.repeat.set(opts.repeat[0], opts.repeat[1]);
    }
    tex.needsUpdate = true;
    return tex;
  }

  function px(ctx, x, y, w, h, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x, y, w, h);
  }

  // Grass top texture
  const texGrassTop = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#6bc459');
    const shades = ['#5eb84d', '#7ad166', '#56ad46', '#83d96e'];
    for (let y = 0; y < 16; y++) {
      for (let x = 0; x < 16; x++) {
        const h = hash2D(x + 3, y + 7);
        if (h < 0.35) px(ctx, x, y, 1, 1, shades[Math.floor(h * 11.4) % shades.length]);
      }
    }
    px(ctx, 3, 4, 1, 1, '#9be882');
    px(ctx, 11, 10, 1, 1, '#9be882');
  });

  // Grass side overhang texture
  const texGrassSide = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#8b5e3c');
    const dirt = ['#7d5233', '#996a45', '#6e462a'];
    for (let y = 3; y < 16; y++) {
      for (let x = 0; x < 16; x++) {
        const h = hash2D(x * 2 + 11, y * 3 + 5);
        if (h < 0.42) px(ctx, x, y, 1, 1, dirt[Math.floor(h * 7) % dirt.length]);
      }
    }
    const fringe = [4, 5, 4, 3, 5, 6, 4, 3, 4, 5, 4, 6, 5, 3, 4, 5];
    for (let x = 0; x < 16; x++) {
      px(ctx, x, 0, 1, fringe[x], '#68c256');
      px(ctx, x, 0, 1, 2, '#7dd468');
      px(ctx, x, fringe[x] - 1, 1, 1, '#4ea13f');
    }
  });

  // Dirt texture
  const texDirt = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#855838');
    const cols = ['#754b2e', '#946642', '#6b4328', '#a3724b'];
    for (let y = 0; y < 16; y++) {
      for (let x = 0; x < 16; x++) {
        const h = hash2D(x + 19, y + 23);
        if (h < 0.45) px(ctx, x, y, 1, 1, cols[Math.floor(h * 9) % cols.length]);
      }
    }
  });

  // Cliff stone texture
  const texStone = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#7f838f');
    const cols = ['#717582', '#9296a3', '#666a78', '#9fa3b0'];
    for (let y = 0; y < 16; y++) {
      for (let x = 0; x < 16; x++) {
        const h = hash2D(x + 41, y + 13);
        if (h < 0.5) px(ctx, x, y, 1, 1, cols[Math.floor(h * 8) % cols.length]);
      }
    }
    px(ctx, 0, 5, 16, 1, '#646875');
    px(ctx, 0, 11, 16, 1, '#646875');
    px(ctx, 6, 0, 1, 5, '#646875');
    px(ctx, 12, 6, 1, 5, '#646875');
    px(ctx, 4, 12, 1, 4, '#646875');
  });

  const texDeepStone = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#5c6070');
    const cols = ['#4f5363', '#6b7082', '#474b59'];
    for (let y = 0; y < 16; y++) {
      for (let x = 0; x < 16; x++) {
        const h = hash2D(x + 61, y + 31);
        if (h < 0.45) px(ctx, x, y, 1, 1, cols[Math.floor(h * 7) % cols.length]);
      }
    }
  });

  // Cobblestone road texture
  const texCobble = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#a99e8e');
    const stones = [
      [1, 1, 6, 4, '#d9d0c1'], [8, 1, 7, 4, '#cfc5b4'],
      [0, 6, 4, 4, '#cfc5b4'], [5, 6, 6, 4, '#e0d8ca'], [12, 6, 4, 4, '#d2c8b8'],
      [1, 11, 7, 4, '#d5cbb9'], [9, 11, 6, 4, '#dfd7c8']
    ];
    for (const [x, y, w, h, c] of stones) {
      px(ctx, x, y, w, h, c);
      px(ctx, x, y, w, 1, '#ece5d8');
      px(ctx, x, y + h - 1, w, 1, '#bfb4a2');
    }
  });

  // Pond bed texture
  const texPondBed = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#398b96');
    for (let y = 0; y < 16; y++) {
      for (let x = 0; x < 16; x++) {
        const h = hash2D(x + 5, y + 9);
        if (h < 0.3) px(ctx, x, y, 1, 1, '#2f7a85');
        else if (h > 0.8) px(ctx, x, y, 1, 1, '#4ca2ad');
      }
    }
  });

  // Shimmering pixel water texture
  const texWater = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#48c6e0');
    px(ctx, 1, 2, 5, 1, '#84e4f5');
    px(ctx, 9, 5, 4, 1, '#84e4f5');
    px(ctx, 3, 9, 6, 1, '#75dcf0');
    px(ctx, 10, 12, 5, 1, '#84e4f5');
    px(ctx, 2, 14, 3, 1, '#b8f4ff');
    px(ctx, 7, 6, 2, 1, '#b8f4ff');
    px(ctx, 0, 7, 4, 1, '#39b3cf');
    px(ctx, 8, 1, 4, 1, '#39b3cf');
    px(ctx, 6, 13, 4, 1, '#39b3cf');
  }, { repeat: [1, 1] });

  // Wood plank texture
  const texWood = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#b87d4b');
    for (let y = 0; y < 16; y += 4) {
      px(ctx, 0, y, 16, 1, '#c98e59');
      px(ctx, 0, y + 3, 16, 1, '#8f5d34');
    }
    px(ctx, 5, 0, 1, 4, '#8f5d34');
    px(ctx, 11, 4, 1, 4, '#8f5d34');
    px(ctx, 3, 8, 1, 4, '#8f5d34');
    px(ctx, 13, 12, 1, 4, '#8f5d34');
  });

  // Bridge cedar plank texture
  const texBridgeWood = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#c46c43');
    for (let y = 0; y < 16; y += 4) {
      px(ctx, 0, y, 16, 1, '#d97f55');
      px(ctx, 0, y + 3, 16, 1, '#944a2a');
    }
  });

  // Timber & plaster wall texture generator
  function makeWallTexture(base, light, beam) {
    return createPixelTexture(16, (ctx) => {
      px(ctx, 0, 0, 16, 16, base);
      for (let y = 0; y < 16; y++) {
        for (let x = 0; x < 16; x++) {
          if (hash2D(x + 2, y + 8) > 0.72) px(ctx, x, y, 1, 1, light);
        }
      }
      // Corner & horizontal timber beams
      px(ctx, 0, 0, 2, 16, beam);
      px(ctx, 14, 0, 2, 16, beam);
      px(ctx, 0, 0, 16, 2, beam);
      px(ctx, 0, 14, 16, 2, beam);
    });
  }

  // Roof tile texture generator
  function makeRoofTexture(base, dark, light) {
    return createPixelTexture(16, (ctx) => {
      px(ctx, 0, 0, 16, 16, base);
      for (let row = 0; row < 4; row++) {
        const y = row * 4;
        const off = (row % 2) * 2;
        px(ctx, 0, y, 16, 1, light);
        px(ctx, 0, y + 3, 16, 1, dark);
        for (let x = off; x < 16; x += 4) {
          px(ctx, x, y + 1, 1, 3, dark);
        }
      }
    });
  }

  // Striped awning texture generator
  function makeAwningTexture(colA, colB) {
    return createPixelTexture(16, (ctx) => {
      for (let x = 0; x < 16; x++) {
        const stripe = Math.floor(x / 4) % 2 === 0;
        px(ctx, x, 0, 1, 16, stripe ? colA : colB);
        if (x % 4 === 3) {
          ctx.fillStyle = 'rgba(0,0,0,0.12)';
          ctx.fillRect(x, 0, 1, 16);
        }
      }
      ctx.fillStyle = 'rgba(255,255,255,0.16)';
      ctx.fillRect(0, 0, 16, 2);
      ctx.fillStyle = 'rgba(0,0,0,0.16)';
      ctx.fillRect(0, 14, 16, 2);
    });
  }

  // Window textures (albedo & emissive mask)
  const texWindowColor = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#5c3c24'); // frame
    px(ctx, 2, 2, 12, 12, '#82bce0'); // glass
    px(ctx, 3, 3, 3, 3, '#bce6ff');   // glint
    px(ctx, 7, 2, 2, 12, '#5c3c24');  // vertical mullion
    px(ctx, 2, 7, 12, 2, '#5c3c24');  // horizontal mullion
    px(ctx, 0, 14, 16, 2, '#7a5233'); // sill
  });

  const texWindowEmissive = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#000000');
    px(ctx, 2, 2, 5, 5, '#ffd46e');
    px(ctx, 9, 2, 5, 5, '#ffc857');
    px(ctx, 2, 9, 5, 5, '#ffb742');
    px(ctx, 9, 9, 5, 5, '#ffd46e');
    px(ctx, 3, 3, 3, 2, '#fff2b2');
    px(ctx, 10, 10, 3, 2, '#fff2b2');
  });

  // Giant Yarn Ball pixel texture generator
  function makeYarnTexture(main, light, dark) {
    return createPixelTexture(32, (ctx) => {
      px(ctx, 0, 0, 32, 32, main);
      // Criss-crossing wrapped yarn bands
      for (let i = -32; i < 64; i += 4) {
        for (let k = 0; k < 32; k++) {
          const x1 = (i + k) & 31;
          px(ctx, x1, k, 1, 1, dark);
          px(ctx, (x1 + 1) & 31, k, 1, 1, light);
        }
      }
      for (let i = -32; i < 64; i += 6) {
        for (let k = 0; k < 32; k++) {
          const x2 = (i - k + 64) & 31;
          px(ctx, x2, k, 1, 1, main);
          if (k % 2 === 0) px(ctx, (x2 + 1) & 31, k, 1, 1, light);
          px(ctx, (x2 + 2) & 31, k, 1, 1, dark);
        }
      }
    });
  }

  // Hanging Pixel Fish Signboard texture
  const texFishSign = createPixelTexture(16, (ctx) => {
    px(ctx, 0, 0, 16, 16, '#6e4729');
    px(ctx, 1, 1, 14, 14, '#f5e4c3');
    // Pixel fish icon
    px(ctx, 4, 6, 7, 4, '#3d9be9');
    px(ctx, 5, 5, 5, 6, '#3d9be9');
    px(ctx, 6, 6, 4, 2, '#7bc8ff');
    px(ctx, 11, 5, 2, 6, '#2a76ba'); // tail
    px(ctx, 12, 4, 2, 2, '#2a76ba');
    px(ctx, 12, 10, 2, 2, '#2a76ba');
    px(ctx, 5, 7, 1, 1, '#1e1b29');  // eye
  });

  // Pixel foliage texture
  function makeLeavesTexture(base, light, dark, blossom) {
    return createPixelTexture(16, (ctx) => {
      px(ctx, 0, 0, 16, 16, base);
      for (let y = 0; y < 16; y++) {
        for (let x = 0; x < 16; x++) {
          const h = hash2D(x * 3 + 7, y * 5 + 11);
          if (h < 0.28) px(ctx, x, y, 1, 1, dark);
          else if (h > 0.72) px(ctx, x, y, 1, 1, light);
          if (blossom && h > 0.89) px(ctx, x, y, 1, 1, blossom);
        }
      }
    });
  }

  // Pixel Emote Sprites
  const texEmoteZ = createPixelTexture(16, (ctx) => {
    ctx.clearRect(0, 0, 16, 16);
    // Outlined chunky pixel Z
    px(ctx, 3, 2, 10, 12, 'rgba(26, 28, 56, 0.75)');
    px(ctx, 4, 3, 8, 2, '#fff9db');
    px(ctx, 9, 5, 2, 2, '#fff9db');
    px(ctx, 7, 7, 2, 2, '#fff9db');
    px(ctx, 5, 9, 2, 2, '#fff9db');
    px(ctx, 4, 11, 8, 2, '#fff9db');
  });

  const texEmoteFish = createPixelTexture(16, (ctx) => {
    ctx.clearRect(0, 0, 16, 16);
    px(ctx, 1, 2, 14, 11, '#fffdf5');
    px(ctx, 2, 1, 12, 1, '#57483d');
    px(ctx, 2, 13, 12, 1, '#57483d');
    px(ctx, 0, 3, 1, 9, '#57483d');
    px(ctx, 15, 3, 1, 9, '#57483d');
    px(ctx, 6, 14, 3, 2, '#fffdf5');
    // Tiny fish inside bubble
    px(ctx, 3, 6, 6, 4, '#3aa0f2');
    px(ctx, 4, 5, 4, 6, '#3aa0f2');
    px(ctx, 9, 5, 3, 6, '#2375bd');
    px(ctx, 4, 7, 1, 1, '#1a1826');
  });

  const texEmoteHeart = createPixelTexture(16, (ctx) => {
    ctx.clearRect(0, 0, 16, 16);
    const rows = [
      '....11....11....',
      '...1221..1221...',
      '..123221122221..',
      '..123222222221..',
      '..122222222221..',
      '...1222222221...',
      '....12222221....',
      '.....122221.....',
      '......1221......',
      '.......11.......'
    ];
    rows.forEach((r, y) => {
      for (let x = 0; x < r.length; x++) {
        const ch = r[x];
        if (ch === '1') px(ctx, x, y + 3, 1, 1, '#9e1c40');
        else if (ch === '2') px(ctx, x, y + 3, 1, 1, '#ff4d79');
        else if (ch === '3') px(ctx, x, y + 3, 1, 1, '#ffb3c6');
      }
    });
  });

  // Soft radial pixel glow sprite for lanterns & fireflies
  const texGlowHalo = (function() {
    const c = document.createElement('canvas');
    c.width = 32;
    c.height = 32;
    const ctx = c.getContext('2d');
    const g = ctx.createRadialGradient(16, 16, 1, 16, 16, 15);
    g.addColorStop(0, 'rgba(255, 245, 196, 1.0)');
    g.addColorStop(0.35, 'rgba(255, 188, 72, 0.55)');
    g.addColorStop(1, 'rgba(255, 140, 30, 0.0)');
    ctx.fillStyle = g;
    ctx.fillRect(0, 0, 32, 32);
    const t = new THREE.CanvasTexture(c);
    t.encoding = THREE.sRGBEncoding;
    return t;
  })();

  // Cat Coat & Face textures
  function makeCatTextures(spec) {
    const coatTex = createPixelTexture(16, (ctx) => {
      px(ctx, 0, 0, 16, 16, spec.base);
      if (spec.pattern === 'tabby') {
        for (let y = 1; y < 15; y += 3) {
          px(ctx, 0, y, 16, 1, spec.accent);
          px(ctx, 2, y + 1, 5, 1, spec.accent);
          px(ctx, 10, y + 1, 4, 1, spec.accent);
        }
      } else if (spec.pattern === 'calico') {
        px(ctx, 1, 2, 6, 5, spec.accent);
        px(ctx, 9, 8, 6, 6, spec.accent2 || '#2c2735');
        px(ctx, 10, 1, 5, 4, spec.accent);
        px(ctx, 2, 10, 5, 4, spec.accent2 || '#2c2735');
      } else if (spec.pattern === 'tuxedo') {
        px(ctx, 4, 9, 8, 7, spec.accent);
      } else if (spec.pattern === 'spotted') {
        px(ctx, 2, 2, 3, 3, spec.accent);
        px(ctx, 10, 4, 4, 3, spec.accent);
        px(ctx, 5, 9, 4, 4, spec.accent);
        px(ctx, 11, 11, 3, 3, spec.accent);
      } else if (spec.pattern === 'bicolor') {
        px(ctx, 0, 8, 16, 8, spec.accent);
        px(ctx, 4, 6, 8, 3, spec.accent);
      }
    });

    function drawFace(sleeping) {
      return createPixelTexture(16, (ctx) => {
        px(ctx, 0, 0, 16, 16, spec.base);
        if (spec.pattern === 'tabby') {
          // Cute tabby forehead M stripes
          px(ctx, 5, 1, 1, 3, spec.accent);
          px(ctx, 7, 1, 2, 3, spec.accent);
          px(ctx, 10, 1, 1, 3, spec.accent);
          px(ctx, 1, 8, 2, 1, spec.accent);
          px(ctx, 13, 8, 2, 1, spec.accent);
          px(ctx, 4, 10, 8, 5, spec.muzzle || '#ffe8cc');
        } else if (spec.pattern === 'tuxedo' || spec.pattern === 'bicolor') {
          px(ctx, 4, 9, 8, 7, spec.accent);
          px(ctx, 6, 7, 4, 3, spec.accent);
        } else if (spec.pattern === 'calico') {
          px(ctx, 0, 0, 6, 7, spec.accent);
          px(ctx, 10, 0, 6, 6, spec.accent2 || '#2c2735');
        } else if (spec.pattern === 'siamese') {
          px(ctx, 3, 5, 10, 9, spec.accent);
          px(ctx, 4, 4, 8, 10, spec.accent);
        }
        // Eyes
        const eyeCol = spec.eyeColor || '#1c1826';
        if (!sleeping) {
          px(ctx, 3, 6, 3, 3, eyeCol);
          px(ctx, 10, 6, 3, 3, eyeCol);
          // Bright pixel eye glint
          px(ctx, 3, 6, 1, 1, '#ffffff');
          px(ctx, 10, 6, 1, 1, '#ffffff');
          if (spec.iris) {
            px(ctx, 4, 8, 2, 1, spec.iris);
            px(ctx, 11, 8, 2, 1, spec.iris);
          }
        } else {
          // Peaceful curved sleeping eyes
          px(ctx, 3, 8, 3, 1, eyeCol);
          px(ctx, 4, 9, 1, 1, eyeCol);
          px(ctx, 10, 8, 3, 1, eyeCol);
          px(ctx, 11, 9, 1, 1, eyeCol);
        }
        // Rosy cheeks
        px(ctx, 2, 10, 2, 1, 'rgba(255, 128, 152, 0.55)');
        px(ctx, 12, 10, 2, 1, 'rgba(255, 128, 152, 0.55)');
        // Pink nose + cute :3 mouth
        px(ctx, 7, 10, 2, 2, spec.nose || '#ff85a1');
        px(ctx, 6, 12, 1, 1, '#4a3538');
        px(ctx, 7, 13, 2, 1, '#4a3538');
        px(ctx, 9, 12, 1, 1, '#4a3538');
      });
    }

    return {
      coat: coatTex,
      faceAwake: drawFace(false),
      faceSleep: drawFace(true)
    };
  }

  // =========================================================================
  // 3. RENDERER, SCENE, CAMERA, SKY DOME & LIGHTING SYSTEM
  // =========================================================================
  const wrap = document.getElementById('canvas-wrap');
  const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.06;
  wrap.appendChild(renderer.domElement);

  const scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0xb2e3ff, 0.0085);

  const camera = new THREE.PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.25, 180);

  // Sky Dome (custom gradient shader)
  const skyUniforms = {
    uTopColor: { value: new THREE.Color('#47a0f5') },
    uHorizonColor: { value: new THREE.Color('#b6e6ff') },
    uBottomColor: { value: new THREE.Color('#ddf5ff') }
  };
  const skyDome = new THREE.Mesh(
    new THREE.SphereGeometry(96, 24, 16),
    new THREE.ShaderMaterial({
      uniforms: skyUniforms,
      side: THREE.BackSide,
      depthWrite: false,
      fog: false,
      vertexShader: [
        'varying vec3 vWorldPos;',
        'void main() {',
        '  vec4 wp = modelMatrix * vec4(position, 1.0);',
        '  vWorldPos = wp.xyz;',
        '  gl_Position = projectionMatrix * viewMatrix * wp;',
        '}'
      ].join('\n'),
      fragmentShader: [
        'uniform vec3 uTopColor;',
        'uniform vec3 uHorizonColor;',
        'uniform vec3 uBottomColor;',
        'varying vec3 vWorldPos;',
        'void main() {',
        '  float h = normalize(vWorldPos).y;',
        '  vec3 col = (h >= 0.0)',
        '    ? mix(uHorizonColor, uTopColor, pow(clamp(h, 0.0, 1.0), 0.65))',
        '    : mix(uHorizonColor, uBottomColor, pow(clamp(-h, 0.0, 1.0), 0.72));',
        '  gl_FragColor = vec4(col, 1.0);',
        '}'
      ].join('\n')
    })
  );
  scene.add(skyDome);

  // Twinkling chunky pixel stars (visible at sunset & night)
  const starGroup = new THREE.Group();
  const starMat = new THREE.MeshBasicMaterial({ color: 0xfff8dc, transparent: true, opacity: 0, fog: false });
  const starGeo = new THREE.BoxGeometry(0.45, 0.45, 0.45);
  const starTwinkleData = [];
  for (let i = 0; i < 140; i++) {
    const theta = rng() * Math.PI * 2;
    const phi = 0.12 + rng() * 1.15;
    const rad = 76 + rng() * 10;
    const sx = rad * Math.sin(phi) * Math.cos(theta);
    const sy = rad * Math.cos(phi) + 4;
    const sz = rad * Math.sin(phi) * Math.sin(theta);
    const m = new THREE.Mesh(starGeo, starMat);
    m.position.set(sx, sy, sz);
    const sc = 0.6 + rng() * 1.1;
    m.scale.setScalar(sc);
    starGroup.add(m);
    starTwinkleData.push({ mesh: m, base: sc, phase: rng() * Math.PI * 2, speed: 1.5 + rng() * 2.5 });
  }
  scene.add(starGroup);

  // Chunky pixel Sun & Moon in the sky
  const sunMesh = new THREE.Mesh(
    new THREE.BoxGeometry(5.2, 5.2, 5.2),
    new THREE.MeshBasicMaterial({ color: 0xfff3a6, fog: false })
  );
  scene.add(sunMesh);

  const moonGroup = new THREE.Group();
  const moonMat = new THREE.MeshBasicMaterial({ color: 0xfff2bf, transparent: true, opacity: 0, fog: false });
  const moonMain = new THREE.Mesh(new THREE.BoxGeometry(4.0, 4.0, 4.0), moonMat);
  moonGroup.add(moonMain);
  const moonHalo = new THREE.Sprite(new THREE.SpriteMaterial({
    map: texGlowHalo,
    color: 0xb8d4ff,
    transparent: true,
    opacity: 0,
    blending: THREE.AdditiveBlending,
    depthWrite: false,
    fog: false
  }));
  moonHalo.scale.set(14, 14, 1);
  moonGroup.add(moonHalo);
  scene.add(moonGroup);

  // Main Lights
  const hemiLight = new THREE.HemisphereLight(0xa3dcff, 0x629e52, 0.82);
  scene.add(hemiLight);

  const dirLight = new THREE.DirectionalLight(0xfff7e2, 1.32);
  dirLight.position.set(14, 21, 11);
  dirLight.castShadow = true;
  dirLight.shadow.mapSize.width = 2048;
  dirLight.shadow.mapSize.height = 2048;
  dirLight.shadow.camera.near = 2;
  dirLight.shadow.camera.far = 58;
  const sBound = 11.5;
  dirLight.shadow.camera.left = -sBound;
  dirLight.shadow.camera.right = sBound;
  dirLight.shadow.camera.top = sBound;
  dirLight.shadow.camera.bottom = -sBound;
  dirLight.shadow.bias = -0.0005;
  dirLight.shadow.normalBias = 0.04;
  scene.add(dirLight);

  // Root group for the floating island (gently bobs!)
  const islandRoot = new THREE.Group();
  scene.add(islandRoot);

  // Track glowing night materials & lights
  const glowingWindowMats = [];
  const glowingLanternMats = [];
  const lanternHaloSprites = [];
  const warmNightLights = [];

  function addWarmNightLight(x, y, z) {
    const pl = new THREE.PointLight(0xff9f3d, 0.0, 8.2, 1.85);
    pl.position.set(x, y, z);
    islandRoot.add(pl);
    warmNightLights.push(pl);
    return pl;
  }

  // Time-of-Day Presets
  const TIME_PRESETS = {
    day: {
      skyTop: new THREE.Color('#429bf5'),
      skyHorizon: new THREE.Color('#b4e6ff'),
      skyBottom: new THREE.Color('#dcf5ff'),
      fogColor: new THREE.Color('#b4e6ff'),
      fogDensity: 0.0078,
      dirColor: new THREE.Color('#fff8e6'),
      dirIntensity: 1.34,
      dirPos: new THREE.Vector3(14, 21, 11),
      hemiSky: new THREE.Color('#a4dcff'),
      hemiGround: new THREE.Color('#649c54'),
      hemiIntensity: 0.84,
      windowEmissive: 0.06,
      windowTint: new THREE.Color('#b0dff5'),
      lanternEmissive: 0.14,
      haloOpacity: 0.0,
      pointIntensity: 0.0,
      cloudColor: new THREE.Color('#ffffff'),
      waterColor: new THREE.Color('#47c8e3'),
      starOpacity: 0.0,
      moonOpacity: 0.0,
      sunColor: new THREE.Color('#fff6b0'),
      sunScale: 1.0,
      fireflyOpacity: 0.0,
      exposure: 1.06
    },
    sunset: {
      skyTop: new THREE.Color('#3b3275'),
      skyHorizon: new THREE.Color('#ff8052'),
      skyBottom: new THREE.Color('#ffb86e'),
      fogColor: new THREE.Color('#ee8d66'),
      fogDensity: 0.0092,
      dirColor: new THREE.Color('#ff9247'),
      dirIntensity: 1.44,
      dirPos: new THREE.Vector3(18, 7.2, -12),
      hemiSky: new THREE.Color('#ffa270'),
      hemiGround: new THREE.Color('#513457'),
      hemiIntensity: 0.64,
      windowEmissive: 0.92,
      windowTint: new THREE.Color('#ffd382'),
      lanternEmissive: 1.35,
      haloOpacity: 0.45,
      pointIntensity: 0.62,
      cloudColor: new THREE.Color('#ffc4a6'),
      waterColor: new THREE.Color('#5a86a8'),
      starOpacity: 0.28,
      moonOpacity: 0.12,
      sunColor: new THREE.Color('#ff9447'),
      sunScale: 1.45,
      fireflyOpacity: 0.35,
      exposure: 1.02
    },
    night: {
      skyTop: new THREE.Color('#09102b'),
      skyHorizon: new THREE.Color('#162854'),
      skyBottom: new THREE.Color('#0d1736'),
      fogColor: new THREE.Color('#132247'),
      fogDensity: 0.0096,
      dirColor: new THREE.Color('#8eb4ff'),
      dirIntensity: 0.50,
      dirPos: new THREE.Vector3(-13, 17, 13),
      hemiSky: new THREE.Color('#2c4782'),
      hemiGround: new THREE.Color('#141c36'),
      hemiIntensity: 0.44,
      windowEmissive: 2.15,
      windowTint: new THREE.Color('#ffcf6e'),
      lanternEmissive: 2.55,
      haloOpacity: 0.90,
      pointIntensity: 1.48,
      cloudColor: new THREE.Color('#3c5280'),
      waterColor: new THREE.Color('#1d4469'),
      starOpacity: 0.95,
      moonOpacity: 1.0,
      sunColor: new THREE.Color('#ff6633'),
      sunScale: 0.01,
      fireflyOpacity: 1.0,
      exposure: 1.08
    }
  };

  let currentTimeMode = 'day';
  // Live interpolated environment state
  const envState = {
    skyTop: TIME_PRESETS.day.skyTop.clone(),
    skyHorizon: TIME_PRESETS.day.skyHorizon.clone(),
    skyBottom: TIME_PRESETS.day.skyBottom.clone(),
    fogColor: TIME_PRESETS.day.fogColor.clone(),
    fogDensity: TIME_PRESETS.day.fogDensity,
    dirColor: TIME_PRESETS.day.dirColor.clone(),
    dirIntensity: TIME_PRESETS.day.dirIntensity,
    dirPos: TIME_PRESETS.day.dirPos.clone(),
    hemiSky: TIME_PRESETS.day.hemiSky.clone(),
    hemiGround: TIME_PRESETS.day.hemiGround.clone(),
    hemiIntensity: TIME_PRESETS.day.hemiIntensity,
    windowEmissive: TIME_PRESETS.day.windowEmissive,
    windowTint: TIME_PRESETS.day.windowTint.clone(),
    lanternEmissive: TIME_PRESETS.day.lanternEmissive,
    haloOpacity: TIME_PRESETS.day.haloOpacity,
    pointIntensity: TIME_PRESETS.day.pointIntensity,
    cloudColor: TIME_PRESETS.day.cloudColor.clone(),
    waterColor: TIME_PRESETS.day.waterColor.clone(),
    starOpacity: TIME_PRESETS.day.starOpacity,
    moonOpacity: TIME_PRESETS.day.moonOpacity,
    sunColor: TIME_PRESETS.day.sunColor.clone(),
    sunScale: TIME_PRESETS.day.sunScale,
    fireflyOpacity: TIME_PRESETS.day.fireflyOpacity,
    exposure: TIME_PRESETS.day.exposure
  };

  // =========================================================================
  // 4. FLOATING ISLAND VOXEL TERRAIN, POND, WATERFALL & SATELLITES
  // =========================================================================
  const POND_CELLS = new Set([
    '2,1', '3,1',
    '1,2', '2,2', '3,2', '4,2',
    '1,3', '2,3', '3,3', '4,3',
    '2,4', '3,4', '4,4',
    '3,5', '4,5',
    '4,6'
  ]);
  const isPondCell = (gx, gz) => POND_CELLS.has(gx + ',' + gz);

  function isIslandCell(gx, gz) {
    if (isPondCell(gx, gz)) return true;
    const r = Math.hypot(gx * 0.96, gz * 0.98);
    const bump = (hash2D(gx * 0.7 + 13, gz * 0.7 + 29) - 0.5) * 0.85;
    return r <= 7.32 + bump;
  }

  function isCobbleCell(gx, gz) {
    if (isPondCell(gx, gz)) return false;
    // Main Town Square & Fish Market plaza
    if (gx >= -4 && gx <= 0 && gz >= -2 && gz <= 1) return true;
    // Town Hall & Cottage 3 front lane
    if (gx >= -3 && gx <= 1 && gz === -3) return true;
    // South lane & bridge approach
    if (gx >= -2 && gx <= 0 && gz === 2) return true;
    if (gx >= -1 && gx <= 0 && gz === 3) return true;
    if (gx === -1 && gz === 4) return true;
    return false;
  }

  // Materials for terrain
  const matGrassTop = new THREE.MeshStandardMaterial({ map: texGrassTop, roughness: 0.92, metalness: 0.0 });
  const matGrassSide = new THREE.MeshStandardMaterial({ map: texGrassSide, roughness: 0.92, metalness: 0.0 });
  const matDirt = new THREE.MeshStandardMaterial({ map: texDirt, roughness: 0.95, metalness: 0.0 });
  const matCobble = new THREE.MeshStandardMaterial({ map: texCobble, roughness: 0.88, metalness: 0.0 });
  const matStone = new THREE.MeshStandardMaterial({ map: texStone, roughness: 0.94, metalness: 0.0 });
  const matDeepStone = new THREE.MeshStandardMaterial({ map: texDeepStone, roughness: 0.95, metalness: 0.0 });
  const matPondBed = new THREE.MeshStandardMaterial({ map: texPondBed, roughness: 0.9, metalness: 0.0 });
  const matWater = new THREE.MeshStandardMaterial({
    map: texWater,
    color: 0x47c8e3,
    roughness: 0.22,
    metalness: 0.08,
    transparent: true,
    opacity: 0.78,
    depthWrite: false
  });
  const matWood = new THREE.MeshStandardMaterial({ map: texWood, roughness: 0.88, metalness: 0.0 });
  const matDarkWood = new THREE.MeshStandardMaterial({ color: 0x6b4428, roughness: 0.9 });

  // Collect voxel coordinates per material type for InstancedMesh
  const grassPositions = [];
  const cobblePositions = [];
  const dirtPositions = [];
  const stonePositions = [];
  const deepStonePositions = [];
  const pondBedPositions = [];
  const rimEdgeCells = [];

  for (let gx = -8; gx <= 8; gx++) {
    for (let gz = -8; gz <= 8; gz++) {
      if (!isIslandCell(gx, gz)) continue;
      const pond = isPondCell(gx, gz);
      const cobble = isCobbleCell(gx, gz);

      if (pond) {
        pondBedPositions.push([gx, -0.95, gz]);
      } else if (cobble) {
        cobblePositions.push([gx, -0.25, gz]);
      } else {
        grassPositions.push([gx, -0.25, gz]);
      }

      // Track outer edge cells for hanging vines
      const isEdge = !isIslandCell(gx + 1, gz) || !isIslandCell(gx - 1, gz) ||
                     !isIslandCell(gx, gz + 1) || !isIslandCell(gx, gz - 1);
      if (isEdge && !pond) rimEdgeCells.push([gx, gz]);

      // Tapered chunky rocky underside
      const dist = Math.hypot(gx, gz);
      const rockNoise = hash2D(gx + 53, gz + 71);
      const depth = Math.max(
        1,
        Math.round(5.4 - dist * 0.62 + (rockNoise - 0.35) * 2.1)
      );

      const startLayer = pond ? 1 : 0;
      for (let d = startLayer; d < depth; d++) {
        const y = -0.875 - d * 0.75;
        if (d === 0) {
          dirtPositions.push([gx, y, gz]);
        } else if (d <= depth - 2 && d < 3) {
          stonePositions.push([gx, y, gz]);
        } else {
          deepStonePositions.push([gx, y, gz]);
        }
      }
    }
  }

  // Helper to build InstancedMesh
  const dummy = new THREE.Object3D();
  function buildInstances(geo, mat, positions, cast, receive) {
    if (!positions.length) return null;
    const im = new THREE.InstancedMesh(geo, mat, positions.length);
    for (let i = 0; i < positions.length; i++) {
      dummy.position.set(positions[i][0], positions[i][1], positions[i][2]);
      dummy.rotation.set(0, 0, 0);
      dummy.scale.set(1, 1, 1);
      dummy.updateMatrix();
      im.setMatrixAt(i, dummy.matrix);
    }
    im.instanceMatrix.needsUpdate = true;
    im.castShadow = !!cast;
    im.receiveShadow = !!receive;
    islandRoot.add(im);
    return im;
  }

  const topSlabGeo = new THREE.BoxGeometry(1.0, 0.5, 1.0);
  const underBlockGeo = new THREE.BoxGeometry(1.0, 0.75, 1.0);
  const pondBedGeo = new THREE.BoxGeometry(1.0, 0.45, 1.0);

  buildInstances(
    topSlabGeo,
    [matGrassSide, matGrassSide, matGrassTop, matDirt, matGrassSide, matGrassSide],
    grassPositions, true, true
  );
  buildInstances(
    topSlabGeo,
    [matDirt, matDirt, matCobble, matDirt, matDirt, matDirt],
    cobblePositions, true, true
  );
  buildInstances(pondBedGeo, matPondBed, pondBedPositions, false, true);
  buildInstances(underBlockGeo, matDirt, dirtPositions, true, true);
  buildInstances(underBlockGeo, matStone, stonePositions, true, true);
  buildInstances(underBlockGeo, matDeepStone, deepStonePositions, true, false);

  // Hanging chunky pixel vines along cliff edges
  const matVine = new THREE.MeshStandardMaterial({ color: 0x4ca647, roughness: 0.9 });
  const vineBlockGeo = new THREE.BoxGeometry(0.18, 0.24, 0.18);
  rimEdgeCells.forEach(([gx, gz]) => {
    if (hash2D(gx * 5 + 3, gz * 7 + 19) > 0.36) return;
    const len = 3 + Math.floor(hash2D(gx + 2, gz + 91) * 5);
    // Find outward direction
    const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
    for (const [dx, dz] of dirs) {
      if (!isIslandCell(gx + dx, gz + dz)) {
        for (let k = 0; k < len; k++) {
          const v = new THREE.Mesh(vineBlockGeo, matVine);
          v.position.set(
            gx + dx * 0.52 + (k % 2 ? 0.04 : -0.04) * dz,
            -0.35 - k * 0.23,
            gz + dz * 0.52 + (k % 2 ? 0.04 : -0.04) * dx
          );
          islandRoot.add(v);
        }
        break;
      }
    }
  });

  // Pond Water Surface + Stone Coping Rim
  const pondWaterGroup = new THREE.Group();
  const waterTileGeo = new THREE.PlaneGeometry(1.0, 1.0);
  waterTileGeo.rotateX(-Math.PI / 2);
  POND_CELLS.forEach((key) => {
    const [gx, gz] = key.split(',').map(Number);
    const tile = new THREE.Mesh(waterTileGeo, matWater);
    tile.position.set(gx, -0.20, gz);
    tile.receiveShadow = true;
    pondWaterGroup.add(tile);
  });
  islandRoot.add(pondWaterGroup);

  // Pond stone bank pebbles, lily pads & reeds
  const matLily = new THREE.MeshStandardMaterial({ color: 0x47b54a, roughness: 0.85 });
  const matLotus = new THREE.MeshStandardMaterial({ color: 0xff9ec4, roughness: 0.7 });
  const matReed = new THREE.MeshStandardMaterial({ color: 0x48913f, roughness: 0.9 });
  const matCattail = new THREE.MeshStandardMaterial({ color: 0x6b3e24, roughness: 0.9 });

  const lilyPositions = [
    [1.6, 3.2, true], [3.5, 3.5, false], [2.4, 0.95, true],
    [3.8, 4.6, false], [2.4, 4.1, false], [3.6, 1.15, false]
  ];
  const lilyPads = [];
  lilyPositions.forEach(([lx, lz, hasFlower], idx) => {
    const g = new THREE.Group();
    const pad = new THREE.Mesh(new THREE.BoxGeometry(0.46, 0.05, 0.46), matLily);
    g.add(pad);
    // Cute pixel notch accent
    const rim = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.06, 0.32), new THREE.MeshStandardMaterial({ color: 0x5cc957, roughness: 0.85 }));
    rim.position.y = 0.01;
    g.add(rim);
    if (hasFlower) {
      const f = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.12, 0.16), matLotus);
      f.position.y = 0.08;
      g.add(f);
      const fc = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.14, 0.08), new THREE.MeshStandardMaterial({ color: 0xffe46b, roughness: 0.8 }));
      fc.position.y = 0.09;
      g.add(fc);
    }
    g.position.set(lx, -0.18, lz);
    g.rotation.y = idx * 1.1;
    islandRoot.add(g);
    lilyPads.push({ group: g, baseY: -0.18, phase: idx * 1.3 });
  });

  // Reeds & cattails along pond edges
  const reedSpots = [[0.72, 3.4], [0.85, 3.65], [4.35, 3.6], [4.45, 3.85], [1.65, 0.72], [3.4, 5.25], [2.65, 5.15]];
  reedSpots.forEach(([rx, rz], i) => {
    const h = 0.45 + (i % 3) * 0.16;
    const stem = new THREE.Mesh(new THREE.BoxGeometry(0.07, h, 0.07), matReed);
    stem.position.set(rx, -0.12 + h / 2, rz);
    islandRoot.add(stem);
    if (i % 2 === 0) {
      const top = new THREE.Mesh(new THREE.BoxGeometry(0.11, 0.18, 0.11), matCattail);
      top.position.set(rx, -0.12 + h - 0.04, rz);
      islandRoot.add(top);
    }
  });

  // Swimming Koi Fish beneath pond surface
  const koiList = [];
  const koiSpecs = [
    { cx: 2.5, cz: 3.1, rx: 0.95, rz: 0.55, speed: 0.65, phase: 0.0, col: 0xff6b2b, fin: 0xffffff },
    { cx: 3.1, cz: 2.8, rx: 0.75, rz: 0.85, speed: -0.52, phase: 2.2, col: 0xffca3a, fin: 0xff8c42 },
    { cx: 3.4, cz: 4.3, rx: 0.55, rz: 0.45, speed: 0.72, phase: 4.1, col: 0xfff5e6, fin: 0xe63946 }
  ];
  koiSpecs.forEach((ks) => {
    const kg = new THREE.Group();
    const kBody = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.10, 0.28), new THREE.MeshStandardMaterial({ color: ks.col, roughness: 0.5 }));
    kg.add(kBody);
    const kTail = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.10, 0.14), new THREE.MeshStandardMaterial({ color: ks.fin, roughness: 0.5 }));
    kTail.position.z = -0.19;
    kg.add(kTail);
    kg.position.set(ks.cx, -0.48, ks.cz);
    islandRoot.add(kg);
    koiList.push({ group: kg, tail: kTail, spec: ks });
  });

  // Pixel Waterfall spilling off SE pond edge at (4, 6.5)
  const waterfallDrops = [];
  const matFall = new THREE.MeshStandardMaterial({
    color: 0x70dcf5,
    emissive: 0x164a66,
    emissiveIntensity: 0.25,
    transparent: true,
    opacity: 0.82,
    roughness: 0.2
  });
  const matFoam = new THREE.MeshStandardMaterial({ color: 0xeafaff, transparent: true, opacity: 0.85, roughness: 0.5 });
  // Main ribbon column
  const fallRibbon = new THREE.Mesh(new THREE.BoxGeometry(0.66, 5.2, 0.22), matFall);
  fallRibbon.position.set(4.0, -2.8, 6.56);
  islandRoot.add(fallRibbon);
  // Falling animated voxel droplets & mist
  const dropGeo = new THREE.BoxGeometry(0.24, 0.34, 0.24);
  for (let i = 0; i < 14; i++) {
    const d = new THREE.Mesh(dropGeo, i % 3 === 0 ? matFoam : matFall);
    islandRoot.add(d);
    waterfallDrops.push({
      mesh: d,
      offsetX: (rng() - 0.5) * 0.52,
      t: i / 14,
      speed: 0.42 + rng() * 0.22
    });
  }

  // Tiny Floating Satellite Mini-Islets bobbing near the underside
  const satellites = [];
  const satConfigs = [
    { x: -8.9, y: -2.2, z: 4.5, s: 1.05, phase: 0.4 },
    { x: 9.2, y: -1.8, z: -4.2, s: 0.95, phase: 1.9 },
    { x: 7.4, y: -3.2, z: 6.2, s: 0.82, phase: 3.5 },
    { x: -6.8, y: -2.9, z: -7.1, s: 0.9, phase: 5.0 }
  ];
  satConfigs.forEach((sc) => {
    const sg = new THREE.Group();
    const top = new THREE.Mesh(
      new THREE.BoxGeometry(1.15, 0.42, 1.15),
      [matGrassSide, matGrassSide, matGrassTop, matDirt, matGrassSide, matGrassSide]
    );
    top.castShadow = true;
    top.receiveShadow = true;
    sg.add(top);
    const bot = new THREE.Mesh(new THREE.BoxGeometry(0.86, 0.65, 0.86), matStone);
    bot.position.y = -0.52;
    bot.castShadow = true;
    sg.add(bot);
    const tip = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.45, 0.45), matDeepStone);
    tip.position.y = -1.0;
    sg.add(tip);
    sg.position.set(sc.x, sc.y, sc.z);
    sg.scale.setScalar(sc.s);
    sg.rotation.y = sc.phase;
    scene.add(sg);
    satellites.push({ group: sg, baseY: sc.y, phase: sc.phase });
  });

  // =========================================================================
  // 5. TOWN LANDMARKS: COTTAGES, FISH MARKET, YARN PARK, BRIDGE & DETAILS
  // =========================================================================
  // Shared helper to make a glowing lantern unit
  function createLantern(x, y, z, colorHex, withPost, postHeight) {
    const g = new THREE.Group();
    g.position.set(x, y, z);
    if (withPost) {
      const post = new THREE.Mesh(new THREE.BoxGeometry(0.14, postHeight, 0.14), matDarkWood);
      post.position.y = postHeight / 2;
      post.castShadow = true;
      g.add(post);
      const arm = new THREE.Mesh(new THREE.BoxGeometry(0.36, 0.10, 0.10), matDarkWood);
      arm.position.set(0.14, postHeight - 0.06, 0);
      g.add(arm);
    }
    const lx = withPost ? 0.28 : 0;
    const ly = withPost ? postHeight - 0.22 : 0;

    const cap = new THREE.Mesh(new THREE.BoxGeometry(0.24, 0.07, 0.24), matDarkWood);
    cap.position.set(lx, ly + 0.14, 0);
    g.add(cap);

    const bulbMat = new THREE.MeshStandardMaterial({
      color: colorHex || 0xffe49e,
      emissive: new THREE.Color(colorHex || 0xffa630),
      emissiveIntensity: 0.14,
      roughness: 0.35
    });
    glowingLanternMats.push(bulbMat);
    const bulb = new THREE.Mesh(new THREE.BoxGeometry(0.18, 0.22, 0.18), bulbMat);
    bulb.position.set(lx, ly, 0);
    g.add(bulb);

    const base = new THREE.Mesh(new THREE.BoxGeometry(0.20, 0.06, 0.20), matDarkWood);
    base.position.set(lx, ly - 0.13, 0);
    g.add(base);

    const haloMat = new THREE.SpriteMaterial({
      map: texGlowHalo,
      color: colorHex || 0xffb347,
      transparent: true,
      opacity: 0.0,
      blending: THREE.AdditiveBlending,
      depthWrite: false
    });
    const halo = new THREE.Sprite(haloMat);
    halo.position.set(lx, ly, 0);
    halo.scale.set(1.35, 1.35, 1);
    g.add(halo);
    lanternHaloSprites.push(haloMat);

    islandRoot.add(g);
    return g;
  }

  // Helper to create a glowing paned window mesh
  function makeWindowMesh(w, h) {
    const mat = new THREE.MeshStandardMaterial({
      map: texWindowColor,
      emissive: new THREE.Color(0xffbd4a),
      emissiveMap: texWindowEmissive,
      emissiveIntensity: 0.06,
      roughness: 0.4
    });
    glowingWindowMats.push(mat);
    return new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.08), mat);
  }

  // Chimney smoke emitter list
  const chimneyEmitters = [];
  // Rooftop nap decks returned by cottages
  const rooftopDecks = [];

  function buildCottage(opts) {
    const g = new THREE.Group();
    g.position.set(opts.x, 0, opts.z);
    g.rotation.y = opts.rotY || 0;

    const W = opts.w, D = opts.d, H = opts.h;
    const wallMat = new THREE.MeshStandardMaterial({
      map: makeWallTexture(opts.wallColor, opts.wallLight, opts.beamColor || '#6b472b'),
      roughness: 0.9
    });
    const roofMat = new THREE.MeshStandardMaterial({
      map: makeRoofTexture(opts.roofColor, opts.roofDark, opts.roofLight),
      roughness: 0.85
    });

    // Stone plinth foundation
    const plinth = new THREE.Mesh(new THREE.BoxGeometry(W + 0.16, 0.26, D + 0.16), matStone);
    plinth.position.y = 0.13;
    plinth.castShadow = true;
    plinth.receiveShadow = true;
    g.add(plinth);

    // Main walls
    const walls = new THREE.Mesh(new THREE.BoxGeometry(W, H, D), wallMat);
    walls.position.y = 0.24 + H / 2;
    walls.castShadow = true;
    walls.receiveShadow = true;
    g.add(walls);

    // Front door (+Z face)
    const door = new THREE.Mesh(new THREE.BoxGeometry(0.56, 0.95, 0.10), matWood);
    door.position.set(opts.doorX || 0, 0.24 + 0.475, D / 2 + 0.03);
    g.add(door);
    const knob = new THREE.Mesh(new THREE.BoxGeometry(0.07, 0.07, 0.08), new THREE.MeshStandardMaterial({ color: 0xffd24a, roughness: 0.4 }));
    knob.position.set((opts.doorX || 0) + 0.18, 0.24 + 0.46, D / 2 + 0.08);
    g.add(knob);
    // Door step
    const step = new THREE.Mesh(new THREE.BoxGeometry(0.76, 0.12, 0.32), matStone);
    step.position.set(opts.doorX || 0, 0.06, D / 2 + 0.18);
    step.receiveShadow = true;
    g.add(step);

    // Glowing paned windows on front, sides, and back
    const winY = 0.24 + H * 0.56;
    const winXOff = W * 0.31;
    if (opts.frontWindows !== 1) {
      const wL = makeWindowMesh(0.56, 0.56);
      wL.position.set(-winXOff, winY, D / 2 + 0.03);
      g.add(wL);
      const wR = makeWindowMesh(0.56, 0.56);
      wR.position.set(winXOff, winY, D / 2 + 0.03);
      g.add(wR);
    } else {
      const wF = makeWindowMesh(0.68, 0.58);
      wF.position.set(0.45, winY, D / 2 + 0.03);
      g.add(wF);
    }
    // Side windows
    const wSideL = makeWindowMesh(0.54, 0.54);
    wSideL.rotation.y = Math.PI / 2;
    wSideL.position.set(W / 2 + 0.03, winY, 0);
    g.add(wSideL);

    const wSideR = makeWindowMesh(0.54, 0.54);
    wSideR.rotation.y = -Math.PI / 2;
    wSideR.position.set(-W / 2 - 0.03, winY, 0);
    g.add(wSideR);

    // Back window
    const wBack = makeWindowMesh(0.56, 0.54);
    wBack.position.set(0, winY, -D / 2 - 0.03);
    g.add(wBack);

    // Flower box under front window
    const flowerBox = new THREE.Mesh(new THREE.BoxGeometry(0.64, 0.14, 0.18), matDarkWood);
    flowerBox.position.set(opts.frontWindows === 1 ? 0.45 : winXOff, winY - 0.34, D / 2 + 0.11);
    g.add(flowerBox);
    const petalCols = [0xff6b8b, 0xffe066, 0xffffff];
    for (let f = -1; f <= 1; f++) {
      const fl = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.12), new THREE.MeshStandardMaterial({ color: petalCols[f + 1], roughness: 0.8 }));
      fl.position.set((opts.frontWindows === 1 ? 0.45 : winXOff) + f * 0.18, winY - 0.22, D / 2 + 0.11);
      g.add(fl);
    }

    // Chunky Stepped Pixel-Art Hipped Roof with Flat Sunlit Top Nap Deck!
    const roofBaseY = 0.24 + H;
    const tiers = 3;
    const tierH = 0.26;
    let topW = W + 0.44;
    let topD = D + 0.44;
    for (let t = 0; t < tiers; t++) {
      const tw = (W + 0.44) - t * 0.54;
      const td = (D + 0.44) - t * 0.50;
      const tier = new THREE.Mesh(new THREE.BoxGeometry(tw, tierH, td), roofMat);
      tier.position.y = roofBaseY + tierH / 2 + t * tierH;
      tier.castShadow = true;
      tier.receiveShadow = true;
      g.add(tier);
      topW = tw;
      topD = td;
    }
    const roofTopY = roofBaseY + tiers * tierH;

    // Cute pixel chimney at one corner of the roof
    const chimX = -topW * 0.34;
    const chimZ = -topD * 0.22;
    const chim = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.85, 0.42), new THREE.MeshStandardMaterial({ color: 0x9e5446, roughness: 0.9 }));
    chim.position.set(chimX, roofTopY + 0.24, chimZ);
    chim.castShadow = true;
    g.add(chim);
    const chimRim = new THREE.Mesh(new THREE.BoxGeometry(0.52, 0.12, 0.52), matStone);
    chimRim.position.set(chimX, roofTopY + 0.68, chimZ);
    g.add(chimRim);

    // Record world chimney smoke position
    const cosR = Math.cos(opts.rotY || 0);
    const sinR = Math.sin(opts.rotY || 0);
    chimneyEmitters.push({
      x: opts.x + chimX * cosR + chimZ * sinR,
      y: roofTopY + 0.80,
      z: opts.z - chimX * sinR + chimZ * cosR
    });

    // Optional cute Town Hall gable bell / Mayor's cat crest
    if (opts.isTownHall) {
      const crest = new THREE.Mesh(new THREE.BoxGeometry(0.74, 0.52, 0.28), wallMat);
      crest.position.set(0, roofTopY + 0.18, topD / 2 - 0.14);
      crest.castShadow = true;
      g.add(crest);
      const clock = new THREE.Mesh(new THREE.BoxGeometry(0.38, 0.38, 0.08), new THREE.MeshStandardMaterial({
        color: 0xfff4d4, emissive: 0xffd26a, emissiveIntensity: 0.35, roughness: 0.5
      }));
      glowingWindowMats.push(clock.material);
      clock.position.set(0, roofTopY + 0.20, topD / 2 + 0.02);
      g.add(clock);
      // Cat ears on Town Hall roof crest!
      const earL = new THREE.Mesh(new THREE.BoxGeometry(0.18, 0.18, 0.24), roofMat);
      earL.position.set(-0.24, roofTopY + 0.50, topD / 2 - 0.14);
      g.add(earL);
      const earR = earL.clone();
      earR.position.x = 0.24;
      g.add(earR);
    }

    // Optional striped shopfront awning (for SW Bakery / Fish Café)
    if (opts.awningColors) {
      const awnMat = new THREE.MeshStandardMaterial({
        map: makeAwningTexture(opts.awningColors[0], opts.awningColors[1]),
        roughness: 0.82
      });
      const awn = new THREE.Mesh(new THREE.BoxGeometry(W - 0.2, 0.14, 0.88), awnMat);
      awn.position.set(0, 1.56, D / 2 + 0.40);
      awn.rotation.x = 0.28;
      awn.castShadow = true;
      g.add(awn);
      // Scalloped front fringe
      const fringe = new THREE.Mesh(new THREE.BoxGeometry(W - 0.2, 0.18, 0.08), awnMat);
      fringe.position.set(0, 1.38, D / 2 + 0.80);
      g.add(fringe);
    }

    // Cozy doorway sconce lantern
    const scX = (opts.doorX || 0) - 0.44;
    const scZ = D / 2 + 0.18;
    const lx = opts.x + scX * cosR + scZ * sinR;
    const lz = opts.z - scX * sinR + scZ * cosR;
    createLantern(lx, 1.38, lz, 0xffc663, false, 0);

    islandRoot.add(g);

    // Save sunny rooftop deck bounds (offset away from chimney so cats never clip it)
    rooftopDecks.push({
      name: opts.name,
      cx: opts.x + (0.28) * cosR,
      cz: opts.z - (0.28) * sinR,
      halfX: Math.max(0.35, topW * 0.26),
      halfZ: Math.max(0.30, topD * 0.24),
      y: roofTopY
    });

    return g;
  }

  // 1. Town Hall (NW) — Terracotta roof
  buildCottage({
    name: 'Town Hall roof',
    x: -2.6, z: -4.4, w: 3.1, d: 2.3, h: 1.75,
    wallColor: '#f5ead6', wallLight: '#fff6e8', beamColor: '#754e32',
    roofColor: '#d95b43', roofDark: '#a83c2a', roofLight: '#f0785f',
    isTownHall: true
  });

  // 2. Cozy Cat Bakery & Milk Shop (SW) — Mint-teal roof + Coral/Cream striped awning
  buildCottage({
    name: 'Cat Café roof',
    x: -3.4, z: 3.6, w: 2.8, d: 2.2, h: 1.65, rotY: Math.PI,
    doorX: -0.58, frontWindows: 1,
    wallColor: '#f7e4ad', wallLight: '#fff0c7', beamColor: '#7a5233',
    roofColor: '#3ca39c', roofDark: '#297a74', roofLight: '#5ec4bd',
    awningColors: ['#f26d5b', '#fff5e1']
  });

  // 3. Fisherman's Blue-Roof Cottage (N-Center)
  buildCottage({
    name: 'Blue Cottage roof',
    x: 0.7, z: -5.0, w: 2.3, d: 2.1, h: 1.55,
    doorX: -0.35, frontWindows: 1,
    wallColor: '#f2dfd3', wallLight: '#fff0e6', beamColor: '#694a38',
    roofColor: '#4879bf', roofDark: '#305894', roofLight: '#6899de'
  });

  // -------------------------------------------------------------------------
  // FISH MARKET STALLS WITH STRIPED AWNINGS (West Plaza)
  // -------------------------------------------------------------------------
  function buildFishStall(x, z, rotY, colA, colB, fishPalette) {
    const g = new THREE.Group();
    g.position.set(x, 0, z);
    g.rotation.y = rotY;

    const W = 2.0, D = 1.25;
    // Wooden counter base
    const counter = new THREE.Mesh(new THREE.BoxGeometry(W, 0.74, D * 0.78), matWood);
    counter.position.set(0, 0.37, 0.10);
    counter.castShadow = true;
    counter.receiveShadow = true;
    g.add(counter);

    // Counter tabletop
    const top = new THREE.Mesh(new THREE.BoxGeometry(W + 0.12, 0.10, D * 0.88), new THREE.MeshStandardMaterial({ color: 0xd9a673, roughness: 0.85 }));
    top.position.set(0, 0.78, 0.10);
    top.castShadow = true;
    top.receiveShadow = true;
    g.add(top);

    // 4 Corner Timber Posts
    const postGeo = new THREE.BoxGeometry(0.12, 1.85, 0.12);
    [[-W / 2 + 0.08, -D / 2 + 0.08], [W / 2 - 0.08, -D / 2 + 0.08],
     [-W / 2 + 0.08, D / 2 - 0.08], [W / 2 - 0.08, D / 2 - 0.08]].forEach(([px0, pz0]) => {
      const p = new THREE.Mesh(postGeo, matDarkWood);
      p.position.set(px0, 0.925, pz0);
      p.castShadow = true;
      g.add(p);
    });

    // Chunky Striped Awning (sloped roof + scalloped front valance!)
    const awnMat = new THREE.MeshStandardMaterial({
      map: makeAwningTexture(colA, colB),
      roughness: 0.8
    });
    const awnRoof = new THREE.Mesh(new THREE.BoxGeometry(W + 0.32, 0.14, D + 0.42), awnMat);
    awnRoof.position.set(0, 1.88, 0.08);
    awnRoof.rotation.x = 0.24;
    awnRoof.castShadow = true;
    awnRoof.receiveShadow = true;
    g.add(awnRoof);

    // Front striped scallop valance
    const valance = new THREE.Mesh(new THREE.BoxGeometry(W + 0.32, 0.22, 0.08), awnMat);
    valance.position.set(0, 1.66, D / 2 + 0.24);
    valance.castShadow = true;
    g.add(valance);

    // Ice display trays & chunky pixel fish on the counter!
    const matIce = new THREE.MeshStandardMaterial({ color: 0xd4f6ff, roughness: 0.35 });
    for (let t = -1; t <= 1; t++) {
      const tray = new THREE.Mesh(new THREE.BoxGeometry(0.54, 0.08, 0.62), matDarkWood);
      tray.position.set(t * 0.62, 0.86, 0.12);
      g.add(tray);
      const ice = new THREE.Mesh(new THREE.BoxGeometry(0.46, 0.06, 0.54), matIce);
      ice.position.set(t * 0.62, 0.90, 0.12);
      g.add(ice);
      // 2 chunky pixel fish per tray
      for (let f = 0; f < 2; f++) {
        const fc = fishPalette[(t + 1 + f) % fishPalette.length];
        const fishMat = new THREE.MeshStandardMaterial({ color: fc, roughness: 0.45, metalness: 0.15 });
        const fb = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.08, 0.32), fishMat);
        fb.position.set(t * 0.62 + (f === 0 ? -0.10 : 0.10), 0.96, 0.10);
        fb.rotation.y = f === 0 ? 0.12 : -0.10;
        g.add(fb);
        const ft = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.06, 0.09), fishMat);
        ft.position.set(t * 0.62 + (f === 0 ? -0.10 : 0.10), 0.96, -0.09);
        g.add(ft);
      }
    }

    // Wooden fish crate beside stall
    const crate = new THREE.Mesh(new THREE.BoxGeometry(0.46, 0.42, 0.46), matWood);
    crate.position.set(W / 2 + 0.34, 0.21, 0.12);
    crate.castShadow = true;
    crate.receiveShadow = true;
    g.add(crate);
    const crateFish = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.26, 0.12), new THREE.MeshStandardMaterial({ color: 0x56a8e8, roughness: 0.4 }));
    crateFish.position.set(W / 2 + 0.34, 0.48, 0.12);
    crateFish.rotation.z = 0.28;
    g.add(crateFish);

    // Hanging pixel fish signboard on front-left post
    const signBracket = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.08, 0.42), matDarkWood);
    signBracket.position.set(-W / 2 + 0.08, 1.56, D / 2 + 0.16);
    g.add(signBracket);
    const signBoard = new THREE.Mesh(
      new THREE.BoxGeometry(0.06, 0.36, 0.36),
      new THREE.MeshStandardMaterial({ map: texFishSign, roughness: 0.7 })
    );
    signBoard.position.set(-W / 2 + 0.08, 1.34, D / 2 + 0.24);
    g.add(signBoard);

    islandRoot.add(g);
    return g;
  }

  // Stall 1: Red & White striped awning (facing +X into the square)
  buildFishStall(-5.15, -1.25, Math.PI / 2, '#e84142', '#fff8eb', [0x59b2f5, 0xff8c6b, 0xb8d4e8]);
  // Stall 2: Blue & White striped awning (facing +X into the square)
  buildFishStall(-5.15, 1.05, Math.PI / 2, '#2d7cd6', '#fffaf0', [0xffb742, 0x62c4e8, 0xf27d72]);

  // Overhead festive string lanterns across the Fish Market!
  const stringLampColors = [0xffb74a, 0xff7c5c, 0xffe073, 0xff9a52, 0xffd066];
  for (let i = 0; i < 5; i++) {
    const t = i / 4;
    const sx = lerp(-4.4, -2.2, t);
    const sz = lerp(-1.5, 1.4, t);
    const sag = Math.sin(t * Math.PI) * 0.35;
    createLantern(sx, 2.32 - sag, sz, stringLampColors[i], false, 0);
  }
  // Support post for market string lights
  const marketPost = new THREE.Mesh(new THREE.BoxGeometry(0.14, 2.5, 0.14), matDarkWood);
  marketPost.position.set(-2.2, 1.25, 1.45);
  marketPost.castShadow = true;
  islandRoot.add(marketPost);
  // String cable visual
  const stringGeo = new THREE.BoxGeometry(0.04, 0.04, 3.65);
  const stringWire = new THREE.Mesh(stringGeo, matDarkWood);
  stringWire.position.set(-3.3, 2.28, -0.05);
  stringWire.rotation.y = Math.atan2(2.2, 2.9);
  islandRoot.add(stringWire);

  // -------------------------------------------------------------------------
  // TOWN SQUARE GOLDEN-CAT MINI FOUNTAIN
  // -------------------------------------------------------------------------
  const fountainGroup = new THREE.Group();
  fountainGroup.position.set(-0.85, 0, -0.65);
  const fRim = new THREE.Mesh(new THREE.BoxGeometry(1.18, 0.34, 1.18), matStone);
  fRim.position.y = 0.17;
  fRim.castShadow = true;
  fRim.receiveShadow = true;
  fountainGroup.add(fRim);
  const fWater = new THREE.Mesh(new THREE.BoxGeometry(0.92, 0.06, 0.92), matWater);
  fWater.position.y = 0.34;
  fountainGroup.add(fWater);
  const fPillar = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.65, 0.34), matStone);
  fPillar.position.y = 0.55;
  fPillar.castShadow = true;
  fountainGroup.add(fPillar);
  // Cute tiny golden cat statue perched atop the fountain!
  const matGold = new THREE.MeshStandardMaterial({ color: 0xffcf4d, roughness: 0.38, metalness: 0.35 });
  const statBody = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.24, 0.22), matGold);
  statBody.position.y = 0.98;
  fountainGroup.add(statBody);
  const statHead = new THREE.Mesh(new THREE.BoxGeometry(0.24, 0.20, 0.22), matGold);
  statHead.position.y = 1.18;
  fountainGroup.add(statHead);
  const statEarL = new THREE.Mesh(new THREE.BoxGeometry(0.07, 0.08, 0.06), matGold);
  statEarL.position.set(-0.08, 1.31, 0);
  fountainGroup.add(statEarL);
  const statEarR = statEarL.clone();
  statEarR.position.x = 0.08;
  fountainGroup.add(statEarR);
  islandRoot.add(fountainGroup);

  // -------------------------------------------------------------------------
  // YARN PARK: GIANT BALLS OF YARN, TRAILING THREADS, BENCH & SCRATCHING POST
  // -------------------------------------------------------------------------
  function buildGiantYarnBall(x, z, radius, mainCol, lightCol, darkCol, trailDirs) {
    const g = new THREE.Group();
    const yMat = new THREE.MeshStandardMaterial({
      map: makeYarnTexture(mainCol, lightCol, darkCol),
      roughness: 0.92
    });
    // Chunky faceted voxel-ish sphere (8x6 segments gives a wonderfully blocky pixel-art ball!)
    const ball = new THREE.Mesh(new THREE.SphereGeometry(radius, 10, 7), yMat);
    ball.position.y = radius * 0.92;
    ball.castShadow = true;
    ball.receiveShadow = true;
    g.add(ball);

    // Extra chunky wrapped yarn bands around the equator for tactile pixel silhouette
    const bandMat = new THREE.MeshStandardMaterial({ color: lightCol, roughness: 0.9 });
    const band1 = new THREE.Mesh(new THREE.TorusGeometry(radius * 0.96, radius * 0.08, 5, 10), bandMat);
    band1.position.y = radius * 0.92;
    band1.rotation.set(0.6, 0.4, 0.3);
    g.add(band1);
    const band2 = new THREE.Mesh(new THREE.TorusGeometry(radius * 0.96, radius * 0.07, 5, 10), new THREE.MeshStandardMaterial({ color: darkCol, roughness: 0.9 }));
    band2.position.y = radius * 0.92;
    band2.rotation.set(-0.7, 1.1, 0.8);
    g.add(band2);

    // Chunky pixel yarn strand trailing out onto the grass!
    const strandMat = new THREE.MeshStandardMaterial({ color: mainCol, roughness: 0.9 });
    let sx = 0, sz = 0;
    trailDirs.forEach(([dx, dz]) => {
      sx += dx;
      sz += dz;
      const seg = new THREE.Mesh(new THREE.BoxGeometry(0.13, 0.08, 0.13), strandMat);
      seg.position.set(sx, 0.04, sz);
      g.add(seg);
    });

    g.position.set(x, 0, z);
    islandRoot.add(g);
    return g;
  }

  // 4 Giant Colorful Balls of Yarn in Yarn Park!
  buildGiantYarnBall(4.2, -3.5, 0.88, '#ff6b94', '#ff9db8', '#d44872', [
    [-0.75, 0.45], [-0.14, 0.12], [-0.15, 0.08], [-0.14, 0.14], [-0.10, 0.15], [0.04, 0.14]
  ]);
  buildGiantYarnBall(5.6, -1.6, 0.72, '#ffca3a', '#ffe285', '#d99e1e', [
    [-0.62, 0.28], [-0.14, 0.10], [-0.14, 0.02], [-0.12, -0.10], [-0.12, -0.06]
  ]);
  buildGiantYarnBall(2.5, -1.2, 0.56, '#56b4ff', '#91d0ff', '#3184c9', [
    [0.48, 0.22], [0.13, 0.10], [0.13, 0.06], [0.10, 0.13]
  ]);
  buildGiantYarnBall(5.8, -3.6, 0.45, '#6ee0b0', '#a6f5d2', '#42b083', [
    [-0.36, -0.24], [-0.12, -0.08], [-0.12, -0.02]
  ]);

  // Wooden Park Bench in Yarn Park & South Pond Bank
  function buildBench(x, z, rotY) {
    const g = new THREE.Group();
    g.position.set(x, 0, z);
    g.rotation.y = rotY;
    const seat = new THREE.Mesh(new THREE.BoxGeometry(1.05, 0.09, 0.36), matWood);
    seat.position.y = 0.32;
    seat.castShadow = true;
    g.add(seat);
    const back = new THREE.Mesh(new THREE.BoxGeometry(1.05, 0.30, 0.08), matWood);
    back.position.set(0, 0.54, -0.15);
    back.castShadow = true;
    g.add(back);
    const legL = new THREE.Mesh(new THREE.BoxGeometry(0.10, 0.32, 0.32), matDarkWood);
    legL.position.set(-0.42, 0.16, 0);
    g.add(legL);
    const legR = legL.clone();
    legR.position.x = 0.42;
    g.add(legR);
    islandRoot.add(g);
  }
  buildBench(2.4, -3.8, 0.45);
  buildBench(-0.5, 4.7, Math.PI * 0.85);

  // Cute Cat Scratching Post Tower in Yarn Park
  const scratchGroup = new THREE.Group();
  scratchGroup.position.set(4.5, 0, -5.0);
  const scBase = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.12, 0.75), new THREE.MeshStandardMaterial({ color: 0xe8d5b7, roughness: 0.95 }));
  scBase.position.y = 0.06;
  scratchGroup.add(scBase);
  const scPole = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.92, 0.22), new THREE.MeshStandardMaterial({ color: 0xd9b37c, roughness: 0.98 }));
  scPole.position.y = 0.54;
  scPole.castShadow = true;
  scratchGroup.add(scPole);
  const scPerch = new THREE.Mesh(new THREE.BoxGeometry(0.58, 0.12, 0.58), new THREE.MeshStandardMaterial({ color: 0xff8fab, roughness: 0.9 }));
  scPerch.position.y = 1.02;
  scPerch.castShadow = true;
  scratchGroup.add(scPerch);
  islandRoot.add(scratchGroup);

  // Park & Square Streetlamps
  createLantern(2.2, 0, -0.35, 0xffd066, true, 1.85);
  createLantern(0.0, 0, -1.9, 0xffd066, true, 1.85);
  createLantern(-1.3, 0, 3.3, 0xffd066, true, 1.75);

  // -------------------------------------------------------------------------
  // SMALL ARCHED WOODEN BRIDGE OVER THE POND
  // -------------------------------------------------------------------------
  const BRIDGE_X0 = 0.35;
  const BRIDGE_X1 = 4.65;
  const BRIDGE_Z = 2.0;
  const BRIDGE_ARCH_H = 0.74;

  function getBridgeY(x) {
    const u = clamp((x - BRIDGE_X0) / (BRIDGE_X1 - BRIDGE_X0), 0, 1);
    return Math.sin(u * Math.PI) * BRIDGE_ARCH_H;
  }
  function isOnBridge(x, z) {
    return x >= BRIDGE_X0 - 0.1 && x <= BRIDGE_X1 + 0.1 && Math.abs(z - BRIDGE_Z) <= 0.72;
  }

  const bridgeGroup = new THREE.Group();
  const matBridge = new THREE.MeshStandardMaterial({ map: texBridgeWood, roughness: 0.85 });
  const matBridgeRail = new THREE.MeshStandardMaterial({ color: 0xa84b31, roughness: 0.85 });
  const planks = 14;
  for (let i = 0; i < planks; i++) {
    const u = (i + 0.5) / planks;
    const bx = lerp(BRIDGE_X0, BRIDGE_X1, u);
    const by = Math.sin(u * Math.PI) * BRIDGE_ARCH_H;
    const slope = Math.cos(u * Math.PI) * BRIDGE_ARCH_H * Math.PI / (BRIDGE_X1 - BRIDGE_X0);
    const plank = new THREE.Mesh(new THREE.BoxGeometry(0.36, 0.12, 1.32), matBridge);
    plank.position.set(bx, by - 0.05, BRIDGE_Z);
    plank.rotation.z = Math.atan(slope);
    plank.castShadow = true;
    plank.receiveShadow = true;
    bridgeGroup.add(plank);
  }
  // Support pilings down into the pond
  [1.45, 3.55].forEach((px0) => {
    const py = getBridgeY(px0);
    [-0.56, 0.56].forEach((dz) => {
      const piling = new THREE.Mesh(new THREE.BoxGeometry(0.16, py + 0.95, 0.16), matDarkWood);
      piling.position.set(px0, (py - 0.95) / 2, BRIDGE_Z + dz);
      piling.castShadow = true;
      bridgeGroup.add(piling);
    });
  });
  // Arched Handrail Posts & Rails
  const postXs = [BRIDGE_X0 + 0.12, 1.45, 2.5, 3.55, BRIDGE_X1 - 0.12];
  [-0.60, 0.60].forEach((dz) => {
    for (let i = 0; i < postXs.length; i++) {
      const px0 = postXs[i];
      const py = getBridgeY(px0);
      const post = new THREE.Mesh(new THREE.BoxGeometry(0.13, 0.56, 0.13), matBridgeRail);
      post.position.set(px0, py + 0.28, BRIDGE_Z + dz);
      post.castShadow = true;
      bridgeGroup.add(post);
      // Connect rails between adjacent posts
      if (i < postXs.length - 1) {
        const nx = postXs[i + 1];
        const ny = getBridgeY(nx);
        const segLen = Math.hypot(nx - px0, ny - py);
        const rail = new THREE.Mesh(new THREE.BoxGeometry(segLen + 0.06, 0.09, 0.09), matBridgeRail);
        rail.position.set((px0 + nx) / 2, (py + ny) / 2 + 0.50, BRIDGE_Z + dz);
        rail.rotation.z = Math.atan2(ny - py, nx - px0);
        rail.castShadow = true;
        bridgeGroup.add(rail);
      }
    }
  });
  islandRoot.add(bridgeGroup);

  // 4 Warm Glowing Lanterns perched on the Bridge entrance posts!
  createLantern(BRIDGE_X0 + 0.12, getBridgeY(BRIDGE_X0 + 0.12) + 0.68, BRIDGE_Z - 0.60, 0xffc864, false, 0);
  createLantern(BRIDGE_X0 + 0.12, getBridgeY(BRIDGE_X0 + 0.12) + 0.68, BRIDGE_Z + 0.60, 0xffc864, false, 0);
  createLantern(BRIDGE_X1 - 0.12, getBridgeY(BRIDGE_X1 - 0.12) + 0.68, BRIDGE_Z - 0.60, 0xffc864, false, 0);
  createLantern(BRIDGE_X1 - 0.12, getBridgeY(BRIDGE_X1 - 0.12) + 0.68, BRIDGE_Z + 0.60, 0xffc864, false, 0);

  // Warm Night PointLights across town
  addWarmNightLight(-4.2, 2.0, -0.1);  // Fish Market
  addWarmNightLight(-1.3, 2.2, -2.2);  // Town Square & Town Hall
  addWarmNightLight(-2.6, 2.0, 2.2);   // SW Café
  addWarmNightLight(2.5, 1.9, 2.0);    // Pond & Arched Bridge
  addWarmNightLight(3.2, 2.1, -1.7);   // Yarn Park
  addWarmNightLight(0.9, 2.1, -3.5);   // North Cottage

  // -------------------------------------------------------------------------
  // CHUNKY PIXEL TREES, BUSHES, FLOWERS & CLIFF FENCES
  // -------------------------------------------------------------------------
  const matLeavesGreen = new THREE.MeshStandardMaterial({ map: makeLeavesTexture('#4ea845', '#6bc95e', '#388233', null), roughness: 0.9 });
  const matLeavesSakura = new THREE.MeshStandardMaterial({ map: makeLeavesTexture('#f598b5', '#ffc4d6', '#d67494', '#fff0f5'), roughness: 0.88 });
  const matTrunk = new THREE.MeshStandardMaterial({ color: 0x7a4f30, roughness: 0.94 });

  function buildPixelTree(x, z, scale, sakura) {
    const g = new THREE.Group();
    const trunk = new THREE.Mesh(new THREE.BoxGeometry(0.36, 1.15, 0.36), matTrunk);
    trunk.position.y = 0.575;
    trunk.castShadow = true;
    trunk.receiveShadow = true;
    g.add(trunk);

    const lMat = sakura ? matLeavesSakura : matLeavesGreen;
    const crown1 = new THREE.Mesh(new THREE.BoxGeometry(1.42, 0.72, 1.42), lMat);
    crown1.position.y = 1.38;
    crown1.castShadow = true;
    crown1.receiveShadow = true;
    g.add(crown1);

    const crown2 = new THREE.Mesh(new THREE.BoxGeometry(1.06, 0.58, 1.06), lMat);
    crown2.position.y = 1.92;
    crown2.castShadow = true;
    g.add(crown2);

    const crown3 = new THREE.Mesh(new THREE.BoxGeometry(0.58, 0.34, 0.58), lMat);
    crown3.position.y = 2.30;
    crown3.castShadow = true;
    g.add(crown3);

    g.position.set(x, 0, z);
    g.scale.setScalar(scale);
    g.rotation.y = hash2D(x, z) * Math.PI;
    islandRoot.add(g);
  }

  buildPixelTree(-5.7, -3.6, 1.05, false);
  buildPixelTree(-0.8, -6.1, 0.92, true);
  buildPixelTree(3.5, -5.8, 1.08, true);
  buildPixelTree(6.4, -2.5, 0.98, false);
  buildPixelTree(6.2, 0.6, 0.88, false);
  buildPixelTree(-5.7, 3.6, 1.0, true);
  buildPixelTree(-1.7, 5.9, 0.9, false);
  buildPixelTree(1.2, 5.7, 0.95, false);

  // Tiny Pixel Flowers scattered in Yarn Park & grassy corners
  const flowerColors = [0xff6b8b, 0xffe066, 0xffffff, 0xb892ff, 0xff9f52];
  const flowerSpots = [
    [2.9, -2.4], [3.2, -2.1], [4.9, -2.6], [5.1, -0.7], [3.5, -0.6],
    [1.8, -3.2], [5.5, -4.6], [6.1, -1.0], [5.5, 1.8], [5.6, 2.7],
    [0.6, 4.4], [-2.0, 5.1], [-5.8, -2.6], [-4.6, -5.0], [2.4, -5.4]
  ];
  flowerSpots.forEach(([fx, fz], idx) => {
    const stem = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.14, 0.06), matReed);
    stem.position.set(fx, 0.07, fz);
    islandRoot.add(stem);
    const head = new THREE.Mesh(
      new THREE.BoxGeometry(0.14, 0.11, 0.14),
      new THREE.MeshStandardMaterial({ color: flowerColors[idx % flowerColors.length], roughness: 0.75 })
    );
    head.position.set(fx, 0.17, fz);
    islandRoot.add(head);
  });

  // Cute wooden fences along scenic edges
  function buildFenceSegment(x, z, rotY, len) {
    const g = new THREE.Group();
    g.position.set(x, 0, z);
    g.rotation.y = rotY;
    const posts = Math.max(2, Math.round(len / 0.7) + 1);
    for (let i = 0; i < posts; i++) {
      const p = new THREE.Mesh(new THREE.BoxGeometry(0.10, 0.44, 0.10), matWood);
      p.position.set(-len / 2 + (i / (posts - 1)) * len, 0.22, 0);
      p.castShadow = true;
      g.add(p);
    }
    const r1 = new THREE.Mesh(new THREE.BoxGeometry(len, 0.08, 0.06), matWood);
    r1.position.y = 0.34;
    g.add(r1);
    const r2 = r1.clone();
    r2.position.y = 0.18;
    g.add(r2);
    islandRoot.add(g);
  }
  buildFenceSegment(6.5, -0.8, Math.PI / 2, 1.8);
  buildFenceSegment(5.9, 3.0, Math.PI / 2 + 0.3, 1.6);
  buildFenceSegment(-6.4, -0.1, Math.PI / 2, 2.2);
  buildFenceSegment(-0.2, 6.2, 0.1, 2.1);

  // =========================================================================
  // 6. CHUNKY VOXEL CLOUDS DRIFTING BELOW THE ISLAND
  // =========================================================================
  const cloudMat = new THREE.MeshStandardMaterial({
    color: 0xffffff,
    roughness: 0.95,
    metalness: 0.0,
    transparent: true,
    opacity: 0.94
  });
  const clouds = [];
  const CLOUD_SPAN = 46;

  for (let i = 0; i < 28; i++) {
    const cg = new THREE.Group();
    const puffs = 3 + Math.floor(rng() * 4);
    for (let p = 0; p < puffs; p++) {
      const pw = 1.6 + rng() * 2.4;
      const ph = 0.65 + rng() * 0.75;
      const pd = 1.4 + rng() * 1.9;
      const box = new THREE.Mesh(new THREE.BoxGeometry(pw, ph, pd), cloudMat);
      box.position.set(
        (p - (puffs - 1) / 2) * (1.05 + rng() * 0.45),
        (rng() - 0.5) * 0.35,
        (rng() - 0.5) * 1.1
      );
      cg.add(box);
    }
    const cx = (rng() - 0.5) * CLOUD_SPAN * 2;
    const cz = (rng() - 0.5) * CLOUD_SPAN * 1.6;
    // Layered strictly BELOW the floating island (-3.8 to -11.5)
    const cy = -4.2 - rng() * 7.2;
    const sc = 0.75 + rng() * 0.85;
    cg.position.set(cx, cy, cz);
    cg.scale.setScalar(sc);
    scene.add(cg);
    clouds.push({
      group: cg,
      speed: 0.45 + rng() * 0.75,
      baseY: cy,
      bobPhase: rng() * Math.PI * 2,
      baseScale: sc
    });
  }

  // =========================================================================
  // 7. BUTTERFLIES, FIREFLIES & CHIMNEY SMOKE
  // =========================================================================
  const butterflies = [];
  const bfColors = [0xff9838, 0x5cc8ff, 0xffe047, 0xff7eb6, 0xc38cff, 0x6ef2a8, 0xffb347];
  const bfHomes = [
    [3.8, -2.1], [4.9, -2.9], [2.4, -2.4], [4.4, -0.5],
    [1.8, -0.7], [-0.4, 2.9], [5.1, 1.3]
  ];
  const wingGeo = new THREE.BoxGeometry(0.14, 0.02, 0.16);
  bfHomes.forEach(([hx, hz], idx) => {
    const bg = new THREE.Group();
    const wMat = new THREE.MeshBasicMaterial({ color: bfColors[idx % bfColors.length] });
    const wingL = new THREE.Mesh(wingGeo, wMat);
    wingL.position.x = 0.08;
    const wingR = new THREE.Mesh(wingGeo, wMat);
    wingR.position.x = -0.08;
    const body = new THREE.Mesh(new THREE.BoxGeometry(0.04, 0.04, 0.14), new THREE.MeshBasicMaterial({ color: 0x262033 }));
    bg.add(wingL, wingR, body);
    bg.position.set(hx, 0.9, hz);
    islandRoot.add(bg);
    butterflies.push({
      group: bg, wingL, wingR,
      homeX: hx, homeZ: hz,
      rx: 1.0 + (idx % 3) * 0.45,
      rz: 0.9 + ((idx + 1) % 3) * 0.4,
      speed: 0.55 + (idx % 4) * 0.15,
      phase: idx * 1.15,
      x: hx, y: 0.9, z: hz
    });
  });

  // Night Fireflies
  const fireflies = [];
  const fireflyMat = new THREE.SpriteMaterial({
    map: texGlowHalo,
    color: 0xd9ff66,
    transparent: true,
    opacity: 0,
    blending: THREE.AdditiveBlending,
    depthWrite: false
  });
  for (let i = 0; i < 20; i++) {
    const sp = new THREE.Sprite(fireflyMat);
    const angle = (i / 20) * Math.PI * 2;
    const rad = 1.6 + rng() * 4.8;
    const fx = Math.cos(angle) * rad;
    const fz = Math.sin(angle) * rad;
    const fy = 0.6 + rng() * 1.8;
    sp.position.set(fx, fy, fz);
    sp.scale.set(0.38, 0.38, 1);
    islandRoot.add(sp);
    fireflies.push({ sprite: sp, bx: fx, by: fy, bz: fz, phase: rng() * Math.PI * 2, speed: 0.7 + rng() * 0.8 });
  }

  // Chimney Smoke Puffs
  const smokePuffs = [];
  const smokeGeo = new THREE.BoxGeometry(0.20, 0.20, 0.20);
  chimneyEmitters.forEach((em, eIdx) => {
    for (let k = 0; k < 4; k++) {
      const smMat = new THREE.MeshBasicMaterial({ color: 0xf4f0eb, transparent: true, opacity: 0.5 });
      const sm = new THREE.Mesh(smokeGeo, smMat);
      islandRoot.add(sm);
      smokePuffs.push({
        mesh: sm, mat: smMat,
        em,
        t: (k / 4 + eIdx * 0.3) % 1,
        speed: 0.22 + rng() * 0.06
      });
    }
  });

  // =========================================================================
  // 8. CHUNKY PIXEL CATS, NAVIGATION GRAPH & AUTONOMOUS AI
  // =========================================================================
  // Connected Waypoint Graph (verified clear of buildings, pond, fountain & yarn balls)
  const WAYPOINTS = [
    { id: 0,  x: -2.5, z: -2.4, tag: 'square',  neighbors: [1, 4, 5] },
    { id: 1,  x: -3.7, z: -1.2, tag: 'shop1',   faceYaw: -Math.PI / 2, neighbors: [0, 2, 4] },
    { id: 2,  x: -3.7, z:  0.9, tag: 'shop2',   faceYaw: -Math.PI / 2, neighbors: [1, 3, 4] },
    { id: 3,  x: -2.6, z:  1.8, tag: 'shop3',   faceYaw: 0, neighbors: [2, 8, 19] },
    { id: 4,  x: -2.4, z: -0.3, tag: 'square',  neighbors: [0, 1, 2, 8] },
    { id: 5,  x: -0.8, z: -2.4, tag: 'square',  neighbors: [0, 6, 7] },
    { id: 6,  x:  0.8, z: -2.8, tag: 'lane',    neighbors: [5, 14] },
    { id: 7,  x:  0.6, z: -0.5, tag: 'square',  neighbors: [5, 8, 14] },
    { id: 8,  x: -0.5, z:  1.3, tag: 'square',  neighbors: [3, 4, 7, 9, 19] },
    { id: 9,  x:  0.2, z:  2.0, tag: 'bridge',  neighbors: [8, 10] },
    { id: 10, x:  2.5, z:  2.0, tag: 'bridge',  neighbors: [9, 11] },
    { id: 11, x:  4.8, z:  2.0, tag: 'bridge',  neighbors: [10, 12] },
    { id: 12, x:  5.3, z:  0.6, tag: 'bank',    neighbors: [11, 13] },
    { id: 13, x:  4.2, z: -0.2, tag: 'park',    neighbors: [12, 15] },
    { id: 14, x:  1.4, z: -2.0, tag: 'park',    neighbors: [6, 7, 15, 17] },
    { id: 15, x:  3.9, z: -1.8, tag: 'park',    neighbors: [13, 14, 16] },
    { id: 16, x:  5.6, z: -2.6, tag: 'park',    neighbors: [15] },
    { id: 17, x:  3.0, z: -4.6, tag: 'park',    neighbors: [14] },
    { id: 18, x: -0.5, z:  3.7, tag: 'bank',    neighbors: [19, 20] },
    { id: 19, x: -1.2, z:  2.4, tag: 'lane',    neighbors: [3, 8, 18] },
    { id: 20, x:  1.0, z:  4.8, tag: 'bank',    neighbors: [18] }
  ];

  // Obstacle bounding circles/boxes for free butterfly-chase collision clamping
  const OBSTACLE_BOXES = [
    { minX: -4.45, maxX: -0.75, minZ: -5.85, maxZ: -2.95 }, // Town Hall
    { minX: -5.1,  maxX: -1.7,  minZ:  2.25, maxZ:  5.0 },  // SW Cat Café
    { minX: -0.75, maxX:  2.15, minZ: -6.3,  maxZ: -3.7 },  // Blue Cottage
    { minX: -6.2,  maxX: -4.25, minZ: -2.55, maxZ:  2.25 }, // Fish Market Stalls
    { minX: -1.65, maxX: -0.05, minZ: -1.45, maxZ:  0.15 }  // Fountain
  ];
  const OBSTACLE_CIRCLES = [
    { x: 4.2, z: -3.5, r: 1.25 }, // Pink yarn
    { x: 5.6, z: -1.6, r: 1.05 }, // Yellow yarn
    { x: 2.5, z: -1.2, r: 0.90 }, // Blue yarn
    { x: 5.8, z: -3.6, r: 0.80 }  // Mint yarn
  ];

  function isWalkableFree(x, z) {
    const gx = Math.round(x), gz = Math.round(z);
    if (!isIslandCell(gx, gz)) return false;
    if (isPondCell(gx, gz) && !isOnBridge(x, z)) return false;
    if (Math.hypot(x, z) > 6.45) return false;
    for (const b of OBSTACLE_BOXES) {
      if (x >= b.minX && x <= b.maxX && z >= b.minZ && z <= b.maxZ) return false;
    }
    for (const c of OBSTACLE_CIRCLES) {
      if (Math.hypot(x - c.x, z - c.z) < c.r) return false;
    }
    return true;
  }

  function getGroundHeight(x, z) {
    if (isOnBridge(x, z)) return getBridgeY(x);
    return 0;
  }

  // Follow Indicator Ring & Floating Arrow beneath/above followed cat
  const followHaloGroup = new THREE.Group();
  const followRingMat = new THREE.MeshBasicMaterial({ color: 0xffdf6b, transparent: true, opacity: 0.85, side: THREE.DoubleSide });
  const followRing = new THREE.Mesh(new THREE.RingGeometry(0.42, 0.56, 12), followRingMat);
  followRing.rotation.x = -Math.PI / 2;
  followRing.position.y = 0.03;
  followHaloGroup.add(followRing);
  const followArrow = new THREE.Mesh(new THREE.ConeGeometry(0.13, 0.22, 4), new THREE.MeshBasicMaterial({ color: 0xffdf6b }));
  followArrow.rotation.x = Math.PI;
  followArrow.position.y = 1.22;
  followHaloGroup.add(followArrow);
  followHaloGroup.visible = false;
  islandRoot.add(followHaloGroup);

  // Shared invisible raycast hit geometry & material for easy tapping on phones!
  const catHitGeo = new THREE.SphereGeometry(0.62, 8, 6);
  const catHitMat = new THREE.MeshBasicMaterial({
    transparent: true,
    opacity: 0.0,
    depthWrite: false,
    colorWrite: false
  });
  const catHitMeshes = [];

  // 13 Unique Cat Personalities!
  const CAT_SPECS = [
    {
      name: 'Mayor Marmalade',
      role: 'Island Mayor',
      isMayor: true,
      base: '#ff8e2b', accent: '#cf5b12', muzzle: '#ffe2bd', nose: '#ff7a98', eyeColor: '#1d2b1f', iris: '#6fd957',
      pattern: 'tabby', scale: 1.08, startNode: 4, fav: 'shop'
    },
    {
      name: 'Mochi',
      role: 'Calico Explorer',
      base: '#fff8ef', accent: '#f28c38', accent2: '#322c3d', nose: '#ff8ca6',
      pattern: 'calico', scale: 0.98, startNode: 7, fav: 'park'
    },
    {
      name: 'Mackerel',
      role: 'Fish Connoisseur',
      base: '#8a99ad', accent: '#5c6b80', muzzle: '#d9e2ec', nose: '#e07a94',
      pattern: 'tabby', scale: 1.0, startNode: 1, fav: 'shop', bandana: '#2f82e0'
    },
    {
      name: 'Yuzu',
      role: 'Butterfly Chaser',
      base: '#f7c548', accent: '#d99821', muzzle: '#fff0c4', nose: '#ff879c',
      pattern: 'tabby', scale: 0.96, startNode: 15, fav: 'park'
    },
    {
      name: 'Soot',
      role: 'Tuxedo Gentleman',
      base: '#2b2838', accent: '#fffaf2', nose: '#ff90aa', iris: '#ffd24d',
      pattern: 'tuxedo', scale: 1.02, startNode: 8, fav: 'bridge'
    },
    {
      name: 'Matcha',
      role: 'Bridge Stroller',
      base: '#f2e4cc', accent: '#5c4236', nose: '#47332a', eyeColor: '#265c99', iris: '#64b8ff',
      pattern: 'siamese', scale: 0.98, startNode: 10, fav: 'bridge'
    },
    {
      name: 'Tofu',
      role: 'Fluffy Cloud',
      base: '#ffffff', accent: '#f0e8e4', nose: '#ff96b0', iris: '#63b4ff',
      pattern: 'solid', scale: 0.96, startNode: 2, fav: 'shop'
    },
    {
      name: 'Pebble',
      role: 'Cobble Loafer',
      base: '#a3a8b5', accent: '#6d7382', muzzle: '#e3e6ed', nose: '#eb8ca5',
      pattern: 'tabby', scale: 1.0, startNode: 18, fav: 'sleep'
    },
    {
      name: 'Nori',
      role: 'Night Prowler',
      base: '#23273b', accent: '#171a29', nose: '#635c75', eyeColor: '#1a1a24', iris: '#ffbe3d',
      pattern: 'solid', scale: 0.98, startNode: 13, fav: 'park'
    },
    {
      name: 'Pip',
      role: 'Yarn Park Kitten',
      base: '#ff9642', accent: '#fffaf2', nose: '#ff8ca6',
      pattern: 'bicolor', scale: 0.82, startNode: 14, fav: 'park'
    },
    // 3 Rooftop Sun-Napping Cats!
    {
      name: 'Biscuit',
      role: 'Town Hall Sun-Napper',
      base: '#f0b66c', accent: '#c98538', muzzle: '#fff0d6', nose: '#ff8da4',
      pattern: 'tabby', scale: 0.98, rooftopIndex: 0
    },
    {
      name: 'Cinnamon',
      role: 'Café Rooftop Napper',
      base: '#c97b4b', accent: '#8c4b27', nose: '#ff8ca6',
      pattern: 'spotted', scale: 0.96, rooftopIndex: 1
    },
    {
      name: 'Cloud',
      role: 'Blue-Roof Sun-Napper',
      base: '#dce3ed', accent: '#9ba6b8', muzzle: '#ffffff', nose: '#ff9ab5',
      pattern: 'tabby', scale: 0.97, rooftopIndex: 2
    }
  ];

  const cats = [];
  let mayorCat = null;

  function buildCat(spec, index) {
    const tex = makeCatTextures(spec);
    const coatMat = new THREE.MeshStandardMaterial({ map: tex.coat, roughness: 0.88 });
    const faceAwakeMat = new THREE.MeshStandardMaterial({ map: tex.faceAwake, roughness: 0.85 });
    const faceSleepMat = new THREE.MeshStandardMaterial({ map: tex.faceSleep, roughness: 0.85 });
    const earInnerMat = new THREE.MeshStandardMaterial({ color: 0xffa6bc, roughness: 0.85 });
    const pawMat = new THREE.MeshStandardMaterial({
      color: (spec.pattern === 'tuxedo' || spec.pattern === 'bicolor') ? spec.accent :
             (spec.pattern === 'siamese' ? spec.accent : spec.base),
      roughness: 0.88
    });

    const group = new THREE.Group();
    group.scale.setScalar(spec.scale);

    const bodyPivot = new THREE.Group();
    group.add(bodyPivot);

    // Torso
    const torso = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.28, 0.56), coatMat);
    torso.position.set(0, 0.34, 0);
    torso.castShadow = true;
    torso.receiveShadow = true;
    bodyPivot.add(torso);

    // Optional neck bandana
    if (spec.bandana) {
      const band = new THREE.Mesh(
        new THREE.BoxGeometry(0.36, 0.08, 0.14),
        new THREE.MeshStandardMaterial({ color: spec.bandana, roughness: 0.8 })
      );
      band.position.set(0, 0.35, 0.24);
      bodyPivot.add(band);
    }

    // 4 Articulated Legs (pivoting at top y=0.22)
    function makeLeg(lx, lz) {
      const piv = new THREE.Group();
      piv.position.set(lx, 0.22, lz);
      const legMesh = new THREE.Mesh(new THREE.BoxGeometry(0.105, 0.22, 0.105), pawMat);
      legMesh.position.y = -0.11;
      legMesh.castShadow = true;
      piv.add(legMesh);
      bodyPivot.add(piv);
      return piv;
    }
    const legFL = makeLeg(0.11, 0.20);
    const legFR = makeLeg(-0.11, 0.20);
    const legBL = makeLeg(0.11, -0.20);
    const legBR = makeLeg(-0.11, -0.20);

    // Head Pivot
    const headPivot = new THREE.Group();
    headPivot.position.set(0, 0.44, 0.29);
    bodyPivot.add(headPivot);

    const headMats = [coatMat, coatMat, coatMat, coatMat, faceAwakeMat, coatMat];
    const headMesh = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.30, 0.30), headMats);
    headMesh.position.set(0, 0.04, 0.07);
    headMesh.castShadow = true;
    headPivot.add(headMesh);

    // Tiny protruding 3D pixel nose
    const noseMesh = new THREE.Mesh(
      new THREE.BoxGeometry(0.055, 0.04, 0.03),
      new THREE.MeshStandardMaterial({ color: spec.nose || '#ff85a1', roughness: 0.7 })
    );
    noseMesh.position.set(0, 0.00, 0.225);
    headPivot.add(noseMesh);

    // Pointed Voxel Ears
    const earOuterMat = spec.pattern === 'siamese'
      ? new THREE.MeshStandardMaterial({ color: spec.accent, roughness: 0.88 })
      : coatMat;
    [-0.11, 0.11].forEach((ex) => {
      const earBase = new THREE.Mesh(new THREE.BoxGeometry(0.10, 0.10, 0.08), earOuterMat);
      earBase.position.set(ex, 0.22, 0.05);
      earBase.castShadow = true;
      headPivot.add(earBase);
      const earTip = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 0.06), earOuterMat);
      earTip.position.set(ex, 0.29, 0.05);
      headPivot.add(earTip);
      const earIn = new THREE.Mesh(new THREE.BoxGeometry(0.055, 0.06, 0.02), earInnerMat);
      earIn.position.set(ex, 0.22, 0.09);
      headPivot.add(earIn);
    });

    // MAYOR MARMALADE'S TINY HAT!
    if (spec.isMayor) {
      const hatGroup = new THREE.Group();
      hatGroup.position.set(0, 0.20, 0.07);
      hatGroup.rotation.set(-0.06, 0, -0.10);
      const matHat = new THREE.MeshStandardMaterial({ color: 0x242738, roughness: 0.75 });
      const matRibbon = new THREE.MeshStandardMaterial({ color: 0xffd24a, roughness: 0.45, metalness: 0.2 });
      const matClasp = new THREE.MeshStandardMaterial({ color: 0xeb4646, roughness: 0.5 });

      const brim = new THREE.Mesh(new THREE.BoxGeometry(0.28, 0.045, 0.28), matHat);
      brim.castShadow = true;
      hatGroup.add(brim);

      const ribbon = new THREE.Mesh(new THREE.BoxGeometry(0.195, 0.06, 0.195), matRibbon);
      ribbon.position.y = 0.05;
      hatGroup.add(ribbon);

      const clasp = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.065, 0.03), matClasp);
      clasp.position.set(0, 0.05, 0.10);
      hatGroup.add(clasp);

      const crown = new THREE.Mesh(new THREE.BoxGeometry(0.18, 0.17, 0.18), matHat);
      crown.position.y = 0.155;
      crown.castShadow = true;
      hatGroup.add(crown);

      headPivot.add(hatGroup);
    }

    // Articulated 2-Segment Tail
    const tailBase = new THREE.Group();
    tailBase.position.set(0, 0.40, -0.26);
    const tailSeg1 = new THREE.Mesh(new THREE.BoxGeometry(0.085, 0.24, 0.085), pawMat);
    tailSeg1.position.y = 0.11;
    tailSeg1.castShadow = true;
    tailBase.add(tailSeg1);

    const tailTip = new THREE.Group();
    tailTip.position.y = 0.22;
    const tailSeg2 = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.22, 0.08), coatMat);
    tailSeg2.position.y = 0.10;
    tailSeg2.castShadow = true;
    tailTip.add(tailSeg2);
    tailBase.add(tailTip);
    bodyPivot.add(tailBase);

    // Emote sprite above cat (Zzz / fish / heart)
    const emoteMat = new THREE.SpriteMaterial({ map: texEmoteZ, transparent: true, opacity: 0, depthWrite: false });
    const emoteSprite = new THREE.Sprite(emoteMat);
    emoteSprite.position.set(0, 0.95, 0.1);
    emoteSprite.scale.set(0.45, 0.45, 1);
    group.add(emoteSprite);

    // Invisible padded hitbox for effortless tapping on phones & desktop
    const hitMesh = new THREE.Mesh(catHitGeo, catHitMat);
    hitMesh.position.set(0, 0.36, 0.04);
    hitMesh.userData.catIndex = index;
    group.add(hitMesh);
    catHitMeshes.push(hitMesh);

    islandRoot.add(group);

    // Initial position & state
    const isRooftop = typeof spec.rooftopIndex === 'number';
    let initX = 0, initY = 0, initZ = 0;
    let curNode = spec.startNode || 0;
    let roofDeck = null;
    if (isRooftop) {
      roofDeck = rooftopDecks[spec.rooftopIndex];
      initX = roofDeck.cx;
      initY = roofDeck.y;
      initZ = roofDeck.cz;
    } else {
      initX = WAYPOINTS[curNode].x;
      initZ = WAYPOINTS[curNode].z;
      initY = getGroundHeight(initX, initZ);
    }

    group.position.set(initX, initY, initZ);

    const cat = {
      index,
      spec,
      group,
      bodyPivot,
      headPivot,
      headMesh,
      faceAwakeMat,
      faceSleepMat,
      legFL, legFR, legBL, legBR,
      tailBase, tailTip,
      emoteSprite, emoteMat,
      emoteTimer: 0,
      emoteDuration: 1.5,
      emoteStartY: 0.95,

      isRooftop,
      roofDeck,

      x: initX, y: initY, z: initZ,
      yaw: rng() * Math.PI * 2,
      pitch: 0,

      state: isRooftop ? 'SLEEP' : (index === 2 ? 'SHOP' : (index === 3 ? 'CHASE' : 'WALK')),
      stateTimer: isRooftop ? (6 + rng() * 10) : (2 + rng() * 4),
      statusText: isRooftop ? 'Napping in the sun' : 'Strolling around town',

      curNode,
      targetNode: curNode,
      targetX: initX,
      targetZ: initZ,
      chaseButterfly: null,

      walkPhase: rng() * Math.PI * 2,
      blinkTimer: 2 + rng() * 4,
      isBlinking: false,
      sleepBlend: isRooftop ? 1 : 0,
      stretchBlend: 0,
      hopVel: 0,
      hopY: 0,
      zSpawnTimer: rng() * 1.6,
      shopFaceYaw: -Math.PI / 2
    };

    if (!isRooftop) {
      pickNextGroundTarget(cat);
      if (index === 2) {
        cat.state = 'SHOP';
        cat.stateTimer = 5.5;
        cat.shopFaceYaw = -Math.PI / 2;
        cat.yaw = -Math.PI / 2;
        cat.statusText = 'Shopping at the fish market';
      } else if (index === 3) {
        cat.state = 'CHASE';
        cat.chaseButterfly = butterflies[0];
        cat.stateTimer = 6.5;
        cat.statusText = 'Chasing a butterfly';
      } else if (index === 7) {
        cat.state = 'SLEEP';
        cat.sleepBlend = 1;
        cat.stateTimer = 9.0;
        cat.statusText = 'Curled up asleep';
      } else if (index === 6) {
        cat.state = 'STRETCH';
        cat.stateTimer = 3.2;
        cat.statusText = 'Having a big stretch';
      }
    }

    if (spec.isMayor) mayorCat = cat;
    cats.push(cat);
    return cat;
  }

  function triggerEmote(cat, tex, duration) {
    cat.emoteMat.map = tex;
    cat.emoteMat.needsUpdate = true;
    cat.emoteDuration = duration || 1.7;
    cat.emoteTimer = cat.emoteDuration;
    cat.emoteStartY = cat.state === 'SLEEP' ? 0.62 : 0.96;
  }

  function pickNextGroundTarget(cat) {
    const wp = WAYPOINTS[cat.curNode];
    const nb = wp.neighbors;
    // Slight bias toward favorite area or avoiding immediate backtrack
    let choices = nb.filter((id) => id !== cat.prevNode);
    if (!choices.length) choices = nb;

    // Mayor loves patrolling square, fish market & bridge!
    let nextId = choices[Math.floor(rng() * choices.length)];
    if (cat.spec.fav === 'shop' && rng() < 0.45) {
      const marketLike = choices.find((id) => id === 1 || id === 2 || id === 3 || id === 4);
      if (marketLike !== undefined) nextId = marketLike;
    } else if (cat.spec.fav === 'park' && rng() < 0.45) {
      const parkLike = choices.find((id) => id >= 13 && id <= 17);
      if (parkLike !== undefined) nextId = parkLike;
    } else if (cat.spec.fav === 'bridge' && rng() < 0.5) {
      const brLike = choices.find((id) => id >= 9 && id <= 11);
      if (brLike !== undefined) nextId = brLike;
    }

    cat.prevNode = cat.curNode;
    cat.targetNode = nextId;
    const tw = WAYPOINTS[nextId];
    // Slight organic jitter except on the narrow bridge
    const jitter = tw.tag === 'bridge' ? 0.08 : 0.22;
    cat.targetX = tw.x + (rng() - 0.5) * jitter;
    cat.targetZ = tw.z + (rng() - 0.5) * jitter;

    if (tw.tag === 'bridge') cat.statusText = 'Crossing the pond bridge';
    else if (tw.tag === 'park') cat.statusText = 'Exploring Yarn Park';
    else if (tw.tag === 'shop1' || tw.tag === 'shop2' || tw.tag === 'shop3') cat.statusText = 'Heading to the fish market';
    else if (cat.spec.isMayor) cat.statusText = 'Patrolling Cat Island';
    else cat.statusText = 'Strolling around town';
  }

  function decideGroundArrivalAction(cat) {
    const wp = WAYPOINTS[cat.curNode];
    const isNight = currentTimeMode === 'night';

    // Never sleep or stop in the middle of the bridge
    if (wp.tag === 'bridge') {
      cat.state = 'WALK';
      pickNextGroundTarget(cat);
      return;
    }

    // At fish market stalls: high chance to shop!
    if ((wp.tag === 'shop1' || wp.tag === 'shop2' || wp.tag === 'shop3') && rng() < 0.68) {
      cat.state = 'SHOP';
      cat.stateTimer = 4.2 + rng() * 3.5;
      cat.shopFaceYaw = wp.faceYaw;
      cat.statusText = cat.spec.isMayor ? 'Inspecting the fish market' : 'Shopping for fresh fish';
      triggerEmote(cat, texEmoteFish, 2.0);
      return;
    }

    // Check if a fluttering butterfly is nearby -> chase it!
    if (!isNight || rng() < 0.35) {
      let closestBf = null, bestD = 3.2;
      for (const bf of butterflies) {
        const d = Math.hypot(bf.x - cat.x, bf.z - cat.z);
        if (d < bestD) { bestD = d; closestBf = bf; }
      }
      if (closestBf && rng() < (cat.spec.fav === 'park' ? 0.62 : 0.34)) {
        cat.state = 'CHASE';
        cat.chaseButterfly = closestBf;
        cat.stateTimer = 4.8 + rng() * 3.5;
        cat.statusText = 'Chasing a butterfly';
        return;
      }
    }

    const r = rng();
    const sleepChance = isNight ? 0.34 : 0.14;
    if (r < 0.19) {
      cat.state = 'STRETCH';
      cat.stateTimer = 3.2;
      cat.statusText = 'Having a big stretch';
    } else if (r < 0.19 + sleepChance) {
      cat.state = 'SLEEP';
      cat.stateTimer = (isNight ? 10 : 6.5) + rng() * 6;
      cat.statusText = isNight ? 'Curled up for the night' : 'Curled up for a catnap';
    } else {
      cat.state = 'WALK';
      pickNextGroundTarget(cat);
    }
  }

  // Spawn all 13 cats!
  CAT_SPECS.forEach((spec, idx) => buildCat(spec, idx));

  function updateCats(dt, elapsed) {
    for (const cat of cats) {
      cat.stateTimer -= dt;

      // Tap hop physics
      if (cat.hopY > 0 || cat.hopVel > 0) {
        cat.hopY += cat.hopVel * dt;
        cat.hopVel -= 9.5 * dt;
        if (cat.hopY < 0) { cat.hopY = 0; cat.hopVel = 0; }
      }

      // ---- STATE MACHINE ----
      if (cat.isRooftop) {
        const deck = cat.roofDeck;
        if (cat.state === 'SLEEP') {
          cat.statusText = currentTimeMode === 'night'
            ? 'Sleeping under the stars'
            : 'Napping in the sun on ' + deck.name;
          if (cat.stateTimer <= 0) {
            cat.state = 'STRETCH';
            cat.stateTimer = 3.2;
            cat.statusText = 'Stretching on ' + deck.name;
          }
        } else if (cat.state === 'STRETCH') {
          if (cat.stateTimer <= 0) {
            if (rng() < 0.55) {
              cat.state = 'WALK';
              cat.targetX = deck.cx + (rng() - 0.5) * deck.halfX * 1.6;
              cat.targetZ = deck.cz + (rng() - 0.5) * deck.halfZ * 1.6;
              cat.stateTimer = 4.0;
              cat.statusText = 'Pacing along ' + deck.name;
            } else {
              cat.state = 'SLEEP';
              cat.stateTimer = 9 + rng() * 8;
            }
          }
        } else if (cat.state === 'WALK') {
          const dx = cat.targetX - cat.x;
          const dz = cat.targetZ - cat.z;
          const dist = Math.hypot(dx, dz);
          if (dist < 0.08 || cat.stateTimer <= 0) {
            cat.state = 'SLEEP';
            cat.stateTimer = 10 + rng() * 9;
          } else {
            const sp = 0.65 * dt;
            cat.x += (dx / dist) * Math.min(sp, dist);
            cat.z += (dz / dist) * Math.min(sp, dist);
            const wantYaw = Math.atan2(dx, dz);
            cat.yaw += shortestAngleDiff(cat.yaw, wantYaw) * dampFactor(8, dt);
            cat.walkPhase += dt * 9.5;
          }
        }
        cat.y = deck.y;
        cat.pitch = 0;
      } else {
        // GROUND CATS
        if (cat.state === 'WALK') {
          const dx = cat.targetX - cat.x;
          const dz = cat.targetZ - cat.z;
          const dist = Math.hypot(dx, dz);
          if (dist < 0.16) {
            cat.curNode = cat.targetNode;
            decideGroundArrivalAction(cat);
          } else {
            const speed = (cat.spec.isMayor ? 1.12 : 1.05) * (cat.spec.scale < 0.9 ? 1.15 : 1.0);
            const step = Math.min(speed * dt, dist);
            cat.x += (dx / dist) * step;
            cat.z += (dz / dist) * step;
            const wantYaw = Math.atan2(dx, dz);
            cat.yaw += shortestAngleDiff(cat.yaw, wantYaw) * dampFactor(9, dt);
            cat.walkPhase += dt * 11.5;
          }
        } else if (cat.state === 'SHOP') {
          cat.yaw += shortestAngleDiff(cat.yaw, cat.shopFaceYaw) * dampFactor(7, dt);
          if (cat.stateTimer <= 0) {
            if (rng() < 0.25) {
              cat.state = 'STRETCH';
              cat.stateTimer = 3.0;
              cat.statusText = 'Having a big stretch';
            } else {
              cat.state = 'WALK';
              pickNextGroundTarget(cat);
            }
          }
        } else if (cat.state === 'CHASE') {
          const bf = cat.chaseButterfly;
          if (!bf || cat.stateTimer <= 0) {
            // Re-anchor smoothly to nearest waypoint
            let bestId = 0, bestDist = 999;
            for (const wp of WAYPOINTS) {
              if (wp.tag === 'bridge') continue;
              const d = Math.hypot(wp.x - cat.x, wp.z - cat.z);
              if (d < bestDist) { bestDist = d; bestId = wp.id; }
            }
            cat.curNode = bestId;
            cat.targetNode = bestId;
            cat.targetX = WAYPOINTS[bestId].x;
            cat.targetZ = WAYPOINTS[bestId].z;
            cat.state = 'WALK';
            cat.statusText = 'Strolling around town';
          } else {
            const dx = bf.x - cat.x;
            const dz = bf.z - cat.z;
            const dist = Math.hypot(dx, dz);
            const wantYaw = Math.atan2(dx, dz);
            cat.yaw += shortestAngleDiff(cat.yaw, wantYaw) * dampFactor(11, dt);
            if (dist > 0.32) {
              const step = 1.65 * dt;
              const nx = cat.x + (dx / dist) * step;
              const nz = cat.z + (dz / dist) * step;
              if (isWalkableFree(nx, nz)) {
                cat.x = nx;
                cat.z = nz;
                cat.walkPhase += dt * 16.5;
              } else {
                // Hit edge/pond/obstacle -> finish chase gracefully
                cat.stateTimer = 0;
              }
            } else if (cat.hopY === 0 && rng() < dt * 2.5) {
              // Playful tiny pounce hop!
              cat.hopVel = 2.6;
            }
          }
        } else if (cat.state === 'STRETCH') {
          if (cat.stateTimer <= 0) {
            cat.state = 'WALK';
            pickNextGroundTarget(cat);
          }
        } else if (cat.state === 'SLEEP') {
          if (cat.stateTimer <= 0) {
            cat.state = 'STRETCH';
            cat.stateTimer = 3.2;
            cat.statusText = 'Waking up with a stretch';
          }
        }

        // Compute ground/bridge height & gentle pitch over bridge arch
        const gy = getGroundHeight(cat.x, cat.z);
        cat.y = lerp(cat.y, gy, dampFactor(16, dt));
        if (isOnBridge(cat.x, cat.z)) {
          const u = clamp((cat.x - BRIDGE_X0) / (BRIDGE_X1 - BRIDGE_X0), 0, 1);
          const slope = Math.cos(u * Math.PI) * BRIDGE_ARCH_H * Math.PI / (BRIDGE_X1 - BRIDGE_X0);
          const dirX = Math.sin(cat.yaw);
          cat.pitch = lerp(cat.pitch, -slope * dirX * 0.85, dampFactor(10, dt));
        } else {
          cat.pitch = lerp(cat.pitch, 0, dampFactor(10, dt));
        }
      }

      // ---- POSE BLENDING & ARTICULATED ANIMATIONS ----
      const wantSleep = cat.state === 'SLEEP' ? 1 : 0;
      cat.sleepBlend = lerp(cat.sleepBlend, wantSleep, dampFactor(5.5, dt));

      let wantStretch = 0;
      if (cat.state === 'STRETCH') {
        const total = 3.2;
        const p = clamp(1 - cat.stateTimer / total, 0, 1);
        wantStretch = smoothstep(0.0, 0.22, p) * (1 - smoothstep(0.75, 1.0, p));
      }
      cat.stretchBlend = lerp(cat.stretchBlend, wantStretch, dampFactor(10, dt));

      const sl = cat.sleepBlend;
      const st = cat.stretchBlend;
      const isMoving = cat.state === 'WALK' || cat.state === 'CHASE';

      // Blinking & Sleeping Eyes swap
      cat.blinkTimer -= dt;
      if (cat.blinkTimer <= 0) {
        cat.isBlinking = !cat.isBlinking;
        cat.blinkTimer = cat.isBlinking ? 0.14 : (2.6 + rng() * 4.2);
      }
      const eyesClosed = sl > 0.45 || cat.isBlinking;
      const desiredFaceMat = eyesClosed ? cat.faceSleepMat : cat.faceAwakeMat;
      if (cat.headMesh.material[4] !== desiredFaceMat) {
        cat.headMesh.material[4] = desiredFaceMat;
      }

      // Body transform
      const walkBounce = isMoving ? Math.abs(Math.sin(cat.walkPhase)) * 0.045 : 0;
      const breathe = 1 + Math.sin(elapsed * 2.4 + cat.index) * (0.015 + sl * 0.025);
      cat.bodyPivot.position.y = walkBounce * (1 - sl) - sl * 0.18 - st * 0.04 + cat.hopY;
      cat.bodyPivot.rotation.x = st * 0.38 + cat.pitch * (1 - sl);
      cat.bodyPivot.scale.set(
        lerp(1, 1.18, sl) * breathe,
        lerp(1, 0.84, sl) * (2 - breathe),
        lerp(1, 0.80, sl)
      );

      // Legs animation
      const swing = isMoving ? Math.sin(cat.walkPhase) * 0.62 : 0;
      const legScaleY = lerp(1, 0.20, sl);
      cat.legFL.scale.y = legScaleY;
      cat.legFR.scale.y = legScaleY;
      cat.legBL.scale.y = legScaleY;
      cat.legBR.scale.y = legScaleY;

      cat.legFL.rotation.x = lerp(swing, -1.18, st) * (1 - sl);
      cat.legFR.rotation.x = lerp(-swing, -1.18, st) * (1 - sl);
      cat.legBL.rotation.x = lerp(-swing, 0.28, st) * (1 - sl);
      cat.legBR.rotation.x = lerp(swing, 0.28, st) * (1 - sl);

      // Head pose (bobbing when shopping, tucked sideways when curled up asleep!)
      const shopBob = cat.state === 'SHOP' ? Math.sin(elapsed * 4.5 + cat.index) * 0.14 : 0;
      const lookAround = cat.state === 'SHOP' ? Math.sin(elapsed * 1.9 + cat.index) * 0.28 : 0;
      cat.headPivot.position.set(
        lerp(0, 0.07, sl),
        lerp(0.44, 0.27, sl),
        lerp(0.29, 0.19, sl)
      );
      cat.headPivot.rotation.set(
        lerp(shopBob, 0.34, sl) - st * 0.28,
        lerp(lookAround, -0.58, sl),
        lerp(0, 0.26, sl)
      );

      // Tail animation
      const tailSpeed = cat.state === 'CHASE' ? 11.5 : (cat.state === 'SHOP' ? 4.8 : 3.2);
      const tailSway = Math.sin(elapsed * tailSpeed + cat.index * 1.7) * (cat.state === 'CHASE' ? 0.45 : 0.24);
      cat.tailBase.rotation.x = lerp(-0.35 + st * 0.45, -1.48, sl);
      cat.tailBase.rotation.z = lerp(tailSway * (1 - st * 0.7), 1.12, sl);
      cat.tailTip.rotation.x = lerp(0.32 + Math.sin(elapsed * 14) * st * 0.12, 0.2, sl);
      cat.tailTip.rotation.z = lerp(tailSway * 0.85, 0.85, sl);

      // Sleeping Zzz spawning
      if (cat.state === 'SLEEP') {
        cat.zSpawnTimer -= dt;
        if (cat.zSpawnTimer <= 0) {
          cat.zSpawnTimer = 2.4 + rng() * 1.8;
          triggerEmote(cat, texEmoteZ, 1.8);
        }
      }

      // Emote sprite float & fade
      if (cat.emoteTimer > 0) {
        cat.emoteTimer -= dt;
        const prog = 1 - clamp(cat.emoteTimer / cat.emoteDuration, 0, 1);
        cat.emoteSprite.position.y = cat.emoteStartY + prog * 0.58;
        cat.emoteSprite.position.x = Math.sin(prog * Math.PI * 2) * 0.08;
        const fadeIn = smoothstep(0, 0.15, prog);
        const fadeOut = 1 - smoothstep(0.65, 1.0, prog);
        cat.emoteMat.opacity = fadeIn * fadeOut;
      } else {
        cat.emoteMat.opacity = 0;
      }

      // Commit world position inside islandRoot
      cat.group.position.set(cat.x, cat.y, cat.z);
      cat.group.rotation.y = cat.yaw;
    }
  }

  // =========================================================================
  // 9. CAMERA CONTROLLER: DRAG SPIN, PINCH/SCROLL ZOOM, TAP-TO-FOLLOW + UI
  // =========================================================================
  const MIN_ZOOM = 6.2;
  const MAX_ZOOM = 29.0;
  let targetAzimuth = 0.68;
  let targetPolar = 0.94;
  let targetZoom = 18.8;
  let azimuth = targetAzimuth;
  let polar = targetPolar;
  let zoom = targetZoom;

  const currentLookAt = new THREE.Vector3(0, 0.25, 0);
  const desiredLookAt = new THREE.Vector3(0, 0.25, 0);
  const tempVec = new THREE.Vector3();

  let followedCat = null;

  // UI DOM elements
  const followCard = document.getElementById('follow-card');
  const catSwatchEl = document.getElementById('cat-swatch');
  const catNameEl = document.getElementById('cat-name');
  const catStatusEl = document.getElementById('cat-status');
  const unfollowBtn = document.getElementById('unfollow-btn');
  const demoBadgeEl = document.getElementById('demo-badge');
  const timeButtons = Array.from(document.querySelectorAll('.time-btn'));

  function setTimeMode(mode) {
    if (!TIME_PRESETS[mode]) return;
    currentTimeMode = mode;
    timeButtons.forEach((btn) => {
      const active = btn.dataset.mode === mode;
      btn.classList.toggle('active', active);
      btn.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
  }

  function followCat(cat, fromDemo) {
    followedCat = cat;
    if (!cat) {
      followCard.classList.remove('active');
      followHaloGroup.visible = false;
      return;
    }
    catSwatchEl.style.background = cat.spec.base;
    catSwatchEl.textContent = cat.spec.isMayor ? '🎩' : '🐾';
    catNameEl.textContent = cat.spec.name;
    catStatusEl.textContent = cat.statusText;
    followCard.classList.add('active');
    followHaloGroup.visible = true;

    if (!fromDemo) {
      targetZoom = Math.min(targetZoom, 8.6);
      // Joyful tap reaction!
      cat.hopVel = cat.state === 'SLEEP' ? 0 : 2.8;
      triggerEmote(cat, texEmoteHeart, 1.7);
    }
  }

  // Time buttons click handlers
  timeButtons.forEach((btn) => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      cancelDemo();
      setTimeMode(btn.dataset.mode);
    });
  });

  unfollowBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    cancelDemo();
    followCat(null, false);
    targetZoom = Math.max(targetZoom, 17.5);
  });

  // Pointer, Touch Pinch & Wheel Handling
  const raycaster = new THREE.Raycaster();
  const pointerNdc = new THREE.Vector2();
  const activePointers = new Map();
  let isDragging = false;
  let wasPinching = false;
  let dragMoved = 0;
  let lastPtr = { x: 0, y: 0 };
  let pinchStartDist = 1;
  let pinchStartZoom = targetZoom;

  function getTwoPointerDist() {
    const pts = Array.from(activePointers.values());
    return Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
  }

  function handleCanvasTap(clientX, clientY) {
    const rect = renderer.domElement.getBoundingClientRect();
    pointerNdc.x = ((clientX - rect.left) / rect.width) * 2 - 1;
    pointerNdc.y = -((clientY - rect.top) / rect.height) * 2 + 1;
    raycaster.setFromCamera(pointerNdc, camera);

    const hits = raycaster.intersectObjects(catHitMeshes, false);
    if (hits.length > 0) {
      const idx = hits[0].object.userData.catIndex;
      if (typeof idx === 'number' && cats[idx]) {
        followCat(cats[idx], false);
        return;
      }
    }

    // If tapping open sky while following a cat, return to island overview
    if (followedCat) {
      const islandHits = raycaster.intersectObject(islandRoot, true);
      if (islandHits.length === 0) {
        followCat(null, false);
        targetZoom = Math.max(targetZoom, 17.0);
      }
    }
  }

  const domCanvas = renderer.domElement;

  domCanvas.addEventListener('pointerdown', (e) => {
    cancelDemo();
    e.preventDefault();
    try { domCanvas.setPointerCapture(e.pointerId); } catch (_) {}
    activePointers.set(e.pointerId, {
      x: e.clientX, y: e.clientY,
      startTime: performance.now()
    });
    if (activePointers.size === 1) {
      isDragging = true;
      wasPinching = false;
      dragMoved = 0;
      lastPtr = { x: e.clientX, y: e.clientY };
    } else if (activePointers.size === 2) {
      wasPinching = true;
      isDragging = false;
      pinchStartDist = Math.max(getTwoPointerDist(), 10);
      pinchStartZoom = targetZoom;
    }
  }, { passive: false });

  domCanvas.addEventListener('pointermove', (e) => {
    const p = activePointers.get(e.pointerId);
    if (!p) return;
    p.x = e.clientX;
    p.y = e.clientY;

    if (activePointers.size === 2) {
      const dist = Math.max(getTwoPointerDist(), 10);
      targetZoom = clamp(pinchStartZoom * (pinchStartDist / dist), MIN_ZOOM, MAX_ZOOM);
    } else if (activePointers.size === 1 && isDragging && !wasPinching) {
      const dx = e.clientX - lastPtr.x;
      const dy = e.clientY - lastPtr.y;
      dragMoved += Math.hypot(dx, dy);
      targetAzimuth -= dx * 0.0068;
      targetPolar = clamp(targetPolar - dy * 0.0056, 0.28, 1.44);
      lastPtr.x = e.clientX;
      lastPtr.y = e.clientY;
    }
  }, { passive: false });

  function onPointerFinish(e) {
    const p = activePointers.get(e.pointerId);
    activePointers.delete(e.pointerId);
    if (activePointers.size === 0) {
      if (!wasPinching && p && dragMoved < 12 && (performance.now() - p.startTime) < 460) {
        handleCanvasTap(e.clientX, e.clientY);
      }
      isDragging = false;
      wasPinching = false;
    }
  }
  domCanvas.addEventListener('pointerup', onPointerFinish);
  domCanvas.addEventListener('pointercancel', onPointerFinish);

  domCanvas.addEventListener('wheel', (e) => {
    cancelDemo();
    e.preventDefault();
    const step = Math.sign(e.deltaY) * Math.min(Math.abs(e.deltaY), 120) * 0.017;
    targetZoom = clamp(targetZoom + step, MIN_ZOOM, MAX_ZOOM);
  }, { passive: false });

  // =========================================================================
  // 10. #DEMO HANDS-FREE 20-SECOND SHOWCASE LOOP
  // =========================================================================
  const DEMO_DURATION = 20.0;
  let demoMode = false;
  let demoTime = 0;
  let demoPhase = -1;
  const demoFocusOffset = new THREE.Vector3(0, 0.25, 0);

  function checkDemoHash() {
    const h = (window.location.hash || '').toLowerCase();
    const href = (window.location.href || '').toLowerCase();
    if (h === '#demo' || href.endsWith('#demo')) {
      startDemo();
    }
  }

  function startDemo() {
    demoMode = true;
    demoTime = 0;
    demoPhase = -1;
    demoBadgeEl.classList.add('active');
    setTimeMode('day');
    followCat(null, true);
  }

  function cancelDemo() {
    if (!demoMode) return;
    demoMode = false;
    demoBadgeEl.classList.remove('active');
  }

  // Any real touch/pointer/wheel anywhere ends #demo immediately
  window.addEventListener('touchstart', (e) => { if (e.isTrusted) cancelDemo(); }, { passive: true, capture: true });
  window.addEventListener('pointerdown', (e) => { if (e.isTrusted) cancelDemo(); }, { passive: true, capture: true });
  window.addEventListener('wheel', (e) => { if (e.isTrusted) cancelDemo(); }, { passive: true, capture: true });
  window.addEventListener('hashchange', checkDemoHash);

  function updateDemo(dt) {
    if (!demoMode) return;
    demoTime = (demoTime + dt) % DEMO_DURATION;

    if (demoTime < 4.5) {
      // Phase 0: Bright Day establishing spin showing floating island & clouds below
      const u = demoTime / 4.5;
      if (demoPhase !== 0) {
        demoPhase = 0;
        setTimeMode('day');
        followCat(null, true);
      }
      targetAzimuth = lerp(0.55, 1.35, u);
      targetPolar = lerp(1.06, 0.86, u);
      targetZoom = lerp(19.6, 17.2, u);
      demoFocusOffset.set(0, 0.25, 0);
    } else if (demoTime < 9.2) {
      // Phase 1: Follow Mayor Marmalade (orange cat in tiny hat) & Fish Market
      const u = (demoTime - 4.5) / 4.7;
      if (demoPhase !== 1) {
        demoPhase = 1;
        setTimeMode('day');
        if (mayorCat) {
          // Gently steer mayor to market/square so striped awnings & hat shine together
          if (mayorCat.state === 'SLEEP') {
            mayorCat.state = 'WALK';
            mayorCat.targetNode = 1;
            mayorCat.targetX = WAYPOINTS[1].x;
            mayorCat.targetZ = WAYPOINTS[1].z;
          }
          followCat(mayorCat, true);
        }
      }
      targetAzimuth = lerp(1.35, 2.35, u);
      targetPolar = lerp(0.92, 1.02, u);
      targetZoom = lerp(8.4, 7.2, Math.sin(u * Math.PI));
    } else if (demoTime < 14.0) {
      // Phase 2: Sunset over Yarn Park, Pond Bridge & Rooftop Nappers
      const u = (demoTime - 9.2) / 4.8;
      if (demoPhase !== 2) {
        demoPhase = 2;
        followCat(null, true);
        setTimeMode('sunset');
      }
      targetAzimuth = lerp(2.35, 4.15, u);
      targetPolar = lerp(0.84, 0.94, u);
      targetZoom = lerp(13.8, 15.2, u);
      demoFocusOffset.set(lerp(2.0, 0.6, u), lerp(0.55, 0.45, u), lerp(-1.6, 1.2, u));
    } else if (demoTime < 18.6) {
      // Phase 3: Night — glowing cottage windows, market & bridge lanterns, stars & clouds
      const u = (demoTime - 14.0) / 4.6;
      if (demoPhase !== 3) {
        demoPhase = 3;
        followCat(null, true);
        setTimeMode('night');
      }
      targetAzimuth = lerp(4.15, 6.28 + 0.35, u);
      targetPolar = lerp(0.94, 1.15, u);
      targetZoom = lerp(15.2, 19.2, u);
      demoFocusOffset.set(lerp(0.6, 0, u), 0.3, lerp(1.2, 0, u));
    } else {
      // Phase 4: Seamless sunrise loop back to Day
      const u = (demoTime - 18.6) / 1.4;
      if (demoPhase !== 4) {
        demoPhase = 4;
        setTimeMode('day');
        followCat(null, true);
      }
      targetAzimuth = lerp(6.28 + 0.35, 6.28 + 0.55, u);
      targetPolar = lerp(1.15, 1.06, u);
      targetZoom = lerp(19.2, 19.6, u);
      demoFocusOffset.set(0, 0.25, 0);
    }
  }

  checkDemoHash();

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

  // =========================================================================
  // 11. MAIN ANIMATION LOOP
  // =========================================================================
  let lastTime = performance.now();
  let elapsed = 0;

  function updateEnvironment(dt) {
    const p = TIME_PRESETS[currentTimeMode];
    const k = dampFactor(2.4, dt);

    envState.skyTop.lerp(p.skyTop, k);
    envState.skyHorizon.lerp(p.skyHorizon, k);
    envState.skyBottom.lerp(p.skyBottom, k);
    envState.fogColor.lerp(p.fogColor, k);
    envState.fogDensity = lerp(envState.fogDensity, p.fogDensity, k);
    envState.dirColor.lerp(p.dirColor, k);
    envState.dirIntensity = lerp(envState.dirIntensity, p.dirIntensity, k);
    envState.dirPos.lerp(p.dirPos, k);
    envState.hemiSky.lerp(p.hemiSky, k);
    envState.hemiGround.lerp(p.hemiGround, k);
    envState.hemiIntensity = lerp(envState.hemiIntensity, p.hemiIntensity, k);
    envState.windowEmissive = lerp(envState.windowEmissive, p.windowEmissive, k);
    envState.windowTint.lerp(p.windowTint, k);
    envState.lanternEmissive = lerp(envState.lanternEmissive, p.lanternEmissive, k);
    envState.haloOpacity = lerp(envState.haloOpacity, p.haloOpacity, k);
    envState.pointIntensity = lerp(envState.pointIntensity, p.pointIntensity, k);
    envState.cloudColor.lerp(p.cloudColor, k);
    envState.waterColor.lerp(p.waterColor, k);
    envState.starOpacity = lerp(envState.starOpacity, p.starOpacity, k);
    envState.moonOpacity = lerp(envState.moonOpacity, p.moonOpacity, k);
    envState.sunColor.lerp(p.sunColor, k);
    envState.sunScale = lerp(envState.sunScale, p.sunScale, k);
    envState.fireflyOpacity = lerp(envState.fireflyOpacity, p.fireflyOpacity, k);
    envState.exposure = lerp(envState.exposure, p.exposure, k);

    // Apply to scene & shaders
    skyUniforms.uTopColor.value.copy(envState.skyTop);
    skyUniforms.uHorizonColor.value.copy(envState.skyHorizon);
    skyUniforms.uBottomColor.value.copy(envState.skyBottom);
    scene.fog.color.copy(envState.fogColor);
    scene.fog.density = envState.fogDensity;
    renderer.toneMappingExposure = envState.exposure;

    dirLight.color.copy(envState.dirColor);
    dirLight.intensity = envState.dirIntensity;
    dirLight.position.copy(envState.dirPos);
    hemiLight.color.copy(envState.hemiSky);
    hemiLight.groundColor.copy(envState.hemiGround);
    hemiLight.intensity = envState.hemiIntensity;

    // Glowing windows & lanterns
    for (let i = 0; i < glowingWindowMats.length; i++) {
      glowingWindowMats[i].emissiveIntensity = envState.windowEmissive;
    }
    const flicker = 1 + Math.sin(elapsed * 6.5) * 0.04;
    for (let i = 0; i < glowingLanternMats.length; i++) {
      glowingLanternMats[i].emissiveIntensity = envState.lanternEmissive * flicker;
    }
    for (let i = 0; i < lanternHaloSprites.length; i++) {
      lanternHaloSprites[i].opacity = envState.haloOpacity * (0.92 + Math.sin(elapsed * 4.2 + i) * 0.08);
    }
    for (let i = 0; i < warmNightLights.length; i++) {
      warmNightLights[i].intensity = envState.pointIntensity * (0.94 + Math.sin(elapsed * 5.0 + i * 1.3) * 0.06);
    }

    cloudMat.color.copy(envState.cloudColor);
    matWater.color.copy(envState.waterColor);

    // Stars, Sun & Moon
    starMat.opacity = envState.starOpacity;
    starGroup.visible = envState.starOpacity > 0.01;
    if (starGroup.visible) {
      for (let i = 0; i < starTwinkleData.length; i++) {
        const s = starTwinkleData[i];
        s.mesh.scale.setScalar(s.base * (0.72 + Math.sin(elapsed * s.speed + s.phase) * 0.35));
      }
    }

    sunMesh.position.copy(envState.dirPos).normalize().multiplyScalar(78);
    sunMesh.material.color.copy(envState.sunColor);
    sunMesh.scale.setScalar(envState.sunScale);
    sunMesh.visible = envState.sunScale > 0.05;

    moonGroup.position.set(-42, 46, 40);
    moonMat.opacity = envState.moonOpacity;
    moonHalo.material.opacity = envState.moonOpacity * 0.55;
    moonGroup.visible = envState.moonOpacity > 0.02;

    // Fireflies
    fireflyMat.opacity = envState.fireflyOpacity;
    for (let i = 0; i < fireflies.length; i++) {
      const f = fireflies[i];
      f.sprite.visible = envState.fireflyOpacity > 0.02;
      if (f.sprite.visible) {
        f.sprite.position.set(
          f.bx + Math.sin(elapsed * f.speed + f.phase) * 0.55,
          f.by + Math.sin(elapsed * f.speed * 1.4 + f.phase) * 0.35,
          f.bz + Math.cos(elapsed * f.speed * 0.9 + f.phase) * 0.55
        );
        const pulse = 0.25 + (Math.sin(elapsed * 4.5 + f.phase) * 0.5 + 0.5) * 0.26;
        f.sprite.scale.set(pulse, pulse, 1);
      }
    }
  }

  function animate(now) {
    requestAnimationFrame(animate);
    const dt = Math.min((now - lastTime) / 1000, 0.05);
    lastTime = now;
    elapsed += dt;

    // Gentle floating island breathing bob
    const islandBob = Math.sin(elapsed * 0.85) * 0.09;
    islandRoot.position.y = islandBob;

    // Satellite mini-islets bob
    for (let i = 0; i < satellites.length; i++) {
      const s = satellites[i];
      s.group.position.y = s.baseY + Math.sin(elapsed * 1.05 + s.phase) * 0.26;
      s.group.rotation.y += dt * 0.08;
    }

    // Drifting clouds below the island
    for (let i = 0; i < clouds.length; i++) {
      const c = clouds[i];
      c.group.position.x += c.speed * dt;
      if (c.group.position.x > CLOUD_SPAN) c.group.position.x = -CLOUD_SPAN;
      c.group.position.y = c.baseY + Math.sin(elapsed * 0.55 + c.bobPhase) * 0.24;
      // Soft scale fade at far edges so wrap is seamless
      const edgeFade = 1 - smoothstep(CLOUD_SPAN * 0.72, CLOUD_SPAN, Math.abs(c.group.position.x));
      c.group.scale.setScalar(c.baseScale * Math.max(0.01, edgeFade));
    }

    // Pond shimmering ripples, lily pads, koi fish & cascading pixel waterfall
    texWater.offset.x = (elapsed * 0.08) % 1;
    texWater.offset.y = (elapsed * 0.05) % 1;

    for (let i = 0; i < lilyPads.length; i++) {
      const lp = lilyPads[i];
      lp.group.position.y = lp.baseY + Math.sin(elapsed * 1.9 + lp.phase) * 0.018;
    }

    for (let i = 0; i < koiList.length; i++) {
      const k = koiList[i];
      const a = elapsed * k.spec.speed + k.spec.phase;
      const nx = k.spec.cx + Math.cos(a) * k.spec.rx;
      const nz = k.spec.cz + Math.sin(a) * k.spec.rz;
      const vx = -Math.sin(a) * k.spec.rx * k.spec.speed;
      const vz = Math.cos(a) * k.spec.rz * k.spec.speed;
      k.group.position.set(nx, -0.48 + Math.sin(elapsed * 2 + i) * 0.02, nz);
      k.group.rotation.y = Math.atan2(vx, vz);
      k.tail.rotation.y = Math.sin(elapsed * 10 + i) * 0.35;
    }

    for (let i = 0; i < waterfallDrops.length; i++) {
      const wd = waterfallDrops[i];
      wd.t = (wd.t + wd.speed * dt) % 1;
      const fallY = -0.22 - wd.t * wd.t * 5.6;
      const outZ = 6.52 + wd.t * 0.55;
      wd.mesh.position.set(4.0 + wd.offsetX, fallY, outZ);
      const s = 0.65 + (1 - wd.t) * 0.55;
      wd.mesh.scale.set(s, s * 1.2, s);
    }

    // Chimney smoke puffs
    for (let i = 0; i < smokePuffs.length; i++) {
      const sp = smokePuffs[i];
      sp.t = (sp.t + sp.speed * dt) % 1;
      sp.mesh.position.set(
        sp.em.x + sp.t * 0.65 + Math.sin(sp.t * 5 + i) * 0.08,
        sp.em.y + sp.t * 1.85,
        sp.em.z + Math.cos(sp.t * 4 + i) * 0.08
      );
      const sc = 0.55 + sp.t * 1.15;
      sp.mesh.scale.setScalar(sc);
      sp.mat.opacity = (1 - sp.t) * 0.45 * (1 - envState.moonOpacity * 0.35);
    }

    // Fluttering Pixel Butterflies
    for (let i = 0; i < butterflies.length; i++) {
      const bf = butterflies[i];
      const t = elapsed * bf.speed + bf.phase;
      const nx = bf.homeX + Math.sin(t) * bf.rx;
      const nz = bf.homeZ + Math.sin(t * 1.45) * bf.rz;
      const ny = 0.85 + Math.sin(t * 2.8) * 0.28;
      const vx = nx - bf.x;
      const vz = nz - bf.z;
      bf.x = nx; bf.y = ny; bf.z = nz;
      bf.group.position.set(nx, ny, nz);
      bf.group.rotation.y = Math.atan2(vx, vz);
      const flap = Math.sin(elapsed * 22 + bf.phase) * 0.78;
      bf.wingL.rotation.z = flap;
      bf.wingR.rotation.z = -flap;
      bf.group.visible = envState.moonOpacity < 0.75; // Butterflies rest at deep night!
    }

    // Update all 13 Cats
    updateCats(dt, elapsed);

    // Update Demo Mode Choreography
    updateDemo(dt);

    // Update Environment Lighting & Glows
    updateEnvironment(dt);

    // Update Follow Indicator & Camera
    if (followedCat) {
      followedCat.group.getWorldPosition(tempVec);
      desiredLookAt.set(tempVec.x, tempVec.y + 0.44, tempVec.z);

      // Keep follow ring centered under followed cat (in islandRoot coords)
      followHaloGroup.position.set(followedCat.x, followedCat.y, followedCat.z);
      followRing.rotation.z = elapsed * 1.4;
      followArrow.position.y = (followedCat.state === 'SLEEP' ? 0.92 : 1.18) + Math.sin(elapsed * 5.0) * 0.08;
      if (catStatusEl.textContent !== followedCat.statusText) {
        catStatusEl.textContent = followedCat.statusText;
      }
    } else if (demoMode) {
      desiredLookAt.set(demoFocusOffset.x, demoFocusOffset.y + islandBob, demoFocusOffset.z);
    } else {
      desiredLookAt.set(0, 0.25 + islandBob, 0);
    }

    const camK = dampFactor(7.5, dt);
    currentLookAt.lerp(desiredLookAt, camK);
    azimuth = lerp(azimuth, targetAzimuth, camK);
    polar = lerp(polar, targetPolar, camK);
    zoom = lerp(zoom, targetZoom, camK);

    const sinP = Math.sin(polar);
    camera.position.set(
      currentLookAt.x + zoom * sinP * Math.sin(azimuth),
      currentLookAt.y + zoom * Math.cos(polar),
      currentLookAt.z + zoom * sinP * Math.cos(azimuth)
    );
    camera.lookAt(currentLookAt);

    renderer.render(scene, camera);
  }

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