--local aura_env = aura_env
local CRESTS = {
    [0]={shortName="神勇石",color=HEIRLOOM_BLUE_COLOR},
    [1]={shortName="风化纹章",color=UNCOMMON_GREEN_COLOR,achieve=40942},
    [2]={shortName="蚀刻纹章",color=RARE_BLUE_COLOR,achieve=40943},
    [3]={shortName="符文纹章",color=ITEM_EPIC_COLOR,achieve=40944},
    [4]={shortName="鎏金纹章",color=ITEM_LEGENDARY_COLOR},
}

-- Upgrade tiers with crest change points 
-- ([i]=CRESTS[x]) where i = the upgrade level where crest type changes
-- i=4 means to upgrade from rank 4 to the next rank.
local UPGRADE_TIERS = {
    {
        name="Explorer", minIlvl=597, maxIlvl=619, maxUpgrade=8, color=ITEM_POOR_COLOR,
        crestLevels={ [1]=CRESTS[0], [4]=CRESTS[0], [8]=nil }
    },
    {
        name="Adventurer", minIlvl=610, maxIlvl=632, maxUpgrade=8, color=WHITE_FONT_COLOR,
        crestLevels={ [1]=CRESTS[0], [4]=CRESTS[1], [8]=nil }
    },
    {
        name="Veteran", minIlvl=623, maxIlvl=645, maxUpgrade=8, color=UNCOMMON_GREEN_COLOR,
        crestLevels={ [1]=CRESTS[1], [4]=CRESTS[2], [8]=nil }
    },
    {
        name="Champion", minIlvl=636, maxIlvl=658, maxUpgrade=8, color=RARE_BLUE_COLOR,
        crestLevels={ [1]=CRESTS[2], [4]=CRESTS[3], [8]=nil }
    },
    {
        name="Hero", minIlvl=649, maxIlvl=671, maxUpgrade=8, color=ITEM_EPIC_COLOR,
        crestLevels={ [1]=CRESTS[3], [4]=CRESTS[4], [8]=nil }
    },
    {
        name="Myth", minIlvl=662, maxIlvl=684, maxUpgrade=8, color=ITEM_LEGENDARY_COLOR,
        crestLevels={ [1]=CRESTS[4], [8]=nil }
    },
}

local SetValueToKey = function(list, field, valuesArray)
    local newList = {}
    for _,v in ipairs(list) do
        local key = v
        local data = true
        if field then 
            key = v[field]
        end
        if tonumber(key) then 
            key = tonumber(key)
        end
        if valuesArray then
            data = v
        end
        newList[key]=data
    end
    return newList
end

-- Get crest dynamically based on upgrade level
local function GetCrestForLevel(crestLevels, current, maxUpgrade)
    -- If at max upgrade, no crest is required
    if current == maxUpgrade then
        return nil
    end
    
    local selectedCrest = nil
    for level, crest in pairs(crestLevels) do
        if current >= level then
            selectedCrest = crest -- Update to highest applicable crest
        end
    end
    return selectedCrest
end

-- Get tier data based on item level and upgrade level
local function GetUpgradeTierData(ilvl, current, total)
    for _, tier in ipairs(UPGRADE_TIERS) do
        if ilvl >= tier.minIlvl and ilvl <= tier.maxIlvl and total == tier.maxUpgrade then
            -- Calculate expected ilvl for current upgrade level
            local step = (tier.maxIlvl - tier.minIlvl) / (tier.maxUpgrade - 1)
            local expectedIlvl = tier.minIlvl + (current - 1) * step
            local diff = math.abs(ilvl - expectedIlvl)
            
            if diff <= step then
                return {
                    name = tier.name, --english name
                    minIlvl = tier.minIlvl,
                    maxIlvl = tier.maxIlvl,
                    color = tier.color,
                    crest = GetCrestForLevel(tier.crestLevels, current, tier.maxUpgrade)
                }
            end
        end
    end
    return nil
end

-- process tooltip data
local function ProcessTooltip(tooltip, data)   
    local itemName, itemLink = TooltipUtil.GetDisplayedItem(tooltip)
    if not itemLink then return end
    
    --Create ItemMixin from itemLink
    local item = Item:CreateFromItemLink(itemLink)
    if item:IsItemEmpty() then return end
    local itemName, itemLink, itemLevel = item:GetItemName(), item:GetItemLink(), item:GetCurrentItemLevel()
    
    --Loop over current tooltip lines
    for i = 1, tooltip:NumLines() do
        local line = _G[tooltip:GetName().."TextLeft"..i]
        local text = line:GetText()
        
        if text and text:match(ITEM_UPGRADE_TOOLTIP_FORMAT_STRING:gsub("%%s %%d/%%d", "(%%D+ %%d+/%%d+)")) then
            local tier, current, total = text:match(ITEM_UPGRADE_TOOLTIP_FORMAT_STRING:gsub("%%s %%d/%%d", "(%%D+) (%%d+)/(%%d+)"))
            
            local tierData = GetUpgradeTierData(tonumber(itemLevel), tonumber(current), tonumber(total))
            if not tierData then return end            
            
            --Modify Upgrade Rank tooltip line
            local minIlvl = tierData.minIlvl
            local maxIlvl = tierData.maxIlvl
            if minIlvl and maxIlvl and itemLevel >= minIlvl and itemLevel <= maxIlvl then
                local tierHexColorMarkup = ""
                local rangeHexColorMarkup = ""
                
                --if aura_env.config.colorRange then
                    --rangeHexColorMarkup = CreateColor(unpack(aura_env.config.ilvlRangeColor)):GenerateHexColorMarkup()
                --end 
                --if aura_env.config.colorRank then
                    tierHexColorMarkup = tierData.color:GenerateHexColorMarkup()
                --end
                
                local newLineText = string.format("%s%d/%d %s|r %s[%d-%d]|r", 
                    tierHexColorMarkup, current, total, tier, 
                    rangeHexColorMarkup, minIlvl, maxIlvl
                )
                line:SetText(newLineText)
                line:Show()
            end
            
            --Add Crest required to upgrade
            if tierData.crest then  -- and aura_env.config.showUpgradeCurrency
                local crest = tierData.crest
                if crest then
                    local crestName = crest.shortName
                    local crestName_colored = crest.color:WrapTextInColorCode(crestName)
                    local achieve = crest.achieve and select(13, GetAchievementInfo(crest.achieve))
                    local rightLineText = "|A:2329:20:20:1:-1|a"..(not achieve and crestName_colored or "")
                    local rightLine = _G[tooltip:GetName().."TextRight"..i]
                    rightLine:SetText(rightLineText)
                    rightLine:Show()
                end
            end 
        end
    end
end


local function OnTooltipSetItem(tooltip, data)
    ProcessTooltip(tooltip, data)
end

--if not aura_env.region.hooked then
    --aura_env.region.hooked = true
    TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Item, OnTooltipSetItem)
--end