from __future__ import annotations

THEMES: dict[str, dict[str, str]] = {
    "default": {
        "bg": "#121212",
        "panel": "#1e1e1e",
        "text": "#e0e0e0",
        "muted": "#808080",
        "border": "#333333",
        "accent": "#6b5b7a",
        "accent_text": "#e0e0e0",
        "hover": "#2c2c2c",
    },
    "gruvbox": {
        "bg": "#fbf1c7",
        "panel": "#ebdbb2",
        "text": "#3c3836",
        "muted": "#665c54",
        "border": "#d5c4a1",
        "accent": "#665c54",
        "accent_text": "#fbf1c7",
        "hover": "#f2e5bc",
    },
    "gruvbox-dark": {
        "bg": "#282828",
        "panel": "#32302f",
        "text": "#ebdbb2",
        "muted": "#a89984",
        "border": "#504945",
        "accent": "#665c54",
        "accent_text": "#ebdbb2",
        "hover": "#3c3836",
    },
    "dracula": {
        "bg": "#282a36",
        "panel": "#21222c",
        "text": "#f8f8f2",
        "muted": "#b3b3b3",
        "border": "#44475a",
        "accent": "#6272a4",
        "accent_text": "#f8f8f2",
        "hover": "#2f3140",
    },
    "nord": {
        "bg": "#2e3440",
        "panel": "#3b4252",
        "text": "#eceff4",
        "muted": "#d8dee9",
        "border": "#4c566a",
        "accent": "#5e6779",
        "accent_text": "#eceff4",
        "hover": "#434c5e",
    },
    "solarized-light": {
        "bg": "#fdf6e3",
        "panel": "#eee8d5",
        "text": "#586e75",
        "muted": "#657b83",
        "border": "#ddd6c1",
        "accent": "#657b83",
        "accent_text": "#fdf6e3",
        "hover": "#f5efdc",
    },
    "solarized-dark": {
        "bg": "#002b36",
        "panel": "#073642",
        "text": "#eee8d5",
        "muted": "#93a1a1",
        "border": "#0f4a5a",
        "accent": "#586e75",
        "accent_text": "#eee8d5",
        "hover": "#0a3f4d",
    },
    "catppuccin-mocha": {
        "bg": "#1e1e2e",
        "panel": "#181825",
        "text": "#cdd6f4",
        "muted": "#a6adc8",
        "border": "#313244",
        "accent": "#585b70",
        "accent_text": "#cdd6f4",
        "hover": "#242438",
    },

    "catppuccin-latte": {
        "bg": "#eff1f5",
        "panel": "#e6e9ef",
        "text": "#4c4f69",
        "muted": "#6c6f85",
        "border": "#ccd0da",
        "accent": "#7c7f93",
        "accent_text": "#eff1f5",
        "hover": "#dce0e8",
    },
    "catppuccin-frappe": {
        "bg": "#303446",
        "panel": "#292c3c",
        "text": "#c6d0f5",
        "muted": "#a5adce",
        "border": "#414559",
        "accent": "#626880",
        "accent_text": "#c6d0f5",
        "hover": "#3b3f52",
    },
    "catppuccin-macchiato": {
        "bg": "#24273a",
        "panel": "#1e2030",
        "text": "#cad3f5",
        "muted": "#a5adcb",
        "border": "#363a4f",
        "accent": "#5b6078",
        "accent_text": "#cad3f5",
        "hover": "#2e3244",
    },
    "tokyo-night": {
        "bg": "#1a1b26",
        "panel": "#16161e",
        "text": "#c0caf5",
        "muted": "#565f89",
        "border": "#292e42",
        "accent": "#565f89",
        "accent_text": "#c0caf5",
        "hover": "#24283b",
    },
    "tokyo-night-storm": {
        "bg": "#24283b",
        "panel": "#1f2335",
        "text": "#c0caf5",
        "muted": "#565f89",
        "border": "#3b4261",
        "accent": "#565f89",
        "accent_text": "#c0caf5",
        "hover": "#292e42",
    },
    "tokyo-night-light": {
        "bg": "#d5d6db",
        "panel": "#cbccd1",
        "text": "#343b58",
        "muted": "#6172af",
        "border": "#b4b5ba",
        "accent": "#6e7191",
        "accent_text": "#d5d6db",
        "hover": "#c4c5ca",
    },
    "one-dark": {
        "bg": "#282c34",
        "panel": "#21252b",
        "text": "#abb2bf",
        "muted": "#5c6370",
        "border": "#3e4451",
        "accent": "#5c6370",
        "accent_text": "#abb2bf",
        "hover": "#2c323c",
    },
    "one-light": {
        "bg": "#fafafa",
        "panel": "#f0f0f0",
        "text": "#383a42",
        "muted": "#a0a1a7",
        "border": "#d3d3d3",
        "accent": "#8a8b91",
        "accent_text": "#383a42",
        "hover": "#e5e5e5",
    },
    "monokai-pro": {
        "bg": "#2d2a2e",
        "panel": "#221f22",
        "text": "#fcfcfa",
        "muted": "#939293",
        "border": "#403e41",
        "accent": "#5b5759",
        "accent_text": "#fcfcfa",
        "hover": "#363337",
    },
    "github-dark": {
        "bg": "#0d1117",
        "panel": "#161b22",
        "text": "#c9d1d9",
        "muted": "#8b949e",
        "border": "#30363d",
        "accent": "#484f58",
        "accent_text": "#c9d1d9",
        "hover": "#21262d",
    },
    "github-light": {
        "bg": "#ffffff",
        "panel": "#f6f8fa",
        "text": "#24292f",
        "muted": "#57606a",
        "border": "#d0d7de",
        "accent": "#6e7781",
        "accent_text": "#24292f",
        "hover": "#eaeef2",
    },
    "material-darker": {
        "bg": "#212121",
        "panel": "#1a1a1a",
        "text": "#eeffff",
        "muted": "#545454",
        "border": "#303030",
        "accent": "#4a4a4a",
        "accent_text": "#eeffff",
        "hover": "#2a2a2a",
    },
    "material-palenight": {
        "bg": "#292d3e",
        "panel": "#232635",
        "text": "#a6accd",
        "muted": "#676e95",
        "border": "#3a3f58",
        "accent": "#575d78",
        "accent_text": "#a6accd",
        "hover": "#32374a",
    },
    "ayu-dark": {
        "bg": "#0b0e14",
        "panel": "#0d1017",
        "text": "#bfbdb6",
        "muted": "#565b66",
        "border": "#1c2029",
        "accent": "#464b55",
        "accent_text": "#bfbdb6",
        "hover": "#151920",
    },
    "ayu-mirage": {
        "bg": "#1f2430",
        "panel": "#1a1f29",
        "text": "#cbccc6",
        "muted": "#707a8c",
        "border": "#2d3444",
        "accent": "#5c6773",
        "accent_text": "#cbccc6",
        "hover": "#272d3a",
    },
    "ayu-light": {
        "bg": "#fafafa",
        "panel": "#f3f4f5",
        "text": "#575f66",
        "muted": "#828c99",
        "border": "#e7e8e9",
        "accent": "#8a9199",
        "accent_text": "#575f66",
        "hover": "#eeeff0",
    },
    "rose-pine": {
        "bg": "#191724",
        "panel": "#1f1d2e",
        "text": "#e0def4",
        "muted": "#6e6a86",
        "border": "#26233a",
        "accent": "#524f67",
        "accent_text": "#e0def4",
        "hover": "#21202e",
    },
    "rose-pine-moon": {
        "bg": "#232136",
        "panel": "#2a273f",
        "text": "#e0def4",
        "muted": "#6e6a86",
        "border": "#393552",
        "accent": "#56526e",
        "accent_text": "#e0def4",
        "hover": "#2d2a41",
    },
    "rose-pine-dawn": {
        "bg": "#faf4ed",
        "panel": "#f2e9e1",
        "text": "#575279",
        "muted": "#9893a5",
        "border": "#dfdad9",
        "accent": "#797593",
        "accent_text": "#faf4ed",
        "hover": "#f4ede8",
    },
    "everforest-dark": {
        "bg": "#2d353b",
        "panel": "#272e33",
        "text": "#d3c6aa",
        "muted": "#859289",
        "border": "#3d484d",
        "accent": "#5c6a5e",
        "accent_text": "#d3c6aa",
        "hover": "#343e44",
    },
    "everforest-light": {
        "bg": "#fdf6e3",
        "panel": "#f4f0d9",
        "text": "#5c6a72",
        "muted": "#829181",
        "border": "#e0dcc7",
        "accent": "#708374",
        "accent_text": "#5c6a72",
        "hover": "#f0ead4",
    },
    "kanagawa": {
        "bg": "#1f1f28",
        "panel": "#16161d",
        "text": "#dcd7ba",
        "muted": "#727169",
        "border": "#2a2a37",
        "accent": "#54546d",
        "accent_text": "#dcd7ba",
        "hover": "#252530",
    },
    "kanagawa-light": {
        "bg": "#f2ecbc",
        "panel": "#e7dba0",
        "text": "#545464",
        "muted": "#8a8980",
        "border": "#d5cea6",
        "accent": "#71717a",
        "accent_text": "#f2ecbc",
        "hover": "#e8e0a9",
    },
    "night-owl": {
        "bg": "#011627",
        "panel": "#001122",
        "text": "#d6deeb",
        "muted": "#637777",
        "border": "#122d42",
        "accent": "#456578",
        "accent_text": "#d6deeb",
        "hover": "#0b2942",
    },
    "synthwave-84": {
        "bg": "#262335",
        "panel": "#1e1a2b",
        "text": "#ffffff",
        "muted": "#848bbd",
        "border": "#34294f",
        "accent": "#524668",
        "accent_text": "#ffffff",
        "hover": "#2e2943",
    },
    "cyberpunk": {
        "bg": "#0a0a0f",
        "panel": "#12121a",
        "text": "#d0d0d0",
        "muted": "#606060",
        "border": "#1a1a25",
        "accent": "#3a3a45",
        "accent_text": "#d0d0d0",
        "hover": "#15151f",
    },
    "high-contrast": {
        "bg": "#000000",
        "panel": "#0a0a0a",
        "text": "#ffffff",
        "muted": "#aaaaaa",
        "border": "#333333",
        "accent": "#555555",
        "accent_text": "#ffffff",
        "hover": "#1a1a1a",
    },
    "paper": {
        "bg": "#f5f5dc",
        "panel": "#ebe7d3",
        "text": "#3b3228",
        "muted": "#6b5e4a",
        "border": "#d4cfbb",
        "accent": "#6b5e4a",
        "accent_text": "#f5f5dc",
        "hover": "#e6e1cc",
    },
}

def _parse_kde_color(color_str: str) -> str | None:
    if not color_str:
        return None
    try:

        parts = [p.strip() for p in color_str.strip().split(",")]
        if len(parts) >= 3:
            r, g, b = int(parts[0]), int(parts[1]), int(parts[2])
            return f"#{r:02x}{g:02x}{b:02x}"
    except Exception:
        pass
    return None

def _adjust_color(hex_color: str, amount: int) -> str:
    try:
        hex_color = hex_color.lstrip("#")
        r = max(0, min(255, int(hex_color[0:2], 16) + amount))
        g = max(0, min(255, int(hex_color[2:4], 16) + amount))
        b = max(0, min(255, int(hex_color[4:6], 16) + amount))
        return f"#{r:02x}{g:02x}{b:02x}"
    except Exception:
        return hex_color

def _get_luminance(hex_color: str) -> float:
    try:
        hex_color = hex_color.lstrip("#")
        r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
        return (r * 299 + g * 587 + b * 114) / 1000
    except Exception:
        return 128

def _read_kde_colors_file(filepath: str) -> dict[str, str] | None:
    import os

    if not os.path.exists(filepath):
        return None

    try:
        with open(filepath, "r") as f:
            content = f.read()

        colors = {}
        current_section = None

        for line in content.split("\n"):
            line = line.strip()
            if not line or line.startswith("#"):
                continue

            if line.startswith("[") and line.endswith("]"):
                current_section = line[1:-1]
                continue

            if "=" in line:
                key, _, value = line.partition("=")
                key = key.strip()
                value = value.strip()

                if current_section == "Colors:Window":
                    if key == "BackgroundNormal":
                        colors["bg"] = _parse_kde_color(value)
                    elif key == "ForegroundNormal":
                        colors["text"] = _parse_kde_color(value)
                    elif key == "ForegroundInactive":
                        colors["muted"] = _parse_kde_color(value)

                elif current_section == "Colors:View":
                    if key == "BackgroundNormal":
                        colors["panel"] = _parse_kde_color(value)
                    elif key == "BackgroundAlternate":
                        colors["hover"] = _parse_kde_color(value)

                elif current_section == "Colors:Button":
                    if key == "BackgroundNormal" and not colors.get("hover"):
                        colors["hover"] = _parse_kde_color(value)
                    elif key == "DecorationFocus":
                        colors["accent"] = _parse_kde_color(value)

                elif current_section == "Colors:Selection":
                    if key == "BackgroundNormal":
                        colors["accent"] = _parse_kde_color(value)
                    elif key == "ForegroundNormal":
                        colors["accent_text"] = _parse_kde_color(value)

                elif current_section == "WM":
                    if key == "activeBackground":
                        colors["border"] = _parse_kde_color(value)
                    elif key == "inactiveBackground" and not colors.get("border"):
                        colors["border"] = _parse_kde_color(value)

        return colors if colors else None
    except Exception:
        return None

def _complete_theme_colors(colors: dict[str, str]) -> dict[str, str] | None:
    if not colors:
        return None

    bg = colors.get("bg")
    text = colors.get("text")

    if not bg or not text:
        return None

    is_dark = _get_luminance(bg) < 128

    if not colors.get("panel"):

        colors["panel"] = _adjust_color(bg, 15 if is_dark else -10)

    if not colors.get("muted"):

        if is_dark:
            colors["muted"] = _adjust_color(text, -60)
        else:
            colors["muted"] = _adjust_color(text, 60)

    if not colors.get("border"):

        colors["border"] = _adjust_color(bg, 40 if is_dark else -30)

    if not colors.get("accent"):

        colors["accent"] = "#5294e2" if is_dark else "#3584e4"

    if not colors.get("accent_text"):

        accent_lum = _get_luminance(colors["accent"])
        colors["accent_text"] = "#ffffff" if accent_lum < 128 else "#000000"

    if not colors.get("hover"):

        colors["hover"] = _adjust_color(bg, 20 if is_dark else -15)

    colors["is_dark"] = is_dark
    return colors

def _read_kdeglobals() -> dict[str, str] | None:
    import os

    colors = _read_kde_colors_file(os.path.expanduser("~/.config/kdeglobals"))
    if colors:
        return _complete_theme_colors(colors)

    return None

def _read_kde_colorscheme() -> dict[str, str] | None:
    import os
    import subprocess

    scheme_name = None

    for cmd in ["kreadconfig5", "kreadconfig6"]:
        try:
            result = subprocess.run(
                [cmd, "--file", "kdeglobals", "--group", "General", "--key", "ColorScheme"],
                capture_output=True, text=True, timeout=2
            )
            if result.returncode == 0 and result.stdout.strip():
                scheme_name = result.stdout.strip()
                break
        except Exception:
            continue

    if not scheme_name:
        return None

    search_paths = [
        os.path.expanduser(f"~/.local/share/color-schemes/{scheme_name}.colors"),
        f"/usr/share/color-schemes/{scheme_name}.colors",
        os.path.expanduser(f"~/.kde4/share/apps/color-schemes/{scheme_name}.colors"),
        f"/usr/share/kde4/apps/color-schemes/{scheme_name}.colors",
    ]

    for path in search_paths:
        colors = _read_kde_colors_file(path)
        if colors:
            return _complete_theme_colors(colors)

    return None

def _read_gtk_css_colors() -> dict[str, str] | None:
    import os
    import subprocess
    import re

    theme_name = None
    try:
        result = subprocess.run(
            ["gsettings", "get", "org.gnome.desktop.interface", "gtk-theme"],
            capture_output=True, text=True, timeout=2
        )
        if result.returncode == 0:
            theme_name = result.stdout.strip().strip("'\"")
    except Exception:
        pass

    if not theme_name:
        return None

    search_paths = [
        os.path.expanduser(f"~/.themes/{theme_name}/gtk-3.0/gtk.css"),
        os.path.expanduser(f"~/.local/share/themes/{theme_name}/gtk-3.0/gtk.css"),
        f"/usr/share/themes/{theme_name}/gtk-3.0/gtk.css",
        os.path.expanduser(f"~/.themes/{theme_name}/gtk-4.0/gtk.css"),
        f"/usr/share/themes/{theme_name}/gtk-4.0/gtk.css",
    ]

    css_content = None
    for path in search_paths:
        if os.path.exists(path):
            try:
                with open(path, "r") as f:
                    css_content = f.read()
                break
            except Exception:
                continue

    if not css_content:
        return None

    colors = {}

    def extract_color(value: str) -> str | None:
        if not value:
            return None
        value = value.strip()

        if value.startswith("#"):
            if len(value) == 4:
                return f"#{value[1]*2}{value[2]*2}{value[3]*2}"
            if len(value) >= 7:
                return value[:7]

        rgb_match = re.match(r"rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)", value)
        if rgb_match:
            r, g, b = int(rgb_match.group(1)), int(rgb_match.group(2)), int(rgb_match.group(3))
            return f"#{r:02x}{g:02x}{b:02x}"
        return None

    color_patterns = [

        (r"@define-color\s+theme_bg_color\s+([^;]+);", "bg"),
        (r"@define-color\s+window_bg_color\s+([^;]+);", "bg"),
        (r"@define-color\s+base_color\s+([^;]+);", "bg"),
        (r"@define-color\s+bg_color\s+([^;]+);", "bg"),

        (r"@define-color\s+theme_fg_color\s+([^;]+);", "text"),
        (r"@define-color\s+window_fg_color\s+([^;]+);", "text"),
        (r"@define-color\s+text_color\s+([^;]+);", "text"),
        (r"@define-color\s+fg_color\s+([^;]+);", "text"),

        (r"@define-color\s+theme_base_color\s+([^;]+);", "panel"),
        (r"@define-color\s+view_bg_color\s+([^;]+);", "panel"),
        (r"@define-color\s+card_bg_color\s+([^;]+);", "panel"),

        (r"@define-color\s+theme_selected_bg_color\s+([^;]+);", "accent"),
        (r"@define-color\s+accent_color\s+([^;]+);", "accent"),
        (r"@define-color\s+accent_bg_color\s+([^;]+);", "accent"),
        (r"@define-color\s+selected_bg_color\s+([^;]+);", "accent"),

        (r"@define-color\s+borders\s+([^;]+);", "border"),
        (r"@define-color\s+border_color\s+([^;]+);", "border"),
        (r"@define-color\s+unfocused_borders\s+([^;]+);", "border"),

        (r"@define-color\s+insensitive_fg_color\s+([^;]+);", "muted"),
        (r"@define-color\s+placeholder_text_color\s+([^;]+);", "muted"),
        (r"@define-color\s+dim_label_color\s+([^;]+);", "muted"),

        (r"@define-color\s+theme_unfocused_bg_color\s+([^;]+);", "hover"),
        (r"@define-color\s+hover_bg_color\s+([^;]+);", "hover"),
    ]

    for pattern, key in color_patterns:
        if colors.get(key):
            continue
        match = re.search(pattern, css_content, re.IGNORECASE)
        if match:
            color = extract_color(match.group(1))
            if color:
                colors[key] = color

    return _complete_theme_colors(colors)

def _read_gtk_dconf_colors() -> dict[str, str] | None:
    import subprocess

    colors = {}

    try:
        result = subprocess.run(
            ["gsettings", "get", "org.gnome.desktop.interface", "accent-color"],
            capture_output=True, text=True, timeout=2
        )
        if result.returncode == 0 and result.stdout.strip():
            accent_name = result.stdout.strip().strip("'\"").lower()

            accent_map = {
                "blue": "#3584e4",
                "teal": "#2190a4",
                "green": "#3a944a",
                "yellow": "#c88800",
                "orange": "#ed5b00",
                "red": "#e62d42",
                "pink": "#d56199",
                "purple": "#9141ac",
                "slate": "#6f8396",
            }
            if accent_name in accent_map:
                colors["accent"] = accent_map[accent_name]
    except Exception:
        pass

    is_dark = None
    try:
        result = subprocess.run(
            ["gsettings", "get", "org.gnome.desktop.interface", "color-scheme"],
            capture_output=True, text=True, timeout=2
        )
        if result.returncode == 0:
            is_dark = "dark" in result.stdout.lower()
    except Exception:
        pass

    if is_dark is None:
        try:
            result = subprocess.run(
                ["gsettings", "get", "org.gnome.desktop.interface", "gtk-theme"],
                capture_output=True, text=True, timeout=2
            )
            if result.returncode == 0:
                is_dark = "dark" in result.stdout.lower()
        except Exception:
            pass

    if is_dark is not None:

        if is_dark:
            colors.setdefault("bg", "#242424")
            colors.setdefault("panel", "#303030")
            colors.setdefault("text", "#ffffff")
            colors.setdefault("muted", "#9a9996")
            colors.setdefault("border", "#1e1e1e")
            colors.setdefault("hover", "#383838")
            colors.setdefault("accent", colors.get("accent", "#3584e4"))
            colors.setdefault("accent_text", "#ffffff")
        else:
            colors.setdefault("bg", "#fafafa")
            colors.setdefault("panel", "#ffffff")
            colors.setdefault("text", "#000000")
            colors.setdefault("muted", "#77767b")
            colors.setdefault("border", "#deddda")
            colors.setdefault("hover", "#f0f0f0")
            colors.setdefault("accent", colors.get("accent", "#3584e4"))
            colors.setdefault("accent_text", "#ffffff")

        colors["is_dark"] = is_dark
        return colors

    return None

def get_gtk_theme_colors() -> dict[str, str] | None:

    colors = _read_gtk_css_colors()
    if colors:
        return colors

    colors = _read_gtk_dconf_colors()
    if colors:
        return colors

    return None

def get_qt_theme_colors() -> dict[str, str] | None:

    colors = _read_kde_colorscheme()
    if colors:
        return colors

    colors = _read_kdeglobals()
    if colors:
        return colors

    return None

def normalize_theme(name: str | None) -> str:
    n = (name or "default").strip().replace("_", "-")
    return n if n in THEMES else "default"

def theme_list() -> list[str]:
    return list(THEMES.keys())

def css_for_theme(name: str, c: dict[str, str]) -> str:
    sel = f"App.theme-{name}"
    bg = c["bg"]
    panel = c["panel"]
    text = c["text"]
    muted = c["muted"]
    border = c["border"]
    accent = c["accent"]
    accent_text = c["accent_text"]
    hover = c["hover"]

    def blend_color(c1: str, c2: str, ratio: float = 0.15) -> str:
        try:
            c1 = c1.lstrip('#')
            c2 = c2.lstrip('#')
            r1, g1, b1 = int(c1[0:2], 16), int(c1[2:4], 16), int(c1[4:6], 16)
            r2, g2, b2 = int(c2[0:2], 16), int(c2[2:4], 16), int(c2[4:6], 16)
            r = int(r1 * (1 - ratio) + r2 * ratio)
            g = int(g1 * (1 - ratio) + g2 * ratio)
            b = int(b1 * (1 - ratio) + b2 * ratio)
            return f"#{r:02x}{g:02x}{b:02x}"
        except:
            return c1

    def lighten(hex_color: str, amount: int = 20) -> str:
        try:
            hex_color = hex_color.lstrip('#')
            r = min(255, int(hex_color[0:2], 16) + amount)
            g = min(255, int(hex_color[2:4], 16) + amount)
            b = min(255, int(hex_color[4:6], 16) + amount)
            return f"#{r:02x}{g:02x}{b:02x}"
        except:
            return hex_color

    def darken(hex_color: str, amount: int = 20) -> str:
        try:
            hex_color = hex_color.lstrip('#')
            r = max(0, int(hex_color[0:2], 16) - amount)
            g = max(0, int(hex_color[2:4], 16) - amount)
            b = max(0, int(hex_color[4:6], 16) - amount)
            return f"#{r:02x}{g:02x}{b:02x}"
        except:
            return hex_color

    accent_soft = blend_color(accent, panel, 0.3)
    accent_softer = blend_color(accent, panel, 0.2)

    input_bg = lighten(bg, 3)

    bg_lighten1 = lighten(bg, 15)
    bg_lighten2 = lighten(bg, 30)
    bg_darken1 = darken(bg, 15)
    bg_darken2 = darken(bg, 30)
    panel_lighten1 = lighten(panel, 15)
    panel_darken1 = darken(panel, 15)
    accent_lighten1 = lighten(accent, 20)
    accent_darken1 = darken(accent, 20)
    border_light = lighten(border, 20)
    border_dark = darken(border, 20)

    return f"""
/* ===== Theme: {name} ===== */
{sel} Screen {{ background: {bg}; color: {text}; }}
{sel} #root, {sel} #main, {sel} #messages, {sel} #settings_content {{ background: {bg}; }}
{sel} #sidebar_full, {sel} #sidebar_rail, {sel} #bottom_bar, {sel} #settings_nav {{ background: {panel}; }}
{sel} #composer_frame {{ background: {bg}; }}
{sel} #sidebar_full, {sel} #sidebar_rail, {sel} #settings_nav {{ border-right: solid {border}; }}
{sel} #bottom_bar, {sel} #composer_frame {{ border-top: solid {border}; }}
{sel} #system_log {{ background: {hover}; color: {muted}; border-bottom: solid {border}; }}
{sel} #info_tab {{ background: {panel}; color: {text}; }}
{sel} #sidebar_handle {{ background: {border}; }}
{sel} #top_info_panel {{ background: {bg}; }}

/* Tabs */
{sel} TabbedContent, {sel} TabPane, {sel} TabBar {{ background: {panel}; border: none; }}
{sel} Tab {{ background: {panel}; color: {muted}; }}
{sel} Tab.-active {{ background: {bg}; color: {text}; }}
{sel} Tab:hover {{ background: {hover}; }}

/* Lists */
{sel} ListView {{ background: {bg}; }}
{sel} ListItem {{ background: transparent; }}
{sel} ListItem:hover {{ background: {hover}; }}
{sel} ListItem.-highlight {{ background: {hover}; border-left: solid {border}; }}
{sel} .chat_item_title, {sel} .req_item_title {{ color: {text}; }}
{sel} .chat_item_sub, {sel} .req_item_sub {{ color: {muted}; }}

/* Buttons - subtle background difference */
{sel} Button {{ background: {hover}; color: {text}; }}
{sel} #btn_settings {{ background: {hover}; color: {text}; }}
{sel} Button:hover {{ background: {bg_lighten1}; }}
{sel} Button.-primary {{ background: {bg_lighten1}; color: {text}; }}
{sel} Button.-primary:hover {{ background: {bg_lighten2}; }}
{sel} Button:focus {{ background: {bg_lighten1}; }}

/* Flat button style (default) - removes 3D borders */
{sel}.btn-style-flat Button {{ border: none; border-top: none; border-bottom: none; }}

/* Inputs - same as background, no contrast */
{sel} Input {{ background: {bg}; color: {text}; border: solid {border}; }}
{sel} Input:focus {{ border: solid {border}; background: {bg}; }}
{sel} Input.-invalid {{ border: solid {border}; background: {bg}; }}

/* TextArea - same as background, no contrast */
{sel} TextArea {{ background: {bg}; color: {text}; border: solid {border}; }}
{sel} TextArea:focus {{ border: solid {border}; background: {bg}; }}
{sel} TextArea .text-area--cursor-line {{ background: {hover}; }}
{sel} TextArea .text-area--cursor-gutter {{ background: {hover}; }}

/* Composer special - same as background */
{sel} #composer {{ background: {bg}; color: {text}; border: none; }}
{sel} #composer:focus {{ background: {bg}; border: none; }}
{sel} #composer .text-area--cursor-line {{ background: {hover}; }}
{sel} #composer_frame {{ background: {bg}; border-top: solid {border}; }}

/* Select widget - same as background */
{sel} Select {{ background: {bg}; color: {text}; border: solid {border}; }}
{sel} Select:focus {{ border: solid {border}; background: {bg}; }}
{sel} Select * {{ background: {bg}; color: {text}; }}
{sel} Select > * {{ background: {bg}; color: {text}; }}
{sel} Select > SelectCurrent {{ background: {bg}; color: {text}; }}
{sel} SelectCurrent {{ background: {bg}; color: {text}; }}
{sel} SelectCurrent * {{ background: {bg}; color: {text}; }}
{sel} SelectOverlay {{ background: {bg}; border: solid {border}; }}
{sel} SelectOverlay:focus {{ border: solid {border}; }}
{sel} OptionList {{ background: {bg}; }}
{sel} OptionList * {{ background: {bg}; }}
{sel} OptionList > .option-list--option {{ color: {text}; background: {bg}; }}
{sel} OptionList > .option-list--option-highlighted {{ background: {hover}; color: {text}; }}
{sel} OptionList > .option-list--option-hover {{ background: {hover}; }}

/* Settings tabs */
{sel} .settings_tab {{ background: {bg}; color: {muted}; }}
{sel} .settings_tab:hover {{ background: {hover}; color: {text}; }}
{sel} .settings_tab.active {{ background: {hover}; color: {text}; border-left: solid {border}; }}

/* Messages */
{sel} .msg {{ background: {bg}; color: {text}; }}
{sel} .msg:hover {{ background: {hover}; border-left: wide {accent}; }}
{sel} .msg.flash {{ background: {hover}; border-left: wide {accent}; }}
{sel} .msg_header {{ color: {text}; }}
{sel} .msg_body {{ color: {text}; }}
{sel} .msg_meta {{ color: {muted}; }}
{sel} .msg_reply {{ background: {bg}; color: {muted}; border-left: solid {accent}; }}

/* Composer */
{sel} #composer_frame {{ background: {bg}; border-top: solid {border}; }}
{sel} #reply_bar {{ color: {accent}; background: {bg}; }}
{sel} #send_btn {{ background: {accent_soft}; color: {text}; }}
{sel} #send_btn:hover {{ background: {accent_softer}; }}

/* Requests */
{sel} #req_in, {sel} #req_out {{ background: {bg}; border: round {border}; }}
{sel} #req_in_title, {sel} #req_out_title {{ color: {muted}; }}

/* Context menu */
{sel} #context_menu_container {{ background: {panel}; border: solid {accent}; }}
{sel} #menu_title {{ background: {accent}; color: {accent_text}; }}
{sel} #menu_items Button {{ background: {panel}; color: {text}; }}
{sel} #menu_items Button:hover {{ background: {accent}; color: {accent_text}; }}

/* Profile dialogs */
{sel} #profile_dialog_panel, {sel} #my_status_panel {{ background: {panel}; border: solid {border}; }}
{sel} .profile_bio_box {{ background: {bg}; border: solid {border}; }}

/* Scrollbars - CRITICAL for theme consistency */
{sel} * {{ scrollbar-background: {bg}; scrollbar-background-hover: {bg}; scrollbar-background-active: {bg}; scrollbar-color: {border}; scrollbar-color-hover: {border_light}; scrollbar-color-active: {border_light}; scrollbar-corner-color: {bg}; }}
{sel} #messages {{ scrollbar-background: {bg}; scrollbar-background-hover: {bg}; scrollbar-background-active: {bg}; scrollbar-color: {border}; scrollbar-color-hover: {border_light}; scrollbar-color-active: {border_light}; scrollbar-corner-color: {bg}; }}
{sel} .code-content-wrapper {{ scrollbar-background: {bg}; scrollbar-background-hover: {bg}; scrollbar-background-active: {bg}; scrollbar-color: {border}; scrollbar-color-hover: {border_light}; scrollbar-color-active: {border_light}; scrollbar-corner-color: {bg}; }}
{sel} VerticalScroll {{ scrollbar-background: {bg}; scrollbar-color: {border}; scrollbar-color-hover: {border_light}; }}
{sel} ScrollableContainer {{ scrollbar-background: {bg}; scrollbar-color: {border}; scrollbar-color-hover: {border_light}; }}
{sel} #settings_scroll {{ scrollbar-background: {bg}; scrollbar-color: {border}; }}

/* Checkboxes and switches */
{sel} Checkbox {{ color: {text}; }}
{sel} Checkbox > .toggle--button {{ background: {panel}; color: {muted}; }}
{sel} Checkbox.-on > .toggle--button {{ background: {accent}; color: {accent_text}; }}
{sel} Switch {{ background: {panel}; }}
{sel} Switch > .switch--slider {{ background: {muted}; }}
{sel} Switch.-on > .switch--slider {{ background: {accent}; }}

/* Progress bars */
{sel} ProgressBar > .bar--bar {{ background: {panel}; }}
{sel} ProgressBar > .bar--complete {{ background: {accent}; }}

/* DataTable */
{sel} DataTable {{ background: {bg}; }}
{sel} DataTable > .datatable--header {{ background: {panel}; color: {text}; }}
{sel} DataTable > .datatable--cursor {{ background: {hover}; }}
{sel} DataTable > .datatable--hover {{ background: {hover}; }}

/* Tree */
{sel} Tree {{ background: {bg}; }}
{sel} Tree > .tree--cursor {{ background: {hover}; }}
{sel} Tree > .tree--highlight {{ background: {hover}; }}
{sel} Tree > .tree--guides {{ color: {border}; }}

/* Labels and Static */
{sel} Label {{ color: {text}; }}
{sel} Static {{ color: {text}; }}
{sel} .section_label {{ color: {muted}; }}
{sel} .section_desc {{ color: {muted}; }}

/* Modal screens */
{sel} ModalScreen {{ background: {bg} 80%; }}

/* Tooltips */
{sel} Tooltip {{ background: {panel}; color: {text}; border: solid {border}; }}

/* Footer */
{sel} Footer {{ background: {panel}; color: {muted}; }}
{sel} Footer > .footer--key {{ background: {accent}; color: {accent_text}; }}

/* Header */
{sel} Header {{ background: {panel}; color: {text}; }}

/* Markdown */
{sel} Markdown {{ background: {bg}; color: {text}; }}
{sel} MarkdownH1, {sel} MarkdownH2, {sel} MarkdownH3 {{ color: {accent}; }}
{sel} MarkdownBlockQuote {{ background: {panel}; border-left: solid {accent}; }}

/* RichLog */
{sel} RichLog {{ background: {bg}; color: {text}; scrollbar-background: {bg}; scrollbar-color: {border}; }}

/* LoadingIndicator */
{sel} LoadingIndicator {{ background: {bg}; color: {accent}; }}

/* Placeholder */
{sel} Placeholder {{ background: {panel}; color: {muted}; border: dashed {border}; }}
"""
