#!/usr/bin/env python3
"""
Windows 11 Tweaker
Author: Lars "Issu" Olsson
A comprehensive GUI tool to configure Windows 11 settings.
"""

# ToDo:
# DEL 01 – Imports, base paths, constants, colour palette
# DEL 02 – Logging setup + global crash catcher
# DEL 03 – Config manager (JSON, persistent settings + window geometry)
# DEL 04 – GUI helpers: no-blink entry/text, scrollable frame, status label,
#           auto-close popup, section label, button factory
# DEL 05 – Cursor blink: disable keyboard caret blink (registry)
# DEL 06 – Sounds: disable startup sound + default/system sounds
# DEL 07 – File associations: clear music / image / video UserChoice
# DEL 08 – Built-in media apps: remove Groove, Photos, Movies & TV, WMP
# DEL 09 – Firefox: hide tab audio icon via userChrome.css
# DEL 10 – Power / energy: set all timeouts to Never
# DEL 11 – Auto-login: no password at Windows startup
# DEL 12 – Aero Shake + Snap Assist: disable
# DEL 13 – Print Screen → Snipping Tool: unbind
# DEL 14 – Windows Defender: disable real-time protection + add exclusions
# DEL 15 – Python version installer: fetch 3 newest, download & install
# DEL 16 – Taskbar cleanup: widgets, task view, chat, copilot, store, outlook
# DEL 16b – Copilot: remove apps (all users + provisioned), policies,
#           taskbar button; Check (read-only) and Restore settings
# DEL 17 – OneDrive: stop, uninstall, disable via policy
# DEL 18 – Display language: Swedish (sv-SE) + 24-hour format
# DEL 19 – Privacy: telemetry, advertising ID, Cortana
# DEL 20 – Default download folder: Windows shell + Chrome + Edge + Firefox
# DEL 21 – Main App class + notebook GUI construction
# DEL 22 – Entry point

# *************** DEL 01 – IMPORTS, PATHS, CONSTANTS ***************

import tkinter as tk
from tkinter import messagebox, ttk, filedialog
import os, sys, json, logging, traceback, subprocess, threading
import urllib.request, re, shutil, ctypes, time, winreg
from datetime import datetime
from pathlib import Path
import os
import sys


# ---- Where Helpfiles and Icons live -----------------------------------------
# Helpfiles is a SIBLING of the program's folder, not a child of it, so the
# answer is "the nearest folder above me that holds Helpfiles". One rule covers
# Py\, Folder-exe\<Name>\ and the old layout alike, so it stops mattering
# where the .py or the .exe is put. Capped at four levels so a stray Helpfiles
# far up the tree is not adopted by accident; nothing found means behave as
# before, which is what keeps a test copy away from live data.
def _find_home(start):
    # Py\ and Folder-exe\<Name>\ are ALWAYS direct children of home, so
    # their own name settles it. This runs BEFORE the walk: a stray
    # Helpfiles inside Py\ used to win the walk and silently became every
    # program's home - that is how Notes lost a day (2026-09-04).
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    if os.path.basename(os.path.dirname(start)).lower() == "folder-exe":
        return os.path.dirname(os.path.dirname(start))
    # Otherwise: the nearest folder above me that HAS a Helpfiles. Capped at
    # four levels so a stray one far up is not adopted by accident; nothing
    # found means behave as before, which keeps a test copy off live data.
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower checks for this before offering the swap


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# A link, a folder, a PDF, a log or an image opened from here should land in MY
# programs - not in Edge, Explorer, Notepad or Adobe.
#
# Registering them as Windows' default apps is possible but miserable, and
# Windows identifies an application by its .exe PATH: point every file type at
# pythonw.exe and Windows sees ONE app called "Python" for all of them, with
# one icon, and Default Apps cannot tell WhyBrowse from F(re)email.
#
# WHICH program opens WHAT is NOT decided here.  It is decided in one file,
#
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
#
# so changing "PDFs open in X instead of PDFull" is one edit in one place, not
# 122 edits in 122 sources.  This block only reads that table and acts on it.
# _FALLBACK_KINDS below is used only when the file cannot be read, so a
# program still works on a machine that has no DefaultHub.
#
# Three rules this block must never break:
#
#   1. It may never raise.  The Help button has to open even when WhyBrowse is
#      missing, broken, or mid-rebuild, and even when defaults.json is gone.
#   2. It may never hand a thing to ITSELF (File_manager opening a folder,
#      WhyBrowse opening a link) - that is how you build a loop.
#   3. Popen, never run().  run() would freeze this program until the browser
#      is closed again.
#
# NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it would start another copy of this program instead of Python.
# (PyManager did exactly that on 2026-09-04 and fork-bombed the machine.)
#
# Cost, measured 2026-09-05: the table is read ONCE, the first time something
# is actually opened - 0.11 ms cold, 0.05 ms warm, plus 0.04 ms of path
# checks.  Nothing is read at start-up, so start-up is not affected at all.

MY_PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False) else __file__))[0]

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the others: a music program
    lives in <root>\\1---Musik\\Py so its home is 1---Musik, and Chess /
    Foul_bridge / Quiz_manager / Railroad_racing are their own worlds - none
    of those has a WhyBrowse or a DefaultHub.  So after its own home it walks
    UP, exactly like _find_home, four levels."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - it is
    not an interpreter, and which() finds it first wherever the Store stub is
    on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


_HUB_PY_ROOTS = None


def _hub_py_roots() -> list:
    """The program folders DefaultHub names, or [] meaning "find them yourself".

    EMPTY IS THE DEFAULT AND IT IS THE RIGHT ONE.  An absolute path in a data
    file is the first thing to break when the tree moves to another drive -
    which it did on 2026-09-08, C: to X:.  Nothing else in this block holds a
    drive letter: _find_home walks up from __file__, and the table stores only
    NAMES ("SeeView"), so a move costs nothing.  A list of absolute paths here
    would be the one file that has to be edited every time, and that is exactly
    what this design is for avoiding.

    So a RELATIVE entry ("1---Musik\\Py") is the intended shape: it is
    resolved against every root in _py_folders, and it survives the move too.
    An absolute one is still honoured - it is his tree - but it is on him."""
    global _HUB_PY_ROOTS
    if _HUB_PY_ROOTS is not None:
        return _HUB_PY_ROOTS
    found = []
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    found = (json.load(fh) or {}).get("py_roots") or []
                break
        except Exception:
            pass                       # unreadable or half-written: automatic
    try:
        _HUB_PY_ROOTS = [str(x).strip() for x in found if str(x).strip()]
    except Exception:
        _HUB_PY_ROOTS = []
    return _HUB_PY_ROOTS


def _py_folders() -> list:
    """Every folder that may hold <Name>.py, nearest first.

    DefaultHub's list first, then the plain <root>\\Py that has always been
    searched.  With no list this is exactly the old behaviour, which is why
    "empty means automatic" costs nothing."""
    out, roots = [], _my_app_roots()
    for entry in _hub_py_roots():
        try:
            if os.path.isabs(entry):
                out.append(entry)
            else:
                for r in roots:
                    out.append(os.path.join(r, entry))
        except Exception:
            continue
    for r in roots:
        out.append(os.path.join(r, "Py"))
    seen, uniq = set(), []
    for d in out:
        try:
            key = os.path.normcase(os.path.abspath(d))
            if key not in seen and os.path.isdir(d):
                seen.add(key)
                uniq.append(d)
        except Exception:
            continue
    return uniq


def _program_candidates(name: str) -> list:
    """Every file that could BE that program, best first.

    ALL the .py folders are searched before ANY build.  The old loop asked
    "script or exe?" one tree at a time, so a stale build in a near tree beat
    the live source in a further one - the very thing "the .py wins" exists to
    prevent."""
    out = []
    for d in _py_folders():
        try:
            p = os.path.join(d, name + ".py")
            if os.path.isfile(p):
                out.append(p)
        except Exception:
            continue
    for root in _my_app_roots():
        try:
            e = os.path.join(root, "Folder-exe", name, name + ".exe")
            if os.path.isfile(e):
                out.append(e)
        except Exception:
            continue
    return out


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, and a build is only the fallback.  The .exe used to be
    preferred, which was wrong on every count:

      * it is not faster - a one-folder build and the .py start in about the
        same time (the ten-times difference was one-FILE builds);
      * it does not help the hand-over - both bind the same port, so a
        running copy takes the argument whichever one is started;
      * and it is the only thing that can be OUT OF DATE.  A build from last
        week does not have this week's source in it, so preferring it means
        quietly running old code.  That is exactly what happened on
        2026-09-05: File_manager's build was a day old and had no command
        line handling at all, so "open this folder" would have opened a
        second window and dropped the path.

    WHERE it looks is DefaultHub's business now, not this block's - see
    _py_folders - so his music programs and the own worlds under 1---Annat
    can be named as targets like anything else.

    subprocess and webbrowser MUST be imported at module level for this to
    work.  They were not, in 57 of 121 programs, and because every call site
    sits inside a bare `except Exception` the failure was completely silent:
    the program simply stopped handing files to his own programs and dropped
    them all on Windows.  That is what made "Save & Open" open nothing at all
    on 2026-09-09, and it left no trace anywhere."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    for path in _program_candidates(name):
        cmd = None
        if path.lower().endswith(".py"):
            pyw = _real_pythonw()
            if pyw:
                cmd = [pyw, path, str(argument)]
            # no interpreter on this machine: try the build instead
        else:
            cmd = [path, str(argument)]
        if not cmd:
            continue
        try:
            subprocess.Popen(cmd, cwd=os.path.dirname(path) or None)
            return True
        except Exception:
            continue                      # try the next candidate
    return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# -----------------------------------------------------------------------------


# ── Resolve base directory (works as .py AND as frozen .exe) ──
if getattr(sys, "frozen", False):
    BASE_DIR = Path(_program_home())
else:
    BASE_DIR = Path(_program_home())

HELPFILES_DIR = BASE_DIR / "Helpfiles"
LOG_DIR       = HELPFILES_DIR / "0---Empty"
SETTINGS_DIR  = HELPFILES_DIR / "0---Settings"
SETTINGS_FILE = SETTINGS_DIR / "settings_config.json"

# Suppress the console window every CLI / PowerShell call would otherwise flash
# on Windows (this tool fires many of them). 0 on non-Windows.
_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0) if sys.platform == "win32" else 0

for _d in (HELPFILES_DIR, LOG_DIR, SETTINGS_DIR):
    _d.mkdir(parents=True, exist_ok=True)

# ── Colour palette – change "steelblue" → "red" etc. freely ──
C_BG          = "#1e1e2e"    # main window background
C_FG          = "#cdd6f4"    # main foreground / text
C_SECTION_BG  = "#181825"    # tab / section background
C_SECTION_FG  = "#cba6f7"    # section header accent
C_ENTRY_BG    = "#313244"    # entry field background
C_ENTRY_FG    = "#cdd6f4"    # entry field text
C_STATUS_OK   = "#a6e3a1"    # status: success  (green)
C_STATUS_WARN = "#f38ba8"    # status: warning  (red)
C_STATUS_INFO = "#89dceb"    # status: info     (cyan)
C_HDR_BG      = "#11111b"    # header bar background

# Button background colours – written out so you can swap one word
C_BTN_APPLY   = "steelblue"   # colour: steelblue
C_BTN_CHECK   = "grey40"      # colour: grey40
C_BTN_DANGER  = "firebrick"   # colour: firebrick
C_BTN_ORANGE  = "darkorange"  # colour: darkorange
C_BTN_BROWSE  = "grey30"      # colour: grey30
C_BTN_GREY    = "grey25"      # colour: grey25

FONT_MAIN    = ("Segoe UI", 10)
FONT_BOLD    = ("Segoe UI", 10, "bold")
FONT_SECTION = ("Segoe UI", 12, "bold")
FONT_SMALL   = ("Segoe UI", 9)

# *************** DEL 02 – LOGGING AND CRASH CATCHER ***************

_log_file = LOG_DIR / f"log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler(_log_file, encoding="utf-8"),
        logging.StreamHandler(sys.stdout),
    ],
)
log = logging.getLogger("IssuTweaker")


def _crash_handler(exc_type, exc_value, exc_tb):
    """Catch any unhandled exception, log it and show a dialog."""
    msg = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    log.critical("UNHANDLED EXCEPTION:\n%s", msg)
    try:
        messagebox.showerror(
            "Windows 11 Tweaker – Crash",
            f"An unexpected error occurred:\n\n{exc_value}\n\n"
            f"Details saved to:\n{_log_file}",
        )
    except Exception:
        pass


sys.excepthook = _crash_handler


def run_thread(fn, *args, **kwargs):
    """Run fn in a daemon thread so the GUI stays responsive."""
    t = threading.Thread(target=fn, args=args, kwargs=kwargs, daemon=True)
    t.start()
    return t


# *************** DEL 03 – CONFIG MANAGER ***************

_DEFAULT_CFG = {
    "window_geometry": "1120x840+80+40",
    "last_tab": 0,
    "download_folder": r"C:\0---Temp",
    "autologin_user": "",
    "defender_excl": "",
}


class _Config:
    def __init__(self):
        self._d = dict(_DEFAULT_CFG)
        self._load()

    def _load(self):
        if SETTINGS_FILE.exists():
            try:
                with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
                    self._d.update(json.load(f))
                log.debug("Config loaded from %s", SETTINGS_FILE)
            except Exception as e:
                log.warning("Config load failed: %s", e)

    def save(self):
        try:
            with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
                json.dump(self._d, f, indent=2, ensure_ascii=False)
            log.debug("Config saved.")
        except Exception as e:
            log.error("Config save failed: %s", e)

    def get(self, key, default=None):
        return self._d.get(key, default)

    def set(self, key, value):
        self._d[key] = value


cfg = _Config()

# *************** DEL 04 – GUI HELPERS ***************

# ── No-blink helpers ──────────────────────────────────────────────────────────

def no_blink(w):
    """Make any Entry or Text widget have a solid (non-blinking) cursor."""
    try:
        w.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass


def mk_entry(parent, **kw):
    """Non-blinking Entry with standard dark styling."""
    e = tk.Entry(
        parent,
        insertofftime=0, insertontime=9999999,
        bg=C_ENTRY_BG, fg=C_ENTRY_FG,
        insertbackground=C_ENTRY_FG,
        relief="flat", font=FONT_MAIN,
        **kw,
    )
    assert e.cget("insertofftime") == 0, "insertofftime assertion failed"
    return e


def mk_text(parent, **kw):
    """Non-blinking Text widget with standard dark styling."""
    t = tk.Text(
        parent,
        insertofftime=0, insertontime=9999999,
        bg=C_ENTRY_BG, fg=C_ENTRY_FG,
        insertbackground=C_ENTRY_FG,
        relief="flat", font=FONT_MAIN,
        **kw,
    )
    assert t.cget("insertofftime") == 0, "insertofftime assertion failed"
    return t


# ── Widget factories ──────────────────────────────────────────────────────────

def mk_btn(parent, text, cmd, color=C_BTN_APPLY, **kw):
    return tk.Button(
        parent, text=text, command=cmd,
        bg=color, fg="white",
        activebackground=color, activeforeground="white",
        relief="flat", font=FONT_BOLD,
        cursor="hand2", padx=10, pady=5,
        **kw,
    )


def section_label(parent, text):
    tk.Label(
        parent, text=f"  ◈  {text}",
        bg=C_SECTION_BG, fg=C_SECTION_FG,
        font=FONT_SECTION, anchor="w",
    ).pack(fill="x", pady=(16, 2))
    tk.Frame(parent, bg=C_SECTION_FG, height=1).pack(fill="x", padx=8)


def status_label(parent):
    lbl = tk.Label(
        parent, text="", bg=C_SECTION_BG,
        fg=C_STATUS_INFO, font=FONT_SMALL, anchor="w",
    )
    lbl.pack(fill="x", padx=10, pady=(2, 0))
    return lbl


def set_status(lbl, msg, color=C_STATUS_INFO):
    lbl.config(text=f"  ▸  {msg}", fg=color)
    log.info(msg)


def auto_close_popup(title, message, delay=1000):
    """Success popup that auto-closes after delay ms. No blinking cursor."""
    top = tk.Toplevel()
    top.title(title)
    top.configure(bg=C_BG)
    top.resizable(False, False)
    top.attributes("-topmost", True)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())
    tk.Label(
        top, text=f"  ✔  {message}  ",
        bg=C_BG, fg=C_STATUS_OK,
        font=FONT_BOLD, padx=20, pady=18,
    ).pack()
    top.after(delay, top.destroy)


# ── Scrollable frame ──────────────────────────────────────────────────────────

class ScrollableFrame(tk.Frame):
    """A vertically scrollable container with mouse-wheel support."""

    def __init__(self, parent, bg=C_SECTION_BG, **kw):
        super().__init__(parent, bg=bg, **kw)
        canvas = tk.Canvas(self, bg=bg, highlightthickness=0)
        sb = tk.Scrollbar(self, orient="vertical", command=canvas.yview)
        self.inner = tk.Frame(canvas, bg=bg)
        self.canvas = canvas
        self.inner.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all")),
        )
        self._win_id = canvas.create_window((0, 0), window=self.inner, anchor="nw")
        canvas.configure(yscrollcommand=sb.set)
        canvas.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        canvas.bind("<Configure>", lambda e: canvas.itemconfig(self._win_id, width=e.width))

        # ONE global handler for all tabs.  It used to be bound once per tab
        # with bind_all, and every bind_all replaces the one before - so the
        # wheel only ever scrolled the LAST tab built (a hidden one).  Now the
        # handler walks up from the widget under the pointer to its own
        # ScrollableFrame.
        if not ScrollableFrame._wheel_bound:
            ScrollableFrame._wheel_bound = True
            canvas.bind_all("<MouseWheel>", ScrollableFrame._on_wheel)

    _wheel_bound = False

    @staticmethod
    def _on_wheel(e):
        w = e.widget
        try:
            if isinstance(w, str):
                w = e.widget = tk._default_root.nametowidget(w)
        except Exception:
            return
        while w is not None:
            if isinstance(w, ScrollableFrame):
                if w.canvas.yview() != (0.0, 1.0):
                    w.canvas.yview_scroll(int(-1 * (e.delta / 120)), "units")
                return
            w = getattr(w, "master", None)


# ── Window icon (Win32) ───────────────────────────────────────────────────────

import platform
import webbrowser  # the open-with block needs this at module level

_APP_ID = "IssuOlsson.Win11Tweaker.1"

def _set_window_icon(root) -> None:
    """Set the taskbar + title-bar icon via both tkinter and Win32 WM_SETICON."""
    if platform.system() != "Windows":
        return
    script_dir = _program_home()
    prog_name  = os.path.splitext(os.path.basename(__file__))[0]
    ico_path   = os.path.join(script_dir, "Icons", f"{prog_name}.ico")
    if not os.path.isfile(ico_path):
        log.warning("Icon not found: %s", ico_path)
        return

    # Kanal 1: tkinters eget API
    try:
        root.iconbitmap(ico_path)
    except Exception as e:
        log.debug("iconbitmap failed: %s", e)

    # Kanal 2: WM_SETICON via Win32 (säkerställer rätt ikon i taskbar / Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            log.debug("FindWindowW returned NULL – icon not set via Win32")
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON,  0,  0, LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16, LR_LOADFROMFILE)
        if hbig: user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml: user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
        log.debug("WM_SETICON applied (hwnd=%s)", hwnd)
    except Exception as e:
        log.debug("Win32 icon error: %s", e)


# ── Registry helpers ──────────────────────────────────────────────────────────

_HIVES = {
    "HKCU": winreg.HKEY_CURRENT_USER,
    "HKLM": winreg.HKEY_LOCAL_MACHINE,
    "HKCR": winreg.HKEY_CLASSES_ROOT,
}


def reg_read(hive, path, name, default=None):
    try:
        with winreg.OpenKey(_HIVES[hive], path, 0, winreg.KEY_READ) as k:
            val, _ = winreg.QueryValueEx(k, name)
            return val
    except Exception:
        return default


def reg_write(hive, path, name, value, vtype=winreg.REG_DWORD):
    try:
        flags = winreg.KEY_SET_VALUE | winreg.KEY_WOW64_64KEY
        with winreg.CreateKeyEx(_HIVES[hive], path, 0, flags) as k:
            winreg.SetValueEx(k, name, 0, vtype, value)
        return True
    except PermissionError:
        log.warning("PermissionError on %s\\%s – run as Admin?", hive, path)
        return False
    except Exception as e:
        log.error("reg_write error: %s", e)
        return False


def reg_delete_value(hive, path, name):
    try:
        flags = winreg.KEY_SET_VALUE | winreg.KEY_WOW64_64KEY
        with winreg.OpenKey(_HIVES[hive], path, 0, flags) as k:
            winreg.DeleteValue(k, name)
        return True
    except Exception:
        return False


def broadcast_settings():
    """Broadcast WM_SETTINGCHANGE so apps pick up registry changes immediately."""
    try:
        ctypes.windll.user32.SendMessageTimeoutW(
            0xFFFF, 0x001A, 0, "Environment", 0x0002, 5000, None
        )
    except Exception:
        pass


def ps_run(script, capture=False, timeout=180):
    """Run a PowerShell script. Returns (returncode, stdout, stderr)."""
    # Full path, never the bare name (CORE rule 8: CreateProcess searches the
    # calling program's own folder first).
    ps_exe = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                          "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
    cmd = [
        ps_exe, "-NoProfile", "-NonInteractive",
        "-ExecutionPolicy", "Bypass",
        "-Command", script,
    ]
    try:
        r = subprocess.run(cmd, capture_output=capture, text=True, timeout=timeout,
                           creationflags=_NO_WINDOW)
        return r.returncode, r.stdout if capture else "", r.stderr if capture else ""
    except Exception as e:
        return -1, "", str(e)


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except Exception:
        return False


# *************** DEL 05 – CURSOR BLINK (KEYBOARD CARET) ***************

def apply_cursor_noblink(st):
    """Disable Windows cursor blink by setting CursorBlinkRate to -1."""
    ok = reg_write("HKCU", r"Control Panel\Desktop",
                   "CursorBlinkRate", "-1", winreg.REG_SZ)
    broadcast_settings()
    if ok:
        set_status(st, "Cursor blink disabled (solid caret). Log out / back in to fully apply.", C_STATUS_OK)
        auto_close_popup("Cursor Blink", "Cursor blink DISABLED ✓")
    else:
        set_status(st, "Failed – try running as Administrator.", C_STATUS_WARN)


def check_cursor_blink(st):
    val = reg_read("HKCU", r"Control Panel\Desktop", "CursorBlinkRate", "530")
    try:
        blinking = int(val) > 0
    except Exception:
        blinking = True
    color = C_STATUS_WARN if blinking else C_STATUS_OK
    label = "BLINKING" if blinking else "SOLID (blink OFF)"
    set_status(st, f"Current CursorBlinkRate = {val!r}  →  {label}", color)


# *************** DEL 05b – TYPING: NO RED MISSPELLED-WORD LINES, NO AUTOCORRECT ***************
#
# Settings > Time & language > Typing: "Highlight misspelled words" and
# "Autocorrect misspelled words".  The red underlines check against the
# dictionary of the typing language, so Swedish written with an English
# dictionary comes out red word for word - and anyone who types without
# looking at the screen cannot use them anyway.  Both are per-user HKCU values
# (no admin needed); a program that is already open keeps its lines until it
# is restarted.
# ToDo: an app with a spell checker of its own (a browser, Electron apps) may
# ignore these two values - then the switch is in that app.

TYPING_KEY = r"SOFTWARE\Microsoft\TabletTip\1.7"
TYPING_VALUES = ("EnableSpellchecking", "EnableAutocorrection")


def apply_disable_spellcheck(st):
    """Highlight misspelled words OFF + Autocorrect misspelled words OFF."""
    ok = all(reg_write("HKCU", TYPING_KEY, name, 0) for name in TYPING_VALUES)
    broadcast_settings()
    if ok:
        set_status(st, "Misspelled-word lines and autocorrect are OFF. Restart the "
                       "programs that still show red lines.", C_STATUS_OK)
        auto_close_popup("Typing", "Misspelled-word lines + autocorrect OFF ✓")
    else:
        set_status(st, "Failed – see the log.", C_STATUS_WARN)


def check_spellcheck(st):
    """Reads the two values; a value that does not exist means Windows' default, ON."""
    parts, any_on = [], False
    for name in TYPING_VALUES:
        val = reg_read("HKCU", TYPING_KEY, name, None)
        on = val is None or val != 0
        any_on = any_on or on
        parts.append("%s = %s  →  %s" % (name, "(not set)" if val is None else val,
                                        "ON" if on else "OFF"))
    set_status(st, "   |   ".join(parts), C_STATUS_WARN if any_on else C_STATUS_OK)


# *************** DEL 06 – SOUNDS (STARTUP & DEFAULT) ***************

def apply_disable_startup_sound(st):
    """Disable the Windows startup chime."""
    ok1 = reg_write(
        "HKLM",
        r"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\BootAnimation",
        "DisableStartupSound", 1,
    )
    # Also clear the sound event entry
    reg_write("HKCU",
              r"AppEvents\Schemes\Apps\.Default\SystemStart\.Current",
              "", "", winreg.REG_SZ)
    if ok1:
        set_status(st, "Startup sound disabled.", C_STATUS_OK)
        auto_close_popup("Startup Sound", "Startup sound DISABLED ✓")
    else:
        set_status(st, "Failed – run as Administrator.", C_STATUS_WARN)


def apply_disable_default_sound(st):
    """Mute the Windows Default Beep / ding event."""
    reg_write("HKCU",
              r"AppEvents\Schemes\Apps\.Default\.Default\.Current",
              "", "", winreg.REG_SZ)
    # Switch the active sound scheme to ".None" (No Sounds)
    reg_write("HKCU", r"AppEvents\Schemes",
              "", ".None", winreg.REG_SZ)
    broadcast_settings()
    set_status(st, "Default sound muted. Sound scheme set to No Sounds.", C_STATUS_OK)
    auto_close_popup("System Sounds", "Default sound MUTED ✓")


# *************** DEL 07 – FILE ASSOCIATIONS ***************

MUSIC_EXTS = [".mp3", ".flac", ".wav", ".ogg", ".aac", ".wma", ".m4a", ".opus", ".ape", ".alac"]
IMAGE_EXTS = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tiff", ".tif", ".ico",
              ".heic", ".heif", ".avif", ".jxl", ".raw", ".cr2", ".nef"]
VIDEO_EXTS = [".mp4", ".mkv", ".avi", ".mov", ".wmv", ".m4v", ".flv", ".webm",
              ".ts", ".m2ts", ".vob", ".mpg", ".mpeg", ".3gp", ".divx"]


def remove_file_assoc(exts, st, label):
    """Remove UserChoice file associations for a list of extensions."""
    cleared = 0
    for ext in exts:
        uc_path = (
            rf"Software\Microsoft\Windows\CurrentVersion\Explorer"
            rf"\FileExts\{ext}\UserChoice"
        )
        # Best-effort: delete via reg command (avoids hash-check block)
        r = subprocess.run(
            f'reg delete "HKCU\\{uc_path}" /f',
            shell=True, capture_output=True, text=True,
            creationflags=_NO_WINDOW,
        )
        if r.returncode == 0:
            cleared += 1
        # Also try with OpenKey in case reg command was blocked
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, uc_path, 0,
                                winreg.KEY_SET_VALUE) as k:
                for val_name in ("ProgId", "Hash"):
                    try:
                        winreg.DeleteValue(k, val_name)
                    except Exception:
                        pass
        except Exception:
            pass
    set_status(
        st,
        f"{label}: cleared associations for {cleared}/{len(exts)} extension(s). "
        "Windows will ask which app to use next time you open these files.",
        C_STATUS_OK,
    )
    auto_close_popup("File Assoc", f"{label} associations removed ✓")


# *************** DEL 08 – BUILT-IN MEDIA APPS ***************

MEDIA_PACKAGES = {
    "Groove Music / Zune Music":     "Microsoft.ZuneMusic",
    "Movies & TV / Zune Video":      "Microsoft.ZuneVideo",
    "Windows Media Player (legacy)": "Microsoft.WindowsMediaPlayer",
    "Photos":                        "Microsoft.Windows.Photos",
    "Camera":                        "Microsoft.WindowsCamera",
}


def disable_media_app(pkg_id, display_name, st):
    def _do():
        set_status(st, f"Removing {display_name}…", C_STATUS_INFO)
        code, out, err = ps_run(
            f'Get-AppxPackage -AllUsers *{pkg_id}* | '
            f'Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue',
            capture=True,
        )
        log.debug("Remove %s: rc=%s err=%s", pkg_id, code, err[:200])
        if code == 0:
            set_status(st, f"{display_name} removed.", C_STATUS_OK)
            auto_close_popup("Apps", f"{display_name} removed ✓")
        else:
            set_status(
                st,
                f"Could not fully remove {display_name} – may require Admin or may already be removed.",
                C_STATUS_WARN,
            )
    run_thread(_do)


# *************** DEL 09 – FIREFOX AUDIO ICON ***************

def find_firefox_profiles():
    """Return a list of existing Firefox profile directories."""
    roaming = Path(os.environ.get("APPDATA", "")) / "Mozilla" / "Firefox" / "Profiles"
    if not roaming.exists():
        return []
    return [p for p in roaming.iterdir() if p.is_dir()]


_FIREFOX_CSS = """\
/* Win11 Tweaker – hide tab audio / muted overlay icon */
.tab-icon-overlay[soundplaying],
.tab-icon-overlay[muted],
.tab-icon-overlay[activemedia-blocked] {
    display: none !important;
}
"""

_FIREFOX_MARKER = "Win11 Tweaker – hide tab audio"


def apply_firefox_audio_icon(st):
    """Inject CSS into every Firefox profile to hide the tab audio indicator."""
    profiles = find_firefox_profiles()
    if not profiles:
        set_status(st, "No Firefox profiles found. Is Firefox installed?", C_STATUS_WARN)
        return
    count = 0
    for prof in profiles:
        # Enable userChrome.css support via user.js
        user_js = prof / "user.js"
        pref_line = 'user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true);\n'
        existing = user_js.read_text(encoding="utf-8") if user_js.exists() else ""
        if "legacyUserProfileCustomizations" not in existing:
            with open(user_js, "a", encoding="utf-8") as fh:
                fh.write(pref_line)
        # Write / update userChrome.css
        chrome_dir = prof / "chrome"
        chrome_dir.mkdir(exist_ok=True)
        css_file = chrome_dir / "userChrome.css"
        existing_css = css_file.read_text(encoding="utf-8") if css_file.exists() else ""
        if _FIREFOX_MARKER not in existing_css:
            with open(css_file, "a", encoding="utf-8") as fh:
                fh.write("\n" + _FIREFOX_CSS)
        count += 1
    set_status(
        st,
        f"Tab audio icon hidden in {count} Firefox profile(s). Close and restart Firefox.",
        C_STATUS_OK,
    )
    auto_close_popup("Firefox", "Firefox audio icon HIDDEN ✓")


# *************** DEL 10 – POWER / ENERGY SETTINGS ***************

def apply_power_no_timeout(st):
    """Set every power timeout (screen, disk, sleep, hibernate) to Never."""
    cmds = [
        "powercfg /change monitor-timeout-ac 0",
        "powercfg /change monitor-timeout-dc 0",
        "powercfg /change disk-timeout-ac 0",
        "powercfg /change disk-timeout-dc 0",
        "powercfg /change standby-timeout-ac 0",
        "powercfg /change standby-timeout-dc 0",
        "powercfg /change hibernate-timeout-ac 0",
        "powercfg /change hibernate-timeout-dc 0",
    ]
    errors = []
    for cmd in cmds:
        r = subprocess.run(cmd, shell=True, capture_output=True, text=True,
                           creationflags=_NO_WINDOW)
        if r.returncode != 0:
            errors.append(cmd.split()[2])
            log.warning("powercfg failed: %s – %s", cmd, r.stderr.strip())
    if not errors:
        set_status(st, "All power timeouts set to Never (AC + DC).", C_STATUS_OK)
        auto_close_popup("Power", "Power timeouts → NEVER ✓")
    else:
        set_status(
            st,
            f"Some settings failed ({', '.join(errors)}). Run as Administrator.",
            C_STATUS_WARN,
        )


def check_power_settings(st):
    r = subprocess.run(
        "powercfg /query SCHEME_CURRENT", shell=True,
        capture_output=True, text=True,
        creationflags=_NO_WINDOW,
    )
    log.debug("Power query:\n%s", r.stdout)
    set_status(st, "Power settings logged – see Helpfiles/0---Empty/log_*.txt", C_STATUS_INFO)


# *************** DEL 11 – AUTO-LOGIN ***************

_WINLOGON = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"


def apply_autologin(username, password, st):
    """Configure Windows to log in automatically (no password prompt)."""
    if not username.strip():
        set_status(st, "Username cannot be empty.", C_STATUS_WARN)
        return
    ok  = reg_write("HKLM", _WINLOGON, "AutoAdminLogon", "1", winreg.REG_SZ)
    ok &= reg_write("HKLM", _WINLOGON, "DefaultUserName", username.strip(), winreg.REG_SZ)
    ok &= reg_write("HKLM", _WINLOGON, "DefaultPassword", password, winreg.REG_SZ)
    reg_delete_value("HKLM", _WINLOGON, "AutoLogonCount")
    if ok:
        set_status(st, f"Auto-login enabled for: {username.strip()}", C_STATUS_OK)
        auto_close_popup("Auto-Login", "Auto-login ENABLED ✓")
    else:
        set_status(st, "Failed – run as Administrator.", C_STATUS_WARN)


def disable_autologin(st):
    reg_write("HKLM", _WINLOGON, "AutoAdminLogon", "0", winreg.REG_SZ)
    set_status(st, "Auto-login disabled.", C_STATUS_OK)
    auto_close_popup("Auto-Login", "Auto-login DISABLED ✓")


# *************** DEL 12 – AERO SHAKE + SNAP ASSIST ***************

_ADVANCED = r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"


def apply_disable_aero_shake(st):
    """Disable Aero Shake (shaking a window to minimize all others)."""
    ok1 = reg_write("HKCU", _ADVANCED, "DisallowShaking", 1)
    ok2 = reg_write("HKLM",
                    r"SOFTWARE\Policies\Microsoft\Windows\Explorer",
                    "NoWindowMinimizingShortcuts", 1)
    broadcast_settings()
    if ok1 or ok2:
        set_status(st, "Aero Shake disabled.", C_STATUS_OK)
        auto_close_popup("Aero Shake", "Aero Shake DISABLED ✓")
    else:
        set_status(st, "Failed – run as Admin.", C_STATUS_WARN)


def apply_disable_snap(st):
    """Disable Snap Assist flyout and automatic snapping suggestions."""
    reg_write("HKCU", _ADVANCED, "EnableSnapAssistFlyout", 0)
    reg_write("HKCU", _ADVANCED, "SnapAssist", 0)
    reg_write("HKCU", _ADVANCED, "EnableSnap", 0)
    # Windows 11 settings page toggle
    reg_write("HKCU",
              r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\TaskbarDeveloperSettings",
              "TaskbarEndTask", 0)
    broadcast_settings()
    set_status(
        st,
        "Snap Assist disabled. "
        "NOTE: Title-bar double-click to maximize is a hard-wired OS behaviour "
        "and cannot be turned off via registry.",
        C_STATUS_OK,
    )
    auto_close_popup("Snap Assist", "Snap Assist DISABLED ✓")


# *************** DEL 13 – PRINT SCREEN → SNIPPING TOOL ***************

def apply_disable_prtscn_snippet(st):
    """Remove the PrtScn → Snipping Tool binding set by Windows 11."""
    ok = reg_write("HKCU",
                   r"Control Panel\Keyboard",
                   "PrintScreenKeyForSnippingEnabled", 0)
    broadcast_settings()
    if ok:
        set_status(st, "PrtScn key unbound from Snipping Tool.", C_STATUS_OK)
        auto_close_popup("PrtScn", "PrtScn → Snipping Tool DISABLED ✓")
    else:
        set_status(st, "Failed.", C_STATUS_WARN)


# *************** DEL 14 – WINDOWS DEFENDER / ANTIVIRUS ***************

def apply_disable_defender(st):
    """
    Disable Defender real-time protection via Group Policy registry keys.
    REQUIRES: Admin + Tamper Protection manually disabled beforehand.
    """
    def _do():
        set_status(st, "Disabling Defender real-time protection…", C_STATUS_INFO)
        wd_policy = r"SOFTWARE\Policies\Microsoft\Windows Defender"
        rt_policy = wd_policy + r"\Real-Time Protection"
        reg_write("HKLM", wd_policy,  "DisableAntiSpyware",          1)
        reg_write("HKLM", rt_policy,  "DisableRealtimeMonitoring",    1)
        reg_write("HKLM", rt_policy,  "DisableBehaviorMonitoring",    1)
        reg_write("HKLM", rt_policy,  "DisableOnAccessProtection",    1)
        reg_write("HKLM", rt_policy,  "DisableScanOnRealtimeEnable",  1)
        reg_write("HKLM", rt_policy,  "DisableIOAVProtection",        1)
        code, out, err = ps_run(
            "Set-MpPreference "
            "-DisableRealtimeMonitoring $true "
            "-DisableBehaviorMonitoring $true "
            "-DisableBlockAtFirstSeen $true "
            "-DisableIOAVProtection $true "
            "-SignatureDisableUpdateOnStartupWithoutEngine $true "
            "-DisableArchiveScanning $true "
            "-Force",
            capture=True,
        )
        log.debug("Set-MpPreference rc=%s err=%s", code, err[:200])
        set_status(
            st,
            "Defender policies applied. "
            "⚠  If protection is still active: Windows Security → "
            "Virus & threat protection → Manage settings → Tamper Protection OFF, then retry.",
            C_STATUS_OK,
        )
    run_thread(_do)


def apply_add_exclusion(folder, st):
    """Add a folder exclusion so Defender never touches it."""
    def _do():
        if not folder.strip():
            set_status(st, "No folder specified.", C_STATUS_WARN)
            return
        Path(folder).mkdir(parents=True, exist_ok=True)
        code, out, err = ps_run(
            f'Add-MpPreference -ExclusionPath "{folder}"', capture=True
        )
        if code == 0:
            set_status(st, f"Exclusion added: {folder}", C_STATUS_OK)
            auto_close_popup("Defender Exclusion", f"Exclusion added ✓")
        else:
            set_status(st, f"Failed: {err.strip()[:160]}", C_STATUS_WARN)
    run_thread(_do)


# *************** DEL 15 – PYTHON VERSION INSTALLER ***************

_PY_URL = "https://www.python.org/downloads/windows/"


def fetch_python_versions():
    """Fetch the 3 newest stable Python 3.x releases (64-bit) from python.org."""
    try:
        with urllib.request.urlopen(_PY_URL, timeout=20) as r:
            html = r.read().decode("utf-8", errors="ignore")
        pattern = (
            r'href="(https://www\.python\.org/ftp/python/'
            r'(3\.\d+\.\d+)/python-\2-amd64\.exe)"'
        )
        seen: dict = {}
        for url, ver in re.findall(pattern, html):
            mm = ".".join(ver.split(".")[:2])
            if mm not in seen:
                seen[mm] = (ver, url)
        sorted_vers = sorted(
            seen.values(),
            key=lambda x: [int(n) for n in x[0].split(".")],
            reverse=True,
        )
        return sorted_vers[:3]
    except Exception as e:
        log.error("Python version fetch: %s", e)
        return []


def download_and_install_python(version, url, st, progress_var):
    def _do():
        dest = LOG_DIR / f"python-{version}-amd64.exe"
        set_status(st, f"Downloading Python {version}…", C_STATUS_INFO)
        try:
            def _report(block, block_size, total):
                if total > 0:
                    progress_var.set(min(block * block_size * 100 / total, 100))
            urllib.request.urlretrieve(url, dest, reporthook=_report)
            set_status(st, f"Download complete. Launching Python {version} installer…", C_STATUS_OK)
            subprocess.Popen([str(dest)], creationflags=_NO_WINDOW)
        except Exception as e:
            set_status(st, f"Download failed: {e}", C_STATUS_WARN)
            log.error("Python download: %s", e)
    run_thread(_do)


# *************** DEL 16 – TASKBAR CLEANUP ***************

def apply_taskbar_buttons(settings_dict, st):
    """Write taskbar registry values and restart Explorer to apply."""
    for reg_name, value in settings_dict.items():
        reg_write("HKCU", _ADVANCED, reg_name, value)
    # Windows 11 24H2 no longer lets TaskbarDa remove the Widgets button (the
    # one that shows "NASDAQ +1,19%" in the left corner).  The policy does,
    # for good, and takes the Widgets key (Win+W) with it.
    if "TaskbarDa" in settings_dict:
        if settings_dict["TaskbarDa"] == 0:
            reg_write("HKLM", r"SOFTWARE\Policies\Microsoft\Dsh",
                      "AllowNewsAndInterests", 0)
        else:
            reg_delete_value("HKLM", r"SOFTWARE\Policies\Microsoft\Dsh",
                             "AllowNewsAndInterests")
    # Restart Explorer
    subprocess.run("taskkill /f /im explorer.exe", shell=True, capture_output=True,
                   creationflags=_NO_WINDOW)
    time.sleep(1.2)
    subprocess.Popen("explorer.exe", shell=True, creationflags=_NO_WINDOW)
    set_status(st, "Taskbar settings applied – Explorer restarted.", C_STATUS_OK)
    auto_close_popup("Taskbar", "Taskbar updated ✓")


def remove_windows_widgets(st):
    """Remove the Windows Web Experience Pack (Widgets) app."""
    def _do():
        set_status(st, "Removing Windows Web Experience Pack (Widgets)…", C_STATUS_INFO)
        ps_run(
            'Get-AppxPackage -AllUsers *WebExperienceHost* | '
            'Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue'
        )
        ps_run(
            'Get-AppxPackage -AllUsers MicrosoftWindows.Client.WebExperience | '
            'Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue'
        )
        subprocess.run(
            'winget uninstall "Windows Web Experience Pack" --silent --accept-source-agreements',
            shell=True, capture_output=True, text=True,
            creationflags=_NO_WINDOW,
        )
        set_status(st, "Widgets / WebExperiencePack removal attempted.", C_STATUS_OK)
        auto_close_popup("Widgets", "Windows Widgets REMOVED ✓")
    run_thread(_do)


def _unpin_taskbar_sync(app_name):
    """Best-effort unpin via Shell COM object (blocks until done)."""
    script = f"""
$shell = New-Object -Com Shell.Application
$tb    = 'shell::{{43826D1E-E718-42EE-BC55-A1E261C37BFE}}'
$items = $shell.NameSpace($tb).Items()
$item  = $items | Where-Object {{ $_.Name -like '*{app_name}*' }} | Select-Object -First 1
if ($item) {{
    $verb = $item.Verbs() | Where-Object {{ $_.Name -match 'Unpin' }} | Select-Object -First 1
    if ($verb) {{ $verb.DoIt() }}
}}
"""
    ps_run(script)


def unpin_taskbar_app(app_name, st):
    """Best-effort unpin via Shell COM object."""
    def _do():
        _unpin_taskbar_sync(app_name)
        set_status(st, f"Unpin attempted: {app_name}", C_STATUS_INFO)
    run_thread(_do)


def remove_ms_store_from_taskbar(st):
    """Remove MS Store taskbar pin via registry."""
    def _do():
        # Remove pinned taskbar shortcut for Store
        ps_run(
            'Get-Process -Name "WinStore.App" -ErrorAction SilentlyContinue | Stop-Process -Force'
        )
        # Taskbar pin data lives in a binary key; best approach is the verb method
        unpin_taskbar_app("Microsoft Store", st)
        # Also disable Store via policy (does not uninstall)
        reg_write("HKLM",
                  r"SOFTWARE\Policies\Microsoft\WindowsStore",
                  "RemoveWindowsStore", 1)
        set_status(st, "Store removal attempted + disabled via policy.", C_STATUS_INFO)
    run_thread(_do)


# *************** DEL 16b – COPILOT: REMOVE FOR GOOD ***************
#
# ToDo: if Copilot ever comes back despite all layers below, the one thing
# left is an AppLocker "packaged app" deny rule (Microsoft's own advice for
# blocking an app; Education supports it).  Not done here: it needs the
# Application Identity service and replaces the machine's AppLocker policy,
# which cannot be tested safely from a script.  Also not touched: the Copilot
# side panel inside Edge (Edge policy HubsSidebarEnabled).
#
# Why a plain uninstall is not enough (checked on Windows 11 Education
# 25H2, build 26200):
#   * "Copilot" on this build is TWO apps.  The Microsoft Copilot app
#     (Microsoft.Copilot) and the Microsoft 365 Copilot app, which is the old
#     Office hub renamed (package Microsoft.MicrosoftOfficeHub, process
#     M365Copilot.exe).  The second one is pushed to PCs with Microsoft 365 by
#     the Office updater, which is why a removed Copilot "shows up again".
#   * Removing the package for ONE user leaves the PROVISIONED copy in the
#     Windows image, so a feature update or a new user account puts it back.
#     The layers below close that:
#       1. remove the app for every user       (Remove-AppxPackage -AllUsers)
#       2. remove the provisioned copy         (Remove-AppxProvisionedPackage)
#       3. mark the package family "Deprovisioned" so Windows does not
#          provision it again from the image during an upgrade
#       4. policy RemoveMicrosoftCopilotApp    (Windows 11 24H2+, Education OK)
#       5. policy TurnOffWindowsCopilot        (old Copilot pane; deprecated
#          but harmless, and it also hides the taskbar button)
#       6. hide the taskbar button             (ShowCopilotButton = 0)
#       7. unpin any leftover Copilot taskbar pin
#   * What NO setting can stop: the Office updater or the Store installing
#     the app again as a NEW install.  Run Check after big updates; running
#     Remove again is safe (it only does what is still needed).
#   * Everything that needs admin (1-4 for HKLM) is skipped with a clear
#     message when the program is not elevated.

_COPILOT_POLICY_KEYS = [
    # (hive, key path, value name)
    ("HKCU", r"Software\Policies\Microsoft\Windows\WindowsCopilot", "TurnOffWindowsCopilot"),
    ("HKLM", r"SOFTWARE\Policies\Microsoft\Windows\WindowsCopilot", "TurnOffWindowsCopilot"),
    ("HKCU", r"Software\Policies\Microsoft\Windows\WindowsAI",      "RemoveMicrosoftCopilotApp"),
    ("HKLM", r"SOFTWARE\Policies\Microsoft\Windows\WindowsAI",      "RemoveMicrosoftCopilotApp"),
]
_DEPROVISIONED = (r"SOFTWARE\Microsoft\Windows\CurrentVersion\Appx"
                  r"\AppxAllUserStore\Deprovisioned")
_M365_PACKAGE  = "Microsoft.MicrosoftOfficeHub"
# Package family names that are always marked (even when not installed now).
_COPILOT_FAMILIES = [
    "Microsoft.Copilot_8wekyb3d8bbwe",
    "Microsoft.Windows.Ai.Copilot.Provider_8wekyb3d8bbwe",
]
_M365_FAMILY = "Microsoft.MicrosoftOfficeHub_8wekyb3d8bbwe"


def _reg_key_exists(hive, path):
    try:
        with winreg.OpenKey(_HIVES[hive], path, 0,
                            winreg.KEY_READ | winreg.KEY_WOW64_64KEY):
            return True
    except OSError:
        return False


def _reg_make_key(hive, path):
    try:
        with winreg.CreateKeyEx(_HIVES[hive], path, 0,
                                winreg.KEY_CREATE_SUB_KEY | winreg.KEY_WOW64_64KEY):
            return True
    except Exception as e:
        log.warning("Could not create %s\\%s: %s", hive, path, e)
        return False


def _reg_delete_key(hive, path):
    try:
        winreg.DeleteKeyEx(_HIVES[hive], path, winreg.KEY_WOW64_64KEY, 0)
        return True
    except Exception:
        return False


def _copilot_ps_head(include_m365, admin):
    """PowerShell prelude: $adm, and Hit(name) = is this a Copilot package."""
    return (
        "$ErrorActionPreference = 'SilentlyContinue'\n"
        f"$adm = ${'true' if admin else 'false'}\n"
        f"$inc = ${'true' if include_m365 else 'false'}\n"
        "function Hit($n) { ($n -like '*Copilot*') -or "
        f"($inc -and $n -eq '{_M365_PACKAGE}') }}\n"
        "if ($adm) { $pk = Get-AppxPackage -AllUsers } else { $pk = Get-AppxPackage }\n"
    )


def copilot_scan(include_m365=True):
    """Read-only.  What Copilot packages exist right now?

    Returns {"admin": bool, "installed": [(name, family, full)],
             "provisioned": [(display, package)], "prov_ok": bool}.
    """
    admin = is_admin()
    script = _copilot_ps_head(include_m365, admin) + (
        "$pk | Where-Object { Hit $_.Name } | ForEach-Object { "
        "'PKG|' + $_.Name + '|' + $_.PackageFamilyName + '|' + $_.PackageFullName }\n"
        "if ($adm) { $pv = Get-AppxProvisionedPackage -Online; "
        "'PROVOK|1'; "
        "$pv | Where-Object { Hit $_.DisplayName } | ForEach-Object { "
        "'PROV|' + $_.DisplayName + '|' + $_.PackageName } }\n"
    )
    code, out, err = ps_run(script, capture=True, timeout=120)
    res = {"admin": admin, "installed": [], "provisioned": [], "prov_ok": False}
    for line in (out or "").splitlines():
        parts = line.strip().split("|")
        if parts[0] == "PKG" and len(parts) >= 4:
            item = (parts[1], parts[2], parts[3])
            if item not in res["installed"]:
                res["installed"].append(item)
        elif parts[0] == "PROV" and len(parts) >= 3:
            res["provisioned"].append((parts[1], parts[2]))
        elif parts[0] == "PROVOK":
            res["prov_ok"] = True
    if code != 0:
        log.warning("Copilot scan: rc=%s err=%s", code, (err or "")[:200])
    return res


def _copilot_families(scan, include_m365):
    fams = list(_COPILOT_FAMILIES)
    if include_m365:
        fams.append(_M365_FAMILY)
    for _n, fam, _f in scan["installed"]:
        if fam and fam not in fams:
            fams.append(fam)
    return fams


def _dism_exe():
    return os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                        "System32", "dism.exe")


def _copilot_say_results(text, say):
    """Turn the OK|/ERR|/DISM| lines of a removal script into readable lines."""
    for line in (text or "").splitlines():
        parts = line.strip().split("|")
        if parts[0] == "OK" and len(parts) >= 2:
            say("Removed: " + parts[1])
        elif parts[0] == "ERR" and len(parts) >= 3:
            say("FAILED: %s - %s" % (parts[1], parts[2][:240]))
        elif parts[0] == "DISM" and len(parts) >= 3:
            say("DISM %s (%s) %s" % (parts[1], parts[2],
                                     parts[3][:160] if len(parts) > 3 else ""))


def _copilot_deploy_errors():
    """The last few Windows app-deployment failures (why a removal was refused)."""
    script = (
        "Get-WinEvent -LogName 'Microsoft-Windows-AppXDeploymentServer/Operational' "
        "-MaxEvents 80 -ErrorAction SilentlyContinue | "
        "Where-Object { $_.Id -in 401,605,648 -and "
        "$_.TimeCreated -gt (Get-Date).AddMinutes(-10) } | Select-Object -First 4 | "
        "ForEach-Object { 'EVT|' + $_.Id + '|' + ($_.Message -replace '\\s+', ' ') }\n"
    )
    _c, out, _e = ps_run(script, capture=True, timeout=60)
    return [l.split("|", 2)[2][:220] for l in (out or "").splitlines()
            if l.startswith("EVT|") and l.count("|") >= 2]


def check_copilot(st, out=None, include_m365=True):
    """Read-only report: apps, policies, button, deprovision marks."""
    say = out or (lambda m: log.info(m))
    set_status(st, "Checking Copilot (nothing is changed)…", C_STATUS_INFO)
    scan = copilot_scan(include_m365)
    say("Administrator: " + ("yes" if scan["admin"] else
        "NO - installed apps are listed for this user only, provisioned "
        "packages cannot be read"))
    say("")
    say("Installed Copilot apps: " + ("none" if not scan["installed"] else ""))
    for name, _fam, full in scan["installed"]:
        say("   " + full)
    if scan["prov_ok"]:
        say("Provisioned in the Windows image: " +
            ("none" if not scan["provisioned"] else ""))
        for _d, pkg in scan["provisioned"]:
            say("   " + pkg)
    else:
        say("Provisioned in the Windows image: unknown (needs Administrator)")
    say("")
    say("Policies:")
    for hive, path, name in _COPILOT_POLICY_KEYS:
        v = reg_read(hive, path, name)
        say("   %s\\...\\%s\\%s = %s" % (hive, path.split("\\")[-1], name,
                                       "not set" if v is None else v))
    btn = reg_read("HKCU", _ADVANCED, "ShowCopilotButton")
    say("Taskbar Copilot button (ShowCopilotButton): " +
        ("default (shown)" if btn is None else
         "hidden" if btn == 0 else "shown"))
    marked = [f for f in _copilot_families(scan, include_m365)
              if _reg_key_exists("HKLM", _DEPROVISIONED + "\\" + f)]
    say("Marked 'Deprovisioned' (not re-provisioned by upgrades): %d of %d"
        % (len(marked), len(_copilot_families(scan, include_m365))))
    locked = (all(reg_read(h, p, n) == 1 for h, p, n in _COPILOT_POLICY_KEYS)
              and btn == 0)
    if not scan["installed"] and not scan["provisioned"] and locked:
        set_status(st, "Copilot is gone and locked down.", C_STATUS_OK)
    else:
        set_status(st, "Copilot is NOT fully removed - see the list.", C_STATUS_WARN)


def remove_copilot(st, out=None, include_m365=True):
    """Remove Copilot with every layer described above (blocks until done)."""
    say = out or (lambda m: log.info(m))
    admin = is_admin()
    set_status(st, "Removing Copilot…", C_STATUS_INFO)
    say("Administrator: " + ("yes" if admin else
        "NO - machine-wide steps will be skipped. Run the program as "
        "Administrator for a lasting removal."))
    before = copilot_scan(include_m365)
    for _n, _fam, full in before["installed"]:
        say("Found: " + full)
    if before["provisioned"]:
        for _d, pkg in before["provisioned"]:
            say("Found (provisioned): " + pkg)

    created_pol = list(cfg.get("copilot_created_policies", []))
    created_keys = list(cfg.get("copilot_created_keys", []))

    # 1. Policies + taskbar button
    for hive, path, name in _COPILOT_POLICY_KEYS:
        if hive == "HKLM" and not admin:
            say("Skipped (needs Administrator): %s %s" % (name, hive))
            continue
        if reg_read(hive, path, name) is None:
            entry = [hive, path, name]
            if entry not in created_pol:
                created_pol.append(entry)
        if reg_write(hive, path, name, 1):
            say("Policy set: %s\\...\\%s = 1" % (hive, name))
        else:
            say("FAILED to set policy %s %s" % (hive, name))
    reg_write("HKCU", _ADVANCED, "ShowCopilotButton", 0)
    say("Taskbar Copilot button hidden.")

    # 2. Mark the package families Deprovisioned (before removing them)
    if admin:
        for fam in _copilot_families(before, include_m365):
            path = _DEPROVISIONED + "\\" + fam
            if _reg_key_exists("HKLM", path):
                continue
            if _reg_make_key("HKLM", path):
                created_keys.append(fam)
                say("Marked Deprovisioned: " + fam)
    cfg.set("copilot_created_policies", created_pol)
    cfg.set("copilot_created_keys", created_keys)
    cfg.save()

    # 3. Unpin any leftover taskbar pin, then remove the apps
    _unpin_taskbar_sync("Copilot")
    # Every step is wrapped in try/catch and reports its own error text: a
    # failing Remove-* used to end the whole pipeline without a word.
    stop_ps = (
        "Get-Process | Where-Object { $_.Path -like '*\\WindowsApps\\*Copilot*' -or "
        f"($inc -and $_.Path -like '*\\WindowsApps\\{_M365_PACKAGE}*') }} | "
        "Stop-Process -Force\n"
    )
    script = _copilot_ps_head(include_m365, admin) + stop_ps + (
        "$pk | Where-Object { Hit $_.Name } | ForEach-Object {\n"
        "  $f = $_.PackageFullName\n"
        "  try { if ($adm) { Remove-AppxPackage -Package $f -AllUsers -ErrorAction Stop } "
        "else { Remove-AppxPackage -Package $f -ErrorAction Stop }; 'OK|' + $f }\n"
        "  catch { 'ERR|' + $f + '|' + ($_.Exception.Message -replace '\\s+', ' ') } }\n"
        "if ($adm) { Get-AppxProvisionedPackage -Online | "
        "Where-Object { Hit $_.DisplayName } | ForEach-Object {\n"
        "  $f = $_.PackageName\n"
        "  try { Remove-AppxProvisionedPackage -Online -PackageName $f -ErrorAction Stop | Out-Null; 'OK|' + $f }\n"
        "  catch { 'ERR|' + $f + '|' + ($_.Exception.Message -replace '\\s+', ' ') } } }\n"
    )
    code, outp, err = ps_run(script, capture=True, timeout=300)
    _copilot_say_results(outp, say)
    if code != 0:
        log.warning("Copilot removal: rc=%s err=%s", code, (err or "")[:300])

    # 4. Verify; if Windows refused, try the fall-backs once
    after = copilot_scan(include_m365)
    if after["installed"] or after["provisioned"]:
        say("Windows refused the first attempt - trying the fall-backs.")
        fb = _copilot_ps_head(include_m365, admin) + stop_ps + (
            # per-user removal (what Settings > Apps > Uninstall does)
            "$pk | Where-Object { Hit $_.Name } | ForEach-Object {\n"
            "  $f = $_.PackageFullName\n"
            "  try { Remove-AppxPackage -Package $f -ErrorAction Stop; 'OK|current user: ' + $f }\n"
            "  catch { 'ERR|current user: ' + $f + '|' + ($_.Exception.Message -replace '\\s+', ' ') } }\n"
            # the Windows image copy through DISM
            "if ($adm) { Get-AppxProvisionedPackage -Online | "
            "Where-Object { Hit $_.DisplayName } | ForEach-Object {\n"
            "  $f = $_.PackageName\n"
            f"  $o = & '{_dism_exe()}' /Online /Remove-ProvisionedAppxPackage /PackageName:$f\n"
            "  'DISM|' + $f + '|exit ' + $LASTEXITCODE + '|' + (($o | Select-Object -Last 3) -join ' ') } }\n"
        )
        code, outp, err = ps_run(fb, capture=True, timeout=300)
        _copilot_say_results(outp, say)
        after = copilot_scan(include_m365)
    broadcast_settings()
    left = after["installed"] + after["provisioned"]
    if left:
        for line in _copilot_deploy_errors():
            say("Windows log: " + line)
        for item in left:
            say("STILL THERE: " + item[-1])
        set_status(st, "Copilot is still present - %d item(s). Windows refused "
                       "the removal; see the list." % len(left), C_STATUS_WARN)
    else:
        say("Verified: no Copilot package left." +
            ("" if after["prov_ok"] else
             " (Provisioned copies could not be checked without Administrator.)"))
        if not admin:
            set_status(st, "Copilot removed for this user only - run as "
                           "Administrator for the lasting part.", C_STATUS_WARN)
        else:
            set_status(st, "Copilot removed and locked down. Sign out and in "
                           "(or restart Explorer) to refresh the taskbar.",
                       C_STATUS_OK)
            auto_close_popup("Copilot", "Copilot REMOVED ✓")


def restore_copilot(st, out=None):
    """Undo the settings part: policies, button, Deprovisioned marks.

    Only what this program created is removed (remembered in the config).  The
    apps themselves are not reinstalled - get them from the Microsoft Store.
    """
    say = out or (lambda m: log.info(m))
    admin = is_admin()
    for hive, path, name in cfg.get("copilot_created_policies", []):
        if hive == "HKLM" and not admin:
            say("Skipped (needs Administrator): %s %s" % (hive, name))
            continue
        if reg_delete_value(hive, path, name):
            say("Policy removed: %s\\...\\%s" % (hive, name))
    for fam in cfg.get("copilot_created_keys", []):
        if not admin:
            say("Skipped (needs Administrator): Deprovisioned mark " + fam)
            continue
        if _reg_delete_key("HKLM", _DEPROVISIONED + "\\" + fam):
            say("Deprovisioned mark removed: " + fam)
    reg_write("HKCU", _ADVANCED, "ShowCopilotButton", 1)
    say("Taskbar Copilot button: shown again (press Apply Taskbar Settings "
        "or sign out/in).")
    if admin:
        cfg.set("copilot_created_policies", [])
        cfg.set("copilot_created_keys", [])
        cfg.save()
    broadcast_settings()
    set_status(st, "Copilot settings restored. Reinstall the apps from the "
                   "Microsoft Store if you want them.", C_STATUS_OK)


# *************** DEL 17 – ONEDRIVE ***************

def apply_remove_onedrive(st):
    def _do():
        set_status(st, "Stopping OneDrive…", C_STATUS_INFO)
        subprocess.run("taskkill /f /im OneDrive.exe", shell=True, capture_output=True,
                       creationflags=_NO_WINDOW)
        time.sleep(1)
        # Find uninstaller
        candidates = [
            Path(os.environ.get("SystemRoot", r"C:\Windows")) / "SysWOW64" / "OneDriveSetup.exe",
            Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "OneDriveSetup.exe",
            Path(os.environ.get("LOCALAPPDATA", "")) / "Microsoft" / "OneDrive" / "OneDriveSetup.exe",
        ]
        uninstalled = False
        for p in candidates:
            if p.exists():
                log.debug("Running OneDrive uninstaller: %s", p)
                subprocess.run([str(p), "/uninstall"],
                               capture_output=True, text=True, timeout=180,
                               creationflags=_NO_WINDOW)
                uninstalled = True
                break
        # Disable via Group Policy
        od_policy = r"SOFTWARE\Policies\Microsoft\Windows\OneDrive"
        reg_write("HKLM", od_policy, "DisableFileSyncNGSC",                  1)
        reg_write("HKLM", od_policy, "DisableLibrariesDefaultSaveToOneDrive", 1)
        # Remove startup entry
        reg_delete_value("HKCU",
                         r"Software\Microsoft\Windows\CurrentVersion\Run",
                         "OneDrive")
        # Remove shell namespace entries
        for clsid in (
            "{018D5C66-4533-4307-9B53-224DE2ED1FE6}",
            "{04271989-C4B6-4B6B-B66B-7B7C742CF869}",
        ):
            reg_delete_value("HKCU",
                             rf"Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{clsid}",
                             "")
        if uninstalled:
            set_status(st, "OneDrive uninstalled + startup entry removed + policy disabled.", C_STATUS_OK)
            auto_close_popup("OneDrive", "OneDrive REMOVED ✓")
        else:
            set_status(st,
                       "Uninstaller not found – disabled via policy and startup removed. "
                       "OneDrive may already have been removed.",
                       C_STATUS_WARN)
    run_thread(_do)


# *************** DEL 18 – DISPLAY LANGUAGE AND REGIONAL SETTINGS ***************

def apply_set_swedish(st):
    def _do():
        set_status(st, "Applying Swedish language and 24-hour format…", C_STATUS_INFO)
        script = r"""
$list = New-WinUserLanguageList sv-SE
Set-WinUserLanguageList $list -Force
Set-WinUILanguageOverride -Language sv-SE
Set-WinSystemLocale        -SystemLocale sv-SE
Set-Culture                -CultureInfo  sv-SE
Set-WinHomeLocation        -GeoId        221
"""
        code, _, err = ps_run(script, capture=True)
        # 24-hour clock via registry (takes immediate effect for new windows)
        reg_write("HKCU", r"Control Panel\International", "sTimeFormat", "HH:mm:ss",      winreg.REG_SZ)
        reg_write("HKCU", r"Control Panel\International", "sShortTime",  "HH:mm",          winreg.REG_SZ)
        reg_write("HKCU", r"Control Panel\International", "iTime",       "1",              winreg.REG_SZ)
        reg_write("HKCU", r"Control Panel\International", "iTLZero",     "1",              winreg.REG_SZ)
        reg_write("HKCU", r"Control Panel\International", "Locale",      "0000041D",       winreg.REG_SZ)
        reg_write("HKCU", r"Control Panel\International", "sLanguage",   "SVE",            winreg.REG_SZ)
        reg_write("HKCU", r"Control Panel\International", "sCountry",    "Sweden",         winreg.REG_SZ)
        broadcast_settings()
        if code == 0:
            set_status(st,
                       "Swedish language + 24-hour format applied. Restart for full effect.",
                       C_STATUS_OK)
            auto_close_popup("Language", "Swedish + 24h clock SET ✓")
        else:
            set_status(st,
                       f"Partial success (rc={code}). "
                       "24h clock applied. Language requires restart. err=" + err[:120],
                       C_STATUS_WARN)
    run_thread(_do)


def apply_swedish_only(st):
    """Swedish ONLY: no English (US) input language, so no "ENG" in the tray.

    The tray indicator is there because Windows was installed in English: the
    display language is en-US, and Windows refuses to drop English while no
    Swedish language pack exists.  So the pack is installed first (a download
    of a few minutes), then Swedish becomes the display language, the only
    input language and the default for the sign-in screen and new users.
    One restart is needed before the ENG disappears."""
    def _do():
        set_status(st, "Installing the Swedish language pack - this downloads "
                       "and takes a few minutes…", C_STATUS_INFO)
        script = r"""
$ErrorActionPreference = 'Continue'
try { Install-Language -Language sv-SE -ErrorAction Stop } catch { Write-Output ("Install-Language: " + $_.Exception.Message) }
try { Set-SystemPreferredUILanguage -Language sv-SE -ErrorAction Stop } catch { Write-Output ("UI language: " + $_.Exception.Message) }
Set-WinUILanguageOverride -Language sv-SE
$list = New-WinUserLanguageList sv-SE
Set-WinUserLanguageList $list -Force
Set-WinDefaultInputMethodOverride -InputTip '041D:0000041D'
Set-WinSystemLocale -SystemLocale sv-SE
Set-Culture -CultureInfo sv-SE
Set-WinHomeLocation -GeoId 221
try { Copy-UserInternationalSettingsToSystem -WelcomeScreen $true -NewUser $true } catch { Write-Output ("Copy to system: " + $_.Exception.Message) }
"""
        code, out, err = ps_run(script, capture=True, timeout=1800)
        # Keyboard layouts: Swedish only, nothing "substituted" back to US.
        reg_write("HKCU", r"Keyboard Layout\Preload", "1", "0000041d", winreg.REG_SZ)
        for n in range(2, 10):
            reg_delete_value("HKCU", r"Keyboard Layout\Preload", str(n))
        try:
            winreg.DeleteKey(winreg.HKEY_CURRENT_USER,
                             r"Keyboard Layout\Substitutes")
        except Exception:
            pass
        broadcast_settings()
        log.info("apply_swedish_only rc=%s out=%s err=%s",
                 code, (out or "")[:300], (err or "")[:300])
        note = (out or "").strip().replace("\n", " | ")[:140]
        if code == 0 and not note:
            set_status(st, "Swedish only. Restart Windows - then ENG is gone.",
                       C_STATUS_OK)
            auto_close_popup("Language", "Swedish only SET ✓  (restart)")
        else:
            set_status(st, "Done, with notes (rc=%s): %s  - restart Windows "
                           "and look again." % (code, note or (err or "")[:120]),
                       C_STATUS_WARN)
    run_thread(_do)


# *************** DEL 18b – DESKTOP PICTURE ***************
#
# After a reinstall the desktop was a flat purple: the picture setting said
# "Windows Spotlight" (BackgroundType 3), which Windows Education cannot
# download, so Windows fell back to the background COLOUR.  Choosing a picture
# here sets the file AND switches the setting back to "Picture".

WALLPAPER_STYLES = {
    # name: (WallpaperStyle, TileWallpaper)
    "Fill":    ("10", "0"),
    "Fit":     ("6",  "0"),
    "Stretch": ("2",  "0"),
    "Tile":    ("0",  "1"),
    "Center":  ("0",  "0"),
    "Span":    ("22", "0"),
}


def apply_solid_background(rgb, st):
    """No picture at all: the desktop is one flat colour.

    Four things have to agree, or Windows quietly goes back to a picture:
    the picture path is emptied, the setting is "Solid colour" (1), the
    colour itself is stored, and Spotlight - the pictures that arrive with
    Windows by themselves, and the "Learn more about this picture" icon that
    comes with them - is switched off."""
    r, g, b = rgb
    reg_write("HKCU", r"Control Panel\Colors", "Background",
              "%d %d %d" % (r, g, b), winreg.REG_SZ)
    reg_write("HKCU", r"Software\Microsoft\Windows\CurrentVersion\Explorer\Wallpapers",
              "BackgroundType", 1)
    cloud = r"Software\Policies\Microsoft\Windows\CloudContent"
    reg_write("HKCU", cloud, "DisableWindowsSpotlightFeatures", 1)
    reg_write("HKCU", cloud, "DisableSpotlightCollectionOnDesktop", 1)
    for sub in ("NewStartPanel", "ClassicStartMenu"):
        reg_write("HKCU",
                  r"Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons"
                  "\\" + sub,
                  "{2cc5ca98-6485-489a-920e-b3e88a6ccce3}", 1)
    # An empty path removes the picture; the colour below then shows.
    ctypes.windll.user32.SystemParametersInfoW(20, 0, "", 3)
    colorref = r | (g << 8) | (b << 16)
    arr = (ctypes.c_int * 1)(1)                 # COLOR_BACKGROUND
    cols = (ctypes.c_uint32 * 1)(colorref)
    ctypes.windll.user32.SetSysColors(1, arr, cols)
    broadcast_settings()
    set_status(st, "Desktop is now the flat colour #%02X%02X%02X.  If a "
                   "picture still shows, sign out and in once." % (r, g, b),
               C_STATUS_OK)
    auto_close_popup("Desktop", "Plain background SET ✓")


def apply_set_wallpaper(path, style, st):
    path = (path or "").strip().strip('"')
    if not path or not os.path.isfile(path):
        set_status(st, "Pick a picture file first.", C_STATUS_WARN)
        return
    try:
        # A copy of our own: the original may sit on a drive that is not
        # there at logon (it was E: and became X: this very day).
        keep = Path(os.environ.get("APPDATA", "")) / "Win11Tweaker"
        keep.mkdir(parents=True, exist_ok=True)
        target = keep / ("wallpaper" + Path(path).suffix.lower())
        if os.path.abspath(path).lower() != str(target).lower():
            shutil.copyfile(path, target)
    except Exception as e:
        set_status(st, "Could not copy the picture: %s" % e, C_STATUS_WARN)
        return
    ws, tile = WALLPAPER_STYLES.get(style, WALLPAPER_STYLES["Fill"])
    reg_write("HKCU", r"Control Panel\Desktop", "WallpaperStyle", ws, winreg.REG_SZ)
    reg_write("HKCU", r"Control Panel\Desktop", "TileWallpaper", tile, winreg.REG_SZ)
    # 0 = Picture (3 was Spotlight, 1 = solid colour, 2 = slideshow)
    reg_write("HKCU", r"Software\Microsoft\Windows\CurrentVersion\Explorer\Wallpapers",
              "BackgroundType", 0)
    # SPIF_UPDATEINIFILE | SPIF_SENDCHANGE: written to the registry, announced.
    ok = ctypes.windll.user32.SystemParametersInfoW(20, 0, str(target), 3)
    if ok:
        set_status(st, "Wallpaper set (%s): %s" % (style, path), C_STATUS_OK)
        auto_close_popup("Wallpaper", "Wallpaper SET ✓")
    else:
        set_status(st, "Windows refused the picture (error %s)."
                   % ctypes.GetLastError(), C_STATUS_WARN)


# *************** DEL 19 – PRIVACY: TELEMETRY, ADVERTISING ID, CORTANA ***************

def apply_disable_telemetry(st):
    """Set telemetry to level 0 (Security) and stop the DiagTrack service."""
    ok1 = reg_write("HKLM",
                    r"SOFTWARE\Policies\Microsoft\Windows\DataCollection",
                    "AllowTelemetry", 0)
    ok2 = reg_write("HKLM",
                    r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection",
                    "AllowTelemetry", 0)
    reg_write("HKCU",
              r"Software\Microsoft\Windows\CurrentVersion\Privacy",
              "TailoredExperiencesWithDiagnosticDataEnabled", 0)
    ps_run(
        "Stop-Service  DiagTrack        -Force -ErrorAction SilentlyContinue; "
        "Set-Service   DiagTrack        -StartupType Disabled -ErrorAction SilentlyContinue; "
        "Stop-Service  dmwappushservice -Force -ErrorAction SilentlyContinue; "
        "Set-Service   dmwappushservice -StartupType Disabled -ErrorAction SilentlyContinue"
    )
    if ok1 or ok2:
        set_status(st, "Telemetry level 0 + DiagTrack/dmwappushservice stopped & disabled.", C_STATUS_OK)
        auto_close_popup("Telemetry", "Telemetry DISABLED ✓")
    else:
        set_status(st, "Partial – run as Administrator.", C_STATUS_WARN)


def apply_disable_advertising_id(st):
    ok = reg_write("HKCU",
                   r"Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo",
                   "Enabled", 0)
    reg_write("HKCU",
              r"Software\Microsoft\Windows\CurrentVersion\Privacy",
              "TailoredExperiencesWithDiagnosticDataEnabled", 0)
    if ok:
        set_status(st, "Advertising ID disabled.", C_STATUS_OK)
        auto_close_popup("Advertising ID", "Advertising ID DISABLED ✓")
    else:
        set_status(st, "Failed.", C_STATUS_WARN)


def apply_disable_cortana(st):
    ok = reg_write("HKLM",
                   r"SOFTWARE\Policies\Microsoft\Windows\Windows Search",
                   "AllowCortana", 0)
    reg_write("HKCU",
              r"Software\Microsoft\Windows\CurrentVersion\Search",
              "CortanaEnabled", 0)
    reg_write("HKCU",
              r"Software\Microsoft\Windows\CurrentVersion\Search",
              "BingSearchEnabled", 0)
    # Remove Cortana package if present
    ps_run("Get-AppxPackage *Microsoft.549981C3F5F10* | "
           "Remove-AppxPackage -ErrorAction SilentlyContinue")
    if ok:
        set_status(st, "Cortana disabled via policy + package removal attempted.", C_STATUS_OK)
        auto_close_popup("Cortana", "Cortana DISABLED ✓")
    else:
        set_status(st, "Partial – run as Admin.", C_STATUS_WARN)


# *************** DEL 20 – DEFAULT DOWNLOAD FOLDER ***************

def _set_chromium_download(prefs_path: Path, folder: str, errors: list, browser: str):
    """Patch a Chromium-based browser Preferences JSON to set the download dir."""
    if not prefs_path.exists():
        errors.append(f"{browser}: prefs file not found ({prefs_path})")
        return
    try:
        with open(prefs_path, "r", encoding="utf-8") as fh:
            data = json.load(fh)
        data.setdefault("download", {})["default_directory"] = folder
        data["download"]["prompt_for_download"] = False
        with open(prefs_path, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
        log.debug("%s prefs updated: %s", browser, prefs_path)
    except Exception as e:
        errors.append(f"{browser}: {e}")
        log.warning("Prefs error %s: %s", browser, e)


def apply_set_downloads(folder: str, st):
    def _do():
        if not folder.strip():
            set_status(st, "No folder specified.", C_STATUS_WARN)
            return
        Path(folder).mkdir(parents=True, exist_ok=True)

        # Windows shell Downloads folder (KNOWNFOLDERID {374DE290…})
        _GUID = "{374DE290-123F-4565-9164-39C4925E467B}"
        _shell_folder_path = (
            r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
        )
        reg_write("HKCU", _shell_folder_path, _GUID, folder, winreg.REG_SZ)
        reg_write("HKCU",
                  r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders",
                  _GUID, folder, winreg.REG_SZ)

        errors = []

        # Chrome
        chrome_prefs = (
            Path(os.environ.get("LOCALAPPDATA", ""))
            / "Google" / "Chrome" / "User Data" / "Default" / "Preferences"
        )
        _set_chromium_download(chrome_prefs, folder, errors, "Chrome")

        # Edge
        edge_prefs = (
            Path(os.environ.get("LOCALAPPDATA", ""))
            / "Microsoft" / "Edge" / "User Data" / "Default" / "Preferences"
        )
        _set_chromium_download(edge_prefs, folder, errors, "Edge")

        # Firefox – write to user.js in all profiles
        ff_folder_escaped = folder.replace("\\", "\\\\")
        ff_prefs = (
            f'user_pref("browser.download.dir", "{ff_folder_escaped}");\n'
            'user_pref("browser.download.folderList", 2);\n'
            'user_pref("browser.download.useDownloadDir", true);\n'
        )
        for prof in find_firefox_profiles():
            user_js = prof / "user.js"
            existing = user_js.read_text(encoding="utf-8") if user_js.exists() else ""
            # Remove old download lines, append new
            lines = [
                ln for ln in existing.splitlines(keepends=True)
                if "browser.download.dir" not in ln
                and "browser.download.folderList" not in ln
                and "browser.download.useDownloadDir" not in ln
            ]
            lines.append(ff_prefs)
            user_js.write_text("".join(lines), encoding="utf-8")

        if not errors:
            set_status(
                st,
                f"Download folder set to  {folder}  (Windows + Chrome + Edge + Firefox).",
                C_STATUS_OK,
            )
            auto_close_popup("Downloads", "Download folder SET ✓")
        else:
            set_status(
                st,
                "Applied with notes: " + "  |  ".join(errors),
                C_STATUS_WARN,
            )
    run_thread(_do)


# *************** DEL 20b – PROFILE: SAVE WHAT I CHOSE, RUN IT AGAIN *********
#
# Why this exists.  Everything above CHANGES this machine, and until now
# nothing remembered WHICH of the changes he wanted.  On a new disk that meant
# opening thirteen tabs and clicking every button again from memory - and the
# ones he forgot were the ones he never noticed were missing.
#
# SettingsVault cannot do this half.  It carries per-user settings (his
# wallpaper, Open-Shell, mouse, sound scheme) from machine to machine, but most
# of what this program does is either an HKLM POLICY - machine-wide, needs
# admin, does not travel - or an ACTION with no setting at all behind it:
# uninstalling OneDrive, removing Groove and Photos, powercfg timeouts,
# Defender exclusions, installing Python.  You cannot zip an uninstall.  So the
# two programs are halves of one job, and this is the half that lives here.
#
# A profile is a plain JSON file.  It is a LIST OF WISHES, never a snapshot of
# the registry: "turn the sounds off" survives a new Windows build, a copied
# registry value does not.
#
# DELIBERATELY NOT IN A PROFILE: the auto-login password.  A profile is a file
# he will copy to a laptop, mail to himself or leave in a folder, and a
# Windows password written into it in clear text would outlive every one of
# those moves.  Auto-login stays a button you press by hand.

PROFILE_VERSION = 1

# (key, label, function, argument kind)
#   argument kind:  None    -> fn(status_label)
#                   "folder"-> fn(folder, status_label)
#                   "dict"  -> fn(values_dict, status_label)
def _profile_actions():
    """Built as a function so it is read AFTER every apply_* exists."""
    return [
        ("cursor_noblink",  "Cursor: solid, no blink",
         apply_cursor_noblink, None),
        ("no_spellcheck",   "Typing: no misspelled-word lines, no autocorrect",
         apply_disable_spellcheck, None),
        ("startup_sound",   "Silence the Windows startup sound",
         apply_disable_startup_sound, None),
        ("default_sounds",  "Sound scheme: No Sounds",
         apply_disable_default_sound, None),
        ("firefox_audio",   "Firefox: hide the tab audio icon",
         apply_firefox_audio_icon, None),
        ("power_never",     "Power: never sleep, never turn the screen off",
         apply_power_no_timeout, None),
        ("aero_shake",      "Disable Aero Shake",
         apply_disable_aero_shake, None),
        ("snap_assist",     "Disable Snap Assist",
         apply_disable_snap, None),
        ("prtscn",          "Print Screen: do NOT open the Snipping Tool",
         apply_disable_prtscn_snippet, None),
        ("taskbar_clean",   "Taskbar: hide Widgets, Task View, Chat, Copilot, "
                            "notification bell",
         apply_taskbar_buttons, "dict"),
        ("widgets_remove",  "Remove the Widgets app itself",
         remove_windows_widgets, None),
        ("copilot_remove",  "Remove Copilot for good (apps, policies, "
                            "taskbar button)",
         remove_copilot, None),
        ("store_taskbar",   "Unpin the Microsoft Store from the taskbar",
         remove_ms_store_from_taskbar, None),
        ("onedrive",        "Remove OneDrive",
         apply_remove_onedrive, None),
        ("swedish",         "Swedish (sv-SE) and a 24-hour clock",
         apply_set_swedish, None),
        ("telemetry",       "Turn telemetry down",
         apply_disable_telemetry, None),
        ("advertising_id",  "Turn the advertising ID off",
         apply_disable_advertising_id, None),
        ("cortana",         "Turn Cortana off",
         apply_disable_cortana, None),
        ("downloads",       "Set the download folder (Windows, Chrome, Edge, "
                            "Firefox)", apply_set_downloads, "folder"),
        ("defender_excl",   "Add a Defender exclusion folder",
         apply_add_exclusion, "folder"),
    ]


# What "taskbar_clean" writes.  Exactly the four values the Taskbar tab
# offers, kept here so a profile does not depend on which boxes happen to be
# ticked in the GUI when it runs.
TASKBAR_CLEAN_VALUES = {
    "TaskbarDa":           0,      # Widgets
    "ShowTaskViewButton":  0,
    "TaskbarMn":           0,      # Chat / Teams
    "ShowCopilotButton":   0,
    "ShowNotificationIcon": 0,     # the bell next to the clock
}


def profile_to_dict(chosen: dict) -> dict:
    """chosen: key -> {"on": bool, "arg": value}."""
    return {
        "program": "Win11 Tweaker",
        "profile_version": PROFILE_VERSION,
        "created": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "computer": os.environ.get("COMPUTERNAME", ""),
        "actions": chosen,
    }


def save_profile(path: str, chosen: dict) -> None:
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(profile_to_dict(chosen), fh, indent=2, ensure_ascii=False)
    log.info("Profile written: %s (%d actions ticked)",
             path, sum(1 for v in chosen.values() if v.get("on")))


def load_profile(path: str) -> dict:
    """The actions out of a profile file.  Unknown keys are IGNORED, not an
    error: a profile written by a later version must still be usable here,
    and a key that has been renamed must not stop the other seventeen."""
    with open(path, encoding="utf-8") as fh:
        data = json.load(fh)
    if data.get("profile_version", 1) > PROFILE_VERSION:
        log.warning("Profile is from a newer version (%s); unknown entries "
                    "will be skipped.", data.get("profile_version"))
    known = {k for k, _l, _f, _a in _profile_actions()}
    return {k: v for k, v in (data.get("actions") or {}).items()
            if k in known and isinstance(v, dict)}


# *************** DEL 21 – MAIN APP CLASS AND GUI ***************

class IssuTweaker(tk.Tk):
    """Main application window."""

    def __init__(self):
        # AppUserModelID MÅSTE sättas INNAN tk.Tk() skapas
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(_APP_ID)
        except Exception:
            pass

        super().__init__()
        self.title("Windows 11 Tweaker")
        self.configure(bg=C_BG)
        self.minsize(860, 620)

        geom = cfg.get("window_geometry", "1120x840+80+40")
        self.geometry(geom)
        self.bind("<Configure>", self._save_geometry)

        self._build_gui()
        self.protocol("WM_DELETE_WINDOW", self._on_close)

        # Sätt ikonen på första tick (after tkinter startat mainloop)
        self.after(0, lambda: _set_window_icon(self))

        # Warn once if not admin
        if not is_admin():
            self.after(
                600,
                lambda: messagebox.showwarning(
                    "Administrator Required",
                    "Many settings require Administrator privileges.\n\n"
                    "Right-click the script / EXE → 'Run as administrator'\n"
                    "for full functionality.",
                ),
            )

    # ── Lifecycle ────────────────────────────────────────────────────────────

    def _save_geometry(self, event):
        if event.widget is self:
            cfg.set("window_geometry", self.geometry())

    def _on_close(self):
        try:
            cfg.set("last_tab", self.nb.index(self.nb.select()))
        except Exception:
            pass
        cfg.save()
        self.destroy()

    # ── Master layout ─────────────────────────────────────────────────────────

    def _build_gui(self):
        # ── Menu bar ─────────────────────────────────────────────────────────
        menubar = tk.Menu(self, bg=C_HDR_BG, fg=C_FG,
                          activebackground=C_SECTION_FG, activeforeground=C_HDR_BG,
                          relief="flat", bd=0)
        self.config(menu=menubar)

        def _goto(idx):
            # The numbers below count from "Cursor & Typing" = 0; the Profile
            # tab was put in front of them later, so the notebook index is +1.
            self.nb.select(idx + 1)

        # Display group (indices 0-1)
        m_display = tk.Menu(menubar, tearoff=0, bg="#1a1a2a", fg=C_FG,
                            activebackground=C_SECTION_FG, activeforeground=C_HDR_BG)
        m_display.add_command(label="Cursor & Typing",   command=lambda: _goto(0))
        m_display.add_command(label="Sounds",            command=lambda: _goto(1))
        menubar.add_cascade(label=" 🖥  Display ", menu=m_display)

        # Apps & Files group (indices 2-3)
        m_apps = tk.Menu(menubar, tearoff=0, bg="#1a1a2a", fg=C_FG,
                         activebackground=C_SECTION_FG, activeforeground=C_HDR_BG)
        m_apps.add_command(label="File Associations & Apps", command=lambda: _goto(2))
        m_apps.add_command(label="Firefox",                  command=lambda: _goto(3))
        menubar.add_cascade(label=" 📂  Apps & Files ", menu=m_apps)

        # System group (indices 4-6)
        m_sys = tk.Menu(menubar, tearoff=0, bg="#1a1a2a", fg=C_FG,
                        activebackground=C_SECTION_FG, activeforeground=C_HDR_BG)
        m_sys.add_command(label="Power & Login",    command=lambda: _goto(4))
        m_sys.add_command(label="Snap & PrtScn",    command=lambda: _goto(5))
        m_sys.add_command(label="Defender",         command=lambda: _goto(6))
        m_sys.add_command(label="Language & Region",command=lambda: _goto(10))
        m_sys.add_command(label="Privacy",          command=lambda: _goto(11))
        menubar.add_cascade(label=" ⚙  System ", menu=m_sys)

        # Tools group (indices 7-9, 12)
        m_tools = tk.Menu(menubar, tearoff=0, bg="#1a1a2a", fg=C_FG,
                          activebackground=C_SECTION_FG, activeforeground=C_HDR_BG)
        m_tools.add_command(label="Python Installer",   command=lambda: _goto(7))
        m_tools.add_command(label="Taskbar & Widgets",  command=lambda: _goto(8))
        m_tools.add_command(label="OneDrive",           command=lambda: _goto(9))
        m_tools.add_command(label="Downloads",          command=lambda: _goto(12))
        menubar.add_cascade(label=" 🔧  Tools ", menu=m_tools)

        # Help group
        m_help = tk.Menu(menubar, tearoff=0, bg="#1a1a2a", fg=C_FG,
                         activebackground=C_SECTION_FG, activeforeground=C_HDR_BG)
        m_help.add_command(label="Help",  command=self._show_help)
        m_help.add_separator()
        m_help.add_command(label="About", command=self._show_about)
        menubar.add_cascade(label=" ❓  Help ", menu=m_help)

        # ── Header bar ───────────────────────────────────────────────────────
        hdr = tk.Frame(self, bg=C_HDR_BG, pady=6)
        hdr.pack(fill="x")
        tk.Label(
            hdr, text="⚙   Windows 11 Tweaker",
            bg=C_HDR_BG, fg=C_SECTION_FG, font=("Segoe UI", 14, "bold"),
        ).pack(side="left", padx=16)
        admin_ok    = is_admin()
        admin_color = C_STATUS_OK if admin_ok else C_STATUS_WARN
        admin_text  = "✔ Running as Administrator" if admin_ok else "⚠ NOT Administrator – some features limited"
        tk.Label(hdr, text=admin_text, bg=C_HDR_BG, fg=admin_color,
                 font=FONT_SMALL).pack(side="right", padx=16)

        # ── Notebook (tab strip hidden – navigation via menu) ─────────────────
        style = ttk.Style(self)
        style.theme_use("clam")
        style.configure("TNotebook",     background=C_BG, borderwidth=0)
        style.configure("TNotebook.Tab", background="#313244", foreground=C_FG,
                        padding=[10, 5], font=FONT_BOLD)
        style.map("TNotebook.Tab",
                  background=[("selected", C_SECTION_BG)],
                  foreground=[("selected", C_SECTION_FG)])
        # Hide the tab strip – all navigation goes through the menu bar
        style.layout("TNotebook", [("TNotebook.client", {"sticky": "nswe"})])

        self.nb = ttk.Notebook(self)
        self.nb.pack(fill="both", expand=True, padx=6, pady=4)

        # Breadcrumb label shows which section is active
        self._breadcrumb = tk.Label(
            self, text="", bg=C_BG, fg=C_SECTION_FG,
            font=("Segoe UI", 9, "italic"), anchor="w",
        )
        self._breadcrumb.pack(fill="x", padx=10)

        _tabs = [
            # First, because it is the one that matters on a NEW machine:
            # tick, save, and run the lot on the next disk instead of
            # remembering thirteen tabs' worth of buttons.
            ("Profile",             self._tab_profile),
            ("Cursor & Typing",     self._tab_cursor),       # 0
            ("Sounds",              self._tab_sounds),        # 1
            ("File Assoc & Apps",   self._tab_fileassoc),     # 2
            ("Firefox",             self._tab_firefox),       # 3
            ("Power & Login",       self._tab_power),         # 4
            ("Snap & PrtScn",       self._tab_snap),          # 5
            ("Defender",            self._tab_defender),      # 6
            ("Python Installer",    self._tab_python),        # 7
            ("Taskbar & Widgets",   self._tab_taskbar),       # 8
            ("OneDrive",            self._tab_onedrive),      # 9
            ("Language & Region",   self._tab_language),      # 10
            ("Privacy",             self._tab_privacy),       # 11
            ("Downloads",           self._tab_downloads),     # 12
            ("Background",          self._tab_wallpaper),     # 13
        ]
        self._tab_names = [t[0] for t in _tabs]
        for label, builder in _tabs:
            sf = ScrollableFrame(self.nb)
            self.nb.add(sf, text=label)
            builder(sf.inner)

        def _on_tab_changed(event):
            try:
                idx = self.nb.index(self.nb.select())
                self._breadcrumb.config(text=f"  ▸  {self._tab_names[idx]}")
            except Exception:
                pass

        self.nb.bind("<<NotebookTabChanged>>", _on_tab_changed)

        last = cfg.get("last_tab", 0)
        try:
            self.nb.select(last)
            self._breadcrumb.config(text=f"  ▸  {self._tab_names[last]}")
        except Exception:
            pass

    # ── About dialog ─────────────────────────────────────────────────────────

    def _show_about(self):
        """Stylish About dialog with documentation link and donation info."""
        import webbrowser
        top = tk.Toplevel(self.root if hasattr(self, "root") else self)
        top.title("About – Windows 11 Tweaker")
        top.configure(bg=C_HDR_BG)
        top.resizable(False, False)
        top.transient(self)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        # ── Header ────────────────────────────────────────────────────────────
        tk.Label(top, text="⚙", bg=C_HDR_BG, fg=C_SECTION_FG,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(top, text="Windows 11 Tweaker",
                 bg=C_HDR_BG, fg=C_SECTION_FG,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(top, text="A comprehensive GUI tool to configure Windows 11",
                 bg=C_HDR_BG, fg="#89898a",
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
        tk.Frame(top, bg="#3a3a4a", height=1).pack(fill="x", padx=20)

        # ── Author ────────────────────────────────────────────────────────────
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C_HDR_BG, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

        # ── Documentation link ────────────────────────────────────────────────
        DOC_URL = (
            "https://docs.google.com/document/d/"
            "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
        doc_lbl = tk.Label(top, text="📄  View documentation",
                           bg=C_HDR_BG, fg=C_SECTION_FG,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
        doc_lbl.pack(pady=(6, 2))
        doc_lbl.bind("<Button-1>", lambda e: open_url(DOC_URL))
        doc_lbl.bind("<Enter>",    lambda e: doc_lbl.configure(fg="#b4d4ff"))
        doc_lbl.bind("<Leave>",    lambda e: doc_lbl.configure(fg=C_SECTION_FG))

        tk.Frame(top, bg="#3a3a4a", height=1).pack(fill="x", padx=20, pady=(14, 0))

        # ── Donation section ──────────────────────────────────────────────────
        tk.Label(top, text="☕  If you enjoy this tool, a small gift is always welcome!",
                 bg=C_HDR_BG, fg="#89898a",
                 font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg="#1a1a2a", padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))

        REVOLUT_URL = "https://revolut.me/lars72oeh"
        PAYPAL_URL  = "https://paypal.me/issusbarn"
        WISE_URL    = "https://wise.com/pay/me/larsdenniso"

        for icon, label, url in [
            ("💳", "Revolut",  REVOLUT_URL),
            ("🅿",  "PayPal",   PAYPAL_URL),
            ("🌍", "Wise",     WISE_URL),
        ]:
            lbl = tk.Label(donate_frame, text=f"{icon}  {label}",
                           bg="#1a1a2a", fg=C_SECTION_FG,
                           font=("Segoe UI", 9, "underline"), cursor="hand2")
            lbl.pack(anchor="w", pady=2)
            lbl.bind("<Button-1>", lambda e, u=url: open_url(u))
            lbl.bind("<Enter>",    lambda e, l=lbl: l.configure(fg="#b4d4ff"))
            lbl.bind("<Leave>",    lambda e, l=lbl: l.configure(fg=C_SECTION_FG))

        # ── Close button ──────────────────────────────────────────────────────
        tk.Frame(top, bg="#3a3a4a", height=1).pack(fill="x", padx=20, pady=(8, 0))
        tk.Button(top, text="Close",
                  command=top.destroy,
                  bg=C_BTN_GREY, fg="white",
                  activebackground=C_BTN_GREY, activeforeground="white",
                  relief="flat", font=FONT_BOLD, cursor="hand2",
                  padx=20, pady=6).pack(pady=12)

    # ── Help dialog ───────────────────────────────────────────────────────────

    def _show_help(self):
        """Full help dialog explaining all features."""
        top = tk.Toplevel(self.root if hasattr(self, "root") else self)
        top.title("Help – Windows 11 Tweaker")
        top.configure(bg=C_SECTION_BG)
        top.resizable(True, True)
        top.geometry("680x620")
        top.transient(self)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        # Header
        hdr = tk.Frame(top, bg=C_HDR_BG, pady=8)
        hdr.pack(fill="x")
        tk.Label(hdr, text="❓  Windows 11 Tweaker – Help",
                 bg=C_HDR_BG, fg=C_SECTION_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left", padx=14)
        tk.Label(hdr, text="Press ESC to close",
                 bg=C_HDR_BG, fg="#89898a",
                 font=("Segoe UI", 8, "italic")).pack(side="right", padx=14)

        # Scrollable text area
        frm = tk.Frame(top, bg=C_SECTION_BG)
        frm.pack(fill="both", expand=True, padx=10, pady=8)
        sb  = tk.Scrollbar(frm, orient="vertical")
        txt = tk.Text(frm, bg=C_SECTION_BG, fg=C_FG,
                      font=("Segoe UI", 9),
                      wrap="word", relief="flat",
                      yscrollcommand=sb.set,
                      insertofftime=0, insertontime=9999999,
                      padx=10, pady=6, state="normal")
        sb.config(command=txt.yview)
        sb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)

        # Tag styles
        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"),  foreground=C_SECTION_FG)
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"),  foreground=C_STATUS_INFO)
        txt.tag_configure("body", font=("Segoe UI", 9),           foreground=C_FG)
        txt.tag_configure("warn", font=("Segoe UI", 9, "italic"), foreground=C_STATUS_WARN)
        txt.tag_configure("sep",  font=("Segoe UI", 4))

        def h1(t):  txt.insert("end", f"\n{t}\n", "h1")
        def h2(t):  txt.insert("end", f"  ◈  {t}\n", "h2")
        def body(t):txt.insert("end", f"      {t}\n", "body")
        def warn(t):txt.insert("end", f"      ⚠  {t}\n", "warn")
        def sep():  txt.insert("end", "\n", "sep")

        h1("Overview")
        body("Windows 11 Tweaker is a GUI tool that lets you apply common Windows 11")
        body("customisations, privacy settings, and clean-up tasks in a single click —")
        body("without needing to open regedit, PowerShell, or Group Policy Editor manually.")
        body("Navigate between sections using the menu bar at the top of the window.")
        sep()
        warn("Many settings write to the Windows registry or call PowerShell.")
        warn("Run the program as Administrator for full functionality.")

        h1("Display")
        h2("Cursor & Typing")
        body("Sets CursorBlinkRate = -1 in the registry so the keyboard text cursor")
        body("is always solid (no blinking). Log out and back in to apply fully.")
        body("Use 'Check current rate' to read the registry value before changing it.")
        sep()
        h2("Typing (same tab)")
        body("Turns off 'Highlight misspelled words' and 'Autocorrect misspelled words'")
        body("(Settings > Time & language > Typing) by writing EnableSpellchecking and")
        body("EnableAutocorrection = 0 under HKCU\\SOFTWARE\\Microsoft\\TabletTip\\1.7.")
        body("No Administrator needed. Restart programs that still show red lines; a")
        body("program with a spell checker of its own may ignore the setting.")
        sep()
        h2("Sounds")
        body("Disable Startup Sound: prevents the Windows start-up chime.")
        body("Disable All System Sounds: clears the Default Beep event and switches")
        body("the active sound scheme to 'No Sounds', silencing all system audio events.")

        h1("Apps & Files")
        h2("File Associations & Apps")
        body("Clears UserChoice registry keys for music, image, and video file extensions.")
        body("After clearing, Windows will ask which app to open the file type with")
        body("instead of launching a Microsoft default app automatically.")
        body("Also lets you uninstall bundled Microsoft media apps (Groove, Photos,")
        body("Movies & TV, Windows Media Player) via Remove-AppxPackage.")
        warn("Removing AppX packages requires Administrator.")
        sep()
        h2("Firefox")
        body("Injects a one-line CSS rule into every Firefox profile's userChrome.css")
        body("that hides the speaker / muted overlay icon on browser tabs.")
        body("Close Firefox before applying, then restart it afterwards.")

        h1("System")
        h2("Power & Login")
        body("Sets monitor, disk, standby, and hibernate timeouts to Never for both")
        body("AC (plugged in) and DC (battery) power plans via powercfg.")
        body("Auto-Login: writes your credentials to Winlogon in HKLM so Windows")
        body("skips the password prompt on startup.")
        warn("Auto-Login stores the password in plain text in the registry.")
        sep()
        h2("Snap & PrtScn")
        body("Aero Shake: disables the 'shake a window to minimise all others' gesture.")
        body("Snap Assist: turns off the snap flyout and snap suggestions.")
        body("Print Screen: removes the Windows 11 binding that opens Snipping Tool")
        body("when PrtScn is pressed.")
        sep()
        h2("Defender")
        body("Applies Group Policy registry keys to permanently disable real-time scanning.")
        body("IMPORTANT – first manually disable Tamper Protection in Windows Security,")
        body("otherwise the registry changes will be overwritten.")
        body("Also allows adding a folder exclusion (whitelist) to Defender.")
        warn("Disabling Defender reduces system security. Use with caution.")
        sep()
        h2("Language & Region")
        body("Sets the Windows display language to Swedish (sv-SE), configures the")
        body("system locale, home location, and culture. Also switches the clock to")
        body("24-hour format (HH:mm:ss). A full restart is required after applying.")
        sep()
        h2("Privacy")
        body("Telemetry: sets DiagnosticAndUsage level to 0 (Security) and stops")
        body("the DiagTrack service, preventing diagnostic data uploads to Microsoft.")
        body("Advertising ID: disables the per-user advertising identifier used")
        body("for targeted ads across apps.")
        body("Cortana: applies Group Policy keys to disable and remove Cortana.")

        h1("Tools")
        h2("Python Installer")
        body("Fetches the three most recent stable Python 3 releases from python.org.")
        body("Click 'Fetch Available Python Versions', then use the Download & Install")
        body("button next to the version you want. The installer runs automatically.")
        sep()
        h2("Taskbar & Widgets")
        body("Check the items you want to hide, then click Apply. Explorer restarts")
        body("automatically to make the changes visible.")
        body("Items: Widgets button, Task View, Chat/Teams, Copilot button.")
        body("Also allows unpinning apps from the taskbar (Store, Outlook, Mail)")
        body("and removing the Windows Web Experience Pack (Widgets app).")
        sep()
        h2("OneDrive")
        body("Full removal in 5 steps: kills the process, runs the uninstaller,")
        body("removes the startup registry entry, sets Group Policy to disable sync,")
        body("and removes OneDrive from the Explorer namespace.")
        warn("Requires Administrator for the Group Policy step.")
        sep()
        h2("Downloads")
        body("Sets the Windows shell Downloads folder to a custom path and configures")
        body("Chrome, Edge, and Firefox to save files there automatically.")
        body("The folder is created if it does not exist. Close all browsers first.")

        txt.config(state="disabled")

        # Close button
        tk.Button(top, text="Close  (ESC)",
                  command=top.destroy,
                  bg=C_BTN_GREY, fg="white",
                  activebackground=C_BTN_GREY, activeforeground="white",
                  relief="flat", font=FONT_BOLD, cursor="hand2",
                  padx=20, pady=6).pack(pady=(4, 10))

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Cursor & Blink
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_profile(self, p):
        """Tick what this machine should get, save it, run it on the next one.

        See DEL 20b for why this lives here and not in SettingsVault: most of
        what this program does is a machine-wide policy or an outright action,
        and neither can be carried in a zip.
        """
        section_label(p, "Profile – save what you chose, run it on a new PC")
        tk.Label(
            p,
            text="Tick the changes this machine should have, then Save.  On a "
                 "new computer: Load, then Run.\nThe auto-login PASSWORD is "
                 "deliberately never written to a profile - that button stays "
                 "manual.",
            bg=C_SECTION_BG, fg=C_FG, justify="left", anchor="w",
            font=("Segoe UI", 9),
        ).pack(fill="x", padx=14, pady=(0, 8))

        self._prof_vars = {}      # key -> BooleanVar
        self._prof_args = {}      # key -> StringVar  (folder actions only)

        for key, label, _fn, kind in _profile_actions():
            row = tk.Frame(p, bg=C_SECTION_BG)
            row.pack(fill="x", padx=14, pady=1)
            var = tk.BooleanVar(value=False)
            self._prof_vars[key] = var
            tk.Checkbutton(
                row, text="   " + label, variable=var,
                bg=C_SECTION_BG, fg=C_FG, selectcolor=C_ENTRY_BG,
                activebackground=C_SECTION_BG, activeforeground=C_FG,
                anchor="w", font=("Segoe UI", 9),
            ).pack(side="left")
            if kind == "folder":
                sv = tk.StringVar(value="")
                self._prof_args[key] = sv
                e = mk_entry(row, textvariable=sv, width=34)
                e.pack(side="left", padx=(8, 4))
                mk_btn(row, "Browse…",
                       lambda s=sv: self._prof_browse(s),
                       color=C_BTN_BROWSE).pack(side="left")

        self._prof_status = status_label(p)

        brow = tk.Frame(p, bg=C_SECTION_BG)
        brow.pack(fill="x", padx=14, pady=(10, 4))
        mk_btn(brow, "Save profile…", self._prof_save,
               color=C_BTN_CHECK).pack(side="left", padx=(0, 6))
        mk_btn(brow, "Load profile…", self._prof_load,
               color=C_BTN_CHECK).pack(side="left", padx=(0, 6))
        mk_btn(brow, "Run everything ticked", self._prof_run,
               color=C_BTN_DANGER).pack(side="left")

        tk.Label(p, text="What happened:", bg=C_SECTION_BG, fg=C_SECTION_FG,
                 anchor="w", font=("Segoe UI", 9, "bold")
                 ).pack(fill="x", padx=14, pady=(10, 2))
        self._prof_log = mk_text(p, height=10, width=90)
        self._prof_log.pack(fill="both", expand=True, padx=14, pady=(0, 10))

    # ---- Profile helpers -------------------------------------------------

    def _prof_browse(self, strvar):
        d = filedialog.askdirectory(title="Pick a folder", parent=self)
        if d:
            strvar.set(os.path.normpath(d))

    def _prof_say(self, msg, colour=C_STATUS_INFO):
        set_status(self._prof_status, msg, colour)
        try:
            self._prof_log.configure(state="normal")
            self._prof_log.insert("end", msg + "\n")
            self._prof_log.see("end")
            self._prof_log.configure(state="disabled")
        except Exception:
            pass

    def _prof_collect(self) -> dict:
        out = {}
        for key, _label, _fn, kind in _profile_actions():
            entry = {"on": bool(self._prof_vars[key].get())}
            if kind == "folder":
                entry["arg"] = self._prof_args[key].get().strip()
            out[key] = entry
        return out

    def _prof_save(self):
        chosen = self._prof_collect()
        n = sum(1 for v in chosen.values() if v["on"])
        if not n:
            self._prof_say("Nothing is ticked, so there is nothing to save.",
                           C_STATUS_WARN)
            return
        path = filedialog.asksaveasfilename(
            parent=self, title="Save profile",
            defaultextension=".json",
            initialfile="win11_profile_%s.json"
                        % datetime.now().strftime("%Y-%m-%d"),
            filetypes=[("Profile", "*.json"), ("All files", "*.*")])
        if not path:
            return
        try:
            save_profile(path, chosen)
        except Exception as exc:
            log.exception("Could not save the profile")
            self._prof_say("Could not save: %s" % exc, C_STATUS_WARN)
            return
        self._prof_say("Saved %d ticked action(s) to %s"
                       % (n, os.path.basename(path)), C_STATUS_OK)

    def _prof_load(self):
        path = filedialog.askopenfilename(
            parent=self, title="Load profile",
            filetypes=[("Profile", "*.json"), ("All files", "*.*")])
        if not path:
            return
        try:
            actions = load_profile(path)
        except Exception as exc:
            log.exception("Could not read the profile")
            self._prof_say("Could not read that file: %s" % exc, C_STATUS_WARN)
            return
        for key, var in self._prof_vars.items():
            var.set(bool(actions.get(key, {}).get("on", False)))
        for key, sv in self._prof_args.items():
            sv.set(str(actions.get(key, {}).get("arg", "") or ""))
        n = sum(1 for v in actions.values() if v.get("on"))
        self._prof_say("Loaded %s - %d action(s) ticked.  Nothing has been "
                       "changed yet; press Run." % (os.path.basename(path), n),
                       C_STATUS_OK)

    def _prof_run(self):
        """Run every ticked action, one after another, on a worker thread.

        Each one is wrapped on its own: a step that fails must not take the
        remaining seventeen with it, and a machine that is half-configured
        without saying which half is worse than one that reports the failure.
        """
        chosen = self._prof_collect()
        todo = [(k, lbl, fn, kind) for k, lbl, fn, kind in _profile_actions()
                if chosen.get(k, {}).get("on")]
        if not todo:
            self._prof_say("Nothing is ticked.", C_STATUS_WARN)
            return
        missing = [lbl for k, lbl, _f, kind in todo
                   if kind == "folder" and not chosen[k].get("arg")]
        if missing:
            self._prof_say("Give a folder for: " + "; ".join(missing),
                           C_STATUS_WARN)
            return

        def _do():
            self._prof_say("Running %d action(s)..." % len(todo))
            ok = bad = 0
            for key, label, fn, kind in todo:
                try:
                    self._prof_say("  -> %s" % label)
                    if kind == "folder":
                        fn(chosen[key]["arg"], self._prof_status)
                    elif kind == "dict":
                        fn(dict(TASKBAR_CLEAN_VALUES), self._prof_status)
                    else:
                        fn(self._prof_status)
                    ok += 1
                except Exception as exc:
                    bad += 1
                    log.exception("Profile action %s failed", key)
                    self._prof_say("     FAILED: %s" % exc, C_STATUS_WARN)
            self._prof_say(
                "Done: %d applied, %d failed.  Some changes need a sign-out "
                "or a restart." % (ok, bad),
                C_STATUS_OK if not bad else C_STATUS_WARN)

        run_thread(_do)

    # ─────────────────────────────────────────────────────────────────────────

    def _tab_cursor(self, p):
        section_label(p, "Keyboard Caret – Solid Cursor (No Blink)")
        tk.Label(
            p,
            text="Sets CursorBlinkRate = -1 in the registry so the text cursor is\n"
                 "always solid instead of blinking. Log out and back in to apply fully.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st = status_label(p)
        row = tk.Frame(p, bg=C_SECTION_BG)
        row.pack(fill="x", padx=12, pady=6)
        mk_btn(row, "Check current rate",
               lambda: check_cursor_blink(st), color=C_BTN_CHECK).pack(side="left", padx=4)
        mk_btn(row, "Disable cursor blink → SOLID",
               lambda: apply_cursor_noblink(st), color=C_BTN_APPLY).pack(side="left", padx=4)

        section_label(p, "Typing – No Red Misspelled-Word Lines, No Autocorrect")
        tk.Label(
            p,
            text="Switches off Settings → Time & language → Typing → 'Highlight misspelled\n"
                 "words' and 'Autocorrect misspelled words'. Restart programs that still show\n"
                 "red lines. A program with a spell checker of its own may ignore this.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st_typing = status_label(p)
        row2 = tk.Frame(p, bg=C_SECTION_BG)
        row2.pack(fill="x", padx=12, pady=6)
        mk_btn(row2, "Check current setting",
               lambda: check_spellcheck(st_typing), color=C_BTN_CHECK).pack(side="left", padx=4)
        mk_btn(row2, "Turn off red lines + autocorrect",
               lambda: apply_disable_spellcheck(st_typing), color=C_BTN_APPLY).pack(side="left", padx=4)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Sounds
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_sounds(self, p):
        section_label(p, "Startup Sound")
        st1 = status_label(p)
        mk_btn(p, "Disable Startup Sound",
               lambda: apply_disable_startup_sound(st1),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Default / System Sounds")
        tk.Label(
            p,
            text="Clears the Windows Default Beep event and switches the active\n"
                 "sound scheme to 'No Sounds'. All system sound events are silenced.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st2 = status_label(p)
        mk_btn(p, "Disable All System Sounds",
               lambda: apply_disable_default_sound(st2),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        tk.Label(
            p,
            text="Tip: Control Panel → Sound → Sounds tab → Scheme: 'No Sounds' "
                 "lets you manage individual event sounds visually.",
            bg=C_SECTION_BG, fg=C_STATUS_INFO, font=FONT_SMALL, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: File Assoc & Apps
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_fileassoc(self, p):
        section_label(p, "Remove File Associations (Music / Image / Video)")
        tk.Label(
            p,
            text="Deletes UserChoice registry keys so Windows will prompt you to\n"
                 "choose an app the next time you open these file types.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st_fa = status_label(p)
        row = tk.Frame(p, bg=C_SECTION_BG)
        row.pack(fill="x", padx=12, pady=6)
        mk_btn(row, "Clear MUSIC assoc",
               lambda: remove_file_assoc(MUSIC_EXTS, st_fa, "Music"),
               color=C_BTN_APPLY).pack(side="left", padx=4)
        mk_btn(row, "Clear IMAGE assoc",
               lambda: remove_file_assoc(IMAGE_EXTS, st_fa, "Image"),
               color=C_BTN_APPLY).pack(side="left", padx=4)
        mk_btn(row, "Clear VIDEO assoc",
               lambda: remove_file_assoc(VIDEO_EXTS, st_fa, "Video"),
               color=C_BTN_APPLY).pack(side="left", padx=4)

        section_label(p, "Remove Built-in Microsoft Media Apps")
        tk.Label(
            p,
            text="Uninstalls bundled media apps via PowerShell Remove-AppxPackage.\n"
                 "Requires Administrator. Apps can be reinstalled from the Microsoft Store.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st_app = status_label(p)
        for name, pkg in MEDIA_PACKAGES.items():
            mk_btn(
                p, f"Remove: {name}",
                lambda n=name, pk=pkg: disable_media_app(pk, n, st_app),
                color=C_BTN_DANGER,
            ).pack(anchor="w", padx=12, pady=3)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Firefox
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_firefox(self, p):
        section_label(p, "Firefox – Hide Tab Audio / Muted Icon")
        tk.Label(
            p,
            text="Injects a CSS rule into every Firefox profile's userChrome.css that\n"
                 "hides the speaker / muted overlay on tabs.\n"
                 "Close Firefox before applying, then restart it after.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st = status_label(p)
        mk_btn(p, "Hide Firefox Tab Audio Icon",
               lambda: apply_firefox_audio_icon(st),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Detected Firefox Profiles")
        profs = find_firefox_profiles()
        if profs:
            for prof in profs:
                tk.Label(p, text=f"  •  {prof}",
                         bg=C_SECTION_BG, fg=C_STATUS_INFO, font=FONT_SMALL,
                         anchor="w").pack(fill="x", padx=24, pady=1)
        else:
            tk.Label(p, text="  No Firefox profiles found.",
                     bg=C_SECTION_BG, fg=C_STATUS_WARN, font=FONT_SMALL,
                     anchor="w").pack(fill="x", padx=24)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Power & Login
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_power(self, p):
        section_label(p, "Power / Energy – Disable All Auto Turn-Offs")
        tk.Label(
            p,
            text="Sets monitor, disk, standby and hibernate timeouts to Never\n"
                 "for both AC (plugged in) and DC (battery).",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st1 = status_label(p)
        row = tk.Frame(p, bg=C_SECTION_BG)
        row.pack(fill="x", padx=12, pady=6)
        mk_btn(row, "Check power settings (log)",
               lambda: check_power_settings(st1), color=C_BTN_CHECK).pack(side="left", padx=4)
        mk_btn(row, "Set ALL timeouts → Never",
               lambda: apply_power_no_timeout(st1), color=C_BTN_APPLY).pack(side="left", padx=4)

        section_label(p, "Auto-Login – No Password at Windows Startup")
        tk.Label(
            p,
            text="Stores credentials in HKLM\\…\\Winlogon so Windows skips the login screen.\n"
                 "WARNING: Password is stored in plain text in the registry.\n"
                 "Suitable only for single-user PCs where physical security is not a concern.",
            bg=C_SECTION_BG, fg=C_STATUS_WARN, font=FONT_SMALL, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        frm = tk.Frame(p, bg=C_SECTION_BG)
        frm.pack(fill="x", padx=12, pady=6)

        tk.Label(frm, text="Windows username:", bg=C_SECTION_BG, fg=C_FG,
                 font=FONT_MAIN).grid(row=0, column=0, sticky="w", pady=3)
        self._al_user = mk_entry(frm, width=32)
        self._al_user.grid(row=0, column=1, sticky="w", padx=10)
        self._al_user.insert(0, cfg.get("autologin_user", ""))

        tk.Label(frm, text="Password:",         bg=C_SECTION_BG, fg=C_FG,
                 font=FONT_MAIN).grid(row=1, column=0, sticky="w", pady=3)
        self._al_pass = mk_entry(frm, width=32, show="●")
        self._al_pass.grid(row=1, column=1, sticky="w", padx=10)

        st2 = status_label(p)

        def _do_login():
            cfg.set("autologin_user", self._al_user.get())
            apply_autologin(self._al_user.get(), self._al_pass.get(), st2)

        self._al_user.bind("<Return>", lambda e: _do_login())
        self._al_pass.bind("<Return>", lambda e: _do_login())

        row2 = tk.Frame(p, bg=C_SECTION_BG)
        row2.pack(fill="x", padx=12, pady=6)
        mk_btn(row2, "Enable Auto-Login",  _do_login,
               color=C_BTN_APPLY).pack(side="left", padx=4)
        mk_btn(row2, "Disable Auto-Login",
               lambda: disable_autologin(st2), color=C_BTN_DANGER).pack(side="left", padx=4)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Snap & PrtScn
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_snap(self, p):
        section_label(p, "Aero Shake – Disable")
        tk.Label(
            p,
            text="Prevents the 'shake a window to minimize all others' gesture.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720, anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st1 = status_label(p)
        mk_btn(p, "Disable Aero Shake",
               lambda: apply_disable_aero_shake(st1),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Snap Assist – Disable")
        tk.Label(
            p,
            text="Turns off the Snap Assist flyout and snap suggestions.\n"
                 "Note: double-clicking a title bar to maximize/restore is a hard-wired\n"
                 "Windows behaviour that cannot be turned off via the registry alone.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st2 = status_label(p)
        mk_btn(p, "Disable Snap Assist",
               lambda: apply_disable_snap(st2),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Print Screen → Snipping Tool – Unbind")
        tk.Label(
            p,
            text="Removes the Windows 11 binding that opens Snipping Tool\n"
                 "when PrtScn is pressed (also stops CTRL+V auto-launching Snipping Tool).",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st3 = status_label(p)
        mk_btn(p, "Disable PrtScn → Snipping Tool",
               lambda: apply_disable_prtscn_snippet(st3),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Defender
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_defender(self, p):
        section_label(p, "Windows Defender – Disable Real-Time Protection")
        tk.Label(
            p,
            text="Applies Group Policy registry keys to permanently disable real-time scanning.\n\n"
                 "REQUIRED FIRST STEP (manual):\n"
                 "  1. Open Windows Security\n"
                 "  2. Virus & threat protection → Manage settings\n"
                 "  3. Turn OFF  'Tamper Protection'\n"
                 "  4. Then click the button below.\n\n"
                 "Requires Administrator. A restart may be needed for full effect.",
            bg=C_SECTION_BG, fg=C_STATUS_WARN, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st1 = status_label(p)
        mk_btn(
            p,
            "DISABLE Real-Time Protection (permanent, via Group Policy)",
            lambda: apply_disable_defender(st1),
            color=C_BTN_DANGER,
        ).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Add Folder Exclusion (Defender whitelist)")
        tk.Label(
            p,
            text="Defender will never scan or delete files inside the excluded folder.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720, anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        row = tk.Frame(p, bg=C_SECTION_BG)
        row.pack(fill="x", padx=12, pady=4)
        self._excl_entry = mk_entry(row, width=52)
        self._excl_entry.pack(side="left", padx=(0, 6))
        self._excl_entry.insert(0, cfg.get("defender_excl", ""))

        st2 = status_label(p)

        def _browse():
            d = filedialog.askdirectory(title="Select folder to exclude from Defender")
            if d:
                self._excl_entry.delete(0, tk.END)
                self._excl_entry.insert(0, d.replace("/", "\\"))
                cfg.set("defender_excl", d.replace("/", "\\"))

        def _add():
            cfg.set("defender_excl", self._excl_entry.get())
            apply_add_exclusion(self._excl_entry.get(), st2)

        self._excl_entry.bind("<Return>", lambda e: _add())
        mk_btn(row, "Browse…", _browse, color=C_BTN_BROWSE).pack(side="left", padx=4)
        mk_btn(row, "Add Exclusion", _add, color=C_BTN_APPLY).pack(side="left", padx=4)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Python Installer
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_python(self, p):
        section_label(p, "Python – Download and Install (3 Newest Versions)")
        tk.Label(
            p,
            text="Fetches the 3 most recent stable Python 3 releases from python.org\n"
                 "and offers a one-click download + installer launch (64-bit, Windows).",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)

        self._py_st       = status_label(p)
        self._py_progress = tk.DoubleVar(value=0.0)
        ttk.Progressbar(
            p, variable=self._py_progress, maximum=100, length=420,
        ).pack(anchor="w", padx=12, pady=4)

        self._py_ver_frame = tk.Frame(p, bg=C_SECTION_BG)
        self._py_ver_frame.pack(fill="x", padx=12, pady=4)
        tk.Label(
            self._py_ver_frame,
            text="Click 'Fetch Versions' to load available releases from python.org.",
            bg=C_SECTION_BG, fg=C_STATUS_INFO, font=FONT_SMALL,
        ).pack(anchor="w")

        def _fetch():
            set_status(self._py_st, "Fetching Python versions from python.org…", C_STATUS_INFO)
            for w in self._py_ver_frame.winfo_children():
                w.destroy()

            def _work():
                versions = fetch_python_versions()
                self.after(0, lambda: _populate(versions))

            run_thread(_work)

        def _populate(versions):
            for w in self._py_ver_frame.winfo_children():
                w.destroy()
            if not versions:
                set_status(
                    self._py_st,
                    "Could not retrieve versions – check internet connection.",
                    C_STATUS_WARN,
                )
                return
            set_status(self._py_st, f"Found {len(versions)} release(s).", C_STATUS_OK)
            for ver, url in versions:
                row = tk.Frame(self._py_ver_frame, bg=C_SECTION_BG)
                row.pack(fill="x", pady=4)
                tk.Label(
                    row, text=f"Python  {ver}   (64-bit Windows)",
                    bg=C_SECTION_BG, fg=C_FG, font=FONT_BOLD, width=36, anchor="w",
                ).pack(side="left")
                mk_btn(
                    row,
                    f"Download & Install  {ver}",
                    lambda v=ver, u=url: download_and_install_python(
                        v, u, self._py_st, self._py_progress
                    ),
                    color=C_BTN_ORANGE,
                ).pack(side="left", padx=8)

        mk_btn(p, "Fetch Available Python Versions",
               _fetch, color=C_BTN_ORANGE).pack(anchor="w", padx=12, pady=8)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Taskbar & Widgets
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_taskbar(self, p):
        section_label(p, "Taskbar Buttons – Show / Hide")
        tk.Label(
            p,
            text="Check the items you want to hide, then click Apply.\n"
                 "Explorer will restart automatically to apply the changes.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)

        _tb_items = [
            ("Widgets button (NASDAQ / weather in the left corner)",
                                 "TaskbarDa",           0),
            ("Task View button", "ShowTaskViewButton",   0),
            ("Chat / Teams",     "TaskbarMn",            0),
            ("Copilot button",   "ShowCopilotButton",    0),
            ("Notification bell (next to the clock)",
                                 "ShowNotificationIcon", 0),
        ]
        self._tb_vars = {}
        for label, reg_name, _default in _tb_items:
            var = tk.IntVar(value=1)   # default = hide (value 0 → hidden)
            self._tb_vars[reg_name] = var
            tk.Checkbutton(
                p, text=f"   Hide:  {label}",
                variable=var,
                bg=C_SECTION_BG, fg=C_FG,
                selectcolor=C_ENTRY_BG,
                activebackground=C_SECTION_BG, activeforeground=C_FG,
                font=FONT_MAIN,
            ).pack(anchor="w", padx=24, pady=2)

        st1 = status_label(p)

        def _apply_tb():
            # If checkbox is ticked → hide the button → value 0
            settings = {k: 0 if v.get() else 1 for k, v in self._tb_vars.items()}
            apply_taskbar_buttons(settings, st1)

        mk_btn(p, "Apply Taskbar Settings (restarts Explorer)",
               _apply_tb, color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=8)

        section_label(p, "Unpin Apps from Taskbar")
        tk.Label(
            p,
            text="Best-effort unpin using the Windows Shell COM API.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720, anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st2 = status_label(p)
        for app_name in ("Microsoft Store", "Outlook", "Mail"):
            mk_btn(
                p, f"Unpin from taskbar:  {app_name}",
                lambda a=app_name: unpin_taskbar_app(a, st2),
                color=C_BTN_GREY,
            ).pack(anchor="w", padx=12, pady=3)
        mk_btn(p, "Remove MS Store (unpin + disable via policy)",
               lambda: remove_ms_store_from_taskbar(st2),
               color=C_BTN_DANGER).pack(anchor="w", padx=12, pady=3)

        section_label(p, "Remove Windows Web Experience Pack (Widgets App)")
        tk.Label(
            p,
            text="Removes the Microsoft Widgets app and the underlying WebExperienceHost package.\n"
                 "Requires Administrator.  Uses both AppxPackage removal and winget.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st3 = status_label(p)
        mk_btn(p, "Remove Windows Widgets / WebExperiencePack",
               lambda: remove_windows_widgets(st3),
               color=C_BTN_DANGER).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Remove Copilot for good")
        tk.Label(
            p,
            text="Removes the Copilot apps for every user, removes the copy kept in the\n"
                 "Windows image, marks them so upgrades do not put them back, sets the\n"
                 "Copilot policies, hides the taskbar button and unpins leftovers.\n"
                 "Requires Administrator for the lasting part.  'Check' changes nothing;\n"
                 "'Restore settings' undoes the policies and the button (not the apps).",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        self._cp_m365 = tk.IntVar(value=1)
        tk.Checkbutton(
            p, text="   Also remove the Microsoft 365 Copilot app "
                    "(Microsoft.MicrosoftOfficeHub)",
            variable=self._cp_m365,
            bg=C_SECTION_BG, fg=C_FG, selectcolor=C_ENTRY_BG,
            activebackground=C_SECTION_BG, activeforeground=C_FG,
            font=FONT_MAIN,
        ).pack(anchor="w", padx=24, pady=2)
        st4 = status_label(p)
        cp_box = mk_text(p, height=12, width=100, wrap="none")
        cp_box.pack(anchor="w", padx=12, pady=4)

        def _cp_say(msg):
            def _add():
                cp_box.insert("end", msg + "\n")
                cp_box.see("end")
            cp_box.after(0, _add)

        def _cp_run(fn, *args, **kw):
            cp_box.delete("1.0", "end")
            run_thread(lambda: fn(st4, _cp_say, *args, **kw))

        def _cp_remove():
            inc = bool(self._cp_m365.get())
            what = ("the Microsoft Copilot app and the Microsoft 365 Copilot app"
                    if inc else "the Microsoft Copilot app")
            if not messagebox.askyesno(
                    "Remove Copilot",
                    f"This removes {what} for all users, sets the Copilot "
                    "policies and hides the taskbar button.\n\nContinue?"):
                return
            _cp_run(remove_copilot, include_m365=inc)

        crow = tk.Frame(p, bg=C_SECTION_BG)
        crow.pack(anchor="w", padx=12, pady=6)
        mk_btn(crow, "Check Copilot (changes nothing)",
               lambda: _cp_run(check_copilot,
                               include_m365=bool(self._cp_m365.get())),
               color=C_BTN_CHECK).pack(side="left", padx=4)
        mk_btn(crow, "Remove Copilot for good", _cp_remove,
               color=C_BTN_DANGER).pack(side="left", padx=4)
        mk_btn(crow, "Restore settings", lambda: _cp_run(restore_copilot),
               color=C_BTN_GREY).pack(side="left", padx=4)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: OneDrive
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_onedrive(self, p):
        section_label(p, "OneDrive – Stop, Uninstall, Disable")
        tk.Label(
            p,
            text="Steps performed:\n"
                 "  1. Kill the OneDrive process\n"
                 "  2. Run the OneDrive uninstaller (/uninstall)\n"
                 "  3. Remove the OneDrive startup registry entry\n"
                 "  4. Set Group Policy to disable OneDrive sync permanently\n"
                 "  5. Remove OneDrive from the Explorer namespace\n\n"
                 "Requires Administrator for the policy step.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)
        st = status_label(p)
        mk_btn(p, "Remove OneDrive – Full",
               lambda: apply_remove_onedrive(st),
               color=C_BTN_DANGER).pack(anchor="w", padx=12, pady=6)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Language & Region
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_language(self, p):
        section_label(p, "Display Language – Swedish (sv-SE)")
        tk.Label(
            p,
            text="Sets Windows UI language, system locale, culture, home location\n"
                 "and regional format to Swedish.  A full restart is required.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)

        section_label(p, "Clock – 24-Hour Format")
        tk.Label(
            p,
            text="Sets sTimeFormat = HH:mm:ss and sShortTime = HH:mm in the registry.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720, anchor="w",
        ).pack(fill="x", padx=12, pady=4)

        st = status_label(p)
        mk_btn(p, "Set Swedish Language + 24-Hour Clock",
               lambda: apply_set_swedish(st),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=8)

        section_label(p, "Swedish ONLY – remove English / the ENG indicator")
        tk.Label(
            p,
            text="Installs the Swedish language pack (a download, a few minutes), makes\n"
                 "Swedish the display language and the ONLY input language, and does the\n"
                 "same for the sign-in screen.  Restart Windows afterwards - then ENG\n"
                 "is gone from the tray and you cannot switch language any more.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=4)
        st_se = status_label(p)
        mk_btn(p, "Swedish only – remove English",
               lambda: apply_swedish_only(st_se),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=8)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Wallpaper
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_wallpaper(self, p):
        from tkinter import colorchooser
        section_label(p, "Plain Background – one flat colour, no pictures")
        tk.Label(
            p,
            text="Pick a colour and click Set.  This empties the picture, switches the\n"
                 "background setting to Solid colour and turns Windows Spotlight off (the\n"
                 "pictures that come with Windows by themselves, and the 'Learn more about\n"
                 "this picture' icon).",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)

        cur = reg_read("HKCU", r"Control Panel\Colors", "Background", "142 140 216")
        try:
            r0, g0, b0 = (int(x) for x in str(cur).split()[:3])
        except Exception:
            r0, g0, b0 = 142, 140, 216
        start = cfg.get("background_color", "#%02x%02x%02x" % (r0, g0, b0))
        self._bg_hex = tk.StringVar(value=start)

        crow = tk.Frame(p, bg=C_SECTION_BG)
        crow.pack(fill="x", padx=12, pady=6)
        swatch = tk.Label(crow, text="      ", bg=start, relief="solid", bd=1)
        swatch.pack(side="left")
        tk.Label(crow, textvariable=self._bg_hex, bg=C_SECTION_BG, fg=C_FG,
                 font=FONT_MAIN, width=9).pack(side="left", padx=8)

        def _set_hex(h):
            self._bg_hex.set(h)
            swatch.configure(bg=h)

        def _choose():
            res = colorchooser.askcolor(color=self._bg_hex.get(),
                                        title="Choose the desktop colour")
            if res and res[1]:
                _set_hex(res[1])

        mk_btn(crow, "Choose colour…", _choose,
               color=C_BTN_BROWSE).pack(side="left", padx=4)
        prow = tk.Frame(p, bg=C_SECTION_BG)
        prow.pack(fill="x", padx=12, pady=2)
        for name, h in (("Black", "#000000"), ("Dark grey", "#202020"),
                        ("Grey", "#606060"), ("Dark blue", "#1f2a44"),
                        ("Purple", "#8e8cd8")):
            mk_btn(prow, name, lambda hh=h: _set_hex(hh),
                   color=C_BTN_GREY).pack(side="left", padx=3)

        st_bg = status_label(p)

        def _apply_bg():
            h = self._bg_hex.get().lstrip("#")
            cfg.set("background_color", "#" + h)
            cfg.save()
            apply_solid_background(
                (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)), st_bg)

        mk_btn(p, "Set Plain Background", _apply_bg,
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=8)

        section_label(p, "Or a Picture (optional)")
        tk.Label(
            p,
            text="Pick an image file, choose how it fits, and click Set.  The picture is\n"
                 "copied to %APPDATA%\\Win11Tweaker so it survives a drive-letter change,\n"
                 "and the background setting is switched to Picture.\n"
                 "Windows' own pictures are in C:\\Windows\\Web\\Wallpaper.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)

        row = tk.Frame(p, bg=C_SECTION_BG)
        row.pack(fill="x", padx=12, pady=6)
        tk.Label(row, text="Picture:", bg=C_SECTION_BG, fg=C_FG,
                 font=FONT_MAIN).pack(side="left")
        self._wp_entry = mk_entry(row, width=52)
        self._wp_entry.pack(side="left", padx=8)
        self._wp_entry.insert(0, cfg.get("wallpaper_path", ""))

        def _browse():
            start = os.path.dirname(self._wp_entry.get().strip()) or \
                r"C:\Windows\Web\Wallpaper"
            f = filedialog.askopenfilename(
                title="Select the desktop picture",
                initialdir=start if os.path.isdir(start) else None,
                filetypes=[("Pictures", "*.jpg *.jpeg *.png *.bmp *.webp"),
                           ("All files", "*.*")])
            if f:
                self._wp_entry.delete(0, tk.END)
                self._wp_entry.insert(0, f.replace("/", "\\"))

        mk_btn(row, "Browse…", _browse, color=C_BTN_BROWSE).pack(side="left", padx=4)

        srow = tk.Frame(p, bg=C_SECTION_BG)
        srow.pack(fill="x", padx=12, pady=4)
        tk.Label(srow, text="Fit:", bg=C_SECTION_BG, fg=C_FG,
                 font=FONT_MAIN).pack(side="left")
        self._wp_style = tk.StringVar(value=cfg.get("wallpaper_style", "Fill"))
        ttk.Combobox(srow, textvariable=self._wp_style, state="readonly",
                     values=list(WALLPAPER_STYLES), width=10).pack(side="left", padx=8)

        st = status_label(p)

        def _apply():
            cfg.set("wallpaper_path", self._wp_entry.get().strip())
            cfg.set("wallpaper_style", self._wp_style.get())
            cfg.save()
            apply_set_wallpaper(self._wp_entry.get(), self._wp_style.get(), st)

        mk_btn(p, "Set as Desktop Picture", _apply,
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=8)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Privacy
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_privacy(self, p):
        section_label(p, "Telemetry – Disable (level 0 + stop DiagTrack)")
        st1 = status_label(p)
        mk_btn(p, "Disable Telemetry",
               lambda: apply_disable_telemetry(st1),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Advertising ID – Disable")
        st2 = status_label(p)
        mk_btn(p, "Disable Advertising ID",
               lambda: apply_disable_advertising_id(st2),
               color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)

        section_label(p, "Cortana – Disable and Remove")
        st3 = status_label(p)
        mk_btn(p, "Disable Cortana",
               lambda: apply_disable_cortana(st3),
               color=C_BTN_DANGER).pack(anchor="w", padx=12, pady=6)

    # ─────────────────────────────────────────────────────────────────────────
    # TAB: Downloads
    # ─────────────────────────────────────────────────────────────────────────

    def _tab_downloads(self, p):
        section_label(p, "Default Download Folder")
        tk.Label(
            p,
            text="Sets the Windows shell Downloads folder and configures Chrome, Edge\n"
                 "and Firefox to save downloaded files to the specified path.\n"
                 "The folder is created automatically if it does not exist.\n"
                 "Close Chrome / Edge / Firefox before applying.",
            bg=C_SECTION_BG, fg=C_FG, font=FONT_MAIN, wraplength=720,
            justify="left", anchor="w",
        ).pack(fill="x", padx=12, pady=6)

        row = tk.Frame(p, bg=C_SECTION_BG)
        row.pack(fill="x", padx=12, pady=6)
        tk.Label(row, text="Folder:", bg=C_SECTION_BG, fg=C_FG,
                 font=FONT_MAIN).pack(side="left")
        self._dl_entry = mk_entry(row, width=46)
        self._dl_entry.pack(side="left", padx=8)
        self._dl_entry.insert(0, cfg.get("download_folder", r"C:\0---Temp"))

        st = status_label(p)

        def _browse():
            d = filedialog.askdirectory(title="Select default download folder")
            if d:
                self._dl_entry.delete(0, tk.END)
                self._dl_entry.insert(0, d.replace("/", "\\"))

        def _apply():
            folder = self._dl_entry.get().strip()
            cfg.set("download_folder", folder)
            apply_set_downloads(folder, st)

        self._dl_entry.bind("<Return>", lambda e: _apply())
        mk_btn(row, "Browse…", _browse, color=C_BTN_BROWSE).pack(side="left", padx=4)
        mk_btn(p, "Set Download Folder (Windows + Chrome + Edge + Firefox)",
               _apply, color=C_BTN_APPLY).pack(anchor="w", padx=12, pady=6)


# *************** DEL 22 – MAIN ENTRY POINT ***************

if __name__ == "__main__":
    app = IssuTweaker()   # class name kept for internal compatibility
    app.mainloop()
