--[[
TooltipUtils.lua - Mr. Mythical Gear Check Tooltip Utilities

Purpose: Functions for scanning item tooltips for various information
Dependencies: None
Author: Braunerr
--]]

local MrMythicalGearCheck = MrMythicalGearCheck or {}
MrMythicalGearCheck.TooltipUtils = {}

local TooltipUtils = MrMythicalGearCheck.TooltipUtils

--- Scan item tooltip for socket information
--- @param itemLink string Item link to scan
--- @param socketKeywords table Array of keywords to search for
--- @return number Number of empty sockets found
function TooltipUtils.scanTooltipForSockets(itemLink, socketKeywords)
    if not itemLink or not socketKeywords then
        return 0
    end

    if not _G["MrMythicalSocketTooltip"] then
        CreateFrame("GameTooltip", "MrMythicalSocketTooltip", nil, "GameTooltipTemplate")
    end
    local tooltip = _G["MrMythicalSocketTooltip"]
    tooltip:SetOwner(UIParent, "ANCHOR_NONE")
    tooltip:ClearLines()
    tooltip:SetHyperlink(itemLink)

    local emptySocketCount = 0

    local function normalizeTooltipText(text)
        -- Strip texture tags and color codes so matching works consistently.
        local cleaned = text:gsub("|T.-|t", "")
            :gsub("|c%x%x%x%x%x%x%x%x", "")
            :gsub("|r", "")
            :gsub("^%s+", "")
            :gsub("%s+$", "")
        return string.lower(cleaned)
    end

    for i = 1, tooltip:NumLines() do
        local line = _G["MrMythicalSocketTooltipTextLeft" .. i]
        if line then
            local text = line:GetText()
            if text then
                local normalizedText = normalizeTooltipText(text)
                for _, keyword in ipairs(socketKeywords) do
                    local normalizedKeyword = string.lower(keyword)
                    if normalizedKeyword ~= "" and normalizedText:find(normalizedKeyword, 1, true) then
                        emptySocketCount = emptySocketCount + 1
                        break -- Only count once per line
                    end
                end
            end
        end
    end

    tooltip:Hide()
    return emptySocketCount
end

--- Returns true when the item is a held-in-off-hand (INVTYPE_HOLDABLE).
--- Uses equip location from item APIs so this works on every client language.
--- @param itemLink string Item link to inspect
--- @return boolean
function TooltipUtils.scanTooltipForOffHandType(itemLink)
    if not itemLink then
        return false
    end

    local equipLoc
    if C_Item and C_Item.GetItemInfo then
        local ok, result = pcall(function()
            return select(9, C_Item.GetItemInfo(itemLink))
        end)
        if ok then
            equipLoc = result
        end
    end
    if not equipLoc and GetItemInfo then
        equipLoc = select(9, GetItemInfo(itemLink))
    end

    return equipLoc == "INVTYPE_HOLDABLE"
end

-- Export the module
MrMythicalGearCheck.TooltipUtils = TooltipUtils