-- modules/loot/LootAlert.lua
-- Watches group loot rolls and alerts when a BiS item from the active build drops.
-- Delegates UI tracking to LootTracker; plays alert sound and posts chat message.

EbonholdHub.LootAlert = {}

local QUALITY_COLOR = {
    [0] = "9d9d9d", [1] = "ffffff", [2] = "1eff00",
    [3] = "0070dd", [4] = "a335ee", [5] = "ff8000",
}

-- invSlot index → { invSlot, label }, built once from AffixData.SLOTS
local slotByKey      = {}
local slotIndexReady = false

local function EnsureSlotIndex()
    if slotIndexReady then return end
    if not (EbonholdHub.AffixData and EbonholdHub.AffixData.SLOTS) then return end
    for _, sd in ipairs(EbonholdHub.AffixData.SLOTS) do
        slotByKey[sd.key] = { invSlot = sd.invSlot, label = sd.label }
    end
    slotIndexReady = true
end

-- Build itemId → [{ slotLabel, setName, quality, name, invSlot }] from active build.
local function BuildWatchlist()
    local watchlist = {}
    local build = EbonholdHub.Build and EbonholdHub.Build.GetActive and EbonholdHub.Build.GetActive()
    if not build then return watchlist end
    EnsureSlotIndex()
    local sets = build.equipmentSets
    if not sets then return watchlist end
    for _, set in ipairs(sets) do
        local loadout = set.loadout
        if type(loadout) == "table" then
            for slotKey, entry in pairs(loadout) do
                local id = entry and entry.itemId
                if id and id > 0 then
                    if not watchlist[id] then watchlist[id] = {} end
                    local sd = slotByKey[slotKey]
                    table.insert(watchlist[id], {
                        slotLabel = sd and sd.label or slotKey,
                        setName   = (set.name and set.name ~= "") and set.name or "BiS",
                        quality   = entry.quality or 3,
                        name      = entry.name or ("Item " .. id),
                        invSlot   = sd and sd.invSlot,
                    })
                end
            end
        end
    end
    return watchlist
end

local function PlayAlert()
    if PlaySound then pcall(PlaySound, 8959) end
end

local function IsAutoNeedEnabled()
    local gs = EbonholdHubDB and EbonholdHubDB.globalSettings
    return gs and gs.lootAutoNeed == true
end

-- Roll Need; server enforces class restrictions (vanilla API has no canNeed field).
local function TryAutoNeed(rollID)
    if not IsAutoNeedEnabled() then return false end
    if not RollOnLoot then return false end
    pcall(RollOnLoot, rollID, 1)  -- 1 = Need
    return true
end

local function OnStartLootRoll(rollID)
    local link = GetLootRollItemLink and GetLootRollItemLink(rollID)
    if not link then return end

    local itemId = tonumber(link:match("item:(%d+)"))
    if not itemId then return end

    local watchlist = BuildWatchlist()
    local matches   = watchlist[itemId]
    if not matches or #matches == 0 then return end

    -- Deduplicate slot/set descriptions
    local seen      = {}
    local slotParts = {}
    local chatParts = {}
    for _, m in ipairs(matches) do
        local key = m.slotLabel .. "|" .. m.setName
        if not seen[key] then
            seen[key] = true
            slotParts[#slotParts + 1] = m.slotLabel
            chatParts[#chatParts + 1] = "|cffdddddd" .. m.slotLabel .. "|r"
                .. " |cff888888(" .. m.setName .. ")|r"
        end
    end

    -- Get icon + quality from server (texture, name, count, quality, bindOnPickUp)
    local iconPath, serverName, _, serverQuality
    if GetLootRollItemInfo then
        iconPath, serverName, _, serverQuality = GetLootRollItemInfo(rollID)
    end
    local itemName = serverName or matches[1].name
    local quality  = serverQuality or matches[1].quality
    local qColor   = QUALITY_COLOR[quality] or "ffffff"

    -- Register with the tracker UI
    local LT = EbonholdHub.LootTracker
    if LT then
        LT.AddRoll(rollID, {
            name      = itemName,
            iconPath  = iconPath,
            quality   = quality,
            slotLabel = table.concat(slotParts, " / "),
            setName   = matches[1].setName,
        })
    end

    -- Auto-Need roll
    local autoNeeded = TryAutoNeed(rollID)
    if LT then
        LT.SetAutoNeed(rollID, IsAutoNeedEnabled() and autoNeeded or false)
    end

    -- Chat notification
    local autoTag = autoNeeded and "  |cff30ff30>> Auto-Need rolled!|r" or ""
    local chatMsg = string.format(
        "|cff30bff5EbonholdHub:|r BiS item dropped! |cff%s[%s]|r  %s%s",
        qColor, itemName,
        table.concat(chatParts, ", "),
        autoTag
    )
    if DEFAULT_CHAT_FRAME then
        DEFAULT_CHAT_FRAME:AddMessage(chatMsg)
    end

    PlayAlert()
end

-- ── Event handler ─────────────────────────────────────────────────────────────
local eventFrame = CreateFrame("Frame")
eventFrame:SetScript("OnEvent", function(self, event, ...)
    if event == "START_LOOT_ROLL" then
        local rollID = ...
        -- Short delay so GetLootRollItemLink is populated by the client
        local t = 0
        local ticker = CreateFrame("Frame")
        ticker:SetScript("OnUpdate", function(s, dt)
            t = t + dt
            if t >= 0.05 then
                s:SetScript("OnUpdate", nil)
                pcall(OnStartLootRoll, rollID)
            end
        end)
    end
end)

function EbonholdHub.LootAlert.Init()
    eventFrame:RegisterEvent("START_LOOT_ROLL")
end
