#!/bin/bash
#
# slicksddm-customize - Interactive SDDM theme customization tool
#
# Copyright (C) 2026 Ubuntu Budgie Developers
# Licensed under GPLv3
#
# This script provides an interactive interface to customize the slickSDDM theme
# configuration without manually editing theme.conf files.
#

set -e

# Script metadata for help2man
SCRIPT_NAME="slicksddm-customize"
VERSION="1.0.0"
DESCRIPTION="Interactive customization tool for slickSDDM theme"

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Default paths
DEFAULT_THEME_DIR="/usr/share/sddm/themes"
THEME_NAME="${THEME_NAME:-ubuntu-budgie-login}"
THEME_DIR="${DEFAULT_THEME_DIR}/${THEME_NAME}"
CONFIG_FILE="${THEME_DIR}/theme.conf"
BACKUP_DIR="${HOME}/.config/sddm-theme-backups"

# Flags
INTERACTIVE=0
DRY_RUN=0
VERBOSE=0
NO_BACKUP=0

#######################################
# Print script version
#######################################
version() {
    cat << EOF
$SCRIPT_NAME $VERSION
Copyright (C) 2026 Ubuntu Budgie Developers
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
EOF
}

#######################################
# Print help message
#######################################
help() {
    cat << EOF
Usage: $SCRIPT_NAME [OPTION]...

Interactive customization tool for the slickSDDM theme.
Modify theme.conf settings without manual editing.

Options:
  -i, --interactive        Launch interactive configuration wizard
  -s, --set KEY=VALUE      Set a single configuration value
  -g, --get KEY            Get current value for a key
  -l, --list               List all current configuration settings
  -r, --reset              Reset to default configuration
      --reset-section SEC  Reset a specific section to defaults
  -b, --backup             Create backup of current configuration
      --restore FILE       Restore configuration from backup
  -t, --theme NAME         Specify theme name (default: ubuntu-budgie-login)
  -d, --theme-dir DIR      Specify theme directory
      --dry-run            Show what would be changed without applying
      --no-backup          Don't create automatic backup
  -v, --verbose            Enable verbose output
  -h, --help               Display this help and exit
  -V, --version            Display version information and exit

Interactive Mode:
  The interactive mode (-i) provides a menu-driven interface to customize:
    - General settings (scale, animations)
    - Lock screen appearance
    - Login screen layout
    - Colors and fonts
    - Menu buttons and popups
    - Virtual keyboard
    - Tooltips

Examples:
  $SCRIPT_NAME -i
      Launch interactive configuration wizard

  $SCRIPT_NAME --set "LoginScreen.LoginArea.Avatar/active-border-color=#ff0000"
      Set avatar border color to red

  $SCRIPT_NAME --get "LockScreen/background"
      Display current lock screen background

  $SCRIPT_NAME --list | grep color
      List all color-related settings

  $SCRIPT_NAME --backup
      Create timestamped backup of current configuration

  $SCRIPT_NAME --reset-section "LockScreen.Clock"
      Reset clock settings to defaults

  $SCRIPT_NAME --theme custom-theme --dry-run --set "General/scale=1.5"
      Preview scale change for a different theme

Configuration Keys:
  Keys follow the format: Section/key or Section.Subsection/key
  Examples:
    General/scale
    LockScreen/background
    LoginScreen.LoginArea.Avatar/shape
    LoginScreen.MenuArea.Power/display

  Use --list to see all available keys.

Files:
  ${CONFIG_FILE}
      Main theme configuration file

  ${BACKUP_DIR}/
      Automatic backup storage location

  /usr/share/doc/sddm-themes/CUSTOMIZATION.md
      Complete customization reference

Report bugs to: https://github.com/ubuntubudgie/slickSDDM/issues
Project home: https://ubuntubudgie.org
EOF
}

#######################################
# Print colored message
# Arguments:
#   $1 - Color code
#   $2 - Message
#######################################
print_color() {
    echo -e "${1}${2}${NC}"
}

#######################################
# Print error message and exit
# Arguments:
#   $1 - Error message
#   $2 - Exit code (default: 1)
#######################################
error_exit() {
    print_color "$RED" "Error: $1" >&2
    exit "${2:-1}"
}

#######################################
# Print warning message
# Arguments:
#   $1 - Warning message
#######################################
warning() {
    print_color "$YELLOW" "Warning: $1" >&2
}

#######################################
# Print info message
# Arguments:
#   $1 - Info message
#######################################
info() {
    print_color "$CYAN" "$1"
}

#######################################
# Print success message
# Arguments:
#   $1 - Success message
#######################################
success() {
    print_color "$GREEN" "✓ $1"
}

#######################################
# Print verbose message if verbose mode enabled
# Arguments:
#   $1 - Message
#######################################
verbose() {
    if [[ $VERBOSE -eq 1 ]]; then
        print_color "$BLUE" "[VERBOSE] $1"
    fi
}

#######################################
# Check if running with sufficient privileges
#######################################
check_privileges() {
    if [[ $EUID -ne 0 ]] && [[ $DRY_RUN -eq 0 ]]; then
        error_exit "This script must be run with sudo privileges to modify system files.
Try: sudo $SCRIPT_NAME $*" 2
    fi
}

#######################################
# Check if theme directory exists
#######################################
check_theme_exists() {
    if [[ ! -d "$THEME_DIR" ]]; then
        error_exit "Theme directory not found: $THEME_DIR
Please install the theme or specify correct path with --theme-dir" 3
    fi

    if [[ ! -f "$CONFIG_FILE" ]]; then
        error_exit "Configuration file not found: $CONFIG_FILE
Theme installation may be incomplete" 3
    fi
}

#######################################
# Create backup of configuration
# Returns:
#   0 on success, 1 on failure
#######################################
create_backup() {
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local backup_file="${BACKUP_DIR}/${THEME_NAME}_${timestamp}.conf"

    if [[ $NO_BACKUP -eq 1 ]]; then
        verbose "Backup skipped (--no-backup flag)"
        return 0
    fi

    mkdir -p "$BACKUP_DIR"
    
    if cp "$CONFIG_FILE" "$backup_file" 2>/dev/null; then
        success "Backup created: $backup_file"
        return 0
    else
        warning "Failed to create backup"
        return 1
    fi
}

#######################################
# Parse INI-style config file
# Arguments:
#   $1 - Section name (with subsections: "Section.Subsection")
#   $2 - Key name
# Outputs:
#   Current value of the key
# Returns:
#   0 if found, 1 if not found
#######################################
get_config_value() {
    local section="$1"
    local key="$2"
    local in_section=0
    local value=""

    # Convert section format: "Section.Subsection" -> "[Section.Subsection]"
    local section_header="[${section}]"

    while IFS= read -r line; do
        # Trim whitespace
        line=$(echo "$line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        
        # Skip empty lines and comments
        [[ -z "$line" || "$line" =~ ^# || "$line" =~ ^; ]] && continue

        # Check for section header
        if [[ "$line" =~ ^\[.*\]$ ]]; then
            if [[ "$line" == "$section_header" ]]; then
                in_section=1
            else
                in_section=0
            fi
            continue
        fi

        # If in correct section, look for key
        if [[ $in_section -eq 1 && "$line" =~ ^${key}[[:space:]]*= ]]; then
            value=$(echo "$line" | cut -d'=' -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
            echo "$value"
            return 0
        fi
    done < "$CONFIG_FILE"

    return 1
}

#######################################
# Set configuration value
# Arguments:
#   $1 - Section name
#   $2 - Key name
#   $3 - New value
#######################################
set_config_value() {
    local section="$1"
    local key="$2"
    local value="$3"
    local section_header="[${section}]"
    local temp_file="${CONFIG_FILE}.tmp"
    local in_section=0
    local key_found=0

    verbose "Setting ${section}/${key} = ${value}"

    if [[ $DRY_RUN -eq 1 ]]; then
        info "[DRY-RUN] Would set ${section}/${key} = ${value}"
        return 0
    fi

    # Read original file and modify
    while IFS= read -r line || [[ -n "$line" ]]; do
        # Check for section header
        if [[ "$line" =~ ^\[.*\]$ ]]; then
            if [[ "$line" == "$section_header" ]]; then
                in_section=1
            else
                # If we were in the section and didn't find the key, add it
                if [[ $in_section -eq 1 && $key_found -eq 0 ]]; then
                    echo "${key} = ${value}" >> "$temp_file"
                    key_found=1
                fi
                in_section=0
            fi
            echo "$line" >> "$temp_file"
            continue
        fi

        # If in correct section and found the key, replace it
        if [[ $in_section -eq 1 && "$line" =~ ^${key}[[:space:]]*= ]]; then
            echo "${key} = ${value}" >> "$temp_file"
            key_found=1
        else
            echo "$line" >> "$temp_file"
        fi
    done < "$CONFIG_FILE"

    # If section exists but key wasn't found, add it at the end of section
    if [[ $in_section -eq 1 && $key_found -eq 0 ]]; then
        echo "${key} = ${value}" >> "$temp_file"
    fi

    # If section doesn't exist at all, add it at the end
    if [[ $key_found -eq 0 ]]; then
        {
            echo ""
            echo "$section_header"
            echo "${key} = ${value}"
        } >> "$temp_file"
    fi

    # Replace original file
    mv "$temp_file" "$CONFIG_FILE"
    success "Updated ${section}/${key}"
}

#######################################
# List all configuration values
#######################################
list_config() {
    local current_section=""
    
    print_color "$BOLD" "Current Theme Configuration"
    echo "======================================"
    echo "Theme: $THEME_NAME"
    echo "Config: $CONFIG_FILE"
    echo "======================================"
    echo ""

    while IFS= read -r line; do
        # Trim whitespace
        line=$(echo "$line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        
        # Skip empty lines
        [[ -z "$line" ]] && continue

        # Check for comments
        if [[ "$line" =~ ^# || "$line" =~ ^\; ]]; then
            if [[ $VERBOSE -eq 1 ]]; then
                print_color "$BLUE" "$line"
            fi
            continue
        fi

        # Section header
        if [[ "$line" =~ ^\[.*\]$ ]]; then
            current_section=$(echo "$line" | tr -d '[]')
            echo ""
            print_color "$MAGENTA" "[$current_section]"
            continue
        fi

        # Key-value pair
        if [[ "$line" =~ = ]]; then
            local key=$(echo "$line" | cut -d'=' -f1 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
            local value=$(echo "$line" | cut -d'=' -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
            printf "  %-40s = %s\n" "$key" "$value"
        fi
    done < "$CONFIG_FILE"
}

#######################################
# Reset configuration to defaults
# Arguments:
#   $1 - Optional: specific section to reset
#######################################
reset_config() {
    local section="$1"
    local example_file="${THEME_DIR}/theme.conf.example"

    if [[ ! -f "$example_file" ]]; then
        error_exit "Example configuration not found: $example_file
Cannot reset without reference file" 4
    fi

    if [[ $DRY_RUN -eq 1 ]]; then
        if [[ -n "$section" ]]; then
            info "[DRY-RUN] Would reset section: $section"
        else
            info "[DRY-RUN] Would reset entire configuration"
        fi
        return 0
    fi

    # Create backup before reset
    create_backup

    if [[ -z "$section" ]]; then
        # Reset entire config
        print_color "$YELLOW" "This will reset ALL settings to defaults."
        read -p "Are you sure? (yes/no): " confirm
        if [[ "$confirm" != "yes" ]]; then
            info "Reset cancelled"
            return 0
        fi

        cp "$example_file" "$CONFIG_FILE"
        success "Configuration reset to defaults"
    else
        # Reset specific section
        warning "Resetting section: $section"
        
        # Extract section from example file and replace in config
        local temp_file="${CONFIG_FILE}.tmp"
        local in_target_section=0
        local section_header="[${section}]"

        # First, remove the old section
        while IFS= read -r line; do
            if [[ "$line" =~ ^\[.*\]$ ]]; then
                if [[ "$line" == "$section_header" ]]; then
                    in_target_section=1
                    continue
                else
                    in_target_section=0
                fi
            fi

            if [[ $in_target_section -eq 0 ]]; then
                echo "$line" >> "$temp_file"
            fi
        done < "$CONFIG_FILE"

        # Then append the new section from example
        in_target_section=0
        while IFS= read -r line; do
            if [[ "$line" =~ ^\[.*\]$ ]]; then
                if [[ "$line" == "$section_header" ]]; then
                    in_target_section=1
                    echo "$line" >> "$temp_file"
                    continue
                else
                    if [[ $in_target_section -eq 1 ]]; then
                        break
                    fi
                fi
            fi

            if [[ $in_target_section -eq 1 ]]; then
                echo "$line" >> "$temp_file"
            fi
        done < "$example_file"

        mv "$temp_file" "$CONFIG_FILE"
        success "Section $section reset to defaults"
    fi
}

#######################################
# Restore configuration from backup
# Arguments:
#   $1 - Backup file path
#######################################
restore_config() {
    local backup_file="$1"

    if [[ ! -f "$backup_file" ]]; then
        error_exit "Backup file not found: $backup_file" 5
    fi

    if [[ $DRY_RUN -eq 1 ]]; then
        info "[DRY-RUN] Would restore from: $backup_file"
        return 0
    fi

    # Create backup of current config before restoring
    create_backup

    cp "$backup_file" "$CONFIG_FILE"
    success "Configuration restored from: $backup_file"
}

#######################################
# Restart SDDM service
#######################################
restart_sddm() {
    if [[ $DRY_RUN -eq 1 ]]; then
        info "[DRY-RUN] Would restart SDDM service"
        return 0
    fi

    print_color "$YELLOW" "Restart SDDM to apply changes?"
    echo "This will log you out of the current session."
    read -p "Restart now? (yes/no): " confirm

    if [[ "$confirm" == "yes" ]]; then
        info "Restarting SDDM..."
        systemctl restart sddm
    else
        info "Skipped. Restart later with: sudo systemctl restart sddm"
    fi
}

#######################################
# Interactive menu - Main
#######################################
interactive_main_menu() {
    while true; do
        clear
        print_color "$BOLD$CYAN" "╔════════════════════════════════════════════╗"
        print_color "$BOLD$CYAN" "║   slickSDDM Theme Configuration Wizard    ║"
        print_color "$BOLD$CYAN" "╚════════════════════════════════════════════╝"
        echo ""
        echo "Theme: $THEME_NAME"
        echo "Config: $CONFIG_FILE"
        echo ""
        echo "1) General Settings"
        echo "2) Lock Screen"
        echo "3) Login Screen"
        echo "4) Colors & Fonts"
        echo "5) Menu Buttons"
        echo "6) Virtual Keyboard"
        echo "7) Tooltips"
        echo ""
        echo "8) View Current Configuration"
        echo "9) Backup Configuration"
        echo "10) Restore from Backup"
        echo "11) Reset to Defaults"
        echo ""
        echo "Q) Quit (and restart SDDM)"
        echo "X) Exit (without restart)"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1) interactive_general_settings ;;
            2) interactive_lockscreen ;;
            3) interactive_loginscreen ;;
            4) interactive_colors_fonts ;;
            5) interactive_menu_buttons ;;
            6) interactive_virtual_keyboard ;;
            7) interactive_tooltips ;;
            8) list_config | less ;;
            9) create_backup; read -p "Press Enter to continue..." ;;
            10) interactive_restore_backup ;;
            11) interactive_reset ;;
            [Qq]) restart_sddm; exit 0 ;;
            [Xx]) info "Exiting without restart"; exit 0 ;;
            *) warning "Invalid option" ; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - General Settings
#######################################
interactive_general_settings() {
    while true; do
        clear
        print_color "$BOLD" "General Settings"
        echo "════════════════"
        echo ""
        echo "Current values:"
        echo "  Scale: $(get_config_value "General" "scale")"
        echo "  Animations: $(get_config_value "General" "enable-animations")"
        echo "  Background Fill Mode: $(get_config_value "General" "background-fill-mode")"
        echo ""
        echo "1) Set UI Scale (0.5 - 2.0)"
        echo "2) Toggle Animations (true/false)"
        echo "3) Set Background Fill Mode (fill/fit/stretch)"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                read -p "Enter scale value (0.5 - 2.0): " scale
                if [[ "$scale" =~ ^[0-9]*\.?[0-9]+$ ]] && \
                   (( $(echo "$scale >= 0.5" | bc -l) )) && \
                   (( $(echo "$scale <= 2.0" | bc -l) )); then
                    set_config_value "General" "scale" "$scale"
                else
                    warning "Invalid scale value"
                fi
                read -p "Press Enter to continue..."
                ;;
            2)
                current=$(get_config_value "General" "enable-animations")
                if [[ "$current" == "true" ]]; then
                    new_value="false"
                else
                    new_value="true"
                fi
                set_config_value "General" "enable-animations" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            3)
                echo "Select fill mode:"
                echo "1) fill - Scale to fill, may crop"
                echo "2) fit - Scale to fit, may show borders"
                echo "3) stretch - Stretch to fill, may distort"
                read -p "Choice (1-3): " mode_choice
                case $mode_choice in
                    1) set_config_value "General" "background-fill-mode" "fill" ;;
                    2) set_config_value "General" "background-fill-mode" "fit" ;;
                    3) set_config_value "General" "background-fill-mode" "stretch" ;;
                    *) warning "Invalid choice" ;;
                esac
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Lock Screen
#######################################
interactive_lockscreen() {
    while true; do
        clear
        print_color "$BOLD" "Lock Screen Settings"
        echo "════════════════════"
        echo ""
        echo "1) Set Background Image/Video"
        echo "2) Set Background Color"
        echo "3) Toggle Lock Screen Display"
        echo "4) Adjust Blur Amount"
        echo "5) Configure Clock"
        echo "6) Configure Date"
        echo "7) Configure Message"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                read -p "Enter background path: " bg_path
                set_config_value "LockScreen" "background" "$bg_path"
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter color (hex, e.g., #000000): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LockScreen" "background-color" "$color"
                    set_config_value "LockScreen" "use-background-color" "true"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            3)
                current=$(get_config_value "LockScreen" "display")
                if [[ "$current" == "true" ]]; then
                    new_value="false"
                else
                    new_value="true"
                fi
                set_config_value "LockScreen" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            4)
                read -p "Enter blur amount (0-100): " blur
                if [[ "$blur" =~ ^[0-9]+$ ]] && [ "$blur" -ge 0 ] && [ "$blur" -le 100 ]; then
                    set_config_value "LockScreen" "blur" "$blur"
                else
                    warning "Invalid blur value"
                fi
                read -p "Press Enter to continue..."
                ;;
            5) interactive_lockscreen_clock ;;
            6) interactive_lockscreen_date ;;
            7) interactive_lockscreen_message ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Lock Screen Clock
#######################################
interactive_lockscreen_clock() {
    while true; do
        clear
        print_color "$BOLD" "Lock Screen Clock"
        echo "═════════════════"
        echo ""
        echo "Current: $(get_config_value "LockScreen.Clock" "format")"
        echo "  Font: $(get_config_value "LockScreen.Clock" "font-family")"
        echo "  Size: $(get_config_value "LockScreen.Clock" "font-size")"
        echo "  Color: $(get_config_value "LockScreen.Clock" "color")"
        echo ""
        echo "1) Toggle Clock Display"
        echo "2) Set Time Format (e.g., hh:mm or h:mm AP)"
        echo "3) Set Font Family"
        echo "4) Set Font Size"
        echo "5) Set Color"
        echo "6) Set Position"
        echo ""
        echo "B) Back"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                current=$(get_config_value "LockScreen.Clock" "display")
                if [[ "$current" == "true" ]]; then
                    new_value="false"
                else
                    new_value="true"
                fi
                set_config_value "LockScreen.Clock" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter time format (e.g., hh:mm): " format
                set_config_value "LockScreen.Clock" "format" "$format"
                read -p "Press Enter to continue..."
                ;;
            3)
                read -p "Enter font family: " font
                set_config_value "LockScreen.Clock" "font-family" "$font"
                read -p "Press Enter to continue..."
                ;;
            4)
                read -p "Enter font size: " size
                if [[ "$size" =~ ^[0-9]+$ ]]; then
                    set_config_value "LockScreen.Clock" "font-size" "$size"
                else
                    warning "Invalid font size"
                fi
                read -p "Press Enter to continue..."
                ;;
            5)
                read -p "Enter color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LockScreen.Clock" "color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            6)
                echo "Position options:"
                echo "1) top-left     2) top-center     3) top-right"
                echo "4) center-left  5) center         6) center-right"
                echo "7) bottom-left  8) bottom-center  9) bottom-right"
                read -p "Select (1-9): " pos
                positions=("" "top-left" "top-center" "top-right" "center-left" "center" "center-right" "bottom-left" "bottom-center" "bottom-right")
                if [[ "$pos" =~ ^[1-9]$ ]]; then
                    set_config_value "LockScreen.Clock" "position" "${positions[$pos]}"
                else
                    warning "Invalid position"
                fi
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Lock Screen Date
#######################################
interactive_lockscreen_date() {
    while true; do
        clear
        print_color "$BOLD" "Lock Screen Date"
        echo "════════════════"
        echo ""
        echo "Current: $(get_config_value "LockScreen.Date" "format")"
        echo "  Color: $(get_config_value "LockScreen.Date" "color")"
        echo ""
        echo "1) Toggle Date Display"
        echo "2) Set Date Format (e.g., dddd dd MMMM)"
        echo "3) Set Color"
        echo ""
        echo "B) Back"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                current=$(get_config_value "LockScreen.Date" "display")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LockScreen.Date" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter date format: " format
                set_config_value "LockScreen.Date" "format" "$format"
                read -p "Press Enter to continue..."
                ;;
            3)
                read -p "Enter color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LockScreen.Date" "color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Lock Screen Message
#######################################
interactive_lockscreen_message() {
    while true; do
        clear
        print_color "$BOLD" "Lock Screen Message"
        echo "═══════════════════"
        echo ""
        echo "Current: $(get_config_value "LockScreen.Message" "text")"
        echo ""
        echo "1) Toggle Message Display"
        echo "2) Set Message Text"
        echo "3) Set Message Color"
        echo ""
        echo "B) Back"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                current=$(get_config_value "LockScreen.Message" "display")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LockScreen.Message" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter message text: " text
                set_config_value "LockScreen.Message" "text" "$text"
                read -p "Press Enter to continue..."
                ;;
            3)
                read -p "Enter color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LockScreen.Message" "color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Login Screen (simplified)
#######################################
interactive_loginscreen() {
    while true; do
        clear
        print_color "$BOLD" "Login Screen Settings"
        echo "═════════════════════"
        echo ""
        echo "1) Set Background"
        echo "2) Configure Avatar"
        echo "3) Configure Password Input"
        echo "4) Configure Login Button"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                read -p "Enter background path: " bg_path
                set_config_value "LoginScreen" "background" "$bg_path"
                read -p "Press Enter to continue..."
                ;;
            2) interactive_loginscreen_avatar ;;
            3) interactive_loginscreen_password ;;
            4) interactive_loginscreen_button ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Avatar
#######################################
interactive_loginscreen_avatar() {
    while true; do
        clear
        print_color "$BOLD" "Avatar Settings"
        echo "═══════════════"
        echo ""
        echo "Shape: $(get_config_value "LoginScreen.LoginArea.Avatar" "shape")"
        echo "Border Color: $(get_config_value "LoginScreen.LoginArea.Avatar" "active-border-color")"
        echo ""
        echo "1) Set Shape (circle/square)"
        echo "2) Set Active Border Color"
        echo "3) Set Border Radius (for square)"
        echo ""
        echo "B) Back"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                echo "1) circle"
                echo "2) square"
                read -p "Select (1-2): " shape_choice
                case $shape_choice in
                    1) set_config_value "LoginScreen.LoginArea.Avatar" "shape" "circle" ;;
                    2) set_config_value "LoginScreen.LoginArea.Avatar" "shape" "square" ;;
                    *) warning "Invalid choice" ;;
                esac
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter border color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LoginScreen.LoginArea.Avatar" "active-border-color" "$color"
                    set_config_value "LoginScreen.LoginArea.Avatar" "inactive-border-color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            3)
                read -p "Enter border radius (0-100): " radius
                if [[ "$radius" =~ ^[0-9]+$ ]]; then
                    set_config_value "LoginScreen.LoginArea.Avatar" "border-radius" "$radius"
                else
                    warning "Invalid radius"
                fi
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Password Input
#######################################
interactive_loginscreen_password() {
    while true; do
        clear
        print_color "$BOLD" "Password Input Settings"
        echo "═══════════════════════"
        echo ""
        echo "Border Color: $(get_config_value "LoginScreen.LoginArea.PasswordInput" "border-color")"
        echo ""
        echo "1) Set Border Color"
        echo "2) Set Background Opacity"
        echo ""
        echo "B) Back"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                read -p "Enter border color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LoginScreen.LoginArea.PasswordInput" "border-color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter opacity (0.0 - 1.0): " opacity
                if [[ "$opacity" =~ ^[0-1](\.[0-9]+)?$ ]]; then
                    set_config_value "LoginScreen.LoginArea.PasswordInput" "background-opacity" "$opacity"
                else
                    warning "Invalid opacity value"
                fi
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Login Button
#######################################
interactive_loginscreen_button() {
    while true; do
        clear
        print_color "$BOLD" "Login Button Settings"
        echo "═════════════════════"
        echo ""
        echo "Active Color: $(get_config_value "LoginScreen.LoginArea.LoginButton" "active-background-color")"
        echo ""
        echo "1) Set Active Background Color"
        echo "2) Set Content Color"
        echo ""
        echo "B) Back"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                read -p "Enter background color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LoginScreen.LoginArea.LoginButton" "active-background-color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            2)
                read -p "Enter content color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    set_config_value "LoginScreen.LoginArea.LoginButton" "content-color" "$color"
                else
                    warning "Invalid color format"
                fi
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Colors & Fonts (Quick Presets)
#######################################
interactive_colors_fonts() {
    while true; do
        clear
        print_color "$BOLD" "Colors & Fonts - Quick Presets"
        echo "══════════════════════════════"
        echo ""
        echo "1) Apply Blue Theme (Ubuntu Budgie)"
        echo "2) Apply Purple Theme"
        echo "3) Apply Green Theme"
        echo "4) Apply Orange Theme"
        echo "5) Apply Red Theme"
        echo "6) Custom Accent Color"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1) apply_color_theme "#5294e2" "Budgie Blue" ;;
            2) apply_color_theme "#9b59b6" "Purple" ;;
            3) apply_color_theme "#2ecc71" "Green" ;;
            4) apply_color_theme "#f39c12" "Orange" ;;
            5) apply_color_theme "#e74c3c" "Red" ;;
            6)
                read -p "Enter accent color (hex): " color
                if [[ "$color" =~ ^#[0-9A-Fa-f]{6}$ ]]; then
                    apply_color_theme "$color" "Custom"
                else
                    warning "Invalid color format"
                    read -p "Press Enter to continue..."
                fi
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Apply color theme
# Arguments:
#   $1 - Accent color (hex)
#   $2 - Theme name
#######################################
apply_color_theme() {
    local color="$1"
    local name="$2"

    info "Applying $name theme with accent color: $color"

    # Avatar
    set_config_value "LoginScreen.LoginArea.Avatar" "active-border-color" "$color"
    set_config_value "LoginScreen.LoginArea.Avatar" "inactive-border-color" "$color"

    # Password Input
    set_config_value "LoginScreen.LoginArea.PasswordInput" "border-color" "$color"

    # Login Button
    set_config_value "LoginScreen.LoginArea.LoginButton" "content-color" "$color"
    set_config_value "LoginScreen.LoginArea.LoginButton" "active-background-color" "$color"

    # Menu buttons
    set_config_value "LoginScreen.MenuArea.Session" "active-content-color" "$color"
    set_config_value "LoginScreen.MenuArea.Layout" "active-content-color" "$color"
    set_config_value "LoginScreen.MenuArea.Keyboard" "active-content-color" "$color"
    set_config_value "LoginScreen.MenuArea.Power" "active-content-color" "$color"

    # Popups
    set_config_value "LoginScreen.MenuArea.Popups" "active-content-color" "$color"
    set_config_value "LoginScreen.MenuArea.Popups" "border-color" "$color"

    # Virtual Keyboard
    set_config_value "LoginScreen.VirtualKeyboard" "primary-color" "$color"
    set_config_value "LoginScreen.VirtualKeyboard" "selection-background-color" "$color"
    set_config_value "LoginScreen.VirtualKeyboard" "border-color" "$color"

    success "$name theme applied!"
    read -p "Press Enter to continue..."
}

#######################################
# Interactive menu - Menu Buttons (simplified)
#######################################
interactive_menu_buttons() {
    while true; do
        clear
        print_color "$BOLD" "Menu Buttons"
        echo "════════════"
        echo ""
        echo "1) Toggle Session Button"
        echo "2) Toggle Layout Button"
        echo "3) Toggle Keyboard Button"
        echo "4) Toggle Power Button"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                current=$(get_config_value "LoginScreen.MenuArea.Session" "display")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LoginScreen.MenuArea.Session" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            2)
                current=$(get_config_value "LoginScreen.MenuArea.Layout" "display")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LoginScreen.MenuArea.Layout" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            3)
                current=$(get_config_value "LoginScreen.MenuArea.Keyboard" "display")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LoginScreen.MenuArea.Keyboard" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            4)
                current=$(get_config_value "LoginScreen.MenuArea.Power" "display")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LoginScreen.MenuArea.Power" "display" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Virtual Keyboard
#######################################
interactive_virtual_keyboard() {
    while true; do
        clear
        print_color "$BOLD" "Virtual Keyboard Settings"
        echo "═════════════════════════"
        echo ""
        echo "Scale: $(get_config_value "LoginScreen.VirtualKeyboard" "scale")"
        echo "Start Hidden: $(get_config_value "LoginScreen.VirtualKeyboard" "start-hidden")"
        echo ""
        echo "1) Set Scale (0.5 - 2.0)"
        echo "2) Toggle Start Hidden"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                read -p "Enter scale (0.5 - 2.0): " scale
                if [[ "$scale" =~ ^[0-9]*\.?[0-9]+$ ]]; then
                    set_config_value "LoginScreen.VirtualKeyboard" "scale" "$scale"
                else
                    warning "Invalid scale value"
                fi
                read -p "Press Enter to continue..."
                ;;
            2)
                current=$(get_config_value "LoginScreen.VirtualKeyboard" "start-hidden")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "LoginScreen.VirtualKeyboard" "start-hidden" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Tooltips
#######################################
interactive_tooltips() {
    while true; do
        clear
        print_color "$BOLD" "Tooltip Settings"
        echo "════════════════"
        echo ""
        echo "Enabled: $(get_config_value "Tooltips" "enable")"
        echo ""
        echo "1) Toggle Tooltips"
        echo ""
        echo "B) Back to main menu"
        echo ""
        read -p "Select option: " choice

        case $choice in
            1)
                current=$(get_config_value "Tooltips" "enable")
                new_value=$([[ "$current" == "true" ]] && echo "false" || echo "true")
                set_config_value "Tooltips" "enable" "$new_value"
                read -p "Press Enter to continue..."
                ;;
            [Bb]) return ;;
            *) warning "Invalid option"; read -p "Press Enter to continue..." ;;
        esac
    done
}

#######################################
# Interactive menu - Restore Backup
#######################################
interactive_restore_backup() {
    clear
    print_color "$BOLD" "Restore from Backup"
    echo "═══════════════════"
    echo ""

    if [[ ! -d "$BACKUP_DIR" ]] || [[ -z "$(ls -A "$BACKUP_DIR" 2>/dev/null)" ]]; then
        warning "No backups found in $BACKUP_DIR"
        read -p "Press Enter to continue..."
        return
    fi

    echo "Available backups:"
    echo ""
    
    local backups=()
    local i=1
    while IFS= read -r backup; do
        backups+=("$backup")
        echo "$i) $(basename "$backup")"
        ((i++))
    done < <(ls -t "$BACKUP_DIR"/*.conf 2>/dev/null)

    echo ""
    echo "B) Back"
    echo ""
    read -p "Select backup to restore: " choice

    if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -lt "$i" ]; then
        local selected="${backups[$((choice-1))]}"
        print_color "$YELLOW" "Restore from: $(basename "$selected")"
        read -p "Are you sure? (yes/no): " confirm
        if [[ "$confirm" == "yes" ]]; then
            restore_config "$selected"
        else
            info "Restore cancelled"
        fi
    elif [[ "$choice" =~ ^[Bb]$ ]]; then
        return
    else
        warning "Invalid selection"
    fi

    read -p "Press Enter to continue..."
}

#######################################
# Interactive menu - Reset
#######################################
interactive_reset() {
    clear
    print_color "$BOLD" "Reset Configuration"
    echo "═══════════════════"
    echo ""
    print_color "$YELLOW" "WARNING: This will reset settings to defaults!"
    echo ""
    echo "1) Reset entire configuration"
    echo "2) Reset specific section"
    echo ""
    echo "B) Back (cancel)"
    echo ""
    read -p "Select option: " choice

    case $choice in
        1)
            reset_config ""
            ;;
        2)
            echo ""
            echo "Enter section name (e.g., LockScreen.Clock):"
            read -p "> " section
            if [[ -n "$section" ]]; then
                reset_config "$section"
            else
                warning "No section specified"
            fi
            ;;
        [Bb])
            return
            ;;
        *)
            warning "Invalid option"
            ;;
    esac

    read -p "Press Enter to continue..."
}

#######################################
# Parse command line arguments
#######################################
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -i|--interactive)
                INTERACTIVE=1
                shift
                ;;
            -s|--set)
                if [[ -z "$2" ]]; then
                    error_exit "Option --set requires an argument (KEY=VALUE)"
                fi
                SET_VALUE="$2"
                shift 2
                ;;
            -g|--get)
                if [[ -z "$2" ]]; then
                    error_exit "Option --get requires an argument (KEY)"
                fi
                GET_KEY="$2"
                shift 2
                ;;
            -l|--list)
                LIST=1
                shift
                ;;
            -r|--reset)
                RESET=1
                shift
                ;;
            --reset-section)
                if [[ -z "$2" ]]; then
                    error_exit "Option --reset-section requires an argument"
                fi
                RESET_SECTION="$2"
                shift 2
                ;;
            -b|--backup)
                BACKUP=1
                shift
                ;;
            --restore)
                if [[ -z "$2" ]]; then
                    error_exit "Option --restore requires an argument (FILE)"
                fi
                RESTORE_FILE="$2"
                shift 2
                ;;
            -t|--theme)
                if [[ -z "$2" ]]; then
                    error_exit "Option --theme requires an argument"
                fi
                THEME_NAME="$2"
                THEME_DIR="${DEFAULT_THEME_DIR}/${THEME_NAME}"
                CONFIG_FILE="${THEME_DIR}/theme.conf"
                shift 2
                ;;
            -d|--theme-dir)
                if [[ -z "$2" ]]; then
                    error_exit "Option --theme-dir requires an argument"
                fi
                THEME_DIR="$2"
                CONFIG_FILE="${THEME_DIR}/theme.conf"
                shift 2
                ;;
            --dry-run)
                DRY_RUN=1
                shift
                ;;
            --no-backup)
                NO_BACKUP=1
                shift
                ;;
            -v|--verbose)
                VERBOSE=1
                shift
                ;;
            -h|--help)
                help
                exit 0
                ;;
            -V|--version)
                version
                exit 0
                ;;
            *)
                error_exit "Unknown option: $1
Try '$SCRIPT_NAME --help' for more information."
                ;;
        esac
    done
}

#######################################
# Main execution
#######################################
main() {
    parse_args "$@"

    # Check theme exists
    check_theme_exists

    # Handle different modes
    if [[ $INTERACTIVE -eq 1 ]]; then
        check_privileges "$@"
        interactive_main_menu
    elif [[ -n "$SET_VALUE" ]]; then
        check_privileges "$@"
        # Parse KEY=VALUE
        local key="${SET_VALUE%%=*}"
        local value="${SET_VALUE#*=}"
        local section="${key%%/*}"
        local key_name="${key#*/}"
        
        if [[ "$section" == "$key" ]] || [[ -z "$key_name" ]]; then
            error_exit "Invalid format. Use: Section/key=value or Section.Subsection/key=value"
        fi

        create_backup
        set_config_value "$section" "$key_name" "$value"
        
        if [[ $DRY_RUN -eq 0 ]]; then
            info "Remember to restart SDDM: sudo systemctl restart sddm"
        fi
    elif [[ -n "$GET_KEY" ]]; then
        local section="${GET_KEY%%/*}"
        local key_name="${GET_KEY#*/}"
        
        if [[ "$section" == "$GET_KEY" ]] || [[ -z "$key_name" ]]; then
            error_exit "Invalid format. Use: Section/key or Section.Subsection/key"
        fi

        value=$(get_config_value "$section" "$key_name")
        if [[ $? -eq 0 ]]; then
            echo "$value"
        else
            error_exit "Key not found: $GET_KEY" 6
        fi
    elif [[ $LIST -eq 1 ]]; then
        list_config
    elif [[ $RESET -eq 1 ]]; then
        check_privileges "$@"
        reset_config ""
    elif [[ -n "$RESET_SECTION" ]]; then
        check_privileges "$@"
        reset_config "$RESET_SECTION"
    elif [[ $BACKUP -eq 1 ]]; then
        create_backup
    elif [[ -n "$RESTORE_FILE" ]]; then
        check_privileges "$@"
        restore_config "$RESTORE_FILE"
    else
        # No options provided
        help
        exit 0
    fi
}

# Run main function
main "$@"
