--[[
============================================================================
Enhanced Mount Tracker  -  Modules/MountTooltip.lua
============================================================================
Adds a "Mount Drops" section to the tooltip when you hover an NPC that drops
(or is the rare/boss source of) a mount in our data set.

Pattern mirrors ETB's BossLootTooltip:
  - A reverse index npcID -> {spellID,...} is built LAZILY on the first
    unit-tooltip, not at login.
  - We hook GameTooltip's OnTooltipSetUnit. Blizzard re-fires that script
    whenever it refreshes a unit tooltip (health/level/etc.), so re-adding
    our lines there keeps them from being wiped.
  - Suppressed in combat to avoid tooltip churn during a pull.

Each line shows the mount name, a collected (green check) / missing (red)
marker, and — when AtlasLoot had the figure — the drop rate.
============================================================================
]]--

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

EMT.MountTooltip = EMT.MountTooltip or {}
local MT = EMT.MountTooltip

MT.enabled    = true
MT._npcIndex  = nil      -- npcID -> { spellID, spellID, ... }
MT._built     = false

local ETB = NS.ETB
local S   = (ETB and ETB.Style) or {}
local HEADER_COLOR    = S.HEADER       or "|cff00ccff"  -- canonical cyan header
local COLLECTED_MARK  = S.MARK_OWNED   or "|TInterface\\RaidFrame\\ReadyCheck-Ready:14:14:0:0|t"
local MISSING_MARK    = S.MARK_MISSING or "|TInterface\\RaidFrame\\ReadyCheck-NotReady:14:14:0:0|t"
local RATE_COLOR      = S.RATE         or "|cffaaaaaa"

-- ----------------------------------------------------------------------------
-- LAZY INDEX
-- ----------------------------------------------------------------------------

function MT:BuildIndex()
    if self._built then return end
    local data = EMT.MountData
    if not data then return end

    local idx = {}
    for spellID, rec in pairs(data) do
        local npc = rec.n
        if npc then
            local list = idx[npc]
            if not list then list = {}; idx[npc] = list end
            list[#list + 1] = spellID
        end
    end
    self._npcIndex = idx
    self._built = true

    local npcs = 0
    for _ in pairs(idx) do npcs = npcs + 1 end
    EMT:Debug("MountTooltip", "index built: " .. npcs .. " mount-dropping NPCs")
end

-- ----------------------------------------------------------------------------
-- GUID -> npcID
-- ----------------------------------------------------------------------------
-- MoP Classic uses the modern GUID format:
--   Creature-0-<server>-<instance>-<zoneUID>-<npcID>-<spawnUID>
-- The npcID is the 6th hyphen-separated field. Vehicles share the layout.

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

-- ----------------------------------------------------------------------------
-- SUPPRESSION
-- ----------------------------------------------------------------------------

local function ShouldSuppress()
    if InCombatLockdown() then return true end
    if UnitAffectingCombat("player") then return true end
    return false
end

-- ----------------------------------------------------------------------------
-- TOOLTIP POPULATION
-- ----------------------------------------------------------------------------

function MT:AddToTooltip(tooltip, npcID)
    if not self.enabled then return end
    self:BuildIndex()
    if not self._npcIndex then return end

    local mounts = self._npcIndex[npcID]
    if not mounts then return end

    local data = EMT.MountData
    local API  = EMT.MountAPI

    -- ETB-style header: gold label with an X/Y collected count.
    local total, collected = 0, 0
    for _, spellID in ipairs(mounts) do
        if data[spellID] then
            total = total + 1
            if API:IsCollected(spellID) then collected = collected + 1 end
        end
    end
    if total == 0 then return end

    tooltip:AddLine(" ")
    tooltip:AddDoubleLine(
        HEADER_COLOR .. "EMT: Collectible Mounts|r",
        (S.Count and S:Count(collected, total))
            or string.format("|cff00ff00%d|r|cffaaaaaa/%d|r", collected, total))

    for _, spellID in ipairs(mounts) do
        local rec = data[spellID]
        if rec then
            local name   = API:GetName(spellID, rec.i)
            local owned  = API:IsCollected(spellID)
            local mark   = owned and COLLECTED_MARK or MISSING_MARK
            local qhex   = API:QualityColor(rec.q)
            local tex    = API:GetIcon(spellID, 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 (Boss / Vendor / World /
            -- Store / ...), with the drop rate appended when known.
            local tag    = EMT.SourceInfo and EMT.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 .. (EMT.SourceInfo and EMT.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()   -- re-fit after adding lines
end

-- ----------------------------------------------------------------------------
-- HOOK
-- ----------------------------------------------------------------------------

function MT:Toggle()
    self.enabled = not self.enabled
    EMT_Settings.tooltip = self.enabled
    EMT:Print("NPC mount tooltips " ..
        (self.enabled and "|cff44ff44enabled|r" or "|cffff5555disabled|r"))
end

EMT:RegisterInit(function()
    EMT_Settings = EMT_Settings or {}
    if EMT_Settings.tooltip ~= nil then
        MT.enabled = EMT_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
            MT:AddToTooltip(tooltip, npcID)
        end
    end)

    EMT:Debug("MountTooltip", "tooltip hook installed")
end)
