--[[
============================================================================
ETB - TooltipEnhancer.lua (Side Panel)
============================================================================
Shows ETB info (collection, source, crafting) in a separate panel
anchored next to the Blizzard tooltip. No longer modifies GameTooltip.
============================================================================
]]--

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

ETB.TooltipEnhancer = {
    initialized = false,
}

local TE = ETB.TooltipEnhancer
local PANEL_WIDTH = 260
local MAX_LINES = 20

-- =============================================================================
-- SIDE PANEL FRAME
-- =============================================================================

local sidePanel = nil
local sidePanelLines = {}
local sidePanelLineCount = 0
local lastItemID = nil

local function GetOrCreateSidePanel()
    if sidePanel then return sidePanel end

    sidePanel = CreateFrame("Frame", "ETBTooltipSidePanel", UIParent, "BackdropTemplate")
    sidePanel:SetSize(PANEL_WIDTH, 60)
    sidePanel:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
        tile = true, tileSize = 32, edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    })
    sidePanel:SetFrameStrata("TOOLTIP")
    sidePanel:Hide()

    -- Title
    sidePanel.title = sidePanel:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    sidePanel.title:SetPoint("TOPLEFT", 8, -8)
    sidePanel.title:SetText("|cffffd100Enhanced Transmog Browser|r")

    return sidePanel
end

local function AddPanelLine(text, r, g, b)
    sidePanelLineCount = sidePanelLineCount + 1
    local line = sidePanelLines[sidePanelLineCount]
    if not line then
        line = sidePanel:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        line:SetWidth(PANEL_WIDTH - 16)
        line:SetJustifyH("LEFT")
        line:SetWordWrap(true)
        sidePanelLines[sidePanelLineCount] = line
    end
    line:SetPoint("TOPLEFT", 8, -22 - (sidePanelLineCount - 1) * 14)
    line:SetText(text)
    if r then line:SetTextColor(r, g, b) end
    line:Show()
end

local function AddPanelDoubleLine(leftText, rightText)
    sidePanelLineCount = sidePanelLineCount + 1
    local line = sidePanelLines[sidePanelLineCount]
    if not line then
        line = sidePanel:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        line:SetWidth(PANEL_WIDTH - 16)
        line:SetJustifyH("LEFT")
        line:SetWordWrap(true)
        sidePanelLines[sidePanelLineCount] = line
    end
    line:SetPoint("TOPLEFT", 8, -22 - (sidePanelLineCount - 1) * 14)
    line:SetText(leftText .. "  " .. (rightText or ""))
    line:Show()
end

local function ClearPanel()
    for i = 1, sidePanelLineCount do
        sidePanelLines[i]:Hide()
    end
    sidePanelLineCount = 0
    lastItemID = nil
end

local function ShowPanel()
    if sidePanelLineCount == 0 then
        sidePanel:Hide()
        return
    end
    -- Size to content
    local height = 30 + sidePanelLineCount * 14
    sidePanel:SetHeight(height)

    -- Anchor to the right of GameTooltip
    sidePanel:ClearAllPoints()
    sidePanel:SetPoint("TOPLEFT", GameTooltip, "TOPRIGHT", 4, 0)
    sidePanel:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
    sidePanel:Show()
end

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

function TE:Initialize()
    if self.initialized then return end

    if not ETB.Settings:Get("tooltips.enhance") then
        return
    end

    GetOrCreateSidePanel()

    -- Hook GameTooltip
    GameTooltip:HookScript("OnTooltipSetItem", function(tooltip)
        TE:OnTooltipSetItem(tooltip)
    end)

    -- Hide panel when tooltip hides
    GameTooltip:HookScript("OnHide", function()
        if sidePanel then sidePanel:Hide() end
        lastItemID = nil
    end)

    -- Hook ItemRefTooltip (linked items in chat)
    if ItemRefTooltip then
        ItemRefTooltip:HookScript("OnTooltipSetItem", function(tooltip)
            TE:OnTooltipSetItem(tooltip)
        end)
    end

    -- Disable CollectionTooltip if it exists (we handle collection status now)
    if ETB.CollectionTooltip then
        ETB.CollectionTooltip.enabled = false
    end

    self.initialized = true
end

-- =============================================================================
-- TOOLTIP HANDLER — populate side panel
-- =============================================================================

function TE:OnTooltipSetItem(tooltip)
    if not tooltip or not sidePanel 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

    -- Skip if same item (avoid flicker from repeated OnTooltipSetItem)
    if itemID == lastItemID then return end
    lastItemID = itemID

    ClearPanel()

    -- Collection status
    self:AddCollectionInfo(itemID)

    -- Source info
    if ETB.Settings:Get("tooltips.showSource") then
        self:AddSourceInfo(itemID)
    end

    -- Crafting info
    self:AddCraftingInfo(itemID)

    -- Favorite
    if ETB.FavoritesManager and ETB.FavoritesManager:IsFavorite(itemID) then
        AddPanelLine("|cffffd100★ Favorited|r")
    end

    -- Wishlist
    if ETB.Wishlist and ETB.Wishlist:HasItem(itemID) then
        AddPanelLine("|cffffcc00On your wishlist|r")
    end

    -- ERB BiS info
    local ERB = ETB.ERB
    if ERB and ERB.DataBridge then
        local bisInfo = ERB.DataBridge:GetItemBiSInfo(itemID)
        if bisInfo then
            AddPanelLine(" ")
            local rc = bisInfo.rank == 1 and "|cffff8000" or "|cffa335ee"
            AddPanelLine(rc .. "BiS Rank #" .. bisInfo.rank .. " — " .. bisInfo.label .. "|r")
            local bossName = ERB.DataBridge:GetBossName(itemID)
            if bossName then
                AddPanelLine("|cff888888Drops from: " .. bossName .. "|r")
            end
        end
    end

    -- Item IDs (debug)
    if ETB.Settings:Get("tooltips.showItemIDs") then
        AddPanelLine(" ")
        AddPanelLine("|cff888888ItemID: " .. itemID .. "|r")
    end

    ShowPanel()
end

-- =============================================================================
-- INFO SECTIONS (write to side panel, not tooltip)
-- =============================================================================

function TE:AddCollectionInfo(itemID)
    -- Only equippable items (classID 2=Weapon, 4=Armor)
    if GetItemInfoInstant then
        local _, _, _, equipLoc, _, classID = GetItemInfoInstant(itemID)
        if not classID or (classID ~= 2 and classID ~= 4) then return end
        if not equipLoc or equipLoc == "" or equipLoc == "INVTYPE_NON_EQUIP" then
            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

    local isCollected = false
    local appearanceID, sourceID

    if C_TransmogCollection and C_TransmogCollection.GetItemInfo then
        local ok, appID, srcID = pcall(C_TransmogCollection.GetItemInfo, itemID)
        if ok then appearanceID = appID; sourceID = srcID end
        if not appearanceID then
            local _, itemLink = GetItemInfo(itemID)
            if itemLink then
                ok, appID, srcID = pcall(C_TransmogCollection.GetItemInfo, itemLink)
                if ok then appearanceID = appID; sourceID = srcID end
            end
        end
    end

    if not isCollected and appearanceID and C_TransmogCollection.GetAllAppearanceSources then
        local ok, allSources = pcall(C_TransmogCollection.GetAllAppearanceSources, appearanceID)
        if ok and allSources and C_TransmogCollection.PlayerHasTransmogItemModifiedAppearance then
            for _, sid in ipairs(allSources) do
                local hasOK, hasIt = pcall(C_TransmogCollection.PlayerHasTransmogItemModifiedAppearance, sid)
                if hasOK and hasIt then isCollected = true; break end
            end
        end
    end

    if not isCollected and appearanceID and C_TransmogCollection.GetAppearanceSources then
        local srcOK, sources = pcall(C_TransmogCollection.GetAppearanceSources, appearanceID)
        if srcOK and sources then
            for _, src in ipairs(sources) do
                if type(src) == "table" and src.isCollected then isCollected = true; break end
            end
        end
    end

    if not isCollected and sourceID and C_TransmogCollection.PlayerHasTransmogItemModifiedAppearance then
        local ok, result = pcall(C_TransmogCollection.PlayerHasTransmogItemModifiedAppearance, sourceID)
        if ok and result then isCollected = true end
    end

    if isCollected then
        AddPanelLine("|cff00ff00✓ Appearance Collected|r")
    else
        AddPanelLine("|cffff6666✗ Not Collected|r")
    end
end

function TE:AddSourceInfo(itemID)
    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
                AddPanelLine(line)
            end
            return
        end
    end

    if ETB.SourceData_ATT then
        local source = ETB.SourceData_ATT:GetPrimarySource(itemID)
        if source and source.name ~= "Unknown" then
            AddPanelLine("|cffffd100Source:|r " .. source.name)
            if source.location and source.location ~= "" then
                AddPanelLine("|cffffd100Location:|r " .. source.location)
            end
            if ETB.TierPieceToToken then
                local tokenID = ETB.TierPieceToToken[itemID]
                if tokenID then
                    local tokenName = GetItemInfo(tokenID)
                    if tokenName then
                        AddPanelLine("|cffff8000Token:|r " .. tokenName)
                    end
                end
            end
        end
    end
end

local PROFESSION_NAMES = {
    [164]="Blacksmithing",[165]="Leatherworking",[171]="Alchemy",
    [182]="Herbalism",[186]="Mining",[197]="Tailoring",
    [202]="Engineering",[333]="Enchanting",[755]="Jewelcrafting",
    [773]="Inscription",[185]="Cooking",[129]="First Aid",
}

function TE:AddCraftingInfo(itemID)
    if not ETB.RecipeData then return end
    local recipe = ETB.RecipeData[itemID]
    if not recipe then return end

    local skillLine = recipe[2] or 0
    local spellID = recipe[4] or recipe[3] or 0
    local profName = PROFESSION_NAMES[skillLine] or "Crafted"

    local skillStr = ""
    if spellID > 0 then
        local spellName = GetSpellInfo(spellID)
        if spellName then skillStr = " |cff888888(" .. spellName .. ")|r" end
    end

    AddPanelLine("|cff66bbffCrafted: " .. profName .. "|r" .. skillStr)

    if ETB.ReagentData and spellID > 0 then
        local reags = ETB.ReagentData[spellID]
        if reags then
            AddPanelLine("|cff888888Reagents:|r")
            for _, entry in ipairs(reags) do
                local reagName = GetItemInfo(entry[1]) or ("Item #" .. entry[1])
                AddPanelLine("  " .. reagName .. " x" .. entry[2])
            end
        end
    end
end

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

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

function TE:Disable()
    ETB.Settings:Set("tooltips.enhance", false)
end

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