--- AppBorders.lua

local logger = hs.logger.new("AppBorders")
logger.i("Init")

-- 1. Variables must be global (no 'local') so they don't get garbage collected
global_border = nil
isBorderEnabled = false -- This tracks if the mode is ON or OFF

function initBorder()
    local win = hs.window.focusedWindow()
    local frame
    if win ~= nil then
        frame = win:frame()
    else
        frame = hs.geometry.new(0, 0, 0, 0)
    end
    
    global_border = hs.drawing.rectangle(frame)
    global_border:setStrokeColor({ ["red"] = 1, ["blue"] = 0, ["green"] = 0, ["alpha"] = 0.8 })
    global_border:setFill(false)
    global_border:setStrokeWidth(8)
    
    -- Only show if enabled
    if isBorderEnabled then
        global_border:show()
    end
end

function redrawBorder(window, name, event)
    -- If the toggle is OFF, make sure border is hidden and stop
    if not isBorderEnabled then
        if global_border then global_border:hide() end
        return 
    end

    -- Skip specific apps
    if name == 'Kontrollzentrum' then return end

    local win = hs.window.focusedWindow()
    if win ~= nil then
        -- Create the border object if it doesn't exist yet
        if not global_border then initBorder() end
        
        local newFrame = win:frame()
        local currentFrame = global_border:frame()
        
        if not newFrame:equals(currentFrame) then
            global_border:setFrame(newFrame)
        end
        global_border:show()
    else
        if global_border then global_border:hide() end
    end
end

-- 2. Setup the window filter (but it won't do anything until isBorderEnabled is true)
allwindows = hs.window.filter.new(nil)
allwindows:subscribe(hs.window.filter.windowCreated, redrawBorder)
allwindows:subscribe(hs.window.filter.windowDestroyed, redrawBorder)
allwindows:subscribe(hs.window.filter.windowFocused, redrawBorder)
allwindows:subscribe(hs.window.filter.windowMoved, redrawBorder)
allwindows:subscribe(hs.window.filter.windowUnfocused, redrawBorder)

-- 3. THE TOGGLE FUNCTION
function toggleAppBorders()
    isBorderEnabled = not isBorderEnabled
    
    if isBorderEnabled then
        hs.alert.show("Window Borders: ON")
        if not global_border then initBorder() end
        redrawBorder() -- Trigger immediate draw
    else
        hs.alert.show("Window Borders: OFF")
        if global_border then global_border:hide() end
    end
end

-- 4. THE HOTKEY (Change "B" or the modifiers to your liking)
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "B", function()
    toggleAppBorders()
end)
