local addonName, ns = ...

-- Main addon frame
local addon = CreateFrame("Frame")
addon:RegisterEvent("ADDON_LOADED")
addon:RegisterEvent("PLAYER_LOGIN")
addon:RegisterEvent("PLAYER_LOGOUT")

-- Event handler
addon:SetScript("OnEvent", function(self, event, ...)
    if event == "ADDON_LOADED" then
        local loadedAddon = ...
        if loadedAddon == addonName then
            ns.OnAddonLoaded()
        end
    elseif event == "PLAYER_LOGIN" then
        ns.OnPlayerLogin()
    elseif event == "PLAYER_LOGOUT" then
        ns.OnPlayerLogout()
    end
end)

-- Called when addon is loaded
function ns.OnAddonLoaded()
    ns.InitConfig()
end

function ns.OnPlayerLogin()
    ns.Castbar:Initialize()
    ns.MirrorTimers:Initialize()
    ns.InitMinimapIcon()
end

function ns.OnPlayerLogout()
    ns.Castbar:Cleanup()
end

-- Slash command
SLASH_NCASTBAR1 = "/ncastbar"
SlashCmdList["NCASTBAR"] = function(msg)
    msg = msg and msg:lower():trim() or ""
    if msg == "debug" then
        if not nCastbarDB.profile then return end
        nCastbarDB.profile.debugChat = not nCastbarDB.profile.debugChat
        ns.Print("Debug Chat: " .. (nCastbarDB.profile.debugChat and "|cff00ff00ON|r" or "|cffff4444OFF|r"))
    elseif msg == "reload" or msg == "r" then
        ns.Castbar:Reload()
    else
        ns.Print("/ncastbar debug  – Chat-Debug an/aus")
        ns.Print("/ncastbar reload – Castbars neu erstellen")
    end
end

-- Toggle minimap icon on/off
function ns.ToggleMinimapIcon()
    if not nCastbarDB.minimap then
        nCastbarDB.minimap = {hide = false}
    end
    nCastbarDB.minimap.hide = not nCastbarDB.minimap.hide

    local LibDBIcon = LibStub("LibDBIcon-1.0", true)
    if LibDBIcon then
        if nCastbarDB.minimap.hide then
            LibDBIcon:Hide("nCastbar")
            ns.Print("Minimap icon: |cffff0000OFF|r")
        else
            LibDBIcon:Show("nCastbar")
            ns.Print("Minimap icon: |cff00ff00ON|r")
        end
    end
end

-- Initialize minimap icon
function ns.InitMinimapIcon()
    -- Ensure minimap table exists in main DB (not profile)
    if not nCastbarDB.minimap then
        nCastbarDB.minimap = {hide = false}
    end
    
    local LibDBIcon = LibStub("LibDBIcon-1.0", true)
    if LibDBIcon then
        if not nCastbarDB.minimap.hide then
            LibDBIcon:Show("nCastbar")
        else
            LibDBIcon:Hide("nCastbar")
        end
    end
end


