--[[
============================================================================
Enhanced Pet Tracker  -  Modules/PetTooltip.lua
============================================================================
Adds a "Pet Drops" section to an NPC's tooltip when that NPC drops a battle
pet in our data set. Same lazy-index pattern as Enhanced Mount Tracker's
mount tooltip — the npcID -> pets reverse index is built on first hover, not
at login.

Note: if Enhanced Mount Tracker is also installed, an NPC that drops both a
mount and a pet will show both sections (each addon hooks the tooltip
independently and appends). That is harmless; a future shared core would
merge them into one collection section.
============================================================================
]]--

local ADDON_NAME, NS = ...
local EPT = NS.EPT
if not EPT then return end

EPT.PetTooltip = EPT.PetTooltip or {}
local PT = EPT.PetTooltip

PT.enabled   = true
PT._npcIndex = nil
PT._built    = false

local HEADER_COLOR   = "|cffffd100"  -- ETB gold
local COLLECTED_MARK = "|cff00ff88\226\156\147|r"  -- ETB green
local MISSING_MARK   = "|cffff5555\226\156\151|r"
local RATE_COLOR     = "|cffaaaaaa"

function PT:BuildIndex()
    if self._built then return end
    local data = EPT.PetData
    if not data then return end
    local idx = {}
    for speciesID, rec in pairs(data) do
        if rec.n then
            local list = idx[rec.n]
            if not list then list = {}; idx[rec.n] = list end
            list[#list + 1] = speciesID
        end
    end
    self._npcIndex = idx
    self._built = true
end

local function NPCIDFromGUID(guid)
    if not guid then return nil end
    local kind = strsplit("-", guid)
    if kind ~= "Creature" and kind ~= "Vehicle" then return nil end
    local id = select(6, strsplit("-", guid))
    return id and tonumber(id) or nil
end

local function ShouldSuppress()
    return InCombatLockdown() or UnitAffectingCombat("player")
end

function PT:AddToTooltip(tooltip, npcID)
    if not self.enabled then return end
    self:BuildIndex()
    if not self._npcIndex then return end
    local pets = self._npcIndex[npcID]
    if not pets then return end

    local data = EPT.PetData
    local API  = EPT.PetAPI

    local total, collected = 0, 0
    for _, speciesID in ipairs(pets) do
        if data[speciesID] then
            total = total + 1
            if API:IsCollected(speciesID) then collected = collected + 1 end
        end
    end
    if total == 0 then return end

    tooltip:AddLine(" ")
    tooltip:AddDoubleLine(
        HEADER_COLOR .. "EPT: Collectible Pets|r",
        string.format("|cff00ff88%d|r|cff808080/%d|r", collected, total))
    for _, speciesID in ipairs(pets) do
        local rec = data[speciesID]
        if rec then
            local name  = API:GetName(speciesID, rec.i)
            local owned = API:IsCollected(speciesID)
            local mark  = owned and COLLECTED_MARK or MISSING_MARK
            local qhex  = API:QualityColor(rec.q)
            local tex   = API:GetIcon(speciesID, rec.i)
            local img   = tex and ("|T" .. tex .. ":16:16:0:0|t ") or ""
            local line  = mark .. " " .. img .. qhex .. name .. "|r"
            -- Right column always names the source (Wild / Boss / Vendor /
            -- Store / ...), with the drop rate appended when known.
            local tag   = EPT.SourceInfo and EPT.SourceInfo:SourceTag(rec) or ""
            local right
            if rec.u == 1 or rec.u == 2 then
                right = "|cffff8800removed|r"
            elseif rec.dr then
                right = tag .. " " .. RATE_COLOR .. (EPT.SourceInfo and EPT.SourceInfo:FormatRate(rec.dr) or "?") .. "|r"
            else
                right = tag
            end
            if right ~= "" then
                tooltip:AddDoubleLine("  " .. line, right)
            else
                tooltip:AddLine("  " .. line)
            end
        end
    end
    tooltip:Show()
end

function PT:Toggle()
    self.enabled = not self.enabled
    EPT_Settings.tooltip = self.enabled
    EPT:Print("NPC pet tooltips " ..
        (self.enabled and "|cff44ff44enabled|r" or "|cffff5555disabled|r"))
end

EPT:RegisterInit(function()
    EPT_Settings = EPT_Settings or {}
    if EPT_Settings.tooltip ~= nil then
        PT.enabled = EPT_Settings.tooltip
    end

    GameTooltip:HookScript("OnTooltipSetUnit", function(tooltip)
        if ShouldSuppress() then return end
        local _, unit = tooltip:GetUnit()
        if not unit then return end
        local npcID = NPCIDFromGUID(UnitGUID(unit))
        if npcID then
            PT:AddToTooltip(tooltip, npcID)
        end
    end)
end)
