#!/bin/bash

# Minimize All Windows - Simplified and Improved

osascript <<EOF
tell application "System Events"
    set allApps to name of (every process whose visible is true)
end tell

repeat with appName in allApps
    -- Skip problematic apps
    if appName is not in {"Finder", "SystemUIServer", "Dock", "Electron", "MSTeams", "nxdock"} and ¬
       appName does not contain "Helper" and ¬
       appName does not contain "Agent" then
        
        try
            -- Activate the app
            tell application appName
                activate
            end tell
            delay 1.0
            
            -- Make sure it's frontmost and send keystroke
            tell application "System Events"
                tell process appName
                    try
                        -- Ensure the process is frontmost
                        set frontmost to true
                        delay 0.3
                        
                        -- Send Command+M to minimize the frontmost window
                        keystroke "m" using command down
                    end try
                end tell
            end tell
            delay 0.3
        on error
            -- Skip apps that cause errors
        end try
    end if
end repeat

-- Handle Finder windows
tell application "Finder"
    try
        set allWindows to every Finder window
        repeat with aWindow in allWindows
            set miniaturized of aWindow to true
        end repeat
    end try
end tell
EOF

echo "Done minimizing all windows"
