#!/run/current-system/sw/bin/bash

# Firefox search script for wofi + hyprland
# Usage: firefox-search [search term]

# Read search term from argument or prompt with wofi
if [ -n "$1" ]; then
    search_term="$1"
else
    # Show wofi with just search bar, no suggestions
    search_term=$(echo "" | wofi --dmenu --prompt "Search Firefox:" --cache-file=/dev/null --lines=0)
fi

# Exit if no search term provided or cancelled
if [ -z "$search_term" ]; then
    exit 0
fi

# Check if Firefox is running
firefox_class=$(hyprctl clients | grep -q "class: firefox" && echo "found" || echo "")

if [ -n "$firefox_class" ]; then
    # Firefox is running, focus it and send search
    hyprctl dispatch focuswindow "class:firefox"
    sleep 0.3
    
    # Open new tab and search using xdotool (if available) or hyprctl
    if command -v xdotool &> /dev/null; then
        xdotool key ctrl+t
        sleep 0.3
        xdotool type "$search_term"
        sleep 0.1
        xdotool key Return
    else
        # Fallback: use Firefox remote commands
        firefox --new-tab "https://www.google.com/search?q=$(echo "$search_term" | sed 's/ /+/g')" &
    fi
else
    # Firefox not running, start it with search
    firefox --search "$search_term" &
    sleep 1.5
    hyprctl dispatch focuswindow "class:firefox"
fi