InspectUI_Themes = InspectUI_Themes or {
    current = "default",
    registry = {}
}
InspectUI_Themes.listeners = InspectUI_Themes.listeners or {}

local function getThemeStoragePlayer()
    if not getSpecificPlayer then return nil end

    local player = getSpecificPlayer(0)
    if player and player.getModData then
        return player
    end

    return nil
end

local function getStoredThemeId()
    local player = getThemeStoragePlayer()
    if player then
        local md = player:getModData()
        if md and md.InspectUIThemeId and md.InspectUIThemeId ~= "" then
            return md.InspectUIThemeId
        end
    end

    local md = ModData.getOrCreate("InspectUI")
    if md and md.themeId and md.themeId ~= "" then
        return md.themeId
    end

    return nil
end

local function saveThemeId(id)
    if not id or id == "" then return end

    local player = getThemeStoragePlayer()
    if player then
        local md = player:getModData()
        md.InspectUIThemeId = id
        if player.transmitModData then
            pcall(player.transmitModData, player)
        end
    end

    local md = ModData.getOrCreate("InspectUI")
    md.themeId = id
end

function InspectUI_RegisterTheme(id, def)
    if not id or not def then return end
    InspectUI_Themes.registry[id] = def
end

function InspectUI_GetTheme()
    return InspectUI_Themes.registry[InspectUI_Themes.current]
        or InspectUI_Themes.registry["default"]
end

function InspectUI_GetThemeId()
    return InspectUI_Themes.current or "default"
end

function InspectUI_SetTheme(id)
    if not InspectUI_Themes.registry[id] then
        id = "default"
    end

    InspectUI_Themes.current = id
    saveThemeId(id)

    local listeners = InspectUI_Themes.listeners
    if listeners then
        for ui in pairs(listeners) do
            if ui and ui.onThemeChanged then
                ui:onThemeChanged(id)
            end
        end
    end
end

function InspectUI_LoadTheme()
    local id = getStoredThemeId() or "default"

    if not InspectUI_Themes.registry[id] then
        id = "default"
    end

    InspectUI_Themes.current = id
end

if Events and Events.OnCreatePlayer then
    Events.OnCreatePlayer.Add(function()
        if InspectUI_LoadTheme then
            InspectUI_LoadTheme()
        end
    end)
end
