/* global React */
// =========================================================================
// MOUNTAIN SCENE — high-fidelity pixel art landscape with 8 variants.
// Single SVG scene rendered behind the desktop. Variant swaps palette + overlays.
// =========================================================================

const { useMemo: useScMemo } = React;

// ─── Deterministic pseudo-random ─────────────────────────────────────────
const rnd = (s) => { const x = Math.sin(s * 12.9898 + 78.233) * 43758.5453; return x - Math.floor(x); };

// ─── Midpoint-displaced jagged line ──────────────────────────────────────
function jagged(a, b, depth, amp, seed) {
  if (depth <= 0) return [a];
  const mx = (a[0] + b[0]) / 2;
  const my = (a[1] + b[1]) / 2 + (rnd(seed) - 0.5) * amp;
  const mid = [Math.round(mx), Math.round(my)];
  return [
    ...jagged(a, mid, depth - 1, amp * 0.55, seed * 1.7 + 1),
    ...jagged(mid, b, depth - 1, amp * 0.55, seed * 1.9 + 3),
  ];
}

function buildSilhouette(anchors, depth, amp, seedBase) {
  const pts = [];
  for (let i = 0; i < anchors.length - 1; i++) {
    pts.push(...jagged(anchors[i], anchors[i + 1], depth, amp, seedBase + i * 7.3));
  }
  pts.push(anchors[anchors.length - 1]);
  return pts;
}

// ─── Mountain anchors (shared across all variants) ───────────────────────
const BACK_ANCHORS = [
  [0, 116], [22, 102], [50, 110], [80, 96], [110, 104],
  [140, 90], [170, 100], [200, 88], [230, 102], [262, 92], [294, 104], [320, 100],
];

const MID_ANCHORS = [
  [0, 134], [18, 122], [38, 130], [62, 110], [88, 96], [110, 108],
  [134, 95], [162, 80], [188, 102], [212, 88], [240, 98], [268, 84], [296, 100], [320, 112],
];

const FRONT_ANCHORS = [
  [0, 178], [12, 158], [26, 138], [42, 118], [58, 92], [74, 64],
  [88, 36], [102, 22], [114, 32], [126, 56], [138, 80],
  [152, 102], [168, 122], [186, 138], [202, 130], [218, 116],
  [232, 100], [248, 82], [262, 64], [274, 78], [286, 100],
  [302, 124], [318, 148], [320, 168],
];

const BACK_PTS  = buildSilhouette(BACK_ANCHORS, 3, 4, 100);
const MID_PTS   = buildSilhouette(MID_ANCHORS, 4, 5, 200);
const FRONT_PTS = buildSilhouette(FRONT_ANCHORS, 4, 5, 300);

const polyStr = (pts, baseY) =>
  `0,${baseY} ${pts.map(p => `${p[0]},${p[1]}`).join(' ')} 320,${baseY}`;

// ─── Snow-cap polygons (drawn lighter on top of mountains) ───────────────
// Build a thin strip following the upper edge for portions where peaks rise high
function buildSnowCap(pts, thresholdY, offset) {
  const segs = [];
  let cur = null;
  pts.forEach((p, i) => {
    if (p[1] <= thresholdY) {
      if (!cur) cur = { top: [], bottom: [] };
      cur.top.push(p);
      cur.bottom.push([p[0], p[1] + offset + Math.round(rnd(i * 3) * 2)]);
    } else if (cur) {
      segs.push(cur); cur = null;
    }
  });
  if (cur) segs.push(cur);
  return segs.map(seg => [...seg.top, ...seg.bottom.reverse()].map(p => `${p[0]},${p[1]}`).join(' '));
}

const FRONT_SNOW = buildSnowCap(FRONT_PTS, 70, 8);
const MID_SNOW  = buildSnowCap(MID_PTS, 100, 6);

// ─── Forest row (dense pines) ────────────────────────────────────────────
function buildForest(count, baseY, minH, maxH, seedBase, jitterX = 4) {
  const trees = [];
  for (let i = 0; i < count; i++) {
    const x = Math.round((i / (count - 1)) * 320 + (rnd(seedBase + i) - 0.5) * jitterX);
    const h = Math.round(minH + rnd(seedBase + i * 1.7 + 50) * (maxH - minH));
    trees.push({ x, h, baseY });
  }
  return trees;
}
const FOREST_FAR = buildForest(70, 140, 6, 14, 400);
const FOREST_MID = buildForest(55, 152, 10, 22, 500);
const FOREST_NEAR = buildForest(45, 168, 14, 32, 600);

function PineTree({ x, h, baseY, color }) {
  const w = Math.max(4, Math.round(h * 0.45));
  // Triangle with a darker trunk pixel
  const path = `M ${x - w} ${baseY} L ${x} ${baseY - h} L ${x + w} ${baseY} Z`;
  return <path d={path} fill={color} />;
}

function ForestBand({ trees, color }) {
  return (
    <g>{trees.map((t, i) => <PineTree key={i} {...t} color={color} />)}</g>
  );
}

// ─── Palettes per variant ────────────────────────────────────────────────
const PALETTES = {
  night: {
    sky0:'#06081e', sky1:'#101542', sky2:'#1c2358',
    dither0:'#0a0d2e', dither1:'#161c4d',
    mtnBack:'#1a1f4a', mtnMid:'#0f1235', mtnFront:'#06081e',
    snow:'#3a3a78', forest0:'#0a0e25', forest1:'#06081a', forest2:'#04040f',
    ground:'#06081a', disc:'#fff4c4', discGlow:'rgba(255,244,196,0.18)',
  },
  sunset: {
    sky0:'#5a2b6e', sky1:'#a05690', sky2:'#e89b7a',
    dither0:'#7d3a82', dither1:'#c47388',
    mtnBack:'#7a4a8a', mtnMid:'#4e2a5a', mtnFront:'#2a142e',
    snow:'#e89b7a', forest0:'#1a0a25', forest1:'#0e0418', forest2:'#06010d',
    ground:'#48243a', disc:'#fff4dc', discGlow:'rgba(255,244,220,0.32)',
  },
  forest: {
    sky0:'#3a5a7a', sky1:'#7a9aaa', sky2:'#c0d4b0',
    dither0:'#5a7a92', dither1:'#9bb5b0',
    mtnBack:'#4a6a8a', mtnMid:'#2e4565', mtnFront:'#1a2a45',
    snow:'#e8f0f0', forest0:'#1f4a2a', forest1:'#143820', forest2:'#0a2515',
    ground:'#1f4a2a', disc:'#fff8b8', discGlow:'rgba(255,248,184,0.25)',
  },
  snow: {
    sky0:'#5a7a9a', sky1:'#9aaacc', sky2:'#dde8f0',
    dither0:'#7a90b0', dither1:'#bcccd8',
    mtnBack:'#6a82a0', mtnMid:'#4a6285', mtnFront:'#2a3a55',
    snow:'#ffffff', forest0:'#2a3a55', forest1:'#1a2540', forest2:'#0a1530',
    ground:'#dde8f0', disc:'#fff8e8', discGlow:'rgba(255,248,232,0.28)',
  },
  fire: {
    sky0:'#08081f', sky1:'#1a1240', sky2:'#2a1f55',
    dither0:'#0e0e2f', dither1:'#221848',
    mtnBack:'#2a2055', mtnMid:'#16103a', mtnFront:'#08081f',
    snow:'#4a3a78', forest0:'#0a0820', forest1:'#050415', forest2:'#02020a',
    ground:'#0a0820', disc:'#fff4c4', discGlow:'rgba(255,244,196,0.15)',
  },
  coffee: {
    sky0:'#5a3a4a', sky1:'#a85f5a', sky2:'#e8a890',
    dither0:'#824a52', dither1:'#cd877a',
    mtnBack:'#7a4a5a', mtnMid:'#502a3a', mtnFront:'#2a1525',
    snow:'#e8a890', forest0:'#1a0a15', forest1:'#0e040a', forest2:'#060105',
    ground:'#3a1f2a', disc:'#fff4d4', discGlow:'rgba(255,244,212,0.3)',
  },
  rain: {
    sky0:'#1a2a45', sky1:'#3a4a6a', sky2:'#5a6a8a',
    dither0:'#2a3a55', dither1:'#4a5a7a',
    mtnBack:'#3a4868', mtnMid:'#222f4a', mtnFront:'#0e1525',
    snow:'#7a8aa8', forest0:'#0a1525', forest1:'#050a15', forest2:'#02050a',
    ground:'#0a1525', disc:'#7a8aa8', discGlow:'rgba(122,138,168,0.15)',
  },
  space: {
    sky0:'#020010', sky1:'#0a0220', sky2:'#180a35',
    dither0:'#05011a', dither1:'#10052a',
    mtnBack:'#2a1545', mtnMid:'#1a0a25', mtnFront:'#050010',
    snow:'#6a4a85', forest0:'#020005', forest1:'#000003', forest2:'#000002',
    ground:'#020005', disc:'#fff4c4', discGlow:'rgba(255,244,196,0.2)',
  },
};

// ─── Dither patterns (defined once, swapped via fill) ────────────────────
function DitherDefs({ id, color }) {
  // 50% checkerboard
  return (
    <pattern id={id} x="0" y="0" width="2" height="2" patternUnits="userSpaceOnUse">
      <rect width="1" height="1" fill={color} />
      <rect x="1" y="1" width="1" height="1" fill={color} />
    </pattern>
  );
}

function DitherSparse({ id, color }) {
  // 25% — every 4th
  return (
    <pattern id={id} x="0" y="0" width="4" height="4" patternUnits="userSpaceOnUse">
      <rect width="1" height="1" fill={color} />
      <rect x="2" y="2" width="1" height="1" fill={color} />
    </pattern>
  );
}

function DitherDense({ id, color }) {
  // 75% — inverse sparse
  return (
    <pattern id={id} x="0" y="0" width="4" height="4" patternUnits="userSpaceOnUse">
      <rect width="4" height="4" fill={color} />
      <rect x="1" y="1" width="1" height="1" fill="transparent" />
      <rect x="3" y="3" width="1" height="1" fill="transparent" />
    </pattern>
  );
}

// ─── Sky with dithered transitions ───────────────────────────────────────
function Sky({ p }) {
  return (
    <g>
      <rect width="320" height="180" fill={p.sky0} />
      {/* dither band sky0 → sky1 (4 progressive levels) */}
      <rect y="30" width="320" height="3" fill={`url(#dith-a)`} />
      <rect y="33" width="320" height="3" fill={`url(#dith-b)`} />
      <rect y="36" width="320" height="3" fill={`url(#dith-c)`} />
      {/* solid sky1 mid band */}
      <rect y="39" width="320" height="28" fill={p.sky1} />
      {/* dither sky1 → sky2 */}
      <rect y="67" width="320" height="3" fill={`url(#dith-d)`} />
      <rect y="70" width="320" height="3" fill={`url(#dith-e)`} />
      <rect y="73" width="320" height="3" fill={`url(#dith-f)`} />
      {/* solid sky2 lower */}
      <rect y="76" width="320" height="46" fill={p.sky2} />
    </g>
  );
}

// ─── Sun / Moon disc (pixel-art circle built from rects) ─────────────────
function Disc({ p, cx, cy, r, glow = true }) {
  const pixels = [];
  for (let dy = -r; dy <= r; dy++) {
    for (let dx = -r; dx <= r; dx++) {
      if (dx * dx + dy * dy <= r * r) {
        pixels.push([cx + dx, cy + dy]);
      }
    }
  }
  const glowR = r + 3;
  const glowPixels = [];
  if (glow) {
    for (let dy = -glowR; dy <= glowR; dy++) {
      for (let dx = -glowR; dx <= glowR; dx++) {
        const dist = dx * dx + dy * dy;
        if (dist > r * r && dist <= glowR * glowR) {
          glowPixels.push([cx + dx, cy + dy]);
        }
      }
    }
  }
  return (
    <g>
      {glow && glowPixels.map(([px, py], i) => (
        <rect key={`g${i}`} x={px} y={py} width="1" height="1" fill={p.discGlow} />
      ))}
      {pixels.map(([px, py], i) => (
        <rect key={i} x={px} y={py} width="1" height="1" fill={p.disc} />
      ))}
      {/* crater pixels */}
      <rect x={cx - 3} y={cy - 1} width="2" height="2" fill={p.disc} opacity="0.55" />
      <rect x={cx + 2} y={cy - 3} width="2" height="1" fill={p.disc} opacity="0.5" />
      <rect x={cx - 1} y={cy + 2} width="1" height="1" fill={p.disc} opacity="0.45" />
      <rect x={cx + 1} y={cy + 4} width="2" height="2" fill={p.disc} opacity="0.5" />
    </g>
  );
}

// ─── Stars overlay (for night / fire / space) ────────────────────────────
const STAR_FIELD = Array.from({ length: 110 }, (_, i) => ({
  x: Math.round(rnd(i * 1.3) * 320),
  y: Math.round(rnd(i * 2.7 + 1) * 80),
  size: rnd(i * 3.1 + 2) > 0.92 ? 2 : 1,
  hue: rnd(i * 4.7 + 3),
  d: rnd(i * 5.3 + 7) * 3,
}));

function Stars({ animOn, dense = false }) {
  const field = dense ? STAR_FIELD : STAR_FIELD.slice(0, 60);
  return (
    <g>
      {field.map((s, i) => {
        const color = s.hue > 0.93 ? '#ff8fb8' : s.hue > 0.85 ? '#a8b8ff' : '#f6ecd6';
        return (
          <rect key={i} x={s.x} y={s.y} width={s.size} height={s.size} fill={color}>
            {animOn && <animate attributeName="opacity" values="0.3;1;0.3" dur={`${2 + s.d}s`} repeatCount="indefinite" begin={`${s.d}s`} />}
          </rect>
        );
      })}
    </g>
  );
}

// ─── Rain overlay ────────────────────────────────────────────────────────
const RAIN_STREAKS = Array.from({ length: 90 }, (_, i) => ({
  x: Math.round(rnd(i * 1.4) * 320),
  y: Math.round(rnd(i * 2.3) * 120),
  len: 4 + Math.floor(rnd(i * 3.1) * 4),
  dur: 0.5 + rnd(i * 4.7) * 0.4,
  delay: rnd(i * 5.3) * 1.5,
}));

function Rain({ animOn, color = '#aac0d8' }) {
  return (
    <g opacity="0.7">
      {RAIN_STREAKS.map((s, i) => (
        <rect key={i} x={s.x} y={s.y} width="1" height={s.len} fill={color}>
          {animOn && (
            <>
              <animate attributeName="y" from={s.y - 30} to={180} dur={`${s.dur}s`} repeatCount="indefinite" begin={`${s.delay}s`} />
              <animate attributeName="opacity" values="0;0.8;0.8;0" dur={`${s.dur}s`} repeatCount="indefinite" begin={`${s.delay}s`} />
            </>
          )}
        </rect>
      ))}
    </g>
  );
}

// ─── Snow overlay ────────────────────────────────────────────────────────
const SNOW_FLAKES = Array.from({ length: 70 }, (_, i) => ({
  x: Math.round(rnd(i * 1.7) * 320),
  y: Math.round(rnd(i * 2.4) * 130),
  size: rnd(i * 3.3) > 0.7 ? 2 : 1,
  dur: 3 + rnd(i * 4.1) * 4,
  delay: rnd(i * 5.7) * 4,
  drift: (rnd(i * 6.7) - 0.5) * 12,
}));

function SnowOverlay({ animOn }) {
  return (
    <g>
      {SNOW_FLAKES.map((s, i) => (
        <rect key={i} x={s.x} y={s.y} width={s.size} height={s.size} fill="#ffffff">
          {animOn && (
            <>
              <animate attributeName="y" from="-4" to="180" dur={`${s.dur}s`} repeatCount="indefinite" begin={`${s.delay}s`} />
              <animate attributeName="x" values={`${s.x};${s.x + s.drift};${s.x}`} dur={`${s.dur}s`} repeatCount="indefinite" begin={`${s.delay}s`} />
            </>
          )}
        </rect>
      ))}
    </g>
  );
}

// ─── Cabin + Fire overlay (pixel-art) ────────────────────────────────────
function CabinFire({ animOn }) {
  return (
    <g>
      {/* cabin body */}
      <g transform="translate(120, 130)">
        {/* pixel roof — stepped triangle */}
        <rect x="6" y="0" width="20" height="2" fill="#5a3828" />
        <rect x="4" y="2" width="24" height="2" fill="#5a3828" />
        <rect x="2" y="4" width="28" height="2" fill="#5a3828" />
        <rect x="0" y="6" width="32" height="2" fill="#5a3828" />
        <rect x="-2" y="8" width="36" height="2" fill="#5a3828" />
        <rect x="-2" y="10" width="36" height="2" fill="#4a2e1e" />
        {/* roof highlight */}
        <rect x="6" y="0" width="20" height="1" fill="#6a4838" />
        <rect x="4" y="2" width="24" height="1" fill="#6a4838" />
        {/* walls */}
        <rect x="0" y="12" width="32" height="22" fill="#4a2e1e" />
        {/* log lines */}
        <rect x="0" y="14" width="32" height="1" fill="#3a2418" />
        <rect x="0" y="18" width="32" height="1" fill="#3a2418" />
        <rect x="0" y="22" width="32" height="1" fill="#3a2418" />
        <rect x="0" y="26" width="32" height="1" fill="#3a2418" />
        <rect x="0" y="30" width="32" height="1" fill="#3a2418" />
        {/* door */}
        <rect x="13" y="22" width="7" height="12" fill="#1a0e08" />
        <rect x="13" y="22" width="7" height="1" fill="#2a1810" />
        <rect x="17" y="27" width="1" height="2" fill="#ffe8a3" />
        {/* windows */}
        <rect x="3" y="15" width="6" height="5" fill="#ffe8a3" />
        <rect x="6" y="15" width="1" height="5" fill="#ffd070" />
        <rect x="3" y="17" width="6" height="1" fill="#ffd070" />
        <rect x="24" y="15" width="6" height="5" fill="#ffe8a3" />
        <rect x="27" y="15" width="1" height="5" fill="#ffd070" />
        <rect x="24" y="17" width="6" height="1" fill="#ffd070" />
        {/* chimney */}
        <rect x="22" y="-4" width="4" height="6" fill="#3a2418" />
        <rect x="22" y="-4" width="4" height="1" fill="#4a2e1e" />
        {/* smoke pixels */}
        {animOn && (
          <>
            <rect x="23" y="-8" width="2" height="2" fill="#aabbc8" opacity="0.5">
              <animate attributeName="y" values="-5;-18;-28" dur="3s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="0;0.4;0" dur="3s" repeatCount="indefinite" />
            </rect>
            <rect x="22" y="-10" width="2" height="2" fill="#8a9aac" opacity="0.35">
              <animate attributeName="y" values="-7;-22;-34" dur="3.5s" repeatCount="indefinite" begin="0.5s" />
              <animate attributeName="opacity" values="0;0.3;0" dur="3.5s" repeatCount="indefinite" begin="0.5s" />
            </rect>
          </>
        )}
      </g>

      {/* campfire — pixel art */}
      <g transform="translate(180, 158)">
        {/* stone ring */}
        <rect x="-7" y="6" width="2" height="2" fill="#4a4a5a" />
        <rect x="-4" y="7" width="2" height="2" fill="#3a3a4a" />
        <rect x="-1" y="8" width="2" height="2" fill="#4a4a5a" />
        <rect x="2" y="7" width="2" height="2" fill="#3a3a4a" />
        <rect x="5" y="6" width="2" height="2" fill="#4a4a5a" />
        {/* logs */}
        <rect x="-5" y="4" width="10" height="2" fill="#3a2418" />
        <rect x="-4" y="2" width="3" height="2" fill="#5a3828" />
        <rect x="2" y="2" width="3" height="2" fill="#5a3828" />
        {/* ground glow — pixel dither */}
        <rect x="-10" y="9" width="2" height="1" fill="#ff8040" opacity="0.2" />
        <rect x="-6" y="10" width="2" height="1" fill="#ff8040" opacity="0.3" />
        <rect x="6" y="10" width="2" height="1" fill="#ff8040" opacity="0.3" />
        <rect x="9" y="9" width="2" height="1" fill="#ff8040" opacity="0.2" />
        {animOn ? (
          <g>
            {/* outer flame pixels (toggling positions) */}
            <rect x="-3" y="0" width="2" height="2" fill="#ff5c40">
              <animate attributeName="y" values="0;-1;0" dur="0.4s" repeatCount="indefinite" />
            </rect>
            <rect x="1" y="-1" width="2" height="2" fill="#ff5c40">
              <animate attributeName="y" values="-1;0;-1" dur="0.35s" repeatCount="indefinite" />
            </rect>
            <rect x="-2" y="-3" width="2" height="2" fill="#ff8040">
              <animate attributeName="y" values="-3;-4;-3" dur="0.3s" repeatCount="indefinite" />
            </rect>
            <rect x="1" y="-4" width="2" height="2" fill="#ff8040">
              <animate attributeName="y" values="-4;-3;-4" dur="0.38s" repeatCount="indefinite" />
            </rect>
            {/* tip flame */}
            <rect x="-1" y="-6" width="2" height="2" fill="#ffd040">
              <animate attributeName="y" values="-6;-8;-6" dur="0.5s" repeatCount="indefinite" />
            </rect>
            <rect x="0" y="-8" width="1" height="1" fill="#fff4a0">
              <animate attributeName="y" values="-8;-10;-8" dur="0.45s" repeatCount="indefinite" />
            </rect>
            {/* inner bright core */}
            <rect x="-1" y="-2" width="2" height="2" fill="#ffd040">
              <animate attributeName="opacity" values="1;0.7;1" dur="0.3s" repeatCount="indefinite" />
            </rect>
            {/* sparks */}
            <rect x="1" y="-6" width="1" height="1" fill="#fff4a0">
              <animate attributeName="y" values="-6;-16;-24" dur="1.4s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="0;1;0" dur="1.4s" repeatCount="indefinite" />
            </rect>
            <rect x="-3" y="-4" width="1" height="1" fill="#ff8040">
              <animate attributeName="y" values="-4;-14;-22" dur="1.8s" repeatCount="indefinite" begin="0.4s" />
              <animate attributeName="opacity" values="0;1;0" dur="1.8s" repeatCount="indefinite" begin="0.4s" />
            </rect>
          </g>
        ) : (
          <g>
            <rect x="-2" y="-2" width="2" height="2" fill="#ff5c40" />
            <rect x="0" y="-4" width="2" height="2" fill="#ff8040" />
            <rect x="-1" y="-6" width="2" height="2" fill="#ffd040" />
          </g>
        )}
      </g>
    </g>
  );
}

// ─── Coffee mug overlay (foreground) ─────────────────────────────────────
function CoffeeMug({ animOn }) {
  return (
    <g transform="translate(150, 124)">
      {/* wooden table */}
      <rect x="-70" y="46" width="140" height="2" fill="#5a3a28" />
      <rect x="-70" y="48" width="140" height="14" fill="#3a2418" />
      <rect x="-70" y="48" width="140" height="1" fill="#4a2e1e" />
      <rect x="-50" y="54" width="40" height="1" fill="#4a2e1e" opacity="0.6" />
      <rect x="10" y="56" width="50" height="1" fill="#4a2e1e" opacity="0.6" />

      {/* mug shadow */}
      <ellipse cx="0" cy="46" rx="28" ry="3" fill="#1a0e08" opacity="0.5" />

      {/* mug body */}
      <rect x="-18" y="22" width="36" height="24" fill="#f6ecd6" />
      <rect x="-18" y="22" width="36" height="2" fill="#dccab0" />
      <rect x="-18" y="42" width="36" height="2" fill="#a89880" />
      <rect x="-18" y="44" width="36" height="2" fill="#5a4a30" />
      <rect x="-16" y="20" width="32" height="2" fill="#dccab0" />
      <rect x="-16" y="20" width="32" height="1" fill="#f6ecd6" />
      {/* coffee surface */}
      <rect x="-15" y="22" width="30" height="3" fill="#3a1f10" />
      <rect x="-15" y="22" width="30" height="1" fill="#5a3018" />
      <rect x="-8" y="23" width="6" height="1" fill="#7a4a28" />

      {/* handle */}
      <rect x="18" y="28" width="2" height="10" fill="#dccab0" />
      <rect x="20" y="28" width="4" height="2" fill="#dccab0" />
      <rect x="20" y="36" width="4" height="2" fill="#dccab0" />
      <rect x="22" y="30" width="2" height="6" fill="#dccab0" />
      <rect x="22" y="30" width="2" height="6" fill="transparent" stroke="none" />

      {/* steam */}
      {animOn && (
        <g>
          <path d="M -6,16 Q -8,12 -4,8 Q -2,4 -6,0" stroke="#f6ecd6" strokeWidth="1.5" fill="none" opacity="0.7">
            <animate attributeName="opacity" values="0;0.7;0" dur="2.5s" repeatCount="indefinite" />
            <animateTransform attributeName="transform" type="translate" values="0 0; 0 -8; 0 -16" dur="2.5s" repeatCount="indefinite" />
          </path>
          <path d="M 2,16 Q 4,12 0,8 Q -2,4 2,0" stroke="#f6ecd6" strokeWidth="1.5" fill="none" opacity="0.7">
            <animate attributeName="opacity" values="0;0.6;0" dur="3s" repeatCount="indefinite" begin="0.8s" />
            <animateTransform attributeName="transform" type="translate" values="0 0; 0 -10; 0 -18" dur="3s" repeatCount="indefinite" begin="0.8s" />
          </path>
          <path d="M 7,16 Q 9,12 5,8 Q 3,4 7,0" stroke="#f6ecd6" strokeWidth="1.5" fill="none" opacity="0.6">
            <animate attributeName="opacity" values="0;0.6;0" dur="2.8s" repeatCount="indefinite" begin="1.6s" />
            <animateTransform attributeName="transform" type="translate" values="0 0; 0 -9; 0 -17" dur="2.8s" repeatCount="indefinite" begin="1.6s" />
          </path>
        </g>
      )}
    </g>
  );
}

// ─── Space overlay (planets, nebula, comet) — pixel-art style ────────────
function SpaceStuff({ animOn }) {
  // pixel-art nebula: scattered single-pixel dots instead of smooth ellipses
  const nebulaA = [];
  for (let i = 0; i < 40; i++) {
    const x = Math.round(20 + rnd(i * 1.2 + 700) * 80);
    const y = Math.round(30 + rnd(i * 2.3 + 701) * 40);
    const c = rnd(i * 3.4 + 702) > 0.5 ? '#c490e4' : '#ff8fb8';
    nebulaA.push({ x, y, c });
  }
  const nebulaB = [];
  for (let i = 0; i < 30; i++) {
    const x = Math.round(200 + rnd(i * 1.5 + 800) * 80);
    const y = Math.round(25 + rnd(i * 2.6 + 801) * 35);
    const c = rnd(i * 3.7 + 802) > 0.5 ? '#7de2d1' : '#a890e4';
    nebulaB.push({ x, y, c });
  }

  // pixel-art planet body (circle of rects, r=14)
  const planetR = 14;
  const planetPixels = [];
  for (let dy = -planetR; dy <= planetR; dy++) {
    for (let dx = -planetR; dx <= planetR; dx++) {
      if (dx * dx + dy * dy <= planetR * planetR) {
        const band = dy + planetR;
        let color;
        if (band < 6) color = '#e87fa8';
        else if (band < 12) color = '#ff8fb8';
        else if (band < 18) color = '#c490e4';
        else if (band < 24) color = '#ff8fb8';
        else color = '#e87fa8';
        planetPixels.push({ dx, dy, color });
      }
    }
  }

  // pixel-art ring (flat ellipse of rects)
  const ringPixels = [];
  for (let dx = -28; dx <= 28; dx++) {
    const ry = Math.round(3 * Math.sqrt(1 - (dx * dx) / (28 * 28)));
    for (let dy = -ry; dy <= ry; dy++) {
      if (dx * dx + dy * dy > planetR * planetR) {
        const c = Math.abs(dy) === 0 ? '#ff8040' : '#ffd070';
        ringPixels.push({ dx, dy, c });
      }
    }
  }

  // pixel-art small moon (r=5)
  const moonR = 5;
  const moonPixels = [];
  for (let dy = -moonR; dy <= moonR; dy++) {
    for (let dx = -moonR; dx <= moonR; dx++) {
      if (dx * dx + dy * dy <= moonR * moonR) {
        moonPixels.push([dx, dy]);
      }
    }
  }

  return (
    <g>
      {/* nebula pixel clouds */}
      {nebulaA.map((n, i) => (
        <rect key={`na${i}`} x={n.x} y={n.y} width="1" height="1" fill={n.c} opacity="0.35" />
      ))}
      {nebulaB.map((n, i) => (
        <rect key={`nb${i}`} x={n.x} y={n.y} width="1" height="1" fill={n.c} opacity="0.3" />
      ))}

      <Stars animOn={animOn} dense={true} />

      {/* ringed planet — pixel art */}
      <g transform="translate(240, 78)">
        {/* ring behind planet */}
        {ringPixels.filter(p => p.dy > 0).map((p, i) => (
          <rect key={`rb${i}`} x={p.dx} y={p.dy} width="1" height="1" fill={p.c} opacity="0.7" />
        ))}
        {/* planet body */}
        {planetPixels.map((p, i) => (
          <rect key={`pp${i}`} x={p.dx} y={p.dy} width="1" height="1" fill={p.color} />
        ))}
        {/* surface detail */}
        <rect x="-6" y="-3" width="3" height="1" fill="#fff4dc" opacity="0.5" />
        <rect x="3" y="2" width="2" height="1" fill="#ff5c40" opacity="0.7" />
        <rect x="-2" y="5" width="3" height="1" fill="#ff5c40" opacity="0.6" />
        {/* ring in front */}
        {ringPixels.filter(p => p.dy <= 0).map((p, i) => (
          <rect key={`rf${i}`} x={p.dx} y={p.dy} width="1" height="1" fill={p.c} opacity="0.7" />
        ))}
      </g>

      {/* small moon — pixel art */}
      <g transform="translate(50, 30)">
        {moonPixels.map(([dx, dy], i) => (
          <rect key={`m${i}`} x={dx} y={dy} width="1" height="1" fill="#dde8f0" />
        ))}
        <rect x="-2" y="-1" width="2" height="1" fill="#a0a8c0" />
        <rect x="1" y="1" width="1" height="1" fill="#a0a8c0" />
        <rect x="-1" y="3" width="2" height="1" fill="#a0a8c0" />
      </g>

      {/* comet streaking */}
      {animOn && (
        <g>
          <rect x="0" y="0" width="2" height="2" fill="#fff4dc">
            <animateTransform attributeName="transform" type="translate" from="-20,80" to="340,30" dur="8s" repeatCount="indefinite" />
          </rect>
          <rect x="-4" y="1" width="4" height="1" fill="#ff8fb8" opacity="0.7">
            <animateTransform attributeName="transform" type="translate" from="-20,80" to="340,30" dur="8s" repeatCount="indefinite" />
          </rect>
          <rect x="-10" y="1" width="6" height="1" fill="#c490e4" opacity="0.4">
            <animateTransform attributeName="transform" type="translate" from="-20,80" to="340,30" dur="8s" repeatCount="indefinite" />
          </rect>
        </g>
      )}

      {/* tiny satellite blinking */}
      {animOn && (
        <rect x="160" y="38" width="2" height="2" fill="#ff5c40">
          <animate attributeName="opacity" values="0;1;0" dur="1.5s" repeatCount="indefinite" />
        </rect>
      )}
    </g>
  );
}

// ─── Lightning flash for rain ────────────────────────────────────────────
function LightningFlash({ animOn }) {
  if (!animOn) return null;
  return (
    <rect width="320" height="180" fill="#f6f4ff" opacity="0">
      <animate attributeName="opacity"
        values="0;0;0;0;0;0;0.8;0;0.3;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0"
        dur="14s" repeatCount="indefinite" />
    </rect>
  );
}

// ─── Birds for sunset / forest ───────────────────────────────────────────
function Birds({ animOn, color = '#1a1230' }) {
  if (!animOn) return null;
  return (
    <g fill={color}>
      <g>
        <path d="M 0,0 L 2,-2 L 4,0 M 4,0 L 6,-2 L 8,0" stroke={color} strokeWidth="0.8" fill="none">
          <animateTransform attributeName="transform" type="translate" from="-10,40" to="330,50" dur="22s" repeatCount="indefinite" />
        </path>
      </g>
      <g>
        <path d="M 0,0 L 2,-2 L 4,0 M 4,0 L 6,-2 L 8,0" stroke={color} strokeWidth="0.8" fill="none">
          <animateTransform attributeName="transform" type="translate" from="-10,55" to="330,42" dur="28s" repeatCount="indefinite" begin="5s" />
        </path>
      </g>
      <g>
        <path d="M 0,0 L 2,-2 L 4,0" stroke={color} strokeWidth="0.8" fill="none">
          <animateTransform attributeName="transform" type="translate" from="-10,32" to="330,38" dur="34s" repeatCount="indefinite" begin="11s" />
        </path>
      </g>
    </g>
  );
}

// ─── Foreground (water/ground) ───────────────────────────────────────────
function Foreground({ p, variant }) {
  // bottom strip with subtle dither
  if (variant === 'snow') {
    return (
      <g>
        <rect y="156" width="320" height="24" fill={p.ground} />
        <rect y="154" width="320" height="2" fill="url(#dith-g)" />
        {/* footprints */}
        <rect x="40" y="164" width="2" height="1" fill="#a8b8c8" />
        <rect x="44" y="166" width="2" height="1" fill="#a8b8c8" />
        <rect x="48" y="164" width="2" height="1" fill="#a8b8c8" />
        <rect x="52" y="166" width="2" height="1" fill="#a8b8c8" />
      </g>
    );
  }
  return (
    <g>
      <rect y="158" width="320" height="22" fill={p.ground} />
      <rect y="156" width="320" height="2" fill="url(#dith-g)" />
    </g>
  );
}

// ─── Main scene ──────────────────────────────────────────────────────────
function MountainScene({ variant = 'night', animOn = true }) {
  const p = PALETTES[variant] || PALETTES.night;
  const showDisc = variant !== 'rain' && variant !== 'space';
  // disc position varies per variant
  const discCfg = {
    night:  { cx: 256, cy: 26, r: 10, glow: true },
    sunset: { cx: 270, cy: 32, r: 12, glow: true },
    forest: { cx: 50,  cy: 28, r: 9,  glow: true },
    snow:   { cx: 260, cy: 24, r: 9,  glow: true },
    fire:   { cx: 268, cy: 22, r: 8,  glow: true },
    coffee: { cx: 245, cy: 30, r: 11, glow: true },
    rain:   null,
    space:  null,
  }[variant];

  return (
    <svg
      viewBox="0 0 320 180"
      preserveAspectRatio="xMidYMid slice"
      shapeRendering="crispEdges"
      style={{ width: '100%', height: '100%', display: 'block', imageRendering: 'pixelated' }}>
      <defs>
        <DitherSparse id="dith-a" color={p.sky1} />
        <DitherDefs    id="dith-b" color={p.sky1} />
        <DitherDense   id="dith-c" color={p.sky1} />
        <DitherSparse id="dith-d" color={p.sky2} />
        <DitherDefs    id="dith-e" color={p.sky2} />
        <DitherDense   id="dith-f" color={p.sky2} />
        <DitherDefs    id="dith-g" color={p.ground} />
      </defs>

      <Sky p={p} />
      {variant === 'space' && <SpaceStuff animOn={animOn} />}
      {(variant === 'night' || variant === 'fire' || variant === 'coffee') && (
        <Stars animOn={animOn} dense={variant === 'night' || variant === 'fire'} />
      )}
      {showDisc && discCfg && <Disc p={p} {...discCfg} />}

      {/* mountains */}
      <polygon points={polyStr(BACK_PTS, 180)} fill={p.mtnBack} />

      {/* mid snow */}
      <polygon points={polyStr(MID_PTS, 180)} fill={p.mtnMid} />
      {variant === 'snow' && MID_SNOW.map((pts, i) => (
        <polygon key={`ms-${i}`} points={pts} fill={p.snow} opacity="0.85" />
      ))}

      {/* front mountain */}
      <polygon points={polyStr(FRONT_PTS, 180)} fill={p.mtnFront} />
      {(variant === 'snow' || variant === 'sunset' || variant === 'forest') && FRONT_SNOW.map((pts, i) => (
        <polygon key={`fs-${i}`} points={pts} fill={p.snow} opacity={variant === 'snow' ? 0.95 : 0.6} />
      ))}

      {/* forest bands */}
      <ForestBand trees={FOREST_FAR} color={p.forest0} />
      <ForestBand trees={FOREST_MID} color={p.forest1} />
      <ForestBand trees={FOREST_NEAR} color={p.forest2} />

      {/* snow drift on forest for snow variant */}
      {variant === 'snow' && (
        <g opacity="0.6">
          {FOREST_NEAR.filter((_, i) => i % 2 === 0).map((t, i) => (
            <rect key={i} x={t.x - 2} y={t.baseY - t.h - 1} width="4" height="2" fill="#ffffff" />
          ))}
        </g>
      )}

      <Foreground p={p} variant={variant} />

      {/* overlays */}
      {variant === 'rain' && <Rain animOn={animOn} color="#aac0d8" />}
      {variant === 'rain' && <LightningFlash animOn={animOn} />}
      {variant === 'snow' && <SnowOverlay animOn={animOn} />}
      {variant === 'fire' && <CabinFire animOn={animOn} />}
      {variant === 'coffee' && <CoffeeMug animOn={animOn} />}
      {variant === 'sunset' && <Birds animOn={animOn} color="#1a0a25" />}
      {variant === 'forest' && <Birds animOn={animOn} color="#0a1a08" />}
    </svg>
  );
}

// ─── Compact preview (for ambience cards) ────────────────────────────────
function ScenePreview({ variant, animOn = true }) {
  return (
    <div style={{ width: '100%', height: '100%', position: 'relative', overflow: 'hidden' }}>
      <MountainScene variant={variant} animOn={animOn} />
    </div>
  );
}

Object.assign(window, { MountainScene, ScenePreview, PALETTES });
