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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
HYPR_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"
THEME_DIR="$HYPR_DIR/Themes"
CURRENT_THEME="$HYPR_DIR/current-theme.conf"
HYPRLOCK_CONF="$HYPR_DIR/hyprlock.conf"
HYPRPAPER_CONF="$HYPR_DIR/hyprpaper.conf"
CURRENT_WALLPAPER="$HYPR_DIR/current-wallpaper"
WOFI_STYLE="${XDG_CONFIG_HOME:-$HOME/.config}/wofi/style.css"
SWAYNC_STYLE="${XDG_CONFIG_HOME:-$HOME/.config}/swaync/style.css"
WAYBAR_STYLE="${XDG_CONFIG_HOME:-$HOME/.config}/waybar/style.css"
GTK3_SETTINGS="${XDG_CONFIG_HOME:-$HOME/.config}/gtk-3.0/settings.ini"
GTK4_SETTINGS="${XDG_CONFIG_HOME:-$HOME/.config}/gtk-4.0/settings.ini"
GTK3_CSS="${XDG_CONFIG_HOME:-$HOME/.config}/gtk-3.0/gtk.css"
GTK4_CSS="${XDG_CONFIG_HOME:-$HOME/.config}/gtk-4.0/gtk.css"
KDEGLOBALS="${XDG_CONFIG_HOME:-$HOME/.config}/kdeglobals"
KDE_COLOR_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/color-schemes"
LOCAL_ICON_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/icons"
QT6CT_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/qt6ct/qt6ct.conf"
QT5CT_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/qt5ct/qt5ct.conf"
STARSHIP_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/starship.toml"
SDDM_STATE_DIR="/var/lib/pascal-sddm-theme"

notify() {
    notify-send "󰌪 Theme" "$1" >/dev/null 2>&1 || true
}

load_theme() {
    local theme_file="$1"

    NAME=""
    ICON="󰌪"
    WALLPAPER=""
    TRANSITION_TYPE="grow"
    TRANSITION_DURATION="1.0"
    TRANSITION_FPS="60"
    TRANSITION_POS="center"
    ACTIVE_BORDER=""
    INACTIVE_BORDER=""
    ACCENT=""
    ACCENT_2=""
    BACKGROUND=""
    BACKGROUND_SOFT=""
    BACKGROUND_HEX=""
    PANEL_HEX=""
    FOREGROUND=""
    MUTED=""
    SELECTED_TEXT=""
    WAYBAR_PANEL=""
    WAYBAR_ISLAND=""
    WAYBAR_MUTED=""
    WAYBAR_SUCCESS=""
    WAYBAR_WARNING=""
    WAYBAR_DANGER=""
    WAYBAR_BLUE=""
    WAYBAR_CYAN=""
    WAYBAR_ORANGE=""
    WAYBAR_PURPLE=""
    APP_THEME_MODE="prefer-dark"
    GNOME_ACCENT_COLOR="blue"
    GTK_THEME_NAME="Adwaita"
    ICON_THEME_NAME="Adwaita"
    PAPIRUS_FOLDER_COLOR=""
    KDE_COLOR_SCHEME=""

    # shellcheck source=/dev/null
    source "$theme_file"

    if [[ -z "$NAME" || -z "$WALLPAPER" || -z "$ACTIVE_BORDER" || -z "$INACTIVE_BORDER" ||
        -z "$ACCENT" || -z "$ACCENT_2" || -z "$BACKGROUND" || -z "$BACKGROUND_SOFT" ||
        -z "$FOREGROUND" || -z "$MUTED" || -z "$SELECTED_TEXT" ]]; then
        notify "Theme ist unvollstaendig: $(basename "$theme_file")"
        exit 1
    fi

    if [[ ! -f "$WALLPAPER" ]]; then
        notify "Wallpaper nicht gefunden: $WALLPAPER"
        exit 1
    fi

    WAYBAR_PANEL="${WAYBAR_PANEL:-$BACKGROUND_SOFT}"
    WAYBAR_ISLAND="${WAYBAR_ISLAND:-$BACKGROUND}"
    WAYBAR_MUTED="${WAYBAR_MUTED:-$MUTED}"
    WAYBAR_SUCCESS="${WAYBAR_SUCCESS:-$ACCENT_2}"
    WAYBAR_WARNING="${WAYBAR_WARNING:-#f9e2af}"
    WAYBAR_DANGER="${WAYBAR_DANGER:-#f38ba8}"
    WAYBAR_BLUE="${WAYBAR_BLUE:-$ACCENT}"
    WAYBAR_CYAN="${WAYBAR_CYAN:-$ACCENT_2}"
    WAYBAR_ORANGE="${WAYBAR_ORANGE:-#fab387}"
    WAYBAR_PURPLE="${WAYBAR_PURPLE:-$ACCENT_2}"
    BACKGROUND_HEX="${BACKGROUND_HEX:-#18141f}"
    PANEL_HEX="${PANEL_HEX:-#313244}"
    KDE_COLOR_SCHEME="${KDE_COLOR_SCHEME:-${NAME//[^[:alnum:]]/}}"
}

backup_once() {
    local file="$1"
    local backup="$file.before-theme-switcher"

    if [[ -f "$file" && ! -f "$backup" ]]; then
        cp "$file" "$backup"
    fi
}

start_detached() {
    local command_name="$1"
    local unit_name="${command_name//[^[:alnum:]_.-]/-}"

    if command -v systemd-run >/dev/null 2>&1; then
        systemd-run --user --unit="$unit_name" --collect "$@" >/dev/null 2>&1 && return
    fi

    if command -v setsid >/dev/null 2>&1; then
        setsid -f "$@" >/dev/null 2>&1
    else
        "$@" >/dev/null 2>&1 &
    fi
}

restart_waybar() {
    local i

    pkill -x waybar >/dev/null 2>&1 || true

    for i in {1..20}; do
        pgrep -x waybar >/dev/null 2>&1 || break
        sleep 0.05
    done

    pgrep -x waybar >/dev/null 2>&1 && pkill -9 -x waybar >/dev/null 2>&1 || true
    start_detached waybar
}

hex_to_rgb() {
    local hex="${1#'#'}"

    if [[ ! "$hex" =~ ^[0-9a-fA-F]{6}$ ]]; then
        printf '0,0,0\n'
        return
    fi

    printf '%d,%d,%d\n' "0x${hex:0:2}" "0x${hex:2:2}" "0x${hex:4:2}"
}

hex_to_argb() {
    local hex="${1#'#'}"

    if [[ ! "$hex" =~ ^[0-9a-fA-F]{6}$ ]]; then
        printf '#ff000000\n'
        return
    fi

    printf '#ff%s\n' "${hex,,}"
}

write_gtk_settings() {
    mkdir -p "$(dirname "$GTK3_SETTINGS")" "$(dirname "$GTK4_SETTINGS")"
    backup_once "$GTK3_SETTINGS"
    backup_once "$GTK4_SETTINGS"
    backup_once "$GTK3_CSS"
    backup_once "$GTK4_CSS"

    cat >"$GTK3_SETTINGS" <<EOF
[Settings]
gtk-theme-name=$GTK_THEME_NAME
gtk-icon-theme-name=$ICON_THEME_NAME
gtk-application-prefer-dark-theme=1
EOF

    cat >"$GTK4_SETTINGS" <<EOF
[Settings]
gtk-theme-name=$GTK_THEME_NAME
gtk-icon-theme-name=$ICON_THEME_NAME
gtk-application-prefer-dark-theme=1
EOF

    for gtk_css in "$GTK3_CSS" "$GTK4_CSS"; do
        cat >"$gtk_css" <<EOF
@define-color accent_color $ACCENT;
@define-color accent_bg_color $ACCENT;
@define-color accent_fg_color $SELECTED_TEXT;
@define-color window_bg_color $BACKGROUND_HEX;
@define-color window_fg_color $FOREGROUND;
@define-color view_bg_color $BACKGROUND_HEX;
@define-color view_fg_color $FOREGROUND;
@define-color card_bg_color $PANEL_HEX;
@define-color card_fg_color $FOREGROUND;
@define-color popover_bg_color $PANEL_HEX;
@define-color popover_fg_color $FOREGROUND;
@define-color headerbar_bg_color $PANEL_HEX;
@define-color headerbar_fg_color $FOREGROUND;
@define-color sidebar_bg_color $BACKGROUND_HEX;
@define-color sidebar_fg_color $FOREGROUND;
@define-color destructive_color $WAYBAR_DANGER;
@define-color warning_color $WAYBAR_WARNING;
@define-color success_color $WAYBAR_SUCCESS;
EOF
    done

    if command -v gsettings >/dev/null 2>&1 && pgrep -x Hyprland >/dev/null 2>&1; then
        gsettings set org.gnome.desktop.interface color-scheme "$APP_THEME_MODE" >/dev/null 2>&1 || true
        gsettings set org.gnome.desktop.interface accent-color "$GNOME_ACCENT_COLOR" >/dev/null 2>&1 || true
        gsettings set org.gnome.desktop.interface gtk-theme "$GTK_THEME_NAME" >/dev/null 2>&1 || true
        gsettings set org.gnome.desktop.interface icon-theme "$ICON_THEME_NAME" >/dev/null 2>&1 || true
    fi
}

link_icon_if_present() {
    local source="$1"
    local target="$2"

    if [[ -e "$source" ]]; then
        ln -sfn "$source" "$target"
    fi
}

write_papirus_icon_theme() {
    local source_theme="/usr/share/icons/Papirus-Dark"
    local target_theme="$LOCAL_ICON_DIR/$ICON_THEME_NAME"
    local source_places relative_dir target_places source_size size scale suffix
    local folder_color="${PAPIRUS_FOLDER_COLOR:-}"
    local stamp_file="$target_theme/.theme-switcher-stamp"
    local stamp_value="$NAME|$ICON_THEME_NAME|$folder_color"
    local place_dirs=()
    local directories

    [[ -d "$source_theme" && -n "$folder_color" && "$ICON_THEME_NAME" == Papirus-* ]] || return 0

    if [[ -f "$target_theme/index.theme" && -f "$stamp_file" && "$(cat "$stamp_file")" == "$stamp_value" ]]; then
        return 0
    fi

    mkdir -p "$target_theme"
    mapfile -t place_dirs < <(find -L "$source_theme" -path '*/places' -type d | sort)
    directories="$(
        for source_places in "${place_dirs[@]}"; do
            printf '%s,' "${source_places#"$source_theme"/}"
        done
    )"
    directories="${directories%,}"

    cat >"$target_theme/index.theme" <<EOF
[Icon Theme]
Name=$ICON_THEME_NAME
Comment=Papirus-Dark with $folder_color folders for $NAME
Inherits=Papirus-Dark,Papirus,hicolor
Directories=$directories
EOF

    for source_places in "${place_dirs[@]}"; do
        relative_dir="${source_places#"$source_theme"/}"
        target_places="$target_theme/$relative_dir"
        source_size="${relative_dir%%/*}"
        size="${source_size%@*}"
        scale="1"

        if [[ "$source_size" == *"@2x" ]]; then
            scale="2"
        fi

        mkdir -p "$target_places"

        cat >>"$target_theme/index.theme" <<EOF

[$relative_dir]
Context=Places
Type=Fixed
Size=${size%x*}
Scale=$scale
EOF

        link_icon_if_present "$source_places/folder-$folder_color.svg" "$target_places/folder.svg"
        link_icon_if_present "$source_places/folder-$folder_color-open.svg" "$target_places/folder-open.svg"
        link_icon_if_present "$source_places/user-$folder_color-home.svg" "$target_places/user-home.svg"
        link_icon_if_present "$source_places/user-$folder_color-home.svg" "$target_places/folder-home.svg"
        link_icon_if_present "$source_places/user-$folder_color-home.svg" "$target_places/folder_home.svg"
        link_icon_if_present "$source_places/user-$folder_color-home.svg" "$target_places/folder_home2.svg"

        for suffix in \
            activities android apple applications arduino backup books cd code desktop development docker \
            documents documents-open download download-open downloads dropbox favorites games git github gitlab \
            gnome google-drive image-people important java kde linux locked mail mail-cloud mega music music-open \
            network notes obsidian onedrive owncloud pcloud photo photos picture pictures pictures-open print \
            private projects public publicshare publicshare-open recent remote remote-open script snap steam sync \
            syncthing templates templates-open torrent unlocked video videos videos-open vbox vmware wine yellow; do
            link_icon_if_present "$source_places/folder-$folder_color-$suffix.svg" "$target_places/folder-$suffix.svg"
        done
    done

    if command -v gtk-update-icon-cache >/dev/null 2>&1; then
        gtk-update-icon-cache -q "$target_theme" >/dev/null 2>&1 || true
    fi

    printf '%s\n' "$stamp_value" >"$stamp_file"
}

write_qtct_theme() {
    local qt_dir conf_file color_file
    local foreground_argb muted_argb background_argb panel_argb accent_argb accent_2_argb selected_argb danger_argb placeholder_argb
    local active_colors disabled_colors inactive_colors

    foreground_argb="$(hex_to_argb "$FOREGROUND")"
    muted_argb="$(hex_to_argb "$MUTED")"
    background_argb="$(hex_to_argb "${BACKGROUND_HEX:-#18141f}")"
    panel_argb="$(hex_to_argb "${PANEL_HEX:-#313244}")"
    accent_argb="$(hex_to_argb "$ACCENT")"
    accent_2_argb="$(hex_to_argb "$ACCENT_2")"
    selected_argb="$(hex_to_argb "$SELECTED_TEXT")"
    danger_argb="$(hex_to_argb "$WAYBAR_DANGER")"
    placeholder_argb="#80${MUTED#'#'}"

    active_colors="$foreground_argb, $panel_argb, #ffffffff, $muted_argb, $background_argb, $panel_argb, $foreground_argb, #ffffffff, $foreground_argb, $background_argb, $background_argb, #ff000000, $accent_argb, $selected_argb, $accent_2_argb, $danger_argb, $panel_argb, $foreground_argb, $panel_argb, $foreground_argb, $placeholder_argb"
    disabled_colors="$muted_argb, $panel_argb, #ffffffff, $muted_argb, $background_argb, $panel_argb, $muted_argb, #ffffffff, $muted_argb, $background_argb, $background_argb, #ff000000, $panel_argb, $muted_argb, $accent_2_argb, $danger_argb, $panel_argb, $muted_argb, $panel_argb, $muted_argb, $placeholder_argb"
    inactive_colors="$foreground_argb, $panel_argb, #ffffffff, $muted_argb, $background_argb, $panel_argb, $foreground_argb, #ffffffff, $foreground_argb, $background_argb, $background_argb, #ff000000, $accent_argb, $selected_argb, $accent_2_argb, $danger_argb, $panel_argb, $foreground_argb, $panel_argb, $foreground_argb, $placeholder_argb"

    for qt_dir in "${XDG_CONFIG_HOME:-$HOME/.config}/qt6ct" "${XDG_CONFIG_HOME:-$HOME/.config}/qt5ct"; do
        mkdir -p "$qt_dir/colors"
        color_file="$qt_dir/colors/$KDE_COLOR_SCHEME.conf"

        cat >"$color_file" <<EOF
[ColorScheme]
active_colors=$active_colors
disabled_colors=$disabled_colors
inactive_colors=$inactive_colors
EOF
    done

    for conf_file in "$QT6CT_CONF" "$QT5CT_CONF"; do
        mkdir -p "$(dirname "$conf_file")"
        backup_once "$conf_file"

        cat >"$conf_file" <<EOF
[Appearance]
color_scheme_path=$(dirname "$conf_file")/colors/$KDE_COLOR_SCHEME.conf
custom_palette=true
icon_theme=$ICON_THEME_NAME
standard_dialogs=default
style=Fusion

[Fonts]
fixed="JetBrainsMono Nerd Font,10,-1,5,50,0,0,0,0,0"
general="JetBrainsMono Nerd Font,10,-1,5,50,0,0,0,0,0"

[Interface]
activate_item_on_single_click=1
buttonbox_layout=0
cursor_flash_time=1000
dialog_buttons_have_icons=1
double_click_interval=400
gui_effects=@Invalid()
keyboard_scheme=2
menus_have_icons=true
show_shortcuts_in_context_menus=true
stylesheets=@Invalid()
toolbutton_style=4
underline_shortcut=1
wheel_scroll_lines=3

[SettingsWindow]
geometry=@ByteArray()
EOF
    done
}

write_kde_color_scheme() {
    local scheme_file="$KDE_COLOR_DIR/$KDE_COLOR_SCHEME.colors"
    local foreground_rgb muted_rgb background_rgb panel_rgb accent_rgb accent_2_rgb selected_rgb danger_rgb warning_rgb purple_rgb

    mkdir -p "$KDE_COLOR_DIR" "$(dirname "$KDEGLOBALS")"
    backup_once "$KDEGLOBALS"

    foreground_rgb="$(hex_to_rgb "$FOREGROUND")"
    muted_rgb="$(hex_to_rgb "$MUTED")"
    background_rgb="$(hex_to_rgb "${BACKGROUND_HEX:-#18141f}")"
    panel_rgb="$(hex_to_rgb "${PANEL_HEX:-#313244}")"
    accent_rgb="$(hex_to_rgb "$ACCENT")"
    accent_2_rgb="$(hex_to_rgb "$ACCENT_2")"
    selected_rgb="$(hex_to_rgb "$SELECTED_TEXT")"
    danger_rgb="$(hex_to_rgb "$WAYBAR_DANGER")"
    warning_rgb="$(hex_to_rgb "$WAYBAR_WARNING")"
    purple_rgb="$(hex_to_rgb "$WAYBAR_PURPLE")"

    cat >"$scheme_file" <<EOF
[General]
ColorScheme=$KDE_COLOR_SCHEME
Name=$NAME
shadeSortColumn=true

[Colors:Window]
BackgroundNormal=$background_rgb
BackgroundAlternate=$panel_rgb
ForegroundNormal=$foreground_rgb
ForegroundInactive=$muted_rgb
ForegroundActive=$accent_rgb
ForegroundLink=$accent_2_rgb
ForegroundVisited=$purple_rgb
ForegroundNegative=$danger_rgb
ForegroundNeutral=$warning_rgb
ForegroundPositive=$accent_2_rgb

[Colors:View]
BackgroundNormal=$background_rgb
BackgroundAlternate=$panel_rgb
ForegroundNormal=$foreground_rgb
ForegroundInactive=$muted_rgb
ForegroundActive=$accent_rgb
ForegroundLink=$accent_2_rgb
ForegroundVisited=$purple_rgb
ForegroundNegative=$danger_rgb
ForegroundNeutral=$warning_rgb
ForegroundPositive=$accent_2_rgb

[Colors:Button]
BackgroundNormal=$panel_rgb
BackgroundAlternate=$background_rgb
ForegroundNormal=$foreground_rgb
ForegroundInactive=$muted_rgb
ForegroundActive=$accent_rgb
ForegroundLink=$accent_2_rgb
ForegroundVisited=$purple_rgb
ForegroundNegative=$danger_rgb
ForegroundNeutral=$warning_rgb
ForegroundPositive=$accent_2_rgb

[Colors:Selection]
BackgroundNormal=$accent_rgb
BackgroundAlternate=$accent_2_rgb
ForegroundNormal=$selected_rgb
ForegroundInactive=$selected_rgb
ForegroundActive=$selected_rgb
ForegroundLink=$selected_rgb
ForegroundVisited=$selected_rgb
ForegroundNegative=$selected_rgb
ForegroundNeutral=$selected_rgb
ForegroundPositive=$selected_rgb

[Colors:Tooltip]
BackgroundNormal=$panel_rgb
BackgroundAlternate=$background_rgb
ForegroundNormal=$foreground_rgb
ForegroundInactive=$muted_rgb
ForegroundActive=$accent_rgb
ForegroundLink=$accent_2_rgb
ForegroundVisited=$purple_rgb
ForegroundNegative=$danger_rgb
ForegroundNeutral=$warning_rgb
ForegroundPositive=$accent_2_rgb

[KDE]
contrast=4

[WM]
activeBackground=$accent_rgb
activeForeground=$selected_rgb
inactiveBackground=$panel_rgb
inactiveForeground=$muted_rgb
EOF

    if command -v kwriteconfig6 >/dev/null 2>&1 && pgrep -x Hyprland >/dev/null 2>&1; then
        kwriteconfig6 --file kdeglobals --group General --key ColorScheme "$KDE_COLOR_SCHEME" >/dev/null 2>&1 || true
        kwriteconfig6 --file kdeglobals --group General --key Name "$NAME" >/dev/null 2>&1 || true
        kwriteconfig6 --file kdeglobals --group Icons --key Theme "$ICON_THEME_NAME" >/dev/null 2>&1 || true
        kwriteconfig6 --file kdeglobals --group KDE --key widgetStyle Fusion >/dev/null 2>&1 || true
    else
        mkdir -p "$(dirname "$KDEGLOBALS")"
        cat >"$KDEGLOBALS" <<EOF
[General]
ColorScheme=$KDE_COLOR_SCHEME
Name=$NAME

[Icons]
Theme=$ICON_THEME_NAME

[KDE]
widgetStyle=Fusion
EOF
    fi
}

write_app_styles() {
    mkdir -p "$(dirname "$WOFI_STYLE")" "$(dirname "$SWAYNC_STYLE")" "$(dirname "$WAYBAR_STYLE")"
    backup_once "$WOFI_STYLE"
    backup_once "$SWAYNC_STYLE"
    backup_once "$WAYBAR_STYLE"

    cat >"$WOFI_STYLE" <<EOF
* {
    font-family: "JetBrainsMono Nerd Font";
    font-size: 14px;
}

window {
    margin: 0px;
    border: 2px solid $ACCENT;
    border-radius: 12px;
    background-color: $BACKGROUND;
}

#input {
    margin: 10px;
    padding: 10px;
    border-radius: 8px;
    border: none;
    background-color: $BACKGROUND_SOFT;
    color: $ACCENT;
}

#inner-box {
    margin: 5px;
}

#outer-box {
    margin: 10px;
}

#scroll {
    margin: 5px;
}

#text {
    margin: 5px;
    color: $FOREGROUND;
}

#entry {
    padding: 8px;
    border-radius: 8px;
}

#entry:selected {
    background-color: $ACCENT;
    color: $SELECTED_TEXT;
}

#entry:hover {
    background-color: $BACKGROUND_SOFT;
}

#img {
    margin-right: 8px;
}
EOF

    cat >"$SWAYNC_STYLE" <<EOF
* {
  font-family: "JetBrainsMono Nerd Font";
  font-size: 13px;
}

.notification {
  background: $BACKGROUND;
  border-radius: 12px;
  border: 2px solid $ACCENT;
  box-shadow: 0 0 10px $ACCENT;
  padding: 10px;
}

.control-center {
  background: $BACKGROUND;
  border-radius: 15px;
  border: 2px solid $ACCENT;
}

.notification-title {
  color: $ACCENT_2;
  font-weight: bold;
}

.notification-body {
  color: $MUTED;
}
EOF

    cat >"$WAYBAR_STYLE" <<EOF
* {
    min-height: 0;
    font-family: "JetBrainsMono Nerd Font", "JetBrains Mono", sans-serif;
    font-size: 13px;
    font-weight: 700;
    border: none;
    border-radius: 0;
}

window#waybar {
    background: transparent;
    color: $FOREGROUND;
}

tooltip {
    background: $BACKGROUND;
    border: 1px solid $ACCENT;
    border-radius: 10px;
}

tooltip label {
    color: $FOREGROUND;
    padding: 6px 8px;
}

#workspaces {
    margin: 0 0 0 2px;
    padding: 4px;
    background: $WAYBAR_PANEL;
    border: 1px solid $BACKGROUND_SOFT;
    border-radius: 18px;
}

#workspaces button {
    min-width: 26px;
    margin: 0 2px;
    padding: 0 7px;
    color: $WAYBAR_MUTED;
    background: transparent;
    border-radius: 14px;
    transition: all 180ms ease;
}

#workspaces button.active {
    min-width: 34px;
    color: $SELECTED_TEXT;
    background: linear-gradient(135deg, $ACCENT, $ACCENT_2);
    box-shadow: 0 0 14px $BACKGROUND_SOFT;
}

#workspaces button.urgent {
    color: $SELECTED_TEXT;
    background: $WAYBAR_DANGER;
}

#workspaces button:hover {
    color: $FOREGROUND;
    background: $BACKGROUND_SOFT;
}

#dynamic-island {
    margin: 0;
    padding: 0;
    background: $WAYBAR_ISLAND;
    border-top: 1px solid $BACKGROUND_SOFT;
    border-bottom: 1px solid $ACCENT;
    border-radius: 21px;
    box-shadow: 0 10px 28px rgba(0, 0, 0, 0.36);
}

#custom-dynamic-island,
#custom-media-prev,
#custom-media-toggle,
#custom-media-next,
#window,
#clock {
    margin: 0;
    padding: 0 11px;
    background: transparent;
    color: $FOREGROUND;
}

#custom-dynamic-island {
    min-width: 142px;
    padding-left: 16px;
    padding-right: 14px;
    color: $FOREGROUND;
    border-radius: 21px;
}

#custom-dynamic-island.playing {
    color: $WAYBAR_SUCCESS;
}

#custom-dynamic-island.paused {
    color: $WAYBAR_WARNING;
}

#custom-dynamic-island.idle {
    color: $WAYBAR_MUTED;
}

#custom-media-prev,
#custom-media-toggle,
#custom-media-next {
    min-width: 20px;
    padding: 0 9px;
    color: $FOREGROUND;
    border-radius: 14px;
}

#custom-media-prev:hover,
#custom-media-toggle:hover,
#custom-media-next:hover {
    color: $SELECTED_TEXT;
    background: $ACCENT;
}

#window {
    min-width: 90px;
    color: $MUTED;
}

window#waybar.empty #window {
    min-width: 0;
    padding: 0;
    color: transparent;
}

#clock {
    padding-right: 16px;
    color: $WAYBAR_SUCCESS;
}

.island-drawer {
    color: $WAYBAR_MUTED;
}

#cpu,
#memory,
#temperature,
#pulseaudio,
#network,
#battery,
#custom-notifications,
#tray {
    margin: 0 2px;
    padding: 0 10px;
    background: $WAYBAR_PANEL;
    border: 1px solid $BACKGROUND_SOFT;
    border-radius: 16px;
}

#cpu {
    color: $WAYBAR_BLUE;
}

#memory {
    color: $WAYBAR_WARNING;
}

#temperature {
    color: $WAYBAR_SUCCESS;
}

#temperature.critical {
    color: $WAYBAR_DANGER;
    background: $BACKGROUND_SOFT;
}

#pulseaudio {
    color: $WAYBAR_ORANGE;
}

#pulseaudio.muted {
    color: $WAYBAR_MUTED;
}

#network {
    color: $WAYBAR_CYAN;
}

#network.disconnected {
    color: $WAYBAR_DANGER;
}

#battery {
    color: $WAYBAR_SUCCESS;
}

#battery.warning {
    color: $WAYBAR_WARNING;
}

#battery.critical {
    color: $WAYBAR_DANGER;
    background: $BACKGROUND_SOFT;
}

#custom-notifications {
    color: $WAYBAR_PURPLE;
}

#tray {
    padding-right: 12px;
}
EOF
}

write_desktop_app_theme() {
    write_papirus_icon_theme
    write_gtk_settings
    write_qtct_theme
    write_kde_color_scheme
}

write_hyprlock_theme() {
    local accent_rgb accent_2_rgb foreground_rgb muted_rgb background_rgb danger_rgb warning_rgb

    accent_rgb="$(hex_to_rgb "$ACCENT")"
    accent_2_rgb="$(hex_to_rgb "$ACCENT_2")"
    foreground_rgb="$(hex_to_rgb "$FOREGROUND")"
    muted_rgb="$(hex_to_rgb "$MUTED")"
    background_rgb="$(hex_to_rgb "${BACKGROUND_HEX:-#18141f}")"
    danger_rgb="$(hex_to_rgb "$WAYBAR_DANGER")"
    warning_rgb="$(hex_to_rgb "$WAYBAR_WARNING")"

    backup_once "$HYPRLOCK_CONF"

    cat >"$HYPRLOCK_CONF" <<EOF
# Generated by ~/.config/hypr/Scripts/theme-menu.sh

auth {
    pam:enabled = true
    pam:module = hyprlock

    fingerprint:enabled = true
    fingerprint:ready_message = Finger auflegen zum Entsperren
    fingerprint:present_message = Fingerabdruck wird gelesen...
    fingerprint:retry_delay = 250
}

general {
    disable_loading_bar = true
    hide_cursor = true
    grace = 0
    ignore_empty_input = true
}

background {
    monitor =
    path = $WALLPAPER
    blur_passes = 3
    blur_size = 8
    noise = 0.011
    contrast = 1.05
    brightness = 0.72
    vibrancy = 0.18
    vibrancy_darkness = 0.25
}

label {
    monitor =
    text = 󰌪  $NAME
    color = rgba($accent_2_rgb, 0.90)
    font_size = 22
    font_family = JetBrainsMono Nerd Font
    position = 0, 260
    halign = center
    valign = center
}

label {
    monitor =
    text = cmd[update:1000] date +"%H:%M"
    color = rgba($accent_rgb, 0.96)
    font_size = 92
    font_family = JetBrainsMono Nerd Font
    position = 0, 165
    halign = center
    valign = center
}

label {
    monitor =
    text = cmd[update:60000] date +"%A, %d. %B"
    color = rgba($foreground_rgb, 0.82)
    font_size = 22
    font_family = JetBrainsMono Nerd Font
    position = 0, 92
    halign = center
    valign = center
}

input-field {
    monitor =
    size = 390, 62
    outline_thickness = 2
    dots_size = 0.24
    dots_spacing = 0.28
    dots_center = true
    fade_on_empty = false
    rounding = 16

    outer_color = rgba($accent_rgb, 0.72)
    inner_color = rgba($background_rgb, 0.76)
    font_color = rgba($foreground_rgb, 0.92)
    placeholder_text = <i>Passwort oder Fingerprint</i>

    check_color = rgba($accent_2_rgb, 0.88)
    fail_color = rgba($danger_rgb, 0.95)
    capslock_color = rgba($warning_rgb, 0.95)

    position = 0, -20
    halign = center
    valign = center
}

label {
    monitor =
    text = cmd[update:1000] echo "  $(whoami)@$(uname -n)"
    color = rgba($muted_rgb, 0.70)
    font_size = 16
    font_family = JetBrainsMono Nerd Font
    position = 0, -92
    halign = center
    valign = center
}
EOF
}

write_starship_theme() {
    mkdir -p "$(dirname "$STARSHIP_CONF")"
    backup_once "$STARSHIP_CONF"

    cat >"$STARSHIP_CONF" <<EOF
# Generated by ~/.config/hypr/Scripts/theme-menu.sh
add_newline = true
palette = "hypr_theme"

format = """
[╭─](fg:accent_2)\$os\$username\$hostname\$directory\$git_branch\$git_status\$nodejs\$python\$rust\$golang\$cmd_duration\$status\$fill\$time
[╰─](fg:accent)\$character
"""

[palettes.hypr_theme]
accent = "$ACCENT"
accent_2 = "$ACCENT_2"
background = "$BACKGROUND_HEX"
panel = "$PANEL_HEX"
foreground = "$FOREGROUND"
muted = "$MUTED"
selected = "$SELECTED_TEXT"
success = "$WAYBAR_SUCCESS"
warning = "$WAYBAR_WARNING"
danger = "$WAYBAR_DANGER"
blue = "$WAYBAR_BLUE"
cyan = "$WAYBAR_CYAN"
orange = "$WAYBAR_ORANGE"
purple = "$WAYBAR_PURPLE"

[fill]
symbol = " "
style = "fg:panel"

[os]
disabled = false
format = "[ \$symbol ](fg:selected bg:accent)[](fg:accent bg:panel)"
style = "fg:selected bg:accent"

[os.symbols]
Arch = ""
CachyOS = ""
Linux = ""
Ubuntu = ""
Debian = ""
Fedora = ""
NixOS = ""

[username]
show_always = true
style_user = "fg:foreground bg:panel bold"
style_root = "fg:danger bg:panel bold"
format = "[ \$user](fg:foreground bg:panel bold)"

[hostname]
ssh_only = false
style = "fg:muted bg:panel"
format = "[@\$hostname ](fg:muted bg:panel)[](fg:panel bg:background)"

[directory]
style = "fg:accent bg:background bold"
read_only_style = "fg:danger bg:background bold"
truncation_length = 3
truncate_to_repo = true
read_only = " "
format = "[ 󰉋 \$path\$read_only ](fg:accent bg:background bold)"

[git_branch]
symbol = ""
style = "fg:purple bg:background bold"
format = "[on \$symbol \$branch ](fg:purple bg:background bold)"

[git_status]
style = "fg:warning bg:background bold"
format = "([\$all_status\$ahead_behind ](fg:warning bg:background bold))"
conflicted = "=\${count} "
ahead = "⇡\${count} "
behind = "⇣\${count} "
diverged = "⇕⇡\${ahead_count}⇣\${behind_count} "
up_to_date = ""
untracked = "?\${count} "
stashed = "*\${count} "
modified = "!\${count} "
staged = "+\${count} "
renamed = "»\${count} "
deleted = "x\${count} "

[nodejs]
symbol = ""
style = "fg:success bg:background"
format = "[\$symbol \$version ](fg:success bg:background)"

[python]
symbol = ""
style = "fg:warning bg:background"
format = "[\$symbol \$version ](fg:warning bg:background)"

[rust]
symbol = ""
style = "fg:orange bg:background"
format = "[\$symbol \$version ](fg:orange bg:background)"

[golang]
symbol = ""
style = "fg:cyan bg:background"
format = "[\$symbol \$version ](fg:cyan bg:background)"

[cmd_duration]
min_time = 300
style = "fg:orange bg:background"
format = "[took \$duration ](fg:orange bg:background)"

[status]
disabled = false
style = "fg:danger bg:background bold"
symbol = "✖"
format = "[\$symbol \$status ](fg:danger bg:background bold)"

[time]
disabled = false
time_format = "%H:%M"
style = "fg:muted"
format = "[ \$time ](\$style)"

[character]
success_symbol = "[❯](fg:accent bold)"
error_symbol = "[❯](fg:danger bold)"
vimcmd_symbol = "[❮](fg:accent_2 bold)"
EOF
}

write_sddm_theme_assets() {
    local wallpaper_ext wallpaper_target

    [[ -d "$SDDM_STATE_DIR" && -w "$SDDM_STATE_DIR" ]] || return 0

    wallpaper_ext="${WALLPAPER##*.}"
    if [[ "$wallpaper_ext" == "$WALLPAPER" ]]; then
        wallpaper_ext="jpg"
    fi

    wallpaper_target="$SDDM_STATE_DIR/wallpaper.$wallpaper_ext"
    if [[ ! -f "$wallpaper_target" ]] || ! cmp -s "$WALLPAPER" "$wallpaper_target"; then
        cp "$WALLPAPER" "$wallpaper_target"
    fi

    cat >"$SDDM_STATE_DIR/theme.conf" <<EOF
[General]
background=$wallpaper_target
themeName=$NAME
accent=$ACCENT
accent2=$ACCENT_2
backgroundColor=$BACKGROUND_HEX
panelColor=$PANEL_HEX
foreground=$FOREGROUND
muted=$MUTED
selectedText=$SELECTED_TEXT
EOF
}

apply_wallpaper() {
    cat >"$HYPRPAPER_CONF" <<EOF
preload = $WALLPAPER
wallpaper = ,$WALLPAPER
EOF

    printf '%s\n' "$WALLPAPER" >"$CURRENT_WALLPAPER"

    if command -v awww >/dev/null 2>&1; then
        cat >"$(dirname "$HYPRPAPER_CONF")/awww.conf" <<EOF
wallpaper {
    monitor =
    path = $WALLPAPER
    fit_mode = cover
}
EOF
    fi

    if pgrep -x Hyprland >/dev/null 2>&1; then
        if command -v awww >/dev/null 2>&1; then
            if ! pgrep -x awww-daemon >/dev/null 2>&1; then
                start_detached awww-daemon
                sleep 0.2
            fi

            awww img "$WALLPAPER" \
                --transition-type "$TRANSITION_TYPE" \
                --transition-duration "$TRANSITION_DURATION" \
                --transition-fps "$TRANSITION_FPS" \
                --transition-pos "$TRANSITION_POS" >/dev/null 2>&1 || true
            return
        fi

        if command -v swww >/dev/null 2>&1; then
            if ! pgrep -x swww-daemon >/dev/null 2>&1; then
                start_detached swww-daemon
                sleep 0.2
            fi

            swww img "$WALLPAPER" \
                --transition-type "$TRANSITION_TYPE" \
                --transition-duration "$TRANSITION_DURATION" \
                --transition-fps "$TRANSITION_FPS" \
                --transition-pos "$TRANSITION_POS" >/dev/null 2>&1 || true
            return
        fi

        if command -v hyprctl >/dev/null 2>&1; then
            if ! pgrep -x hyprpaper >/dev/null 2>&1; then
                start_detached hyprpaper
                sleep 0.2
            fi

            hyprctl hyprpaper preload "$WALLPAPER" >/dev/null || true
            hyprctl hyprpaper wallpaper ",$WALLPAPER" >/dev/null || true
        fi
    fi

}

apply_theme() {
    local theme_file="$1"
    load_theme "$theme_file"

    cat >"$CURRENT_THEME" <<EOF
# Generated by ~/.config/hypr/Scripts/theme-menu.sh
general {
    col.active_border = $ACTIVE_BORDER
    col.inactive_border = $INACTIVE_BORDER
}
EOF

    write_app_styles
    write_desktop_app_theme
    write_hyprlock_theme
    write_starship_theme
    write_sddm_theme_assets
    apply_wallpaper

    if command -v hyprctl >/dev/null 2>&1 && pgrep -x Hyprland >/dev/null 2>&1; then
        hyprctl keyword general:col.active_border "$ACTIVE_BORDER" >/dev/null || true
        hyprctl keyword general:col.inactive_border "$INACTIVE_BORDER" >/dev/null || true
    fi

    if pgrep -x Hyprland >/dev/null 2>&1; then
        if command -v swaync-client >/dev/null 2>&1; then
            swaync-client -rs >/dev/null 2>&1 || true
        fi

        if command -v waybar >/dev/null 2>&1; then
            restart_waybar
        fi

        if pgrep -x nautilus >/dev/null 2>&1; then
            nautilus -q >/dev/null 2>&1 || pkill -x nautilus >/dev/null 2>&1 || true
        fi

        notify "$NAME aktiviert."
    fi
}

if [[ "${1:-}" == "--apply" ]]; then
    theme_arg="${2:-}"

    if [[ -z "$theme_arg" ]]; then
        notify "Kein Theme angegeben."
        exit 1
    fi

    if [[ -f "$theme_arg" ]]; then
        apply_theme "$theme_arg"
    elif [[ -f "$THEME_DIR/$theme_arg.theme" ]]; then
        apply_theme "$THEME_DIR/$theme_arg.theme"
    else
        notify "Theme nicht gefunden: $theme_arg"
        exit 1
    fi

    exit 0
fi

mkdir -p "$THEME_DIR"

mapfile -t theme_files < <(find "$THEME_DIR" -maxdepth 1 -type f -name '*.theme' | sort)

if ((${#theme_files[@]} == 0)); then
    notify "Keine Themes in $THEME_DIR gefunden."
    exit 1
fi

menu_entries=()
for theme_file in "${theme_files[@]}"; do
    load_theme "$theme_file"
    menu_entries+=("$ICON  $NAME")
done

choice="$(
    printf '%s\n' "${menu_entries[@]}" |
        wofi --dmenu --prompt "󰌪  Theme wechseln" --insensitive
)"

[[ -z "${choice:-}" ]] && exit 0

for i in "${!menu_entries[@]}"; do
    if [[ "$choice" == "${menu_entries[$i]}" ]]; then
        apply_theme "${theme_files[$i]}"
        exit 0
    fi
done
