local prod = {}

-- ==========================================
-- 1. SMART APP SWITCHER (Focus & Mouse Center)
-- ==========================================
function prod.focusApp(appName)
    local app = hs.application.get(appName)
    if app then
        local window = app:mainWindow()
        if window then
            window:unminimize()
            window:focus()
            local f = window:frame()
            -- Centers mouse on the focused window
            hs.mouse.absolutePosition({x = f.x + f.w/2, y = f.y + f.h/2})
        end
    else
        hs.application.launchOrFocus(appName)
    end
end

-- KEY BINDINGS for Item 1
hs.hotkey.bind({"alt"}, "T", function() prod.focusApp("Terminal") end)
hs.hotkey.bind({"alt"}, "G", function() prod.focusApp("Gemini") end)
hs.hotkey.bind({"alt"}, "V", function() prod.focusApp("Visual Studio Code") end)

-- ==========================================
-- 2. GHOST HUNTER (Cleanup & Panic Reset)
-- ==========================================
function prod.ghostHunter()
    local windows = hs.window.allWindows()
    local zombies = 0
    local rescued = 0
    
    for _, win in ipairs(windows) do
        local app = win:application()
        local frame = win:frame()
        
        -- Identify Zombie (No app or no title)
        if not app or (win:title() == "" and not win:isStandard()) then
            zombies = zombies + 1
        end
        
        -- Rescuing windows stuck in "Deep Space" (off-screen coordinates)
        if frame.x < -5000 or frame.y < -5000 or frame.x > 10000 or frame.y > 10000 then
            win:moveToScreen(hs.screen.primaryScreen())
            rescued = rescued + 1
        end
    end

    -- FIX: Replaced forceRefresh() with the default window filter refresh
    hs.window.filter.default:getWindows()
    
    hs.alert.show(string.format("Hunter: %d Ghosts | %d Rescued", zombies, rescued), 2)
end

-- KEY BINDING for Item 2 (Panic Key)
hs.hotkey.bind({"shift", "alt"}, "G", prod.ghostHunter)

-- ==========================================
-- 3. CONTEXTUAL MODES (Workspaces)
-- ==========================================
function prod.modeArchitecture()
    hs.alert.show("Mode: Architecture (Deep Work)", 2)
    hs.application.launchOrFocus("Visual Studio Code")
    hs.application.launchOrFocus("Terminal")
    -- Hide distractions
    local teams = hs.application.get("Microsoft Teams")
    if teams then teams:hide() end
end

function prod.modeCommunication()
    hs.alert.show("Mode: Communication (Email/Teams)", 2)
    hs.application.launchOrFocus("Microsoft Outlook")
    hs.application.launchOrFocus("Microsoft Teams")
end

-- KEY BINDINGS for Item 3
hs.hotkey.bind({"shift", "alt"}, "A", prod.modeArchitecture)
hs.hotkey.bind({"shift", "alt"}, "C", prod.modeCommunication)

-- Loading notification
hs.alert.show("🚀 Productivity Tools Loaded", 1.5)

return prod