#!/usr/bin/env bash

THEMES_DIR="/home/jannick/.config/elnixy/themes"
CURRENT_LINK="/home/jannick/.config/elnixy/current/theme"
WALLPAPERS_DIR="/home/jannick/.config/elnixy/wallpapers"

# Available themes in order
THEMES=("tokyo-night" "catppuccin-mocha" "gruvbox-dark" "nord" "everforest" "kanagawa")

# Get current theme
if [[ -L "$CURRENT_LINK" ]]; then
    CURRENT_THEME=$(basename "$(readlink "$CURRENT_LINK")")
else
    CURRENT_THEME="catppuccin-mocha"
fi

# Find current theme index
CURRENT_INDEX=-1
for i in "${!THEMES[@]}"; do
    if [[ "${THEMES[$i]}" == "$CURRENT_THEME" ]]; then
        CURRENT_INDEX=$i
        break
    fi
done

# Get next theme (cycle back to 0 if at end)
NEXT_INDEX=$(( (CURRENT_INDEX + 1) % ${#THEMES[@]} ))
NEXT_THEME="${THEMES[$NEXT_INDEX]}"

echo "Switching from $CURRENT_THEME to $NEXT_THEME..."

# Update theme symlink first (remove existing then create new)
rm -f "$CURRENT_LINK"
ln -sf "$THEMES_DIR/$NEXT_THEME" "$CURRENT_LINK"

# Update wallpaper to first wallpaper in theme
WALLPAPER_PATH=$(find "$WALLPAPERS_DIR/$NEXT_THEME" -type f \( -name "*.jpg" -o -name "*.png" \) | head -1)
if [[ -n "$WALLPAPER_PATH" ]]; then
    ln -sf "$WALLPAPER_PATH" "/home/jannick/.config/elnixy/current/wallpaper"
fi

# Reload applications
makoctl reload 2>/dev/null || true
pkill -SIGUSR2 waybar 2>/dev/null || true
hyprctl reload

# Reload ghostty config - new ghostty windows will pick up the new theme automatically
# For existing windows, user can press ctrl+shift+, or restart terminal

# Update wallpaper (after hyprctl reload)
if [[ -n "$WALLPAPER_PATH" ]]; then
    pkill hyprpaper 2>/dev/null || true
    sleep 0.2
    nohup hyprpaper > /dev/null 2>&1 &
fi

# Show notification about theme change (after a delay to ensure mako reloaded)
sleep 0.3
notify-send -t 3000 -a "elnixy" -u low "Theme switched to $NEXT_THEME"

echo "Theme switched to $NEXT_THEME"