local _, addon = ...
local HLY = addon.HLY
local P = addon.P
local pairs = pairs
local pcall = pcall
local tonumber = tonumber
local type = type
local _G = _G

local LibStub = _G.LibStub
local AceConfig = LibStub("AceConfig-3.0")
local AceConfigDialog = LibStub("AceConfigDialog-3.0")
local AceDB = LibStub("AceDB-3.0")

local BACKDROP_STYLE = {
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 1,
    insets = { left = 0, right = 0, top = 0, bottom = 0 },
}

local FONT_FALLBACKS = {
    Homespun = "Fonts\\ARIALN.TTF",
    PTSansNarrow = "Fonts\\ARIALN.TTF",
}

function HLY:PLAYER_EQUIPMENT_CHANGED()
    self:RefreshCharacterSlots()
    self:RefreshCompareStats()
end

function HLY:INSPECT_READY()
    self:RefreshInspectSlots()
    self:RefreshCompareStats()
end

function HLY:CopyTable(source)
    if type(source) ~= "table" then
        return source
    end

    local result = {}
    for key, value in pairs(source) do
        result[key] = self:CopyTable(value)
    end
    return result
end

function HLY:GetFontPath(fontName)
    if addon.LSM then
        local path = addon.LSM:Fetch("font", fontName, true)
        if path then
            return path
        end
    end

    return FONT_FALLBACKS[fontName] or STANDARD_TEXT_FONT
end

function HLY:GetFontValues()
    if addon.LSM then
        return addon.LSM:HashTable("font")
    end

    return {
        Homespun = "Homespun",
        Default = "Default",
    }
end

function HLY:GetFontList()
    if addon.LSM and addon.LSM.List then
        local values = {}
        for _, fontName in ipairs(addon.LSM:List("font")) do
            values[fontName] = fontName
        end
        return values
    end

    return self:GetFontValues()
end

function HLY:ApplyFont(text, fontName, fontSize, fontOutline)
    if not text then
        return
    end

    local flags = fontOutline
    if flags == "NONE" then
        flags = ""
    elseif flags == "SHADOWOUTLINE" then
        flags = "OUTLINE"
    end

    local fontPath = self:GetFontPath(fontName)
    local applied = fontPath and text:SetFont(fontPath, fontSize, flags)

    if not applied then
        applied = text:SetFont("Fonts\\FRIZQT__.TTF", fontSize, flags)
    end

    if not applied then
        local defaultFontObject = _G.GameFontNormal
        if defaultFontObject then
            local defaultPath, defaultSize, defaultFlags = defaultFontObject:GetFont()
            applied = defaultPath and text:SetFont(defaultPath, fontSize or defaultSize or 12, flags ~= "" and flags or defaultFlags)
        end
    end

    if not applied then
        text:SetFontObject(_G.GameFontNormal)
    end

    if fontOutline == "SHADOWOUTLINE" then
        text:SetShadowColor(0, 0, 0, 1)
        text:SetShadowOffset(1, -1)
    else
        text:SetShadowColor(0, 0, 0, 0)
        text:SetShadowOffset(0, 0)
    end
end

function HLY:SetPoint(object, point, xOffset, yOffset)
    if not object then
        return
    end

    object:ClearAllPoints()
    object:SetPoint(point or "CENTER", xOffset or 0, yOffset or 0)
end

function HLY:ApplyBackdrop(frame)
    if not frame or frame.hlyBackdropApplied or not frame.SetBackdrop then
        return
    end

    frame:SetBackdrop(BACKDROP_STYLE)
    frame:SetBackdropColor(0.05, 0.05, 0.05, 0.92)
    frame:SetBackdropBorderColor(0.35, 0.35, 0.35, 1)
    frame.hlyBackdropApplied = true
end

function HLY:ShortValue(value, decimals)
    value = tonumber(value) or 0
    decimals = decimals or 0

    local absValue = math.abs(value)
    if absValue >= 1000000 then
        return string.format("%." .. decimals .. "fm", value / 1000000)
    end
    if absValue >= 1000 then
        return string.format("%." .. decimals .. "fk", value / 1000)
    end
    if decimals > 0 and value ~= math.floor(value) then
        return string.format("%." .. decimals .. "f", value)
    end

    return tostring(math.floor(value + 0.5))
end

function HLY:GetClassColor(classFile)
    local color = classFile and RAID_CLASS_COLORS and RAID_CLASS_COLORS[classFile]
    return color or NORMAL_FONT_COLOR
end

function HLY:SafeCall(func, ...)
    if not func then
        return nil
    end

    local ok, result = pcall(func, ...)
    if ok then
        return result
    end

    return nil
end

function HLY:SafeNumber(value, fallback)
    local ok, numberValue = pcall(tonumber, value)
    if ok and numberValue then
        local usable = pcall(function()
            return numberValue >= 0 or numberValue < 0
        end)
        if usable then
            return numberValue
        end
    end

    return fallback or 0
end

function HLY:GetEquippedItemLevel(unit)
    local total, count = 0, 0
    for slot = 1, 17 do
        local link = self:SafeCall(GetInventoryItemLink, unit, slot)
        if link then
            local detailedItemLevel = self:SafeCall(GetDetailedItemLevelInfo, link)
            local itemLevel = self:SafeNumber(detailedItemLevel)
            if itemLevel <= 0 then
                local ok, itemName, itemLink, itemQuality, fallbackItemLevel = pcall(GetItemInfo, link)
                itemLevel = ok and self:SafeNumber(fallbackItemLevel) or 0
            end
            if itemLevel and itemLevel > 0 then
                total = total + itemLevel
                count = count + 1
            end
        end
    end

    if count == 0 then
        return 0
    end

    return total / count
end

function HLY:GetUnitItemLevel(unit)
    if unit == "player" and C_PaperDollInfo and C_PaperDollInfo.GetItemLevel then
        local ok, overall, equipped = pcall(C_PaperDollInfo.GetItemLevel)
        local itemLevel = 0
        if ok then
            itemLevel = self:SafeNumber(equipped)
            if itemLevel <= 0 then
                itemLevel = self:SafeNumber(overall)
            end
        end
        if itemLevel and itemLevel > 0 then
            return itemLevel
        end
    elseif unit ~= "player" and C_PaperDollInfo and C_PaperDollInfo.GetInspectItemLevel then
        local itemLevel = self:SafeNumber(self:SafeCall(C_PaperDollInfo.GetInspectItemLevel, unit))
        if itemLevel and itemLevel > 0 then
            return itemLevel
        end
    end

    return self:GetEquippedItemLevel(unit)
end

function HLY:GetBagItemLink(bagID, slotID)
    bagID = tonumber(bagID)
    slotID = tonumber(slotID)
    if not bagID or not slotID or slotID < 1 then
        return nil
    end

    if C_Container and C_Container.GetContainerItemLink then
        local ok, itemLink = pcall(C_Container.GetContainerItemLink, bagID, slotID)
        if ok then
            return itemLink
        end
        return nil
    end
    if GetContainerItemLink then
        local ok, itemLink = pcall(GetContainerItemLink, bagID, slotID)
        if ok then
            return itemLink
        end
        return nil
    end

    return nil
end

function HLY:GetElvUIBags()
    if self.elvuiBags ~= nil then
        return self.elvuiBags or nil
    end

    if type(_G.ElvUI) == "table" then
        local ok, engine = pcall(unpack, _G.ElvUI)
        if ok and engine and engine.GetModule then
            local found, module = pcall(engine.GetModule, engine, "Bags", true)
            if found and module then
                self.elvuiBags = module
                return module
            end
        end
    end

    self.elvuiBags = false
    return nil
end

function HLY:GetBagButtonInfo(button)
    if not button then
        return nil, nil
    end

    local objectType
    if button.GetObjectType then
        local ok, value = pcall(button.GetObjectType, button)
        if ok then
            objectType = value
        end
    end
    if objectType ~= "Button" and objectType ~= "CheckButton" then
        return nil, nil
    end

    local bagID = button.bagID or button.BagID or button.bag
    if bagID == nil and button.GetBagID then
        local ok, value = pcall(button.GetBagID, button)
        if ok then
            bagID = value
        end
    end
    if bagID == nil and button.GetBag then
        local ok, value = pcall(button.GetBag, button)
        if ok then
            bagID = value
        end
    end

    local slotID = button.slotID or button.SlotID or button.slot
    if slotID == nil and button.GetID then
        local ok, value = pcall(button.GetID, button)
        if ok then
            slotID = value
        end
    end
    if slotID == nil and button.GetSlot then
        local ok, value = pcall(button.GetSlot, button)
        if ok then
            slotID = value
        end
    end

    if bagID == nil then
        local parent = button:GetParent()
        if parent then
            bagID = parent.bagID or parent.BagID
            if bagID == nil and parent.GetID then
                local ok, value = pcall(parent.GetID, parent)
                if ok then
                    bagID = value
                end
            end
        end
    end

    if bagID == nil or slotID == nil then
        return nil, nil
    end

    bagID = tonumber(bagID)
    slotID = tonumber(slotID)
    if not bagID or not slotID or slotID < 1 then
        return nil, nil
    end

    return bagID, slotID
end

function HLY:GetBagRoots()
    local roots, seen = {}, {}

    local function addRoot(frame)
        if frame and not seen[frame] then
            seen[frame] = true
            roots[#roots + 1] = frame
        end
    end

    addRoot(_G.ContainerFrameCombinedBags)
    addRoot(_G.BankPanel)
    addRoot(_G.AccountBankPanel)
    for index = 1, 20 do
        addRoot(_G["ContainerFrame" .. index])
    end

    local elvuiBags = self:GetElvUIBags()
    if elvuiBags then
        addRoot(elvuiBags.BagFrame)
        addRoot(elvuiBags.BankFrame)
    end

    addRoot(_G.BagnonInventoryFrame)
    addRoot(_G.BagnonBankFrame)
    addRoot(_G.BagnonBackpackFrame)

    addRoot(_G.BaganatorBackpackViewFrame)
    addRoot(_G.BaganatorBankViewFrame)
    addRoot(_G.BaganatorSingleViewBackpackViewFrame)
    addRoot(_G.BaganatorSingleViewBankViewFrame)

    return roots
end

function HLY:CollectBagButtons(root, results, seenFrames)
    if not root or seenFrames[root] then
        return
    end

    seenFrames[root] = true

    local bagID, slotID = self:GetBagButtonInfo(root)
    if bagID ~= nil and slotID ~= nil then
        results[#results + 1] = { button = root, bagID = bagID, slotID = slotID }
    end

    local ok, children = pcall(function()
        return { root:GetChildren() }
    end)

    if not ok or not children then
        return
    end

    for _, child in pairs(children) do
        if child then
            self:CollectBagButtons(child, results, seenFrames)
        end
    end
end

function HLY:ForEachBagSlot(callback)
    local results, seenFrames, seenButtons = {}, {}, {}

    for _, root in ipairs(self:GetBagRoots()) do
        self:CollectBagButtons(root, results, seenFrames)
    end

    for _, entry in pairs(results) do
        if not seenButtons[entry.button] then
            seenButtons[entry.button] = true
            callback(entry.button, entry.bagID, entry.slotID)
        end
    end
end

function HLY:HandleBagRefresh()
    self:RefreshAllSlots()
    self:RefreshBindSlots()
end

function HLY:QueueBagRefresh()
    if self.bagRefreshPending then
        return
    end

    self.bagRefreshPending = true
    C_Timer.After(0.05, function()
        self.bagRefreshPending = nil
        self:HandleBagRefresh()
    end)
end

function HLY:GetBagCacheKey(bagID, slotID)
    return tostring(bagID) .. ":" .. tostring(slotID)
end

function HLY:SafeRegisterEvent(eventName, method)
    local ok = pcall(self.RegisterEvent, self, eventName, method)
    return ok
end

function HLY:SetupBagHooks()
    if self.bagHooksSet then
        return
    end

    local elvuiBags = self:GetElvUIBags()
    if elvuiBags then
        hooksecurefunc(elvuiBags, "UpdateSlot", function(_, frame, bagID, slotID)
            local bag = frame and frame.Bags and frame.Bags[bagID]
            local slot = bag and bag[slotID]
            if slot then
                self:UpdateSlotUpgradeText(slot, bagID, slotID)
                self:UpdateSlotBindText(slot, bagID, slotID)
            end
        end)

        hooksecurefunc(elvuiBags, "UpdateAllSlots", function()
            self:QueueBagRefresh()
        end)
    end

    self:SafeRegisterEvent("BAG_UPDATE_DELAYED", "QueueBagRefresh")
    self:SafeRegisterEvent("PLAYERBANKSLOTS_CHANGED", "QueueBagRefresh")
    self:SafeRegisterEvent("BANKFRAME_OPENED", "QueueBagRefresh")
    self:SafeRegisterEvent("PLAYERREAGENTBANKSLOTS_CHANGED", "QueueBagRefresh")
    self:SafeRegisterEvent("BAG_CLOSED", "QueueBagRefresh")
    self:SafeRegisterEvent("BAG_OPEN", "QueueBagRefresh")

    if _G.ContainerFrame_UpdateAll then
        hooksecurefunc("ContainerFrame_UpdateAll", function()
            self:QueueBagRefresh()
        end)
    end

    local function hookFrameShow(frame)
        if frame and not frame.hlyBagHooked then
            frame:HookScript("OnShow", function()
                self:QueueBagRefresh()
            end)
            frame.hlyBagHooked = true
        end
    end

    hookFrameShow(_G.ContainerFrameCombinedBags)
    hookFrameShow(_G.BankPanel)
    hookFrameShow(_G.AccountBankPanel)
    hookFrameShow(_G.BagnonInventoryFrame)
    hookFrameShow(_G.BagnonBankFrame)
    hookFrameShow(_G.BagnonBackpackFrame)
    hookFrameShow(_G.BaganatorBackpackViewFrame)
    hookFrameShow(_G.BaganatorBankViewFrame)
    hookFrameShow(_G.BaganatorSingleViewBackpackViewFrame)
    hookFrameShow(_G.BaganatorSingleViewBankViewFrame)

    if elvuiBags then
        hookFrameShow(elvuiBags.BagFrame)
        hookFrameShow(elvuiBags.BankFrame)
    end

    for index = 1, 20 do
        hookFrameShow(_G["ContainerFrame" .. index])
    end

    self.bagHooksSet = true
end

function HLY:OnInitialize()
    self.database = AceDB:New("HLYQoLDB", {
        profile = self:CopyTable(P.hlyqol),
    }, true)

    self.db = self.database.profile

    AceConfig:RegisterOptionsTable(addon.addonName, self:GetOptions())
    AceConfigDialog:SetDefaultSize(addon.addonName, 900, 700)
    self.optionsFrame = AceConfigDialog:AddToBlizOptions(addon.addonName, addon.displayName)

    self:RegisterChatCommand("hlyqol", "OpenOptions")
end

function HLY:OnEnable()
    self:SetupBagHooks()
    self:SetupUpgradeTrackHooks()
    self:SetupBindHooks()
    self:SetupInspectCompareHooks()
    self:SetupAutoAccept()
    self:SetupJoinReminder()
    self:SetupDeathAlert()
    self:SetupTrinketAlert()
    self:SetupLoot()
    self:SetupLustAlert()
    self:SetupGearCheck()
    self:SetupHLYstats()
    self:SetupMinimapButton()
    self:SetupFrenchConnection()

    self:RegisterEvent("PLAYER_EQUIPMENT_CHANGED")
    self:RegisterEvent("INSPECT_READY")

    self:RefreshAllSlots()
    self:RefreshBindSlots()
    self:RefreshCharacterSlots()
    self:RefreshInspectSlots()
    self:RefreshCompareStats()
end

function HLY:OpenOptions()
    AceConfigDialog:Open(addon.addonName)
end
