#!/bin/sh

# Check if tofi is running
if pgrep -x "tofi" > /dev/null; then
    # Passing as regular tab
    ydotool key 15:1 15:0
    exit
fi


# Get a list of open windows
WINDOWS=$(hyprctl clients | grep "title: " | sed 's/.*title: //')

# If there are no open windows, exit
[ -z "$WINDOWS" ] && exit

# Use tofi to select a window
SELECTED=$(echo "$WINDOWS" | tofi --num-results 10 --padding-left 20% --padding-top 20% --prompt-text "Select a window: ")

# If a window was selected, focus it
if [ -n "$SELECTED" ]; then
    echo "Focusing window: $SELECTED"
    # Check if the selected window is on special workspace
    # hyprctl clients | grep "$SELECTED" -A 10 | grep workspace
    # returns like workspace: -98 (special:magic)
    workspace=$(hyprctl clients | grep "$SELECTED" -A 10 | grep workspace)
    # if workspace is special, try to focus it
    if [[ $workspace == *"special:"* ]]; then
        # Get the workspace name (after the colon)
        workspace_name=$(echo "$workspace" | sed -E 's/.*:\s*([^)]*).*/\1/')
        # Remove number and prefix
        
        echo "Focusing special workspace: $workspace_name"
        # Focus the workspace
        hyprctl dispatch togglespecialworkspace "$workspace_name"
    fi
    # Get the window ID
    window_id=$(hyprctl clients | grep "$SELECTED" -A 10 | grep pid)
    # Get the window ID (after the colon)
    window_id=$(echo "$window_id" | sed -E 's/.*:\s*([^)]*).*/\1/')
    echo "Window ID: $window_id"

    hyprctl dispatch focuswindow pid:"$window_id"
fi
