-- ~/.hammerspoon/Focus.lua
local Focus = {}
local hiddenAppBundleIDs = {}

function Focus.toggle()
    local frontApp = hs.application.frontmostApplication()
    
    -- UNFOCUS: Bring back only what WE hid
    if #hiddenAppBundleIDs > 0 then
        local count = 0
        for _, bid in ipairs(hiddenAppBundleIDs) do
            local app = hs.application.get(bid)
            if app then 
                app:unhide() 
                count = count + 1
            end
        end
        hiddenAppBundleIDs = {}
        hs.alert.show("Focus Off: " .. count .. " apps restored")
        return
    end

    -- FOCUS: Hide background apps instantly
    local allApps = hs.application.runningApplications()
    local count = 0
    
    for _, app in ipairs(allApps) do
        local bid = app:bundleID()
        local name = app:name()

        -- Hide if: Not current app, has a window, isn't already hidden, and isn't Hammerspoon
        if app ~= frontApp and bid and app:mainWindow() and not app:isHidden() then
            if bid ~= "org.hammerspoon.Hammerspoon" and name ~= "Hammerspoon" then
                table.insert(hiddenAppBundleIDs, bid)
                app:hide()
                count = count + 1
            end
        end
    end
    
    if count > 0 then
        hs.alert.show("Focus On: " .. count .. " apps hidden")
    else
        hs.alert.show("Already Focused")
    end
end

hs.hotkey.bind(hyper, "F", Focus.toggle)

print("Focus Module: Stable App-Only Version Loaded")
return Focus