local addonName, DX = ...

local LSM = LibStub("LibSharedMedia-3.0")

local function LoadTalentBackground()
    local eventFrame = CreateFrame("Frame")

    local function ApplyBG()
        local frame = _G.PlayerSpellsFrame
        if not frame or not frame.TalentsFrame then return end

        local bg = frame.TalentsFrame.Background
        if bg then
            local bgPath = LSM:Fetch("background", "DX TalentBG")
            bg:SetAtlas(nil)
            bg:SetTexture(bgPath)
            bg:SetAlpha(1)
            bg:SetDesaturated(false)
            bg:SetVertexColor(1, 1, 1, 1)
            bg:SetDrawLayer("BACKGROUND", -8)
            bg:SetHorizTile(false)
            bg:SetVertTile(false)
        end
    end

    local function SetupHooks()
        local frame = _G.PlayerSpellsFrame
        if not frame then return end

        hooksecurefunc(frame, "Show", function()
            C_Timer.After(0.05, ApplyBG)
        end)
        if frame:IsVisible() then
            ApplyBG()
        end
    end

    if C_AddOns.IsAddOnLoaded("Blizzard_PlayerSpells") then
        SetupHooks()
    else
        eventFrame:SetScript("OnEvent", function(self, event, name)
            if name == "Blizzard_PlayerSpells" then
                SetupHooks()
                self:UnregisterEvent("ADDON_LOADED")
            end
        end)
        eventFrame:RegisterEvent("ADDON_LOADED")
    end
end

DX:AddModule("TalentBackground", LoadTalentBackground)