--[[
============================================================================
ETB v10.0 - TooltipEnhancer.lua
============================================================================
Enhances game tooltips with collection and source info.
============================================================================
]]--

local ADDON_NAME, NS = ...
local ETB = NS.ETB

ETB.TooltipEnhancer = {
    initialized = false,
}

local TE = ETB.TooltipEnhancer

-- =============================================================================
-- INITIALIZATION
-- =============================================================================

function TE:Initialize()
    if self.initialized then return end
    
    if not ETB.Settings:Get("tooltips.enhance") then
        ETB:Debug("TooltipEnhancer", "Tooltips disabled in settings")
        return
    end
    
    -- Hook GameTooltip
    GameTooltip:HookScript("OnTooltipSetItem", function(tooltip)
        TE:OnTooltipSetItem(tooltip)
    end)
    
    -- Hook ItemRefTooltip (for linked items)
    if ItemRefTooltip then
        ItemRefTooltip:HookScript("OnTooltipSetItem", function(tooltip)
            TE:OnTooltipSetItem(tooltip)
        end)
    end
    
    self.initialized = true
    ETB:Debug("TooltipEnhancer", "Tooltip hooks initialized")
end

-- =============================================================================
-- TOOLTIP HANDLER
-- =============================================================================

function TE:OnTooltipSetItem(tooltip)
    if not tooltip then return end
    
    local _, link = tooltip:GetItem()
    if not link then return end
    
    local itemID = tonumber(link:match("item:(%d+)"))
    if not itemID then return end
    
    -- Add separator
    tooltip:AddLine(" ")
    
    -- Collection status
    if ETB.Settings:Get("tooltips.showCollected") then
        self:AddCollectionInfo(tooltip, itemID)
    end
    
    -- Source info
    if ETB.Settings:Get("tooltips.showSource") then
        self:AddSourceInfo(tooltip, itemID)
    end
    
    -- Favorite status
    if ETB.FavoritesManager and ETB.FavoritesManager:IsFavorite(itemID) then
        tooltip:AddLine("|cffffd100★ Favorited|r")
    end
    
    -- Item IDs (debug)
    if ETB.Settings:Get("tooltips.showItemIDs") then
        tooltip:AddLine(" ")
        tooltip:AddDoubleLine("ItemID:", itemID, 0.5, 0.5, 0.5, 1, 1, 1)
    end
    
    tooltip:Show()
end

-- =============================================================================
-- INFO SECTIONS
-- =============================================================================

function TE:AddCollectionInfo(tooltip, itemID)
    if not tooltip or not itemID then return end
    -- Skip non-transmog items (reagents, consumables, quest items, etc.)
    if GetItemInfoInstant then
        local _, _, _, equipLoc, _, classID, subClassID = GetItemInfoInstant(itemID)
        -- classID 0=Consumable, 5=Reagent, 7=Tradeskill, 9=Recipe, 12=Quest, 15=Miscellaneous
        -- Only show collection status for Armor (4) and Weapons (2)
        if not classID or (classID ~= 2 and classID ~= 4) then
            return
        end
        -- Skip non-equippable armor (like tokens without equip slot)
        if not equipLoc or equipLoc == "" or equipLoc == "INVTYPE_NON_EQUIP" then
            -- Exception: some items with no equipLoc still have transmog appearances
            if C_TransmogCollection and C_TransmogCollection.GetItemInfo then
                local appID = C_TransmogCollection.GetItemInfo(itemID)
                if not appID or appID == 0 then
                    return
                end
            else
                return
            end
        end
    end

    -- Check collection status via appearance source chain
    local isCollected = false
    
    if C_TransmogCollection and C_TransmogCollection.GetItemInfo then
        local ok, appID = pcall(C_TransmogCollection.GetItemInfo, itemID)
        if ok and appID and C_TransmogCollection.GetAppearanceSources then
            local srcOK, sources = pcall(C_TransmogCollection.GetAppearanceSources, appID)
            if srcOK and sources then
                for _, src in ipairs(sources) do
                    local sid = type(src) == "table" and src.sourceID or src
                    if sid then
                        local siOK, si = pcall(C_TransmogCollection.GetSourceInfo, sid)
                        if siOK and si and si.isCollected then
                            isCollected = true
                            break
                        end
                    end
                end
            end
        end
    end
    
    if isCollected then
        tooltip:AddLine("|cff00ff00✓ Appearance Collected|r")
    else
        tooltip:AddLine("|cffff6666✗ Appearance Not Collected|r")
    end
end

function TE:AddSourceInfo(tooltip, itemID)
    -- SourceMapper handles all source lookups (enriched from MapperBridge)
    if ETB.SourceMapper and ETB.SourceMapper.initialized then
        local tooltipLines = ETB.SourceMapper:FormatSourceTooltip(itemID)
        if tooltipLines and #tooltipLines > 0 then
            for _, line in ipairs(tooltipLines) do
                tooltip:AddLine(line, 1, 1, 1)
            end
            return
        end
    end
    
    -- Direct fallback to MapperBridge if SourceMapper isn't ready yet
    if ETB.SourceData_ATT then
        local source = ETB.SourceData_ATT:GetPrimarySource(itemID)
        if source and source.name ~= "Unknown" then
            tooltip:AddLine("|cffffd100Source:|r " .. source.name, 1, 1, 1)
            if source.location and source.location ~= "" then
                tooltip:AddLine("|cffffd100Location:|r " .. source.location, 1, 1, 1)
            end
        end
    end
end

-- =============================================================================
-- ENABLE/DISABLE
-- =============================================================================

function TE:Enable()
    ETB.Settings:Set("tooltips.enhance", true)
    if not self.initialized then
        self:Initialize()
    end
    ETB:Print("Tooltip enhancement enabled")
end

function TE:Disable()
    ETB.Settings:Set("tooltips.enhance", false)
    ETB:Print("Tooltip enhancement disabled (requires reload)")
end

function TE:Toggle()
    if ETB.Settings:Get("tooltips.enhance") then
        self:Disable()
    else
        self:Enable()
    end
end

ETB:Debug("TooltipEnhancer", "TooltipEnhancer.lua loaded")
