#!/usr/bin/env bash
set -Eeuo pipefail

THEME_DIR="$HOME/.config/celita"
THEME_FILE="$THEME_DIR/theme"
GTK_DIR="$HOME/.config/gtk-3.0"
GTK_SETTINGS="$GTK_DIR/settings.ini"
GTK_CSS="$GTK_DIR/gtk.css"

current_theme() {
    if [[ -r "$THEME_FILE" ]]; then
        read -r saved_theme < "$THEME_FILE" || true
        case "${saved_theme:-}" in
            light|dark) printf '%s\n' "$saved_theme"; return ;;
        esac
    fi
    local gtk_theme=""
    gtk_theme="$(xfconf-query -c xsettings -p /Net/ThemeName 2>/dev/null || true)"
    if [[ "${gtk_theme,,}" == *dark* ]]; then
        printf 'dark\n'
    else
        printf 'light\n'
    fi
}

available_gtk_theme() {
    local preferred="$1" fallback="$2"
    if [[ -d "/usr/share/themes/$preferred/gtk-3.0" || -d "$HOME/.themes/$preferred/gtk-3.0" ]]; then
        printf '%s\n' "$preferred"
    else
        printf '%s\n' "$fallback"
    fi
}

write_gtk_settings() {
    local gtk_theme="$1" dark_value="$2"
    python3 - "$GTK_SETTINGS" "$gtk_theme" "$dark_value" <<'PY'
import configparser
import sys
from pathlib import Path

path = Path(sys.argv[1])
parser = configparser.ConfigParser(interpolation=None)
parser.optionxform = str
if path.exists():
    try:
        parser.read(path, encoding="utf-8")
    except configparser.Error:
        parser = configparser.ConfigParser(interpolation=None)
        parser.optionxform = str
if not parser.has_section("Settings"):
    parser.add_section("Settings")
parser.set("Settings", "gtk-theme-name", sys.argv[2])
parser.set("Settings", "gtk-application-prefer-dark-theme", sys.argv[3])
with path.open("w", encoding="utf-8") as stream:
    parser.write(stream, space_around_delimiters=False)
PY
}

write_panel_css() {
    local mode="$1"
    python3 - "$GTK_CSS" "$mode" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
mode = sys.argv[2]
text = path.read_text(encoding="utf-8") if path.exists() else ""
begin = "/* BEGIN CELITA VISUAL PANEL */"
end = "/* END CELITA VISUAL PANEL */"
if begin in text and end in text:
    before, rest = text.split(begin, 1)
    _, after = rest.split(end, 1)
    text = before.rstrip() + "\n" + after.lstrip("\n")

if mode == "dark":
    panel, border, foreground = "rgba(24, 24, 24, 0.98)", "rgba(255,255,255,0.08)", "#f4f4f4"
    hover, checked, shadow = "rgba(255,255,255,0.11)", "rgba(255,255,255,0.16)", "rgba(0,0,0,0.28)"
else:
    panel, border, foreground = "rgba(246, 247, 249, 0.98)", "rgba(34,39,46,0.16)", "#20242a"
    hover, checked, shadow = "rgba(18,25,33,0.08)", "rgba(18,25,33,0.13)", "rgba(0,0,0,0.18)"

block = f'''{begin}
.xfce4-panel {{
    background-color: {panel};
    border-top: 1px solid {border};
    color: {foreground};
    box-shadow: 0 -2px 8px {shadow};
}}
.xfce4-panel button,
.xfce4-panel #xfce-panel-toggle-button {{
    min-height: 44px;
    margin: 1px;
    padding: 0 10px;
    border: 0;
    border-radius: 0;
    color: {foreground};
    background-image: none;
    background-color: transparent;
    box-shadow: none;
}}
.xfce4-panel button:hover,
.xfce4-panel #xfce-panel-toggle-button:hover {{ background-color: {hover}; }}
.xfce4-panel button:checked,
.xfce4-panel #xfce-panel-toggle-button:checked {{
    background-color: {checked};
    box-shadow: inset 0 -2px #1687d9;
}}
#tasklist button {{ min-width: 140px; padding: 0 12px; }}
#clock {{ min-width: 64px; padding: 0 13px; font-size: 1em; font-weight: 600; }}
{end}'''
path.write_text(text.rstrip() + "\n\n" + block + "\n", encoding="utf-8")
PY
}

apply_theme() {
    local mode="$1" gtk_theme dark_value
    mkdir -p "$THEME_DIR" "$GTK_DIR"
    printf '%s\n' "$mode" > "$THEME_FILE"
    if [[ "$mode" == dark ]]; then
        gtk_theme="$(available_gtk_theme Fluent-Dark-compact Adwaita-dark)"
        dark_value=true
    else
        gtk_theme="$(available_gtk_theme Fluent-Light-compact Adwaita)"
        dark_value=false
    fi
    write_gtk_settings "$gtk_theme" "$dark_value"
    write_panel_css "$mode"
    xfconf-query -c xsettings -p /Net/ThemeName -s "$gtk_theme" >/dev/null 2>&1 || \
        xfconf-query -c xsettings -n -p /Net/ThemeName -t string -s "$gtk_theme" >/dev/null 2>&1 || true
    xfconf-query -c xsettings -p /Gtk/ApplicationPreferDarkTheme -s "$dark_value" >/dev/null 2>&1 || \
        xfconf-query -c xsettings -n -p /Gtk/ApplicationPreferDarkTheme -t bool -s "$dark_value" >/dev/null 2>&1 || true
    xfce4-panel -r >/dev/null 2>&1 || true
}

requested="${1:-apply}"
case "$requested" in
    light|claro) apply_theme light ;;
    dark|escuro) apply_theme dark ;;
    toggle|alternar)
        if [[ "$(current_theme)" == dark ]]; then apply_theme light; else apply_theme dark; fi
        ;;
    apply|aplicar) apply_theme "$(current_theme)" ;;
    status) current_theme ;;
    *)
        printf 'Uso: %s {claro|escuro|alternar|aplicar|status}\n' "$0" >&2
        exit 2
        ;;
esac
