#!/usr/bin/env python3
"""Classic Windows XP / 95 Screen Savers:
- 3D Maze (OpenGL 3.3 Core Profile, procedural brick/wood/plaster textures,
  right-hand-rule solver, floating ceiling-flipper polyhedra, roaming maze rat,
  OpenGL/XP framed wall posters, spinning 3D smiley trophy, wall rise/sink
  transitions, and classic translucent wireframe maze overlay)
- Windows XP Logo (logon.scr)
- Starfield
- Mystify
"""

import collections
import ctypes
import json
import math
import os
import random
import signal
import sys
import time
from pathlib import Path

os.environ.setdefault("DCONF_PROFILE", "/home/carsten/.config/hypr/dconf/profile")

import cairo
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
gi.require_version("GtkLayerShell", "0.1")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, GtkLayerShell
from PIL import Image, ImageDraw, ImageFont

CONF_PATH = Path("/home/carsten/.config/hypr/xp-screensaver.conf")
MAZE_CONF_PATH = Path("/home/carsten/.config/hypr/xp-maze.json")
LOGO_PATH = "/usr/local/share/wintc/logonui/logo.png"

DEFAULT_MAZE_CFG = {
    "wall": "brick",
    "floor": "wood",
    "ceiling": "plaster",
    "overlay": True,
    "flippers": True,
    "rat": True,
    "speed": 1.0,
    "maze_size": 11,
}


def read_saved_mode():
    if CONF_PATH.exists():
        val = CONF_PATH.read_text(encoding="utf-8").strip().lower()
        if val in ("none", "maze", "xp-logo", "starfield", "mystify"):
            return val
    return "maze"


def read_maze_cfg():
    cfg = dict(DEFAULT_MAZE_CFG)
    if MAZE_CONF_PATH.exists():
        try:
            data = json.loads(MAZE_CONF_PATH.read_text(encoding="utf-8"))
            if isinstance(data, dict):
                cfg.update(data)
        except Exception:
            pass
    return cfg


# =============================================================================
# Minimal OpenGL 3.3 Core bindings via ctypes (libGL.so.1)
# =============================================================================

GL_COLOR_BUFFER_BIT = 0x00004000
GL_DEPTH_BUFFER_BIT = 0x00000100
GL_TRIANGLES = 0x0004
GL_LINES = 0x0001
GL_DEPTH_TEST = 0x0B71
GL_BLEND = 0x0BE2
GL_CULL_FACE = 0x0B44
GL_LESS = 0x0201
GL_SRC_ALPHA = 0x0302
GL_ONE_MINUS_SRC_ALPHA = 0x0303
GL_FLOAT = 0x1406
GL_UNSIGNED_BYTE = 0x1401
GL_FALSE = 0
GL_TRUE = 1
GL_RGBA = 0x1908
GL_TEXTURE_2D = 0x0DE1
GL_TEXTURE0 = 0x84C0
GL_TEXTURE_MAG_FILTER = 0x2800
GL_TEXTURE_MIN_FILTER = 0x2801
GL_TEXTURE_WRAP_S = 0x2802
GL_TEXTURE_WRAP_T = 0x2803
GL_LINEAR = 0x2601
GL_LINEAR_MIPMAP_LINEAR = 0x2703
GL_REPEAT = 0x2901
GL_CLAMP_TO_EDGE = 0x812F
GL_ARRAY_BUFFER = 0x8892
GL_STATIC_DRAW = 0x88E4
GL_DYNAMIC_DRAW = 0x88E8
GL_VERTEX_SHADER = 0x8B31
GL_FRAGMENT_SHADER = 0x8B30
GL_COMPILE_STATUS = 0x8B81
GL_LINK_STATUS = 0x8B82


def _load_gl():
    gl = ctypes.CDLL("libGL.so.1")
    u = ctypes.c_uint
    i = ctypes.c_int
    f = ctypes.c_float
    b = ctypes.c_ubyte
    vp = ctypes.c_void_p
    sz = ctypes.c_ssize_t

    gl.glCreateShader.argtypes = [u]
    gl.glCreateShader.restype = u
    gl.glShaderSource.argtypes = [u, i, ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(i)]
    gl.glCompileShader.argtypes = [u]
    gl.glGetShaderiv.argtypes = [u, u, ctypes.POINTER(i)]
    gl.glGetShaderInfoLog.argtypes = [u, i, ctypes.POINTER(i), ctypes.c_char_p]
    gl.glDeleteShader.argtypes = [u]

    gl.glCreateProgram.argtypes = []
    gl.glCreateProgram.restype = u
    gl.glAttachShader.argtypes = [u, u]
    gl.glLinkProgram.argtypes = [u]
    gl.glGetProgramiv.argtypes = [u, u, ctypes.POINTER(i)]
    gl.glGetProgramInfoLog.argtypes = [u, i, ctypes.POINTER(i), ctypes.c_char_p]
    gl.glUseProgram.argtypes = [u]
    gl.glDeleteProgram.argtypes = [u]

    gl.glGetUniformLocation.argtypes = [u, ctypes.c_char_p]
    gl.glGetUniformLocation.restype = i
    gl.glUniformMatrix4fv.argtypes = [i, i, b, ctypes.POINTER(f)]
    gl.glUniform1i.argtypes = [i, i]
    gl.glUniform1f.argtypes = [i, f]
    gl.glUniform3f.argtypes = [i, f, f, f]
    gl.glUniform4f.argtypes = [i, f, f, f, f]

    gl.glGenVertexArrays.argtypes = [i, ctypes.POINTER(u)]
    gl.glBindVertexArray.argtypes = [u]
    gl.glDeleteVertexArrays.argtypes = [i, ctypes.POINTER(u)]

    gl.glGenBuffers.argtypes = [i, ctypes.POINTER(u)]
    gl.glBindBuffer.argtypes = [u, u]
    gl.glBufferData.argtypes = [u, sz, vp, u]
    gl.glDeleteBuffers.argtypes = [i, ctypes.POINTER(u)]

    gl.glEnableVertexAttribArray.argtypes = [u]
    gl.glVertexAttribPointer.argtypes = [u, i, u, b, i, vp]
    gl.glDrawArrays.argtypes = [u, i, i]

    gl.glGenTextures.argtypes = [i, ctypes.POINTER(u)]
    gl.glBindTexture.argtypes = [u, u]
    gl.glActiveTexture.argtypes = [u]
    gl.glTexImage2D.argtypes = [u, i, i, i, i, i, u, u, vp]
    gl.glTexParameteri.argtypes = [u, u, i]
    gl.glGenerateMipmap.argtypes = [u]
    gl.glDeleteTextures.argtypes = [i, ctypes.POINTER(u)]

    gl.glViewport.argtypes = [i, i, i, i]
    gl.glClearColor.argtypes = [f, f, f, f]
    gl.glClear.argtypes = [u]
    gl.glEnable.argtypes = [u]
    gl.glDisable.argtypes = [u]
    gl.glDepthFunc.argtypes = [u]
    gl.glDepthMask.argtypes = [b]
    gl.glBlendFunc.argtypes = [u, u]
    gl.glLineWidth.argtypes = [f]
    return gl


# =============================================================================
# 4x4 Column-Major Matrix Math (pure Python, zero numpy needed)
# =============================================================================

def mat_identity():
    return [1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1.0]


def mat_mul(a, b):
    out = [0.0] * 16
    for c in range(4):
        c4 = c * 4
        b0, b1, b2, b3 = b[c4], b[c4 + 1], b[c4 + 2], b[c4 + 3]
        for r in range(4):
            out[c4 + r] = a[r] * b0 + a[4 + r] * b1 + a[8 + r] * b2 + a[12 + r] * b3
    return out


def mat_perspective(fovy_rad, aspect, near, far):
    t = 1.0 / math.tan(fovy_rad * 0.5)
    nf = 1.0 / (near - far)
    return [
        t / aspect, 0.0, 0.0, 0.0,
        0.0, t, 0.0, 0.0,
        0.0, 0.0, (far + near) * nf, -1.0,
        0.0, 0.0, 2.0 * far * near * nf, 0.0,
    ]


def mat_lookat(eye, target, up):
    fx, fy, fz = target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]
    fl = math.sqrt(fx * fx + fy * fy + fz * fz) or 1.0
    fx, fy, fz = fx / fl, fy / fl, fz / fl

    sx = fy * up[2] - fz * up[1]
    sy = fz * up[0] - fx * up[2]
    sz = fx * up[1] - fy * up[0]
    sl = math.sqrt(sx * sx + sy * sy + sz * sz) or 1.0
    sx, sy, sz = sx / sl, sy / sl, sz / sl

    ux = sy * fz - sz * fy
    uy = sz * fx - sx * fz
    uz = sx * fy - sy * fx

    return [
        sx, ux, -fx, 0.0,
        sy, uy, -fy, 0.0,
        sz, uz, -fz, 0.0,
        -(sx * eye[0] + sy * eye[1] + sz * eye[2]),
        -(ux * eye[0] + uy * eye[1] + uz * eye[2]),
        (fx * eye[0] + fy * eye[1] + fz * eye[2]),
        1.0,
    ]


def mat_translate(x, y, z):
    return [1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            x, y, z, 1.0]


def mat_scale(x, y, z):
    return [x, 0.0, 0.0, 0.0,
            0.0, y, 0.0, 0.0,
            0.0, 0.0, z, 0.0,
            0.0, 0.0, 0.0, 1.0]


def mat_rot_y(ang):
    c, s = math.cos(ang), math.sin(ang)
    return [c, 0.0, -s, 0.0,
            0.0, 1.0, 0.0, 0.0,
            s, 0.0, c, 0.0,
            0.0, 0.0, 0.0, 1.0]


def mat_rot_x(ang):
    c, s = math.cos(ang), math.sin(ang)
    return [1.0, 0.0, 0.0, 0.0,
            0.0, c, s, 0.0,
            0.0, -s, c, 0.0,
            0.0, 0.0, 0.0, 1.0]


def mat_rot_z(ang):
    c, s = math.cos(ang), math.sin(ang)
    return [c, s, 0.0, 0.0,
            -s, c, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1.0]


# =============================================================================
# Classic Procedural Retro Textures (128x128 RGBA via Pillow)
# =============================================================================

def _clamp(v, lo=0, hi=255):
    return max(lo, min(hi, int(v)))


def gen_brick_texture(size=128):
    rng = random.Random(9501)
    img = Image.new("RGBA", (size, size), (178, 172, 160, 255))
    px = img.load()
    rows = 8
    cols = 4
    rh = size // rows
    cw = size // cols
    mortar = 2

    # Pre-assign per-brick tint
    tints = {}
    for r in range(rows):
        for c in range(cols + 1):
            tints[(r, c)] = (
                rng.randint(-18, 18),
                rng.randint(-10, 10),
                rng.randint(-8, 8),
            )

    for y in range(size):
        row = y // rh
        ly = y % rh
        offset = (cw // 2) if (row % 2 == 1) else 0
        for x in range(size):
            sx = (x + offset) % size
            col = sx // cw
            lx = sx % cw
            if ly < mortar or lx < mortar:
                n = rng.randint(-12, 10)
                px[x, y] = (_clamp(172 + n), _clamp(166 + n), _clamp(155 + n), 255)
            else:
                tr, tg, tb = tints[(row, col)]
                grain = rng.randint(-14, 14)
                # Subtle bevel: lighter top/left edge, darker bottom/right edge
                bevel = 0
                if ly == mortar or lx == mortar:
                    bevel = 22
                elif ly == rh - 1 or lx == cw - 1:
                    bevel = -28
                r_c = _clamp(158 + tr + grain + bevel)
                g_c = _clamp(66 + tg + grain // 2 + bevel // 2)
                b_c = _clamp(50 + tb + grain // 2 + bevel // 2)
                px[x, y] = (r_c, g_c, b_c, 255)
    return img


def gen_wood_texture(size=128, dark=False):
    rng = random.Random(9502 if not dark else 9503)
    img = Image.new("RGBA", (size, size), (168, 126, 78, 255))
    px = img.load()
    planks = 6
    pw = size // planks
    base = (108, 72, 42) if dark else (178, 134, 82)
    plank_shift = [rng.randint(-12, 12) for _ in range(planks)]
    joint_y = [rng.randint(16, size - 16) for _ in range(planks)]

    for y in range(size):
        for x in range(size):
            p = min(planks - 1, x // pw)
            lx = x % pw
            seam = (lx == 0) or (y == joint_y[p])
            wave = math.sin(y * 0.14 + p * 1.9 + math.sin(x * 0.25) * 1.4) * 11.0
            fine = math.sin(x * 1.3 + y * 0.05) * 4.5 + rng.randint(-5, 5)
            sh = plank_shift[p]
            if seam:
                r_c, g_c, b_c = base[0] - 58, base[1] - 46, base[2] - 32
            else:
                hi = 10 if lx == 1 else (-10 if lx == pw - 1 else 0)
                r_c = base[0] + sh + wave + fine + hi
                g_c = base[1] + sh * 0.8 + wave * 0.75 + fine * 0.7 + hi * 0.8
                b_c = base[2] + sh * 0.55 + wave * 0.5 + fine * 0.5 + hi * 0.5
            px[x, y] = (_clamp(r_c), _clamp(g_c), _clamp(b_c), 255)
    return img


def gen_plaster_texture(size=128):
    rng = random.Random(9504)
    img = Image.new("RGBA", (size, size), (222, 218, 206, 255))
    px = img.load()
    tile = size // 2
    for y in range(size):
        ly = y % tile
        for x in range(size):
            lx = x % tile
            n = rng.randint(-14, 14)
            # Classic acoustic ceiling speckle holes
            speck = -36 if rng.random() < 0.045 else 0
            border = 0
            if lx == 0 or ly == 0:
                border = -30
            elif lx == 1 or ly == 1:
                border = 14
            v = 216 + n + speck + border
            px[x, y] = (_clamp(v), _clamp(v - 4), _clamp(v - 14), 255)
    return img


def gen_hedge_texture(size=128):
    rng = random.Random(9505)
    img = Image.new("RGBA", (size, size), (32, 74, 24, 255))
    draw = ImageDraw.Draw(img)
    for _ in range(950):
        x = rng.randint(0, size - 1)
        y = rng.randint(0, size - 1)
        rx = rng.randint(2, 5)
        ry = rng.randint(2, 4)
        shade = rng.randint(-20, 42)
        col = (_clamp(36 + shade * 0.6), _clamp(88 + shade), _clamp(28 + shade * 0.4), 255)
        for ox in (-size, 0, size):
            for oy in (-size, 0, size):
                if -8 <= x + ox <= size + 8 and -8 <= y + oy <= size + 8:
                    draw.ellipse((x + ox - rx, y + oy - ry, x + ox + rx, y + oy + ry), fill=col)
    return img


def gen_stone_texture(size=128):
    rng = random.Random(9506)
    img = Image.new("RGBA", (size, size), (82, 82, 80, 255))
    px = img.load()
    rows = 4
    rh = size // rows
    cols = 4
    cw = size // cols
    shades = {(r, c): rng.randint(-22, 22) for r in range(rows) for c in range(cols + 1)}
    for y in range(size):
        row = y // rh
        ly = y % rh
        off = (cw // 2) if (row % 2) else 0
        for x in range(size):
            sx = (x + off) % size
            col = sx // cw
            lx = sx % cw
            if lx < 2 or ly < 2:
                v = 62 + rng.randint(-8, 8)
                px[x, y] = (_clamp(v), _clamp(v), _clamp(v - 2), 255)
            else:
                s = shades[(row, col)]
                n = rng.randint(-12, 12)
                bev = 18 if (lx == 2 or ly == 2) else (-20 if (lx == cw - 1 or ly == rh - 1) else 0)
                v = 132 + s + n + bev
                px[x, y] = (_clamp(v), _clamp(v - 1), _clamp(v - 5), 255)
    return img


def gen_tile_texture(size=128):
    rng = random.Random(9507)
    img = Image.new("RGBA", (size, size), (220, 220, 220, 255))
    px = img.load()
    half = size // 2
    for y in range(size):
        for x in range(size):
            dark = ((x // half) + (y // half)) % 2 == 1
            lx, ly = x % half, y % half
            n = rng.randint(-6, 6)
            if lx == 0 or ly == 0:
                px[x, y] = (105, 102, 98, 255)
            elif dark:
                px[x, y] = (_clamp(62 + n), _clamp(66 + n), _clamp(74 + n), 255)
            else:
                px[x, y] = (_clamp(228 + n), _clamp(224 + n), _clamp(214 + n), 255)
    return img


def gen_marble_texture(size=128):
    img = Image.new("RGBA", (size, size), (225, 228, 220, 255))
    px = img.load()
    for y in range(size):
        for x in range(size):
            u = x / size * 2.0 * math.pi
            v = y / size * 2.0 * math.pi
            t = math.sin(u * 2.0 + math.sin(v * 2.0 + math.cos(u - v)) * 1.8)
            vein = abs(t)
            f = 0.55 + 0.45 * (vein ** 0.45)
            px[x, y] = (_clamp(232 * f), _clamp(236 * f), _clamp(226 * f), 255)
    return img


def gen_psychedelic_texture(size=128):
    img = Image.new("RGBA", (size, size), (0, 0, 0, 255))
    px = img.load()
    for y in range(size):
        for x in range(size):
            u = x / size * 2.0 * math.pi
            v = y / size * 2.0 * math.pi
            a = math.sin(u * 2.0 + math.sin(v * 3.0)) + math.cos(v * 2.0 - math.cos(u * 2.0))
            r = int(127.5 + 127.5 * math.sin(a * 2.1))
            g = int(127.5 + 127.5 * math.sin(a * 2.1 + 2.094))
            b = int(127.5 + 127.5 * math.sin(a * 2.1 + 4.188))
            px[x, y] = (r, g, b, 255)
    return img


def gen_starry_texture(size=128):
    rng = random.Random(9508)
    img = Image.new("RGBA", (size, size), (8, 12, 30, 255))
    px = img.load()
    for _ in range(95):
        x, y = rng.randint(0, size - 1), rng.randint(0, size - 1)
        b = rng.randint(140, 255)
        px[x, y] = (b, b, _clamp(b + 25), 255)
        if b > 225:
            for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                px[(x + dx) % size, (y + dy) % size] = (120, 130, 180, 255)
    return img


def gen_poster_opengl(size=128):
    """Classic framed 'OpenGL' wall plaque from Windows 95/98 3D Maze."""
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    # Wood/gold picture frame
    d.rectangle((4, 18, size - 5, size - 19), fill=(238, 236, 224, 255), outline=(72, 46, 22, 255), width=6)
    d.rectangle((10, 24, size - 11, size - 25), outline=(188, 152, 72, 255), width=2)
    # Iconic blue OpenGL oval swoosh
    d.ellipse((16, 36, size - 17, size - 37), fill=(36, 98, 178, 255), outline=(18, 54, 118, 255), width=3)
    d.ellipse((22, 42, size - 23, size - 43), outline=(140, 195, 250, 255), width=2)
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 22)
    except Exception:
        font = ImageFont.load_default()
    d.text((size // 2, size // 2), "OpenGL", fill=(255, 255, 255, 255), font=font, anchor="mm")
    return img


def gen_poster_xp(size=128):
    """Framed Windows XP wall poster."""
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    d.rectangle((4, 14, size - 5, size - 15), fill=(20, 56, 138, 255), outline=(72, 46, 22, 255), width=6)
    d.rectangle((10, 20, size - 11, size - 21), outline=(120, 170, 245, 255), width=2)
    # Crisp 4-pane XP flag
    cx, cy = size // 2, size // 2 - 8
    d.polygon([(cx - 24, cy - 18), (cx - 3, cy - 22), (cx - 6, cy - 3), (cx - 27, cy)], fill=(235, 68, 34, 255))
    d.polygon([(cx + 3, cy - 22), (cx + 26, cy - 16), (cx + 22, cy + 2), (cx, cy - 2)], fill=(120, 196, 46, 255))
    d.polygon([(cx - 27, cy + 4), (cx - 6, cy + 2), (cx - 9, cy + 22), (cx - 30, cy + 24)], fill=(38, 148, 242, 255))
    d.polygon([(cx, cy + 3), (cx + 22, cy + 7), (cx + 18, cy + 26), (cx - 3, cy + 22)], fill=(248, 194, 26, 255))
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 14)
    except Exception:
        font = ImageFont.load_default()
    d.text((size // 2, size - 29), "Windows XP", fill=(255, 255, 255, 255), font=font, anchor="mm")
    return img


def gen_start_sprite(size=128):
    """Floating green/gold START sign shown at the beginning of each maze."""
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    # Diamond emerald plaque with gold border
    pts = [(size // 2, 10), (size - 10, size // 2), (size // 2, size - 10), (10, size // 2)]
    d.polygon(pts, fill=(32, 142, 58, 255), outline=(245, 212, 72, 255))
    for i in range(4):
        d.line([pts[i], pts[(i + 1) % 4]], fill=(248, 220, 88, 255), width=5)
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 22)
    except Exception:
        font = ImageFont.load_default()
    d.text((size // 2 + 2, size // 2 + 2), "START", fill=(10, 48, 18, 255), font=font, anchor="mm")
    d.text((size // 2, size // 2), "START", fill=(255, 252, 210, 255), font=font, anchor="mm")
    return img


def gen_smiley_sprite(size=128):
    """Classic spinning golden Smiley Face Trophy at the maze exit."""
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    # Outer golden ring + sunny yellow disc
    d.ellipse((10, 10, size - 11, size - 11), fill=(255, 212, 24, 255), outline=(186, 120, 0, 255), width=5)
    d.ellipse((18, 18, size - 19, size - 19), fill=(255, 228, 52, 255))
    # Specular highlight
    d.ellipse((28, 24, 58, 44), fill=(255, 248, 168, 255))
    # Classic bold eyes
    d.ellipse((38, 40, 52, 58), fill=(20, 18, 14, 255))
    d.ellipse((76, 40, 90, 58), fill=(20, 18, 14, 255))
    # Cheerful classic smile arc
    d.arc((30, 36, size - 31, size - 26), start=22, end=158, fill=(20, 18, 14, 255), width=7)
    return img


def gen_rat_sprite(size=128):
    """Classic Windows 95 3D Maze scurrying grey rat sprite."""
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    # Curled pink tail
    d.arc((6, 62, 54, 104), start=110, end=310, fill=(216, 148, 152, 255), width=5)
    # Plump grey-brown body
    d.ellipse((28, 54, 98, 106), fill=(138, 132, 126, 255), outline=(56, 52, 48, 255), width=3)
    # Lighter belly
    d.ellipse((42, 74, 90, 103), fill=(182, 176, 168, 255))
    # Pointy head & snout facing right
    d.polygon([(78, 60), (118, 82), (82, 98)], fill=(148, 142, 136, 255), outline=(56, 52, 48, 255))
    # Round ears (pink inner)
    d.ellipse((72, 40, 92, 62), fill=(132, 126, 120, 255), outline=(56, 52, 48, 255), width=2)
    d.ellipse((77, 45, 88, 57), fill=(224, 156, 164, 255))
    # Little paws
    d.ellipse((40, 98, 56, 109), fill=(214, 154, 158, 255), outline=(72, 56, 54, 255), width=2)
    d.ellipse((76, 98, 92, 109), fill=(214, 154, 158, 255), outline=(72, 56, 54, 255), width=2)
    # Shiny black eye + pink nose + whiskers
    d.ellipse((94, 70, 102, 78), fill=(16, 16, 18, 255))
    d.point((96, 72), fill=(255, 255, 255, 255))
    d.ellipse((114, 78, 122, 86), fill=(235, 130, 142, 255))
    d.line([(114, 83), (126, 74)], fill=(45, 42, 40, 255), width=2)
    d.line([(114, 85), (126, 86)], fill=(45, 42, 40, 255), width=2)
    d.line([(112, 87), (124, 96)], fill=(45, 42, 40, 255), width=2)
    return img


def get_surface_image(kind):
    makers = {
        "brick": gen_brick_texture,
        "wood": lambda: gen_wood_texture(dark=False),
        "wood-dark": lambda: gen_wood_texture(dark=True),
        "plaster": gen_plaster_texture,
        "hedge": gen_hedge_texture,
        "stone": gen_stone_texture,
        "tile": gen_tile_texture,
        "marble": gen_marble_texture,
        "psychedelic": gen_psychedelic_texture,
        "starry": gen_starry_texture,
    }
    return makers.get(kind, gen_brick_texture)()


# =============================================================================
# Maze Logic: Perfect Maze Generator + Right-Hand-Rule Solver + Rat AI
# =============================================================================

# Directions: 0=N(0,-1), 1=E(1,0), 2=S(0,1), 3=W(-1,0)
DIRS = [(0, -1), (1, 0), (0, 1), (-1, 0)]
OPP = [2, 3, 0, 1]


def generate_maze(size=11):
    # walls[z][x] = [N, E, S, W] True means solid wall
    walls = [[[True, True, True, True] for _ in range(size)] for _ in range(size)]
    vis = [[False] * size for _ in range(size)]
    stack = [(0, 0)]
    vis[0][0] = True
    while stack:
        cx, cz = stack[-1]
        nbrs = []
        for d, (dx, dz) in enumerate(DIRS):
            nx, nz = cx + dx, cz + dz
            if 0 <= nx < size and 0 <= nz < size and not vis[nz][nx]:
                nbrs.append((d, nx, nz))
        if nbrs:
            d, nx, nz = random.choice(nbrs)
            walls[cz][cx][d] = False
            walls[nz][nx][OPP[d]] = False
            vis[nz][nx] = True
            stack.append((nx, nz))
        else:
            stack.pop()

    # BFS from (0,0) to find farthest goal cell + shortest solution path
    q = collections.deque([(0, 0)])
    parent = {(0, 0): None}
    dist = {(0, 0): 0}
    far = (0, 0)
    while q:
        cx, cz = q.popleft()
        if dist[(cx, cz)] > dist[far]:
            far = (cx, cz)
        for d, (dx, dz) in enumerate(DIRS):
            if not walls[cz][cx][d]:
                nx, nz = cx + dx, cz + dz
                if (nx, nz) not in dist:
                    dist[(nx, nz)] = dist[(cx, cz)] + 1
                    parent[(nx, nz)] = (cx, cz)
                    q.append((nx, nz))

    sol_path = []
    cur = far
    while cur is not None:
        sol_path.append(cur)
        cur = parent[cur]
    sol_path.reverse()
    return walls, far, sol_path


# =============================================================================
# GLSL Shaders (#version 330 core)
# =============================================================================

WORLD_VS = """#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec2 aUV;
layout(location = 2) in float aShade;

uniform mat4 uMVP;
uniform mat4 uModel;
uniform float uWallScale;
uniform vec3 uCamPos;

out vec2 vUV;
out float vShade;
out float vDist;

void main() {
    vec3 p = vec3(aPos.x, aPos.y * uWallScale, aPos.z);
    vec4 worldPos = uModel * vec4(p, 1.0);
    vDist = length(worldPos.xyz - uCamPos);
    vUV = aUV;
    vShade = aShade;
    gl_Position = uMVP * vec4(p, 1.0);
}
"""

WORLD_FS = """#version 330 core
in vec2 vUV;
in float vShade;
in float vDist;

uniform sampler2D uTex;
uniform float uAlphaCut;
uniform vec3 uFogColor;
uniform float uFogStart;
uniform float uFogEnd;

out vec4 FragColor;

void main() {
    vec4 tex = texture(uTex, vUV);
    if (tex.a < uAlphaCut) discard;
    float fog = clamp((vDist - uFogStart) / (uFogEnd - uFogStart), 0.0, 0.58);
    vec3 lit = tex.rgb * vShade;
    vec3 col = mix(lit, uFogColor, fog);
    FragColor = vec4(col, tex.a);
}
"""

POLY_VS = """#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;

uniform mat4 uMVP;
uniform mat4 uModel;

out vec3 vNormal;

void main() {
    vNormal = mat3(uModel) * aNormal;
    gl_Position = uMVP * vec4(aPos, 1.0);
}
"""

POLY_FS = """#version 330 core
in vec3 vNormal;

uniform vec4 uColor;

out vec4 FragColor;

void main() {
    vec3 n = normalize(vNormal);
    vec3 l1 = normalize(vec3(0.45, 0.82, 0.36));
    vec3 l2 = normalize(vec3(-0.6, -0.3, -0.7));
    float diff = max(dot(n, l1), 0.0) * 0.72 + max(dot(n, l2), 0.0) * 0.28 + 0.25;
    FragColor = vec4(uColor.rgb * diff, uColor.a);
}
"""

HUD_VS = """#version 330 core
layout(location = 0) in vec2 aPos;
uniform vec4 uColor;
out vec4 vColor;
void main() {
    vColor = uColor;
    gl_Position = vec4(aPos, 0.0, 1.0);
}
"""

HUD_FS = """#version 330 core
in vec4 vColor;
out vec4 FragColor;
void main() {
    FragColor = vColor;
}
"""


# =============================================================================
# Hardware-Accelerated 3D Maze OpenGL Widget (Gtk.GLArea)
# =============================================================================

class Maze3DWidget(Gtk.GLArea):
    def __init__(self, cfg):
        super().__init__()
        self.cfg = cfg
        self.set_has_depth_buffer(True)
        self.set_auto_render(True)
        self.gl = None
        self.ready = False
        self.show_overlay = bool(cfg.get("overlay", True))
        self.speed = max(0.4, min(2.5, float(cfg.get("speed", 1.0))))
        self.maze_size = max(7, min(19, int(cfg.get("maze_size", 11))))

        # GL handles
        self.prog_world = 0
        self.prog_poly = 0
        self.prog_hud = 0
        self.tex = {}
        self.meshes = {}
        self.hud_vao = 0
        self.hud_vbo = 0

        # World / simulation state
        self.last_t = time.monotonic()
        self.elapsed = 0.0
        self._init_new_maze(first=True)

        self.connect("realize", self.on_realize)
        self.connect("unrealize", self.on_unrealize)
        self.connect("render", self.on_render)

    def toggle_overlay(self):
        self.show_overlay = not self.show_overlay

    # ---- Maze state machine ----
    def _init_new_maze(self, first=False):
        self.walls, self.goal, sol_path = generate_maze(self.maze_size)
        self.cx, self.cz = 0, 0
        # Pick initial open heading from (0,0)
        self.heading = 1
        for d in (1, 2, 0, 3):
            if not self.walls[0][0][d]:
                self.heading = d
                break

        self.cam_x = 0.5
        self.cam_z = 0.5
        self.cam_yaw = self.heading * (math.pi * 0.5)
        self.roll_angle = 0.0
        self.roll_from = 0.0
        self.roll_to = 0.0
        self.roll_t = 1.0

        self.state = "RISE"
        self.state_t = 0.0
        self.wall_scale = 0.0
        self.visited = {(0, 0)}

        # Start sign placed 1 cell ahead of start
        dx, dz = DIRS[self.heading]
        self.start_sign = [0.5 + dx * 0.82, 0.5 + dz * 0.82, True]

        # Ceiling flippers along the solution path
        self.flippers = []
        if self.cfg.get("flippers", True) and len(sol_path) > 6:
            count = 2 if len(sol_path) < 16 else 3
            step = max(2, (len(sol_path) - 3) // (count + 1))
            for idx in range(1, count + 1):
                pos = sol_path[min(len(sol_path) - 2, idx * step + 1)]
                if pos != (0, 0) and pos != self.goal:
                    self.flippers.append([pos[0] + 0.5, pos[1] + 0.5, True])

        # Scurrying Maze Rat
        self.rat_enabled = bool(self.cfg.get("rat", True))
        rx = self.maze_size // 2
        rz = self.maze_size // 2
        self.rat_cell = (rx, rz)
        self.rat_next = (rx, rz)
        self.rat_dir = 0
        self.rat_t = 1.0
        self.rat_pos = [rx + 0.5, rz + 0.5]
        self._pick_next_rat_step()

        # Action queue for smooth move/turn
        self.move_from = (0.5, 0.5)
        self.move_to = (0.5, 0.5)
        self.turn_from = self.cam_yaw
        self.turn_to = self.cam_yaw
        self.pending_move = False

        if self.ready and not first:
            self._rebuild_maze_geometry()

    def _pick_next_rat_step(self):
        cx, cz = self.rat_cell
        opts = []
        for d, (dx, dz) in enumerate(DIRS):
            if not self.walls[cz][cx][d]:
                opts.append((d, cx + dx, cz + dz))
        if not opts:
            return
        # Prefer not reversing unless dead end
        non_rev = [o for o in opts if o[0] != OPP[self.rat_dir]]
        chosen = random.choice(non_rev if non_rev else opts)
        self.rat_dir = chosen[0]
        self.rat_next = (chosen[1], chosen[2])
        self.rat_t = 0.0

    def _plan_next_step(self):
        if (self.cx, self.cz) == self.goal:
            self.state = "CELEBRATE"
            self.state_t = 0.0
            return

        # Right-hand rule: Right -> Straight -> Left -> Back
        for delta in (1, 0, 3, 2):
            nd = (self.heading + delta) % 4
            if not self.walls[self.cz][self.cx][nd]:
                dx, dz = DIRS[nd]
                nx, nz = self.cx + dx, self.cz + dz
                if delta == 0:
                    self._begin_move(nx, nz)
                else:
                    # Compute shortest signed angle delta
                    ang_delta = {1: math.pi * 0.5, 3: -math.pi * 0.5, 2: math.pi}[delta]
                    self.turn_from = self.cam_yaw
                    self.turn_to = self.cam_yaw + ang_delta
                    self.heading = nd
                    self.next_cell = (nx, nz)
                    self.pending_move = True
                    self.state = "TURN"
                    self.state_t = 0.0
                    self.turn_dur = (0.62 if delta == 2 else 0.36) / self.speed
                return

    def _begin_move(self, nx, nz):
        self.move_from = (self.cx + 0.5, self.cz + 0.5)
        self.move_to = (nx + 0.5, nz + 0.5)
        self.cx, self.cz = nx, nz
        self.visited.add((nx, nz))
        self.state = "MOVE"
        self.state_t = 0.0
        self.move_dur = 0.44 / self.speed

    def step_simulation(self, dt):
        dt = min(dt, 0.05)
        self.elapsed += dt

        # Update camera roll flip
        if self.roll_t < 1.0:
            self.roll_t = min(1.0, self.roll_t + dt / (0.85 / max(0.7, self.speed)))
            s = self.roll_t * self.roll_t * (3.0 - 2.0 * self.roll_t)
            self.roll_angle = self.roll_from + (self.roll_to - self.roll_from) * s

        # Update roaming rat
        if self.rat_enabled and self.state not in ("RISE", "SINK"):
            self.rat_t += dt * 1.25 * self.speed
            if self.rat_t >= 1.0:
                self.rat_cell = self.rat_next
                self._pick_next_rat_step()
            t = min(1.0, self.rat_t)
            ax, az = self.rat_cell[0] + 0.5, self.rat_cell[1] + 0.5
            bx, bz = self.rat_next[0] + 0.5, self.rat_next[1] + 0.5
            self.rat_pos[0] = ax + (bx - ax) * t
            self.rat_pos[1] = az + (bz - az) * t

        # State machine
        if self.state == "RISE":
            self.state_t += dt
            p = min(1.0, self.state_t / 1.15)
            self.wall_scale = p * p * (3.0 - 2.0 * p)
            if p >= 1.0:
                self.wall_scale = 1.0
                self._plan_next_step()

        elif self.state == "TURN":
            self.state_t += dt
            p = min(1.0, self.state_t / self.turn_dur)
            s = p * p * (3.0 - 2.0 * p)
            self.cam_yaw = self.turn_from + (self.turn_to - self.turn_from) * s
            if p >= 1.0:
                self.cam_yaw = self.turn_to % (2.0 * math.pi)
                if self.pending_move:
                    self.pending_move = False
                    self._begin_move(*self.next_cell)
                else:
                    self._plan_next_step()

        elif self.state == "MOVE":
            self.state_t += dt
            p = min(1.0, self.state_t / self.move_dur)
            self.cam_x = self.move_from[0] + (self.move_to[0] - self.move_from[0]) * p
            self.cam_z = self.move_from[1] + (self.move_to[1] - self.move_from[1]) * p

            # Dismiss Start sign once passed
            if self.start_sign[2]:
                dx = self.cam_x - self.start_sign[0]
                dz = self.cam_z - self.start_sign[1]
                if dx * dx + dz * dz < 0.08:
                    self.start_sign[2] = False

            # Check flippers
            for fl in self.flippers:
                if fl[2]:
                    dx = self.cam_x - fl[0]
                    dz = self.cam_z - fl[1]
                    if dx * dx + dz * dz < 0.09:
                        fl[2] = False
                        self.roll_from = self.roll_angle
                        self.roll_to = self.roll_from + math.pi
                        self.roll_t = 0.0

            if p >= 1.0:
                self.cam_x, self.cam_z = self.move_to
                self._plan_next_step()

        elif self.state == "CELEBRATE":
            self.state_t += dt
            if self.state_t >= 0.95:
                self.state = "SINK"
                self.state_t = 0.0

        elif self.state == "SINK":
            self.state_t += dt
            p = min(1.0, self.state_t / 1.0)
            self.wall_scale = 1.0 - (p * p * (3.0 - 2.0 * p))
            if p >= 1.0:
                self._init_new_maze(first=False)

    # ---- OpenGL resource helpers ----
    def _compile_shader(self, src, stype):
        gl = self.gl
        sh = gl.glCreateShader(stype)
        c_src = ctypes.c_char_p(src.encode("utf-8"))
        gl.glShaderSource(sh, 1, ctypes.byref(c_src), None)
        gl.glCompileShader(sh)
        status = ctypes.c_int(0)
        gl.glGetShaderiv(sh, GL_COMPILE_STATUS, ctypes.byref(status))
        if not status.value:
            buf = ctypes.create_string_buffer(1024)
            gl.glGetShaderInfoLog(sh, 1024, None, buf)
            raise RuntimeError(f"Shader compile error: {buf.value.decode()}")
        return sh

    def _link_program(self, vs_src, fs_src):
        gl = self.gl
        vs = self._compile_shader(vs_src, GL_VERTEX_SHADER)
        fs = self._compile_shader(fs_src, GL_FRAGMENT_SHADER)
        prog = gl.glCreateProgram()
        gl.glAttachShader(prog, vs)
        gl.glAttachShader(prog, fs)
        gl.glLinkProgram(prog)
        status = ctypes.c_int(0)
        gl.glGetProgramiv(prog, GL_LINK_STATUS, ctypes.byref(status))
        gl.glDeleteShader(vs)
        gl.glDeleteShader(fs)
        if not status.value:
            buf = ctypes.create_string_buffer(1024)
            gl.glGetProgramInfoLog(prog, 1024, None, buf)
            raise RuntimeError(f"Program link error: {buf.value.decode()}")
        return prog

    def _upload_texture(self, img, clamp=False):
        gl = self.gl
        img = img.convert("RGBA").transpose(Image.FLIP_TOP_BOTTOM)
        raw = img.tobytes()
        tid = ctypes.c_uint(0)
        gl.glGenTextures(1, ctypes.byref(tid))
        gl.glBindTexture(GL_TEXTURE_2D, tid.value)
        wrap = GL_CLAMP_TO_EDGE if clamp else GL_REPEAT
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        gl.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width, img.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, raw)
        gl.glGenerateMipmap(GL_TEXTURE_2D)
        return tid.value

    def _make_world_mesh(self, floats):
        gl = self.gl
        vao = ctypes.c_uint(0)
        vbo = ctypes.c_uint(0)
        gl.glGenVertexArrays(1, ctypes.byref(vao))
        gl.glGenBuffers(1, ctypes.byref(vbo))
        gl.glBindVertexArray(vao.value)
        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo.value)
        arr = (ctypes.c_float * len(floats))(*floats)
        gl.glBufferData(GL_ARRAY_BUFFER, ctypes.sizeof(arr), arr, GL_STATIC_DRAW)
        stride = 6 * 4
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(0))
        gl.glEnableVertexAttribArray(1)
        gl.glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(12))
        gl.glEnableVertexAttribArray(2)
        gl.glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(20))
        gl.glBindVertexArray(0)
        return (vao.value, vbo.value, len(floats) // 6)

    def _make_poly_mesh(self, floats):
        gl = self.gl
        vao = ctypes.c_uint(0)
        vbo = ctypes.c_uint(0)
        gl.glGenVertexArrays(1, ctypes.byref(vao))
        gl.glGenBuffers(1, ctypes.byref(vbo))
        gl.glBindVertexArray(vao.value)
        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo.value)
        arr = (ctypes.c_float * len(floats))(*floats)
        gl.glBufferData(GL_ARRAY_BUFFER, ctypes.sizeof(arr), arr, GL_STATIC_DRAW)
        stride = 6 * 4
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(0))
        gl.glEnableVertexAttribArray(1)
        gl.glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(12))
        gl.glBindVertexArray(0)
        return (vao.value, vbo.value, len(floats) // 6)

    def _delete_mesh(self, key):
        if key in self.meshes:
            vao, vbo, _ = self.meshes.pop(key)
            self.gl.glDeleteBuffers(1, ctypes.byref(ctypes.c_uint(vbo)))
            self.gl.glDeleteVertexArrays(1, ctypes.byref(ctypes.c_uint(vao)))

    def _add_quad(self, buf, p0, p1, p2, p3, u0=0.0, v0=0.0, u1=1.0, v1=1.0, shade=1.0):
        # Two triangles: p0-p1-p2 and p0-p2-p3
        buf.extend([
            p0[0], p0[1], p0[2], u0, v0, shade,
            p1[0], p1[1], p1[2], u1, v0, shade,
            p2[0], p2[1], p2[2], u1, v1, shade,
            p0[0], p0[1], p0[2], u0, v0, shade,
            p2[0], p2[1], p2[2], u1, v1, shade,
            p3[0], p3[1], p3[2], u0, v1, shade,
        ])

    def _build_octahedron_data(self):
        verts = [
            (0.0, 1.0, 0.0), (0.0, -1.0, 0.0),
            (1.0, 0.0, 0.0), (-1.0, 0.0, 0.0),
            (0.0, 0.0, 1.0), (0.0, 0.0, -1.0),
        ]
        faces = [
            (0, 4, 2), (0, 2, 5), (0, 5, 3), (0, 3, 4),
            (1, 2, 4), (1, 5, 2), (1, 3, 5), (1, 4, 3),
        ]
        out = []
        for a, b, c in faces:
            va, vb, vc = verts[a], verts[b], verts[c]
            ux, uy, uz = vb[0] - va[0], vb[1] - va[1], vb[2] - va[2]
            vx, vy, vz = vc[0] - va[0], vc[1] - va[1], vc[2] - va[2]
            nx = uy * vz - uz * vy
            ny = uz * vx - ux * vz
            nz = ux * vy - uy * vx
            nl = math.sqrt(nx * nx + ny * ny + nz * nz) or 1.0
            nx, ny, nz = nx / nl, ny / nl, nz / nl
            for p in (va, vb, vc):
                out.extend([p[0], p[1], p[2], nx, ny, nz])
        return out

    def _rebuild_maze_geometry(self):
        for k in ("walls", "floor", "ceiling", "poster_gl", "poster_xp"):
            self._delete_mesh(k)

        N = self.maze_size
        wall_v = []
        floor_v = []
        ceil_v = []
        p_gl_v = []
        p_xp_v = []

        # Floor & ceiling extend well into the fog so RISE/SINK meets the horizon seamlessly
        pad = 12.0
        span = float(N) + 2.0 * pad
        self._add_quad(floor_v, (-pad, 0, -pad), (N + pad, 0, -pad), (N + pad, 0, N + pad), (-pad, 0, N + pad),
                       0, 0, span, span, 0.92)
        self._add_quad(ceil_v, (-pad, 1, -pad), (N + pad, 1, -pad), (N + pad, 1, N + pad), (-pad, 1, N + pad),
                       0, 0, span, span, 0.95)

        eps = 0.008
        for z in range(N):
            for x in range(N):
                w = self.walls[z][x]
                # North wall (z edge)
                if w[0]:
                    self._add_quad(wall_v, (x, 0, z), (x + 1, 0, z), (x + 1, 1, z), (x, 1, z), shade=1.0)
                    if random.random() < 0.055 and (x, z) != (0, 0):
                        target = p_gl_v if random.random() < 0.6 else p_xp_v
                        self._add_quad(target, (x + 0.18, 0.20, z + eps), (x + 0.82, 0.20, z + eps),
                                       (x + 0.82, 0.82, z + eps), (x + 0.18, 0.82, z + eps), shade=1.0)
                # South wall (z+1 edge) - emit only on outer boundary to avoid duplicate faces (or interior per cell)
                if w[2] and z == N - 1:
                    self._add_quad(wall_v, (x + 1, 0, z + 1), (x, 0, z + 1), (x, 1, z + 1), (x + 1, 1, z + 1), shade=1.0)
                elif w[2]:
                    # Interior poster facing North on South wall
                    if random.random() < 0.055 and (x, z) != (0, 0):
                        target = p_gl_v if random.random() < 0.6 else p_xp_v
                        self._add_quad(target, (x + 0.82, 0.20, z + 1 - eps), (x + 0.18, 0.20, z + 1 - eps),
                                       (x + 0.18, 0.82, z + 1 - eps), (x + 0.82, 0.82, z + 1 - eps), shade=1.0)
                # West wall (x edge)
                if w[3]:
                    self._add_quad(wall_v, (x, 0, z + 1), (x, 0, z), (x, 1, z), (x, 1, z + 1), shade=0.84)
                    if random.random() < 0.055 and (x, z) != (0, 0):
                        target = p_gl_v if random.random() < 0.6 else p_xp_v
                        self._add_quad(target, (x + eps, 0.20, z + 0.82), (x + eps, 0.20, z + 0.18),
                                       (x + eps, 0.82, z + 0.18), (x + eps, 0.82, z + 0.82), shade=0.90)
                # East wall (x+1 edge) - outer boundary
                if w[1] and x == N - 1:
                    self._add_quad(wall_v, (x + 1, 0, z), (x + 1, 0, z + 1), (x + 1, 1, z + 1), (x + 1, 1, z), shade=0.84)

        self.meshes["walls"] = self._make_world_mesh(wall_v)
        self.meshes["floor"] = self._make_world_mesh(floor_v)
        self.meshes["ceiling"] = self._make_world_mesh(ceil_v)
        if p_gl_v:
            self.meshes["poster_gl"] = self._make_world_mesh(p_gl_v)
        if p_xp_v:
            self.meshes["poster_xp"] = self._make_world_mesh(p_xp_v)

    def on_realize(self, area):
        area.make_current()
        if area.get_error() is not None:
            return
        self.gl = _load_gl()
        gl = self.gl

        self.prog_world = self._link_program(WORLD_VS, WORLD_FS)
        self.prog_poly = self._link_program(POLY_VS, POLY_FS)
        self.prog_hud = self._link_program(HUD_VS, HUD_FS)

        # Uniform locations
        self.u_w_mvp = gl.glGetUniformLocation(self.prog_world, b"uMVP")
        self.u_w_model = gl.glGetUniformLocation(self.prog_world, b"uModel")
        self.u_w_scale = gl.glGetUniformLocation(self.prog_world, b"uWallScale")
        self.u_w_cam = gl.glGetUniformLocation(self.prog_world, b"uCamPos")
        self.u_w_tex = gl.glGetUniformLocation(self.prog_world, b"uTex")
        self.u_w_acut = gl.glGetUniformLocation(self.prog_world, b"uAlphaCut")
        self.u_w_fogc = gl.glGetUniformLocation(self.prog_world, b"uFogColor")
        self.u_w_fogs = gl.glGetUniformLocation(self.prog_world, b"uFogStart")
        self.u_w_foge = gl.glGetUniformLocation(self.prog_world, b"uFogEnd")

        self.u_p_mvp = gl.glGetUniformLocation(self.prog_poly, b"uMVP")
        self.u_p_model = gl.glGetUniformLocation(self.prog_poly, b"uModel")
        self.u_p_col = gl.glGetUniformLocation(self.prog_poly, b"uColor")

        self.u_h_col = gl.glGetUniformLocation(self.prog_hud, b"uColor")

        # Textures
        self.tex["wall"] = self._upload_texture(get_surface_image(self.cfg.get("wall", "brick")))
        self.tex["floor"] = self._upload_texture(get_surface_image(self.cfg.get("floor", "wood")))
        self.tex["ceiling"] = self._upload_texture(get_surface_image(self.cfg.get("ceiling", "plaster")))
        self.tex["poster_gl"] = self._upload_texture(gen_poster_opengl(), clamp=True)
        self.tex["poster_xp"] = self._upload_texture(gen_poster_xp(), clamp=True)
        self.tex["start"] = self._upload_texture(gen_start_sprite(), clamp=True)
        self.tex["smiley"] = self._upload_texture(gen_smiley_sprite(), clamp=True)
        self.tex["rat"] = self._upload_texture(gen_rat_sprite(), clamp=True)

        # Shared billboard quad centered at origin (-0.5..0.5)
        b_quad = []
        self._add_quad(b_quad, (-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0), shade=1.0)
        self.meshes["quad"] = self._make_world_mesh(b_quad)

        # Shared octahedron for ceiling flippers
        self.meshes["octa"] = self._make_poly_mesh(self._build_octahedron_data())

        # HUD VAO/VBO
        h_vao, h_vbo = ctypes.c_uint(0), ctypes.c_uint(0)
        gl.glGenVertexArrays(1, ctypes.byref(h_vao))
        gl.glGenBuffers(1, ctypes.byref(h_vbo))
        gl.glBindVertexArray(h_vao.value)
        gl.glBindBuffer(GL_ARRAY_BUFFER, h_vbo.value)
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 8, ctypes.c_void_p(0))
        gl.glBindVertexArray(0)
        self.hud_vao, self.hud_vbo = h_vao.value, h_vbo.value

        self._rebuild_maze_geometry()
        self.ready = True
        self.last_t = time.monotonic()

    def on_unrealize(self, area):
        if not self.ready:
            return
        area.make_current()
        gl = self.gl
        for key in list(self.meshes.keys()):
            self._delete_mesh(key)
        for tid in self.tex.values():
            gl.glDeleteTextures(1, ctypes.byref(ctypes.c_uint(tid)))
        self.tex.clear()
        if self.hud_vbo:
            gl.glDeleteBuffers(1, ctypes.byref(ctypes.c_uint(self.hud_vbo)))
        if self.hud_vao:
            gl.glDeleteVertexArrays(1, ctypes.byref(ctypes.c_uint(self.hud_vao)))
        for p in (self.prog_world, self.prog_poly, self.prog_hud):
            if p:
                gl.glDeleteProgram(p)
        self.ready = False

    def _draw_world_mesh(self, mesh_key, tex_key, model, vp, wall_scale=1.0, alpha_cut=0.0):
        if mesh_key not in self.meshes:
            return
        gl = self.gl
        vao, _, count = self.meshes[mesh_key]
        mvp = mat_mul(vp, model)
        gl.glUniformMatrix4fv(self.u_w_mvp, 1, GL_FALSE, (ctypes.c_float * 16)(*mvp))
        gl.glUniformMatrix4fv(self.u_w_model, 1, GL_FALSE, (ctypes.c_float * 16)(*model))
        gl.glUniform1f(self.u_w_scale, wall_scale)
        gl.glUniform1f(self.u_w_acut, alpha_cut)
        gl.glActiveTexture(GL_TEXTURE0)
        gl.glBindTexture(GL_TEXTURE_2D, self.tex[tex_key])
        gl.glBindVertexArray(vao)
        gl.glDrawArrays(GL_TRIANGLES, 0, count)

    def _draw_billboard(self, wx, wy, wz, sx, sy, tex_key, vp, spin_y=None):
        if spin_y is not None:
            rot = mat_rot_y(spin_y)
        else:
            # Always face camera horizontally
            ang = math.atan2(self.cam_x - wx, self.cam_z - wz)
            rot = mat_rot_y(ang)
        m = mat_mul(mat_translate(wx, wy, wz), mat_mul(rot, mat_scale(sx, sy, 1.0)))
        self._draw_world_mesh("quad", tex_key, m, vp, wall_scale=1.0, alpha_cut=0.45)

    def _draw_hud_overlay(self, w, h):
        gl = self.gl
        N = self.maze_size
        # Classic translucent wireframe maze overlay in bottom-right corner
        aspect = w / float(h)
        map_h = 0.44  # NDC fraction
        map_w = map_h / aspect
        pad_x = 0.05 / aspect
        pad_y = 0.05
        x0 = 1.0 - pad_x - map_w
        y0 = -1.0 + pad_y
        cw = map_w / N
        ch = map_h / N

        def to_ndc(gx, gz):
            # Flip Z so North is up on map
            return (x0 + gx * cw, y0 + (N - gz) * ch)

        gl.glDisable(GL_DEPTH_TEST)
        gl.glEnable(GL_BLEND)
        gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        gl.glUseProgram(self.prog_hud)
        gl.glBindVertexArray(self.hud_vao)
        gl.glBindBuffer(GL_ARRAY_BUFFER, self.hud_vbo)

        def draw_verts(pts, mode, rgba):
            if not pts:
                return
            arr = (ctypes.c_float * len(pts))(*pts)
            gl.glBufferData(GL_ARRAY_BUFFER, ctypes.sizeof(arr), arr, GL_DYNAMIC_DRAW)
            gl.glUniform4f(self.u_h_col, *rgba)
            gl.glDrawArrays(mode, 0, len(pts) // 2)

        # Translucent dark backdrop
        bg = [
            x0 - 0.012 / aspect, y0 - 0.012,
            x0 + map_w + 0.012 / aspect, y0 - 0.012,
            x0 + map_w + 0.012 / aspect, y0 + map_h + 0.012,
            x0 - 0.012 / aspect, y0 - 0.012,
            x0 + map_w + 0.012 / aspect, y0 + map_h + 0.012,
            x0 - 0.012 / aspect, y0 + map_h + 0.012,
        ]
        draw_verts(bg, GL_TRIANGLES, (0.04, 0.06, 0.12, 0.48))

        # Visited cells subtle tint
        vis_tris = []
        for vx, vz in self.visited:
            ax, ay = to_ndc(vx + 0.15, vz + 0.85)
            bx, by = to_ndc(vx + 0.85, vz + 0.15)
            vis_tris.extend([ax, ay, bx, ay, bx, by, ax, ay, bx, by, ax, by])
        draw_verts(vis_tris, GL_TRIANGLES, (0.28, 0.56, 0.92, 0.22))

        # Maze wireframe walls
        lines = []
        for z in range(N):
            for x in range(N):
                wl = self.walls[z][x]
                if wl[0]:
                    lines.extend([*to_ndc(x, z), *to_ndc(x + 1, z)])
                if wl[3]:
                    lines.extend([*to_ndc(x, z), *to_ndc(x, z + 1)])
                if z == N - 1 and wl[2]:
                    lines.extend([*to_ndc(x, z + 1), *to_ndc(x + 1, z + 1)])
                if x == N - 1 and wl[1]:
                    lines.extend([*to_ndc(x + 1, z), *to_ndc(x + 1, z + 1)])
        gl.glLineWidth(1.6)
        draw_verts(lines, GL_LINES, (0.86, 0.92, 1.0, 0.78))

        def marker(gx, gz, r, rgba):
            cx, cy = to_ndc(gx, gz)
            rx, ry = r * cw, r * ch
            pts = [cx, cy + ry, cx + rx, cy, cx, cy - ry,
                   cx, cy + ry, cx, cy - ry, cx - rx, cy]
            draw_verts(pts, GL_TRIANGLES, rgba)

        # Goal yellow diamond
        marker(self.goal[0] + 0.5, self.goal[1] + 0.5, 0.34, (1.0, 0.86, 0.12, 0.95))
        # Flippers cyan diamonds
        for fl in self.flippers:
            if fl[2]:
                marker(fl[0], fl[1], 0.25, (0.40, 0.86, 1.0, 0.90))
        # Rat warm pink/tan marker
        if self.rat_enabled:
            marker(self.rat_pos[0], self.rat_pos[1], 0.22, (0.95, 0.72, 0.68, 0.92))

        # Player red directional arrow
        px, py = to_ndc(self.cam_x, self.cam_z)
        fx, fz = math.sin(self.cam_yaw), -math.cos(self.cam_yaw)
        # Map screen Y is -Z
        dx, dy = fx * cw * 0.42, -fz * ch * 0.42
        rx, ry = math.cos(self.cam_yaw) * cw * 0.26, math.sin(self.cam_yaw) * ch * 0.26
        arrow = [
            px + dx, py + dy,
            px - dx * 0.65 + rx, py - dy * 0.65 + ry,
            px - dx * 0.65 - rx, py - dy * 0.65 - ry,
        ]
        draw_verts(arrow, GL_TRIANGLES, (1.0, 0.18, 0.18, 0.96))

        gl.glDisable(GL_BLEND)
        gl.glEnable(GL_DEPTH_TEST)

    def on_render(self, area, _gl_ctx):
        if not self.ready:
            return True
        now = time.monotonic()
        dt = now - self.last_t
        self.last_t = now
        self.step_simulation(dt)

        gl = self.gl
        scale = area.get_scale_factor()
        alloc = area.get_allocation()
        w = max(1, alloc.width * scale)
        h = max(1, alloc.height * scale)

        gl.glViewport(0, 0, w, h)
        gl.glClearColor(0.06, 0.05, 0.06, 1.0)
        gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gl.glEnable(GL_DEPTH_TEST)
        gl.glDepthFunc(GL_LESS)
        gl.glDisable(GL_CULL_FACE)
        gl.glDisable(GL_BLEND)

        aspect = w / float(h)
        proj = mat_perspective(math.radians(68.0), aspect, 0.05, 36.0)

        # Camera position & orientation (with smooth 180-deg ceiling-flip roll)
        eye = (self.cam_x, 0.50, self.cam_z)
        fx = math.sin(self.cam_yaw)
        fz = -math.cos(self.cam_yaw)
        target = (eye[0] + fx, eye[1], eye[2] + fz)
        rx, rz = math.cos(self.cam_yaw), math.sin(self.cam_yaw)
        sr, cr = math.sin(self.roll_angle), math.cos(self.roll_angle)
        up = (-sr * rx, cr, -sr * rz)
        view = mat_lookat(eye, target, up)
        vp = mat_mul(proj, view)

        # 1. Textured world geometry (floor, ceiling, walls, posters, sprites)
        gl.glUseProgram(self.prog_world)
        gl.glUniform1i(self.u_w_tex, 0)
        gl.glUniform3f(self.u_w_cam, eye[0], eye[1], eye[2])
        gl.glUniform3f(self.u_w_fogc, 0.07, 0.06, 0.07)
        gl.glUniform1f(self.u_w_fogs, 1.8)
        gl.glUniform1f(self.u_w_foge, 10.5)

        ident = mat_identity()
        self._draw_world_mesh("floor", "floor", ident, vp, wall_scale=1.0)
        self._draw_world_mesh("ceiling", "ceiling", ident, vp, wall_scale=1.0)
        if self.wall_scale > 0.005:
            self._draw_world_mesh("walls", "wall", ident, vp, wall_scale=self.wall_scale)
            self._draw_world_mesh("poster_gl", "poster_gl", ident, vp, wall_scale=self.wall_scale, alpha_cut=0.45)
            self._draw_world_mesh("poster_xp", "poster_xp", ident, vp, wall_scale=self.wall_scale, alpha_cut=0.45)

        # Start sign billboard (faces camera with a gentle sway so text is always readable)
        if self.start_sign[2] and self.wall_scale > 0.2:
            bob = math.sin(self.elapsed * 2.6) * 0.035
            face_ang = math.atan2(self.cam_x - self.start_sign[0], self.cam_z - self.start_sign[1])
            sway = math.sin(self.elapsed * 2.2) * 0.28
            self._draw_billboard(
                self.start_sign[0], (0.50 + bob) * self.wall_scale, self.start_sign[1],
                0.44, 0.44 * self.wall_scale, "start", vp, spin_y=face_ang + sway,
            )

        # Goal Smiley Face Trophy (spins fast during celebration!)
        if self.wall_scale > 0.1:
            spin_rate = 6.5 if self.state == "CELEBRATE" else 2.2
            bob = math.sin(self.elapsed * 3.0) * 0.05
            self._draw_billboard(
                self.goal[0] + 0.5, (0.50 + bob) * self.wall_scale, self.goal[1] + 0.5,
                0.56, 0.56 * self.wall_scale, "smiley", vp, spin_y=self.elapsed * spin_rate,
            )

        # Roaming Maze Rat (hugs the floor!)
        if self.rat_enabled and self.wall_scale > 0.3:
            waddle = abs(math.sin(self.elapsed * 14.0)) * 0.02
            self._draw_billboard(
                self.rat_pos[0], 0.16 + waddle, self.rat_pos[1],
                0.34, 0.30, "rat", vp, spin_y=None,
            )

        # 2. Flat-shaded 3D Floating Flipper Polyhedra (octahedrons)
        if self.wall_scale > 0.2:
            gl.glUseProgram(self.prog_poly)
            vao, _, count = self.meshes["octa"]
            gl.glBindVertexArray(vao)
            for idx, fl in enumerate(self.flippers):
                if not fl[2]:
                    continue
                bob = math.sin(self.elapsed * 2.8 + idx * 1.7) * 0.06
                rot = mat_mul(mat_rot_y(self.elapsed * 2.1 + idx), mat_rot_x(self.elapsed * 1.5))
                m = mat_mul(
                    mat_translate(fl[0], (0.50 + bob) * self.wall_scale, fl[1]),
                    mat_mul(rot, mat_scale(0.18, 0.18 * self.wall_scale, 0.18)),
                )
                mvp = mat_mul(vp, m)
                gl.glUniformMatrix4fv(self.u_p_mvp, 1, GL_FALSE, (ctypes.c_float * 16)(*mvp))
                gl.glUniformMatrix4fv(self.u_p_model, 1, GL_FALSE, (ctypes.c_float * 16)(*m))
                gl.glUniform4f(self.u_p_col, 0.52, 0.78, 0.98, 1.0)
                gl.glDrawArrays(GL_TRIANGLES, 0, count)

        # 3. Classic Translucent Maze Overlay Minimap
        if self.show_overlay:
            self._draw_hud_overlay(w, h)

        return True


# =============================================================================
# Fullscreen Layer-Shell Screen Saver Window
# =============================================================================

class XPScreenSaver(Gtk.Window):
    def __init__(self, mode):
        super().__init__(type=Gtk.WindowType.TOPLEVEL)
        self.mode = mode
        self.start_time = time.monotonic()
        self.init_pointer = None

        self.set_decorated(False)
        GtkLayerShell.init_for_window(self)
        GtkLayerShell.set_layer(self, GtkLayerShell.Layer.OVERLAY)
        GtkLayerShell.set_namespace(self, "xp-screensaver")
        for edge in (GtkLayerShell.Edge.TOP, GtkLayerShell.Edge.BOTTOM, GtkLayerShell.Edge.LEFT, GtkLayerShell.Edge.RIGHT):
            GtkLayerShell.set_anchor(self, edge, True)
        GtkLayerShell.set_exclusive_zone(self, -1)
        GtkLayerShell.set_keyboard_mode(self, GtkLayerShell.KeyboardMode.EXCLUSIVE)

        self.maze_widget = None
        if mode == "maze":
            self.maze_widget = Maze3DWidget(read_maze_cfg())
            self.maze_widget.add_events(Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK)
            self.maze_widget.connect("motion-notify-event", self.on_motion)
            self.maze_widget.connect("button-press-event", lambda *_: Gtk.main_quit())
            self.add(self.maze_widget)
            GLib.timeout_add(16, self._tick_maze)
        else:
            self.da = Gtk.DrawingArea()
            self.da.add_events(Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.BUTTON_PRESS_MASK)
            self.da.connect("draw", self.on_draw)
            self.da.connect("motion-notify-event", self.on_motion)
            self.da.connect("button-press-event", lambda *_: Gtk.main_quit())
            self.add(self.da)

            self.logo_pb = None
            if os.path.exists(LOGO_PATH):
                try:
                    self.logo_pb = GdkPixbuf.Pixbuf.new_from_file(LOGO_PATH)
                except Exception:
                    pass
            self.logo_pos = (0.42, 0.42)
            self.last_jump = 0.0

            self.stars = [[random.uniform(-1, 1), random.uniform(-1, 1), random.uniform(0.05, 1.0)] for _ in range(180)]
            self.polys = []
            for col in ((0.0, 0.85, 1.0), (1.0, 0.35, 0.85)):
                pts = [[random.uniform(0.1, 0.9), random.uniform(0.1, 0.9),
                        random.choice((-1, 1)) * random.uniform(0.004, 0.009),
                        random.choice((-1, 1)) * random.uniform(0.004, 0.009)] for _ in range(4)]
                self.polys.append({"color": col, "pts": pts, "trail": collections.deque(maxlen=10)})

            interval = 33 if mode in ("starfield", "mystify") else 250
            GLib.timeout_add(interval, self.on_tick)

        self.connect("key-press-event", self.on_key)
        self.connect("realize", self._hide_cursor)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda: (Gtk.main_quit(), False)[1])

    def _hide_cursor(self, _w):
        w = self.get_window()
        if w:
            blank = Gdk.Cursor.new_for_display(w.get_display(), Gdk.CursorType.BLANK_CURSOR)
            w.set_cursor(blank)

    def on_key(self, _w, ev):
        # 'M' toggles the classic wireframe Maze Overlay without exiting
        if self.maze_widget is not None and ev.keyval in (Gdk.KEY_m, Gdk.KEY_M):
            self.maze_widget.toggle_overlay()
            return True
        Gtk.main_quit()
        return True

    def on_motion(self, _w, ev):
        if time.monotonic() - self.start_time < 0.85:
            self.init_pointer = (ev.x, ev.y)
            return False
        if self.init_pointer is None:
            self.init_pointer = (ev.x, ev.y)
            return False
        dx = ev.x - self.init_pointer[0]
        dy = ev.y - self.init_pointer[1]
        if dx * dx + dy * dy > 400:
            Gtk.main_quit()
        return False

    def _tick_maze(self):
        if self.maze_widget is not None:
            self.maze_widget.queue_render()
        return True

    def on_tick(self):
        if self.mode == "xp-logo":
            now = time.monotonic()
            if now - self.last_jump >= 4.5:
                self.last_jump = now
                self.logo_pos = (random.uniform(0.08, 0.78), random.uniform(0.08, 0.78))
                self.da.queue_draw()
        elif self.mode == "starfield":
            for s in self.stars:
                s[2] -= 0.018
                if s[2] <= 0.02:
                    s[0] = random.uniform(-1, 1)
                    s[1] = random.uniform(-1, 1)
                    s[2] = 1.0
            self.da.queue_draw()
        elif self.mode == "mystify":
            for poly in self.polys:
                snap = []
                for p in poly["pts"]:
                    p[0] += p[2]
                    p[1] += p[3]
                    if p[0] <= 0.01 or p[0] >= 0.99:
                        p[2] = -p[2]
                        p[0] = max(0.01, min(0.99, p[0]))
                    if p[1] <= 0.01 or p[1] >= 0.99:
                        p[3] = -p[3]
                        p[1] = max(0.01, min(0.99, p[1]))
                    snap.append((p[0], p[1]))
                poly["trail"].append(snap)
            self.da.queue_draw()
        return True

    def on_draw(self, _w, cr):
        a = self.da.get_allocation()
        w, h = a.width, a.height
        cr.set_source_rgb(0.0, 0.0, 0.0)
        cr.rectangle(0, 0, w, h)
        cr.fill()

        if self.mode == "xp-logo":
            lx = int(self.logo_pos[0] * w)
            ly = int(self.logo_pos[1] * h)
            if self.logo_pb:
                Gdk.cairo_set_source_pixbuf(cr, self.logo_pb, lx, ly)
                cr.paint()
            cr.set_source_rgb(0.85, 0.88, 0.95)
            cr.select_font_face("Tahoma", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
            cr.set_font_size(14)
            cr.move_to(lx + 18, ly + 104)
            cr.show_text("Professional")

        elif self.mode == "starfield":
            cx, cy = w / 2.0, h / 2.0
            for x, y, z in self.stars:
                sx = cx + (x / z) * cx * 0.7
                sy = cy + (y / z) * cy * 0.7
                if 0 <= sx < w and 0 <= sy < h:
                    b = max(0.25, 1.0 - z)
                    sz = max(1.2, (1.0 - z) * 3.4)
                    cr.set_source_rgb(b, b, b)
                    cr.rectangle(sx, sy, sz, sz)
                    cr.fill()

        elif self.mode == "mystify":
            cr.set_line_width(1.4)
            for poly in self.polys:
                r, g, b = poly["color"]
                tr = poly["trail"]
                n = len(tr)
                for idx, snap in enumerate(tr):
                    alpha = (idx + 1) / float(max(1, n))
                    cr.set_source_rgba(r, g, b, alpha * 0.9)
                    for i, (px, py) in enumerate(snap):
                        if i == 0:
                            cr.move_to(px * w, py * h)
                        else:
                            cr.line_to(px * w, py * h)
                    cr.close_path()
                    cr.stroke()


def main():
    mode = read_saved_mode()
    for i, arg in enumerate(sys.argv[1:]):
        if arg == "--mode" and i + 2 < len(sys.argv):
            mode = sys.argv[i + 2].lower()
    if mode == "none":
        return
    win = XPScreenSaver(mode)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()
