#!/usr/bin/env python3
"""Native Windows XP Display Properties (Themes, Desktop Wallpaper, Appearance)."""

import json
import os
import subprocess
import sys
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")
from gi.repository import Gtk, Gdk, GdkPixbuf

THEME_ENV = Path("/home/carsten/.config/hypr/xp-theme.env")
HYPRPAPER_CONF = Path("/home/carsten/.config/hypr/hyprpaper.conf")
WALL_DIR = Path("/usr/local/share/backgrounds/wintc")
THEME_SWITCH = "/home/carsten/.local/bin/xp-theme-switch"

THEMES = [
    ("luna-blue",      "Windows XP (Default Blue)",      "#0053E3", "#3D94FF", "#ECE9D8", "#2257D5", "#3C9E3E", "#7A97DF"),
    ("luna-homestead", "Windows XP (Olive Green)",       "#8BA169", "#C6D2A2", "#ECE9D8", "#8EA46C", "#C76C23", "#D4D6BA"),
    ("luna-metallic",  "Windows XP (Silver)",            "#808391", "#C8C8C8", "#E0DFE3", "#B2B4C2", "#3C9E3E", "#D8D9E0"),
    ("royale",         "Media Center style (Royale)",    "#335EA8", "#70B1EB", "#EBE9ED", "#2B5CA8", "#3C9E3E", "#6FA1D9"),
    ("royale-noir",    "Media Center style (Royale Noir)","#272F42","#5C6976", "#EBE9ED", "#1F2636", "#2A3244", "#5F6772"),
    ("zune",           "Zune style",                     "#343434", "#747474", "#E2E2E2", "#282828", "#E36B14", "#747474"),
    ("embedded",       "Embedded style",                 "#3E9DE8", "#70B1EB", "#EBE9ED", "#246EAE", "#2C7EC4", "#6FA1D9"),
    ("professional",   "Professional",                   "#5298F9", "#3573D6", "#ECE9D8", "#3573D6", "#3C9E3E", "#2C60B2"),
    ("classic",        "Windows Classic",                "#0A246A", "#A6CAF0", "#D4D0C8", "#D4D0C8", "#D4D0C8", "#808080"),
]


def hex_rgb(h):
    h = h.lstrip("#")
    return tuple(int(h[i:i+2], 16) / 255.0 for i in (0, 2, 4))


def read_current_env():
    vals = {
        "XP_THEME_KEY": "luna-blue",
        "XP_WALLPAPER": "/usr/local/share/backgrounds/wintc/bliss.jpg",
        "XP_CURSOR_THEME": "standard-with-shadow",
        "XP_CURSOR_SIZE": "24",
    }
    if THEME_ENV.exists():
        for line in THEME_ENV.read_text(encoding="utf-8").splitlines():
            if "=" in line and not line.strip().startswith("#"):
                k, v = line.split("=", 1)
                vals[k.strip()] = v.strip().strip('"').strip("'")
    return vals


class CRTMonitorPreview(Gtk.DrawingArea):
    """Iconic Windows XP Display Properties CRT monitor preview."""

    def __init__(self):
        super().__init__()
        self.set_size_request(260, 178)
        self.theme_info = THEMES[0]
        self.wall_path = "/usr/local/share/backgrounds/wintc/bliss.jpg"
        self.wall_pb = None
        self.ss_mode = None
        self.connect("draw", self.on_draw)
        self._load_wall()

    def set_screensaver_mode(self, mode):
        self.ss_mode = mode
        self.queue_draw()

    def set_theme(self, theme_tuple):
        self.theme_info = theme_tuple
        self.queue_draw()

    def set_wallpaper(self, path):
        if path != self.wall_path:
            self.wall_path = path
            self._load_wall()
            self.queue_draw()

    def _load_wall(self):
        self.wall_pb = None
        if self.wall_path and os.path.exists(self.wall_path):
            try:
                self.wall_pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(self.wall_path, 184, 114, False)
            except Exception:
                self.wall_pb = None

    def on_draw(self, _widget, cr):
        alloc = self.get_allocation()
        cx = alloc.width / 2.0

        # Monitor outer bezel (classic beige/gray CRT frame)
        mw, mh = 208, 138
        mx, my = cx - mw / 2.0, 6
        cr.set_source_rgb(0.78, 0.77, 0.72)
        cr.rectangle(mx, my, mw, mh)
        cr.fill()
        cr.set_source_rgb(0.95, 0.94, 0.90)
        cr.set_line_width(1.5)
        cr.move_to(mx, my + mh)
        cr.line_to(mx, my)
        cr.line_to(mx + mw, my)
        cr.stroke()
        cr.set_source_rgb(0.45, 0.44, 0.40)
        cr.move_to(mx + mw, my)
        cr.line_to(mx + mw, my + mh)
        cr.line_to(mx, my + mh)
        cr.stroke()

        # Monitor stand neck & base
        cr.set_source_rgb(0.68, 0.67, 0.63)
        cr.rectangle(cx - 26, my + mh, 52, 14)
        cr.fill()
        cr.set_source_rgb(0.78, 0.77, 0.72)
        cr.rectangle(cx - 56, my + mh + 14, 112, 10)
        cr.fill()
        cr.set_source_rgb(0.45, 0.44, 0.40)
        cr.rectangle(cx - 56, my + mh + 14, 112, 10)
        cr.stroke()

        # Power LED
        cr.set_source_rgb(0.15, 0.80, 0.25)
        cr.arc(mx + mw - 14, my + mh - 6, 2.2, 0, 6.283)
        cr.fill()

        # Inner screen viewport (184x114)
        sx, sy, sw, sh = int(mx + 12), int(my + 10), 184, 114
        cr.save()
        cr.rectangle(sx, sy, sw, sh)
        cr.clip()

        if self.ss_mode and self.ss_mode != "none":
            self._draw_screensaver_preview(cr, sx, sy, sw, sh)
        else:
            # Wallpaper
            if self.wall_pb:
                Gdk.cairo_set_source_pixbuf(cr, self.wall_pb, sx, sy)
                cr.paint()
            else:
                cr.set_source_rgb(0.23, 0.43, 0.65)
                cr.rectangle(sx, sy, sw, sh)
                cr.fill()

            _, _, hdr1, hdr2, bg, bar_c, start_c, ihdr = self.theme_info

            # Mini inactive window
            ix, iy, iw, ih = sx + 10, sy + 10, 104, 62
            cr.set_source_rgb(*hex_rgb(bg))
            cr.rectangle(ix, iy, iw, ih)
            cr.fill()
            cr.set_source_rgb(*hex_rgb(ihdr))
            cr.rectangle(ix, iy, iw, 13)
            cr.fill()
            cr.set_source_rgb(*hex_rgb(ihdr))
            cr.set_line_width(1)
            cr.rectangle(ix + 0.5, iy + 0.5, iw - 1, ih - 1)
            cr.stroke()

            # Mini active window
            ax, ay, aw, ah = sx + 38, sy + 28, 128, 66
            cr.set_source_rgb(*hex_rgb(bg))
            cr.rectangle(ax, ay, aw, ah)
            cr.fill()
            pat = cairo.LinearGradient(ax, ay, ax, ay + 15)
            pat.add_color_stop_rgb(0.0, *hex_rgb(hdr2))
            pat.add_color_stop_rgb(1.0, *hex_rgb(hdr1))
            cr.set_source(pat)
            cr.rectangle(ax, ay, aw, 15)
            cr.fill()
            # Mini close button
            cr.set_source_rgb(0.87, 0.28, 0.15)
            cr.rectangle(ax + aw - 12, ay + 3, 9, 9)
            cr.fill()
            # Mini white content box & OK button
            cr.set_source_rgb(1, 1, 1)
            cr.rectangle(ax + 6, ay + 20, aw - 12, 26)
            cr.fill()
            cr.set_source_rgb(0.95, 0.94, 0.91)
            cr.rectangle(ax + aw - 38, ay + ah - 15, 32, 11)
            cr.fill()
            cr.set_source_rgb(*hex_rgb(hdr1))
            cr.rectangle(ax + 0.5, ay + 0.5, aw - 1, ah - 1)
            cr.stroke()

            # Mini Taskbar + Start button
            tb_h = 13
            cr.set_source_rgb(*hex_rgb(bar_c))
            cr.rectangle(sx, sy + sh - tb_h, sw, tb_h)
            cr.fill()
            cr.set_source_rgb(*hex_rgb(start_c))
            cr.rectangle(sx, sy + sh - tb_h, 30, tb_h)
            cr.fill()

        cr.restore()

        # Screen inset border
        cr.set_source_rgb(0.25, 0.25, 0.25)
        cr.set_line_width(1)
        cr.rectangle(sx - 0.5, sy - 0.5, sw + 1, sh + 1)
        cr.stroke()

    def _draw_screensaver_preview(self, cr, sx, sy, sw, sh):
        cr.set_source_rgb(0.0, 0.0, 0.0)
        cr.rectangle(sx, sy, sw, sh)
        cr.fill()
        if self.ss_mode == "maze":
            # Classic 3D brick corridor perspective inside CRT
            # Ceiling (plaster)
            cr.set_source_rgb(0.82, 0.80, 0.75)
            cr.move_to(sx, sy)
            cr.line_to(sx + sw, sy)
            cr.line_to(sx + sw - 54, sy + 36)
            cr.line_to(sx + 54, sy + 36)
            cr.close_path()
            cr.fill()
            # Wood floor
            cr.set_source_rgb(0.68, 0.50, 0.30)
            cr.move_to(sx, sy + sh)
            cr.line_to(sx + sw, sy + sh)
            cr.line_to(sx + sw - 54, sy + sh - 36)
            cr.line_to(sx + 54, sy + sh - 36)
            cr.close_path()
            cr.fill()
            # Left & right brick walls
            cr.set_source_rgb(0.56, 0.22, 0.16)
            cr.move_to(sx, sy)
            cr.line_to(sx + 54, sy + 36)
            cr.line_to(sx + 54, sy + sh - 36)
            cr.line_to(sx, sy + sh)
            cr.close_path()
            cr.fill()
            cr.set_source_rgb(0.50, 0.19, 0.14)
            cr.move_to(sx + sw, sy)
            cr.line_to(sx + sw - 54, sy + 36)
            cr.line_to(sx + sw - 54, sy + sh - 36)
            cr.line_to(sx + sw, sy + sh)
            cr.close_path()
            cr.fill()
            # Far end brick wall
            cr.set_source_rgb(0.62, 0.25, 0.19)
            cr.rectangle(sx + 54, sy + 36, sw - 108, sh - 72)
            cr.fill()
            # Mortar lines on far wall
            cr.set_source_rgba(0.85, 0.82, 0.76, 0.45)
            cr.set_line_width(0.8)
            for row in range(1, 5):
                yy = sy + 36 + row * (sh - 72) / 5.0
                cr.move_to(sx + 54, yy)
                cr.line_to(sx + sw - 54, yy)
                cr.stroke()
            # Floating golden smiley trophy in center
            cx, cy = sx + sw / 2.0, sy + sh / 2.0
            cr.set_source_rgb(0.98, 0.84, 0.14)
            cr.arc(cx, cy, 11, 0, 6.283)
            cr.fill()
            cr.set_source_rgb(0.1, 0.1, 0.1)
            cr.arc(cx - 3.5, cy - 2.5, 1.4, 0, 6.283)
            cr.arc(cx + 3.5, cy - 2.5, 1.4, 0, 6.283)
            cr.fill()
            cr.set_line_width(1.4)
            cr.arc(cx, cy + 1, 5.5, 0.4, 2.74)
            cr.stroke()
        elif self.ss_mode == "starfield":
            for i in range(42):
                px = sx + ((i * 37) % sw)
                py = sy + ((i * 23) % sh)
                b = 0.4 + 0.6 * ((i % 5) / 4.0)
                cr.set_source_rgb(b, b, b)
                cr.rectangle(px, py, 1.8, 1.8)
                cr.fill()
        elif self.ss_mode == "mystify":
            cr.set_line_width(1.0)
            for idx, col in enumerate(((0.0, 0.85, 1.0), (1.0, 0.35, 0.85))):
                for t in range(4):
                    cr.set_source_rgba(*col, 0.35 + 0.18 * t)
                    o = t * 5 + idx * 14
                    cr.move_to(sx + 20 + o, sy + 18 + t * 3)
                    cr.line_to(sx + sw - 22 - t * 4, sy + 28 + o * 0.4)
                    cr.line_to(sx + sw - 34 + t * 2, sy + sh - 18 - t * 3)
                    cr.line_to(sx + 30 + t * 4, sy + sh - 32 + idx * 8)
                    cr.close_path()
                    cr.stroke()
        else:
            # Windows XP Logo preview
            cx, cy = sx + sw / 2.0, sy + sh / 2.0 - 4
            for dx, dy, col in [(-14, -10, (0.92, 0.27, 0.14)), (2, -10, (0.47, 0.77, 0.18)),
                                (-14, 4, (0.15, 0.58, 0.95)), (2, 4, (0.97, 0.76, 0.10))]:
                cr.set_source_rgb(*col)
                cr.rectangle(cx + dx, cy + dy, 12, 11)
                cr.fill()
            cr.set_source_rgb(0.88, 0.90, 0.96)
            cr.select_font_face("Tahoma", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
            cr.set_font_size(10)
            cr.move_to(cx - 32, cy + 28)
            cr.show_text("Windows XP")


class XPDisplayProperties(Gtk.Window):
    def __init__(self, initial_tab=0):
        super().__init__(title="Display Properties")
        self.set_wmclass("xp-display-properties", "xp-display-properties")
        self.set_resizable(False)
        self.set_default_size(404, 468)
        self.set_border_width(8)

        self.env = read_current_env()
        self.selected_theme_key = self.env["XP_THEME_KEY"]
        self.selected_wallpaper = self.env["XP_WALLPAPER"]
        self.selected_cursor = self.env["XP_CURSOR_THEME"]
        self.selected_cursor_size = int(self.env.get("XP_CURSOR_SIZE", "24") or 24)

        root = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        self.add(root)

        self.notebook = Gtk.Notebook()
        root.pack_start(self.notebook, True, True, 0)

        self.previews = []
        self._build_themes_tab()
        self._build_desktop_tab()
        self._build_screensaver_tab()
        self._build_appearance_tab()

        self.notebook.set_current_page(initial_tab)

        # Bottom OK / Cancel / Apply
        btns = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        btns.set_halign(Gtk.Align.END)
        for lbl, cb in [("OK", self.on_ok), ("Cancel", lambda *_: Gtk.main_quit()), ("Apply", self.on_apply)]:
            b = Gtk.Button.new_with_label(lbl)
            b.set_size_request(76, 24)
            b.connect("clicked", cb)
            btns.pack_start(b, False, False, 0)
        root.pack_end(btns, False, False, 0)

        self.initial_tab = initial_tab
        self.sync_previews()
        self.connect("key-press-event", lambda _w, ev: Gtk.main_quit() if ev.keyval == Gdk.KEY_Escape else False)
        self.connect("destroy", Gtk.main_quit)

    def sync_previews(self):
        tinfo = next((t for t in THEMES if t[0] == self.selected_theme_key), THEMES[0])
        for p in self.previews:
            p.set_theme(tinfo)
            p.set_wallpaper(self.selected_wallpaper)

    def _build_themes_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        box.set_border_width(12)

        desc = Gtk.Label(label="A theme is a background plus a set of sounds, icons, and other elements to help you personalize your computer with one click.")
        desc.set_line_wrap(True)
        desc.set_max_width_chars(52)
        desc.set_xalign(0.0)
        box.pack_start(desc, False, False, 0)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        lbl = Gtk.Label(label="Theme:")
        row.pack_start(lbl, False, False, 0)
        self.theme_combo = Gtk.ComboBoxText()
        active_idx = 0
        for idx, t in enumerate(THEMES):
            self.theme_combo.append(t[0], t[1])
            if t[0] == self.selected_theme_key:
                active_idx = idx
        self.theme_combo.set_active(active_idx)
        self.theme_combo.connect("changed", self._on_theme_changed)
        row.pack_start(self.theme_combo, True, True, 0)
        box.pack_start(row, False, False, 0)

        frame = Gtk.Frame(label=" Sample: ")
        prev = CRTMonitorPreview()
        prev.set_margin_top(6)
        prev.set_margin_bottom(6)
        frame.add(prev)
        self.previews.append(prev)
        box.pack_start(frame, True, True, 0)

        self.notebook.append_page(box, Gtk.Label(label="Themes"))

    def _build_desktop_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        box.set_border_width(12)

        prev = CRTMonitorPreview()
        self.previews.append(prev)
        box.pack_start(prev, False, False, 0)

        lbl = Gtk.Label(label="Background:")
        lbl.set_xalign(0.0)
        box.pack_start(lbl, False, False, 0)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        sw.set_shadow_type(Gtk.ShadowType.IN)
        sw.set_size_request(260, 145)

        self.wall_store = Gtk.ListStore(str, str)
        walls = sorted(WALL_DIR.glob("*")) if WALL_DIR.exists() else []
        sel_iter = None
        for wp in walls:
            if wp.suffix.lower() in (".jpg", ".jpeg", ".png", ".bmp"):
                it = self.wall_store.append([wp.stem.capitalize(), str(wp)])
                if str(wp) == self.selected_wallpaper:
                    sel_iter = it

        self.wall_view = Gtk.TreeView(model=self.wall_store)
        self.wall_view.set_headers_visible(False)
        col = Gtk.TreeViewColumn("Wallpaper", Gtk.CellRendererText(), text=0)
        self.wall_view.append_column(col)
        sel = self.wall_view.get_selection()
        if sel_iter:
            sel.select_iter(sel_iter)
            self.wall_view.scroll_to_cell(self.wall_store.get_path(sel_iter))
        sel.connect("changed", self._on_wall_selected)
        sw.add(self.wall_view)
        row.pack_start(sw, True, True, 0)

        side = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        browse = Gtk.Button.new_with_label("Browse...")
        browse.set_size_request(82, 24)
        browse.connect("clicked", self._on_browse_wall)
        side.pack_start(browse, False, False, 0)
        row.pack_start(side, False, False, 0)

        box.pack_start(row, True, True, 0)
        self.notebook.append_page(box, Gtk.Label(label="Desktop"))

    def _build_screensaver_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        box.set_border_width(12)

        ss_conf = Path("/home/carsten/.config/hypr/xp-screensaver.conf")
        cur_ss = ss_conf.read_text(encoding="utf-8").strip() if ss_conf.exists() else "maze"
        if cur_ss not in ("none", "maze", "xp-logo", "starfield", "mystify"):
            cur_ss = "maze"

        self.ss_preview = CRTMonitorPreview()
        self.ss_preview.set_screensaver_mode(cur_ss)
        self.previews.append(self.ss_preview)
        box.pack_start(self.ss_preview, False, False, 0)

        frame = Gtk.Frame(label=" Screen saver ")
        inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        inner.set_border_width(10)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        self.ss_combo = Gtk.ComboBoxText()
        for sid, label in [
            ("none", "(None)"),
            ("maze", "3D Maze"),
            ("xp-logo", "Windows XP"),
            ("starfield", "Starfield"),
            ("mystify", "Mystify"),
        ]:
            self.ss_combo.append(sid, label)
        self.ss_combo.set_active_id(cur_ss)
        row.pack_start(self.ss_combo, True, True, 0)

        self.ss_settings_btn = Gtk.Button.new_with_label("Settings...")
        self.ss_settings_btn.set_size_request(76, 24)
        self.ss_settings_btn.set_sensitive(cur_ss == "maze")
        self.ss_settings_btn.connect("clicked", self._on_maze_settings)
        row.pack_start(self.ss_settings_btn, False, False, 0)

        prev_btn = Gtk.Button.new_with_label("Preview")
        prev_btn.set_size_request(70, 24)
        prev_btn.connect("clicked", lambda *_: subprocess.Popen(
            ["/home/carsten/.local/bin/xp-screensaver", "--mode", self.ss_combo.get_active_id() or "maze"],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        ))
        row.pack_start(prev_btn, False, False, 0)
        inner.pack_start(row, False, False, 0)

        def on_ss_changed(combo):
            sid = combo.get_active_id() or "none"
            self.ss_preview.set_screensaver_mode(sid)
            self.ss_settings_btn.set_sensitive(sid == "maze")

        self.ss_combo.connect("changed", on_ss_changed)

        note = Gtk.Label(label="Activates automatically after 4 minutes of idle (press M in 3D Maze to toggle map).", xalign=0)
        note.set_line_wrap(True)
        note.set_max_width_chars(46)
        inner.pack_start(note, False, False, 0)
        frame.add(inner)
        box.pack_start(frame, False, False, 0)
        self.notebook.append_page(box, Gtk.Label(label="Screen Saver"))

    def _on_maze_settings(self, _btn):
        maze_conf = Path("/home/carsten/.config/hypr/xp-maze.json")
        cfg = {
            "wall": "brick", "floor": "wood", "ceiling": "plaster",
            "overlay": True, "flippers": True, "rat": True,
            "speed": 1.0, "maze_size": 11,
        }
        if maze_conf.exists():
            try:
                cfg.update(json.loads(maze_conf.read_text(encoding="utf-8")))
            except Exception:
                pass

        dlg = Gtk.Dialog(title="3D Maze Setup", transient_for=self, flags=0)
        dlg.add_buttons("Cancel", Gtk.ResponseType.CANCEL, "OK", Gtk.ResponseType.OK)
        dlg.set_resizable(False)
        area = dlg.get_content_area()
        area.set_border_width(12)
        area.set_spacing(10)

        tex_frame = Gtk.Frame(label=" Textures ")
        grid = Gtk.Grid(row_spacing=6, column_spacing=10)
        grid.set_border_width(8)

        def make_combo(opts, cur):
            cb = Gtk.ComboBoxText()
            for k, lbl in opts:
                cb.append(k, lbl)
            cb.set_active_id(cur)
            if cb.get_active() < 0:
                cb.set_active(0)
            return cb

        wall_cb = make_combo([
            ("brick", "Brick (Classic)"), ("hedge", "Garden Hedge"),
            ("stone", "Medieval Stone"), ("wood-dark", "Wood Paneling"),
            ("psychedelic", "Psychedelic"),
        ], cfg["wall"])
        floor_cb = make_combo([
            ("wood", "Wood Planks (Classic)"), ("tile", "Checkered Tile"),
            ("marble", "Marble"), ("brick", "Brick"), ("stone", "Stone"),
        ], cfg["floor"])
        ceil_cb = make_combo([
            ("plaster", "Acoustic Plaster (Classic)"), ("wood", "Wood Planks"),
            ("starry", "Starry Night"), ("brick", "Brick"),
        ], cfg["ceiling"])

        grid.attach(Gtk.Label(label="Walls:", xalign=0), 0, 0, 1, 1)
        grid.attach(wall_cb, 1, 0, 1, 1)
        grid.attach(Gtk.Label(label="Floor:", xalign=0), 0, 1, 1, 1)
        grid.attach(floor_cb, 1, 1, 1, 1)
        grid.attach(Gtk.Label(label="Ceiling:", xalign=0), 0, 2, 1, 1)
        grid.attach(ceil_cb, 1, 2, 1, 1)
        tex_frame.add(grid)
        area.pack_start(tex_frame, False, False, 0)

        opt_frame = Gtk.Frame(label=" Options ")
        obox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        obox.set_border_width(8)
        chk_overlay = Gtk.CheckButton.new_with_label("Show translucent Maze Overlay map")
        chk_overlay.set_active(bool(cfg["overlay"]))
        chk_flippers = Gtk.CheckButton.new_with_label("Enable floating 3D ceiling-flipper polyhedra")
        chk_flippers.set_active(bool(cfg["flippers"]))
        chk_rat = Gtk.CheckButton.new_with_label("Enable roaming Maze Rat")
        chk_rat.set_active(bool(cfg["rat"]))
        obox.pack_start(chk_overlay, False, False, 0)
        obox.pack_start(chk_flippers, False, False, 0)
        obox.pack_start(chk_rat, False, False, 0)

        sp_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        sp_row.pack_start(Gtk.Label(label="Walk Speed:", xalign=0), False, False, 0)
        sp_scale = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL, 0.5, 2.0, 0.1)
        sp_scale.set_value(float(cfg.get("speed", 1.0)))
        sp_scale.set_draw_value(False)
        sp_scale.set_size_request(150, -1)
        sp_row.pack_start(sp_scale, True, True, 0)
        obox.pack_start(sp_row, False, False, 0)
        opt_frame.add(obox)
        area.pack_start(opt_frame, False, False, 0)

        dlg.show_all()
        if dlg.run() == Gtk.ResponseType.OK:
            new_cfg = {
                "wall": wall_cb.get_active_id() or "brick",
                "floor": floor_cb.get_active_id() or "wood",
                "ceiling": ceil_cb.get_active_id() or "plaster",
                "overlay": chk_overlay.get_active(),
                "flippers": chk_flippers.get_active(),
                "rat": chk_rat.get_active(),
                "speed": round(sp_scale.get_value(), 2),
                "maze_size": int(cfg.get("maze_size", 11)),
            }
            maze_conf.write_text(json.dumps(new_cfg, indent=2) + "\n", encoding="utf-8")
        dlg.destroy()

    def _build_appearance_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        box.set_border_width(12)

        prev = CRTMonitorPreview()
        self.previews.append(prev)
        box.pack_start(prev, False, False, 0)

        grid = Gtk.Grid()
        grid.set_row_spacing(8)
        grid.set_column_spacing(10)

        grid.attach(Gtk.Label(label="Color scheme:", xalign=0), 0, 0, 1, 1)
        self.scheme_combo = Gtk.ComboBoxText()
        active_idx = 0
        for idx, t in enumerate(THEMES):
            self.scheme_combo.append(t[0], t[1])
            if t[0] == self.selected_theme_key:
                active_idx = idx
        self.scheme_combo.set_active(active_idx)
        self.scheme_combo.connect("changed", self._on_scheme_changed)
        grid.attach(self.scheme_combo, 1, 0, 1, 1)

        grid.attach(Gtk.Label(label="Mouse pointer:", xalign=0), 0, 1, 1, 1)
        self.cursor_combo = Gtk.ComboBoxText()
        self.cursor_combo.append("standard-with-shadow", "Windows XP Standard (with shadow)")
        self.cursor_combo.append("standard-no-shadow", "Windows XP Standard (no shadow)")
        self.cursor_combo.set_active_id(self.selected_cursor)
        grid.attach(self.cursor_combo, 1, 1, 1, 1)

        grid.attach(Gtk.Label(label="Pointer size:", xalign=0), 0, 2, 1, 1)
        self.csize_combo = Gtk.ComboBoxText()
        for sz in ("24", "32"):
            self.csize_combo.append(sz, f"{sz} px")
        self.csize_combo.set_active_id(str(self.selected_cursor_size))
        grid.attach(self.csize_combo, 1, 2, 1, 1)

        box.pack_start(grid, False, False, 4)
        self.notebook.append_page(box, Gtk.Label(label="Appearance"))

    def _on_theme_changed(self, combo):
        tid = combo.get_active_id()
        if tid and tid != self.selected_theme_key:
            self.selected_theme_key = tid
            if hasattr(self, "scheme_combo"):
                self.scheme_combo.set_active_id(tid)
            self.sync_previews()

    def _on_scheme_changed(self, combo):
        tid = combo.get_active_id()
        if tid and tid != self.selected_theme_key:
            self.selected_theme_key = tid
            self.theme_combo.set_active_id(tid)
            self.sync_previews()

    def _on_wall_selected(self, selection):
        model, it = selection.get_selected()
        if it:
            self.selected_wallpaper = model[it][1]
            self.sync_previews()

    def _on_browse_wall(self, _btn):
        dlg = Gtk.FileChooserDialog(
            title="Select Wallpaper",
            parent=self,
            action=Gtk.FileChooserAction.OPEN,
            buttons=("Cancel", Gtk.ResponseType.CANCEL, "Open", Gtk.ResponseType.OK),
        )
        flt = Gtk.FileFilter()
        flt.set_name("Images")
        for pat in ("*.png", "*.jpg", "*.jpeg", "*.bmp", "*.webp"):
            flt.add_pattern(pat)
        dlg.add_filter(flt)
        if dlg.run() == Gtk.ResponseType.OK:
            fn = dlg.get_filename()
            if fn:
                self.selected_wallpaper = fn
                self.sync_previews()
        dlg.destroy()

    def apply_changes(self):
        # 1. Apply visual style if changed
        if self.selected_theme_key != self.env["XP_THEME_KEY"]:
            subprocess.run([THEME_SWITCH, self.selected_theme_key], check=False)
            self.env["XP_THEME_KEY"] = self.selected_theme_key

        # 2. Apply wallpaper via hyprpaper + persist to hyprpaper.conf & xp-theme.env
        if self.selected_wallpaper and os.path.exists(self.selected_wallpaper):
            HYPRPAPER_CONF.write_text(
                f"splash = false\nwallpaper {{\n    monitor =\n    path = {self.selected_wallpaper}\n    fit_mode = cover\n}}\n",
                encoding="utf-8",
            )
            subprocess.run(["hyprctl", "hyprpaper", "wallpaper", f",{self.selected_wallpaper},cover"],
                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
            self.env["XP_WALLPAPER"] = self.selected_wallpaper

        # 3. Apply cursor theme & size
        ctheme = self.cursor_combo.get_active_id() or "standard-with-shadow"
        csize = self.csize_combo.get_active_id() or "24"
        subprocess.run(["hyprctl", "setcursor", ctheme, csize],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
        subprocess.run(
            ["gsettings", "set", "org.gnome.desktop.interface", "cursor-theme", ctheme],
            env={**os.environ, "DCONF_PROFILE": "/home/carsten/.config/hypr/dconf/profile"},
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False,
        )
        subprocess.run(
            ["gsettings", "set", "org.gnome.desktop.interface", "cursor-size", csize],
            env={**os.environ, "DCONF_PROFILE": "/home/carsten/.config/hypr/dconf/profile"},
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False,
        )

        # 4. Persist screen saver choice
        if hasattr(self, "ss_combo"):
            ss_val = self.ss_combo.get_active_id() or "xp-logo"
            Path("/home/carsten/.config/hypr/xp-screensaver.conf").write_text(ss_val + "\n", encoding="utf-8")

        # Persist wallpaper & cursor in xp-theme.env
        if THEME_ENV.exists():
            lines = []
            for line in THEME_ENV.read_text(encoding="utf-8").splitlines():
                if line.startswith("XP_WALLPAPER="):
                    lines.append(f'XP_WALLPAPER="{self.selected_wallpaper}"')
                elif line.startswith("XP_CURSOR_THEME="):
                    lines.append(f'XP_CURSOR_THEME="{ctheme}"')
                elif line.startswith("XP_CURSOR_SIZE="):
                    lines.append(f'XP_CURSOR_SIZE="{csize}"')
                else:
                    lines.append(line)
            THEME_ENV.write_text("\n".join(lines) + "\n", encoding="utf-8")

    def on_apply(self, _btn):
        self.apply_changes()

    def on_ok(self, _btn):
        self.apply_changes()
        Gtk.main_quit()


def main():
    tab = 0
    if "--desktop" in sys.argv:
        tab = 1
    elif "--screensaver" in sys.argv:
        tab = 2
    elif "--appearance" in sys.argv:
        tab = 3
    win = XPDisplayProperties(initial_tab=tab)
    win.show_all()
    win.notebook.set_current_page(tab)
    Gtk.main()


if __name__ == "__main__":
    main()
