--- Caffeine.lua

local obj = {}

-- 1. POPUP ON LOAD
hs.alert.show("Caffeine Loaded", 2)

-- 2. Create the menubar item
-- We use a unique ID just to keep things stable
obj.menu = hs.menubar.new(true, "CaffeineApp")

local on_message = 'Caffeine: ON'
local off_message = 'Caffeine: OFF'
local on_icon = "☕️" 
local off_icon = "😴"
-- Removed since HyperKey is global
-- local hyper = {"cmd", "alt", "ctrl"}

function obj:init(mod, key, description)

    local function setCaffeineDisplay(state)
        if state then
            hs.alert.show(on_message)
            if obj.menu then
                obj.menu:setTitle(on_icon)
                -- This ensures the hover text says "Caffeine: ON"
                obj.menu:setTooltip(on_message)
            end
        else
            hs.alert.show(off_message)
            if obj.menu then
                obj.menu:setTitle(off_icon)
                -- This ensures the hover text says "Caffeine: OFF"
                obj.menu:setTooltip(off_message)
            end
        end
    end

    local function caffeineClicked()
        -- Toggles the system sleep prevention and updates the UI
        setCaffeineDisplay(hs.caffeinate.toggle("displayIdle"))
    end

    if obj.menu then
        obj.menu:setClickCallback(caffeineClicked)
        -- Set initial state based on current system status
        setCaffeineDisplay(hs.caffeinate.get("displayIdle"))
    end

    -- Bind the hotkey (Cmd + Alt + Ctrl + C)
    hs.hotkey.bind(mod, key, caffeineClicked)
end

-- Initialize the object
obj:init(hyper, 'u', "Toggle Caffeine")

return obj
