local _, ns = ...
local M, R, U, I = unpack(ns)
local RewardIcons_DisableBountyColors = false
--local RewardIcons_Size = 34

local GetCurrentMapID, tonumber, format, floor, pairs = 
	  function() return WorldMapFrame:GetMapID() or 0 end, tonumber, format, floor, pairs
local IsQuestComplete, IsQuestCriteriaForBounty = C_QuestLog.IsComplete, C_QuestLog.IsQuestCriteriaForBounty
local function GetCurrencyInfo(id)
	local data = C_CurrencyInfo.GetCurrencyInfo(id)
	return data.name, nil, data.iconFileID
end
local function GetQuestTagInfo(id)
	local data = C_QuestLog.GetQuestTagInfo(id)
	return data.tagID, data.tagName, data.worldQuestType, data.quality, data.isElite, data.tradeskillLineID, data.displayExpiration
end
local function WorldQuestList_IsAzeriteItemAtMaxLevel()
	return C_AzeriteItem.IsAzeriteItemAtMaxLevel()
end

local GetNumQuestLogRewardCurrencies, GetQuestLogRewardCurrencyInfo = GetNumQuestLogRewardCurrencies, GetQuestLogRewardCurrencyInfo
if not GetNumQuestLogRewardCurrencies then
	local reward_cache = {}
	local function GetData(questID)
		local data = reward_cache[questID]
		local t = GetTime()
		if not data or t > data.expTime then
			data = C_QuestLog.GetQuestRewardCurrencies(questID)
			data.expTime = t + 5
		end
		return data
	end
	function GetNumQuestLogRewardCurrencies(questID)
		local data = GetData(questID)
		return #data
	end
	function GetQuestLogRewardCurrencyInfo(i, questID)
		local data = GetData(questID)[i]
		if not data then
			return
		end
		local amount = data.totalRewardAmount
		return data.name, data.texture, amount, data.currencyID
	end
end

local ItemInfoCache = {}
local function GetItemInfoFromLink(itemLink)
	if not itemLink then return 0, 0 end
	if ItemInfoCache[itemLink] then
		return ItemInfoCache[itemLink].itemLevel, ItemInfoCache[itemLink].quality
	end

	local tooltipData = C_TooltipInfo.GetHyperlink(itemLink)
	local foundIlvl = 0
	local foundQuality = 0
	if tooltipData and tooltipData.lines then
		for _, line in ipairs(tooltipData.lines) do
			if line.itemLevel and line.itemLevel > 0 then
				foundIlvl = line.itemLevel
			end
			if line.quality and line.quality > 0 then
				foundQuality = line.quality
			end
			if foundIlvl > 0 and foundQuality > 0 then
				break
			end
		end
	end

	if foundIlvl == 0 then
		local _, _, _, baseIlvl = C_Item.GetItemInfo(itemLink)
		foundIlvl = baseIlvl or 0
	end
	if foundQuality == 0 then
		local _, _, baseQuality = C_Item.GetItemInfo(itemLink)
		foundQuality = baseQuality or 0
	end

	ItemInfoCache[itemLink] = {itemLevel = foundIlvl, quality = foundQuality}
	return foundIlvl, foundQuality
end

local WorldQuestList_QuestIDtoMapID = {}
local CacheQuestItemReward = {}
local CacheIsAnimaItem = {}
local list = {
	[1579] = 2164,
	[1598] = 2163,
	[1600] = 2157,
	[1595] = 2156,
	[1597] = 2103,
	[1596] = 2158,
	[1599] = 2159,
	[1593] = 2160,
	[1594] = 2162,
	[1592] = 2161,
	[1738] = 2373,
	[1739] = 2400,
	[1740] = 2391,
	[1742] = 2391,
	[1804] = 2407,
	[1805] = 2410,
	[1806] = 2465,
	[1807] = 2413,
	[1837] = 2445,
	[1838] = 2449,
	[1839] = 2453,
	[1840] = 2460,
	[1841] = 2455,
	[1842] = 2446,
	[1843] = 2461,
	[1844] = 2457,
	[1845] = 2450,
	[1846] = 2459,
	[1847] = 2458,
	[1848] = 2452,
	[1849] = 2448,
	[1850] = 2454,
	[1851] = 2456,
	[1852] = 2451,
	[1853] = 2447,
	[1907] = 2470,
	[1982] = 2478,
	[2106] = 2510,
	[2031] = 2507,
	[2108] = 2503,
	[2109] = 2511,
	[2420] = 2568,
	[2819] = 2615,
	[2652] = 2574,
	[2903] = 2600,
	[3004] = 2607,
	[3003] = 2605,
	[3002] = 2601,
	[2897] = 2590,
	[2899] = 2570,
}
do
	local prevTime = 0
	local prevRes
	function WorldQuestList_GetCallingQuests()
		local nowTime = GetTime()
		if (nowTime - prevTime < 15) and prevRes then
			return unpack(prevRes)
		end
		prevTime = nowTime
		prevRes = {}
		for i=1,C_QuestLog.GetNumQuestLogEntries() do
			local questID = C_QuestLog.GetQuestIDForLogIndex(i)
			if questID ~= 0 and C_QuestLog.IsQuestCalling(questID) then
				prevRes[#prevRes+1] = questID
			end
		end
		return unpack(prevRes)
	end
end

local GENERAL_MAPS = {
	[947] = 2,
	[875] = 1,
	[876] = 1,
	[619] = 4,
	[905] = 3,
	[994] = 3,
	[572] = 4,
	[113] = 4,
	[424] = 4,
	[12] = 4,
	[13] = 4,
	[101] = 4,
	[1550] = 1,
	[1978] = 1,
	[2274] = 1,
}
local LE = {
	LE_QUEST_TAG_TYPE_INVASION = Enum.QuestTagType.Invasion,
	LE_QUEST_TAG_TYPE_DUNGEON = Enum.QuestTagType.Dungeon,
	LE_QUEST_TAG_TYPE_RAID = Enum.QuestTagType.Raid,
	LE_WORLD_QUEST_QUALITY_RARE = Enum.WorldQuestQuality.Rare,
	LE_WORLD_QUEST_QUALITY_EPIC = Enum.WorldQuestQuality.Epic,
	LE_QUEST_TAG_TYPE_PVP = Enum.QuestTagType.PvP,
	LE_QUEST_TAG_TYPE_PET_BATTLE = Enum.QuestTagType.PetBattle,
	LE_QUEST_TAG_TYPE_PROFESSION = Enum.QuestTagType.Profession,
	LE_ITEM_QUALITY_COMMON = Enum.WorldQuestQuality.Common,
	LE_QUEST_TAG_TYPE_FACTION_ASSAULT = Enum.QuestTagType.FactionAssault,
	LE_QUEST_TAG_TYPE_THREAT = Enum.QuestTagType.Threat,
	BAG_ITEM_QUALITY_COLORS = BAG_ITEM_QUALITY_COLORS,
	ITEM_SPELL_TRIGGER_ONUSE = ITEM_SPELL_TRIGGER_ONUSE,
	ITEM_BIND_ON_EQUIP = ITEM_BIND_ON_EQUIP,
	ARTIFACT_POWER = ARTIFACT_POWER,
	AZERITE = GetCurrencyInfo(1553),
	ORDER_RESOURCES_NAME_LEGION = GetCurrencyInfo(1220),
	ORDER_RESOURCES_NAME_BFA = GetCurrencyInfo(1560),
}

function WorldQuestList_IsShadowlandsZone(mapID)
	mapID = mapID or GetCurrentMapID()
	return mapID >= 1525 and mapID < 2022 and mapID ~= 1978
end

function WorldQuestList_IsDragonflightZone(mapID)
	mapID = mapID or GetCurrentMapID()
	return mapID >= 2022 or mapID == 1978
end

function WorldQuestList_IsAzeriteItemAtMaxLevel()
	return C_AzeriteItem.IsAzeriteItemAtMaxLevel()
end

function WorldQuestList_IsFactionCurrency(currencyID)
	if list[currencyID or 0] then
		return true
	elseif C_CurrencyInfo.GetFactionGrantedByCurrency(currencyID) then
		return true
	else
		return false
	end
end

local function CreateMapTextOverlay(mapFrame,pinName)
	local mapCanvas = mapFrame:GetCanvas()

	local textsFrame = CreateFrame("Frame",nil,mapCanvas)
	textsFrame:SetPoint("TOPLEFT")
	textsFrame:SetSize(1,1)
	textsFrame:SetFrameLevel(10000)

	local textsTable = {}
	textsTable.s = 1
	textsTable.f = textsFrame
	textsTable.c = mapCanvas
	textsTable.prevScale = nil
	textsTable.prevZoom = nil

	local prevScale = nil
	local prevZoom = nil
	local elapsed = 0

	local function UpdateScale()
		local pins = mapFrame.pinPools[pinName]
		if not pins then return end

		local scaleFactor,startScale,endScale

		for obj in mapFrame:EnumeratePinsByTemplate("WorldMap_WorldQuestPinTemplate") do
			scaleFactor = obj.scaleFactor
			startScale = obj.startScale
			endScale = obj.endScale
			break
		end

		local scale
		if startScale and endScale then
			local parentScaleFactor = 1.0 / mapFrame:GetCanvasScale()
			scale = parentScaleFactor * Lerp(startScale, endScale, Saturate(scaleFactor * mapFrame:GetCanvasZoomPercent()))
		else
			scale = 1
		end

		if scale then
			scale = scale * mapFrame:GetGlobalPinScale()
			for i=1,#textsTable do
				textsTable[i]:SetScale(scale)
			end
		end

		textsTable.s = scale or 1
	end

	textsFrame:SetScript("OnUpdate", function(self, e)
		elapsed = elapsed + e

		if elapsed < 0.15 then return end
		elapsed = 0

		local nowScale = mapCanvas:GetScale()
		local nowZoom = mapFrame:GetCanvasZoomPercent()

		if nowScale ~= textsTable.prevScale or nowZoom ~= textsTable.prevZoom then
			textsTable.prevScale = nowScale
			textsTable.prevZoom = nowZoom
			UpdateScale()
		end
	end)

	mapFrame:HookScript("OnShow", function()
		C_Timer.After(0, UpdateScale)
	end)

	return textsTable
end

local WorldMapFrame_TextTable = CreateMapTextOverlay(WorldMapFrame,"WorldMap_WorldQuestPinTemplate")

local function AddText(table,obj,num,text)
	num = num + 1
	local t = table[num]
	if not t then
		t = CreateFrame("Frame",nil,table.c)
		t:SetSize(1,1)
		t.t = t:CreateFontString(nil,"OVERLAY","GameFontWhite")
		t.t:SetPoint("CENTER")
		t:SetScale(table.s)
		table[num] = t
	end

	t.obj = obj:GetParent()

	if t.obj then
		local lvl = t.obj:GetFrameLevel()
		if t.frLvl ~= lvl then
			t:SetFrameLevel(lvl)
			t.frLvl = lvl
		end
	end

	t.t:SetFont(STANDARD_TEXT_FONT,12,"OUTLINE")
	t.t:SetTextColor(1,1,1,1)

	t:SetPoint("CENTER",obj,0,0)
	t.t:SetText(text)

	if not t:IsShown() then
		t:Show()
	end	

	return num
end

function WorldQuestList_WQIcons_AddIcons(frame,pinName)
	local RewardIcons_Size = R.db["Misc"]["WorldQusetRewardIconsSize"]
	frame = frame or WorldMapFrame
	local pins = frame.pinPools[pinName or "WorldMap_WorldQuestPinTemplate"]
	if pins then
		local isWorldMapFrame = frame == WorldMapFrame
		local isRibbonDisabled = isWorldMapFrame and GENERAL_MAPS[GetCurrentMapID()]
		local tCount = 0
		local bountyMapID = frame:GetMapID() or 0
		if bountyMapID == 1014 then bountyMapID = 876 
		elseif bountyMapID == 1011 then bountyMapID = 875 end
		local bounties = C_QuestLog.GetBountiesForMapID(bountyMapID) or {}
		for _,bountyData in pairs(bounties) do
			local t = C_TaskQuest.GetQuestTimeLeftMinutes(bountyData.questID) or 0
			if t < 1440 then
				bountyData.lowTime = true
			elseif t < 2880 then
				bountyData.middleTime = true
			end
			if IsQuestComplete(bountyData.questID) or t == 0 then
				bountyData.completed = true
			end
		end
		local mapsToHighlightCallings = {}
		do
			local p = 1
			local questID = WorldQuestList_GetCallingQuests()
			while questID do
				local mapID, worldQuests, worldQuestsElite, dungeons, treasures = C_QuestLog.GetQuestAdditionalHighlights(questID)
				if mapID and mapID ~= 0 then
					local callingData = {questID = questID, mapID = mapID, worldQuests = worldQuests, worldQuestsElite = worldQuestsElite, dungeons = dungeons, treasures = treasures}

					local t = C_TaskQuest.GetQuestTimeLeftMinutes(questID) or 0
					if t < 1440 then
						callingData.lowTime = true
					elseif t < 2880 then
						callingData.middleTime = true
					end
					if IsQuestComplete(questID) or t == 0 then
						callingData.completed = true
					end

					mapsToHighlightCallings[#mapsToHighlightCallings+1] = callingData
				end
				p = p + 1
				questID = select(p,WorldQuestList_GetCallingQuests())
			end
		end
		if isWorldMapFrame then
			if not WorldMapFrame_TextTable.f:IsShown() then
				WorldMapFrame_TextTable.f:Show()
			end
		end
		local warMode = C_PvP.IsWarModeDesired()
		local warModeBonus = C_PvP.GetWarModeRewardBonus() / 100 + 1		
		local selectedQuestID = C_SuperTrack.GetSuperTrackedQuestID()
		
		for obj in frame:EnumeratePinsByTemplate("WorldMap_WorldQuestPinTemplate") do
			local icon = obj.WQL_rewardIcon
			if obj.questID then
				if not icon then
					icon = obj:CreateTexture(nil,"ARTWORK")
					obj.WQL_rewardIcon = icon
					icon:SetPoint("CENTER",0,0)
					icon:SetSize(RewardIcons_Size,RewardIcons_Size)
					local Border = obj:CreateTexture(nil, 'OVERLAY', nil, 1)
					Border:SetPoint('CENTER', 0, 0)
					Border:SetAtlas('worldquest-emissary-ring')
					Border:SetSize(RewardIcons_Size + 2 , RewardIcons_Size + 2)
					obj.Border = Border
					
					local eliteBorder = obj:CreateTexture(nil, "OVERLAY", nil, 2)
					obj.WQL_EliteBorder = eliteBorder
					eliteBorder:SetPoint("CENTER", icon, "CENTER", 0, 0)
					eliteBorder:SetSize(RewardIcons_Size + 5, RewardIcons_Size + 5)
					eliteBorder:SetAtlas("worldquest-questmarker-dragon")
					eliteBorder:Hide()
							
					local iconWMask = obj:CreateTexture(nil,"ARTWORK")
					obj.WQL_rewardIconWMask = iconWMask
					iconWMask:SetPoint("CENTER",0,0)
					iconWMask:SetSize(RewardIcons_Size,RewardIcons_Size)
						iconWMask:SetMask("Interface\\CharacterFrame\\TempPortraitAlphaMask")
					
					local ribbon = obj:CreateTexture(nil,"BACKGROUND")
					obj.WQL_rewardRibbon = ribbon
					ribbon:SetPoint("TOP",obj,"BOTTOM",0,16)
					ribbon:SetSize(RewardIcons_Size*2,RewardIcons_Size)
					
					if not isWorldMapFrame then
						local ribbonText = obj:CreateFontString(nil,"BORDER","GameFontWhite")
						obj.WQL_rewardRibbonText = ribbonText
						local a1,a2 = ribbonText:GetFont()
						ribbonText:SetFont(a1,12)
						ribbonText:SetPoint("CENTER",ribbon,0,0)
						ribbonText:SetTextColor(0,0,0,1)
					end
					
					local iconTopRight = obj:CreateTexture(nil, "ARTWORK", nil, 7)
					obj.WQL_iconTopRight = iconTopRight
					iconTopRight:SetPoint("CENTER",obj,"TOPRIGHT",0,0)
					iconTopRight:SetSize(RewardIcons_Size*0.7,RewardIcons_Size*0.7)
					iconTopRight.SIZE_MOD = 0.7
					
					local selectionIndicator = obj:CreateTexture(nil, "OVERLAY")
					selectionIndicator:SetPoint("TOP", icon, "TOP", 0, 22)
					selectionIndicator:SetSize(18, 18)
					selectionIndicator:SetTexture("Interface\\Common\\friendship-archivistscodex")
					selectionIndicator:SetDrawLayer("OVERLAY", 7)

					local indicatorFrame = CreateFrame("Frame", nil, obj)
					indicatorFrame:SetAllPoints(selectionIndicator)
					indicatorFrame:SetFrameLevel(obj:GetFrameLevel() + 10)
					selectionIndicator:SetParent(indicatorFrame)

					selectionIndicator:Hide()
					obj.SelectionIndicator = selectionIndicator
					obj.IndicatorFrame = indicatorFrame

					obj.WQL_BountyRing_defSize = obj.BountyRing and obj.BountyRing:GetSize()
				end

				local tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex, displayTimeLeft = GetQuestTagInfo(obj.questID)

				if isElite then
					obj.WQL_EliteBorder:Show()
				else
					obj.WQL_EliteBorder:Hide()
				end
				
				if selectedQuestID and obj.questID == selectedQuestID then
					if obj.SelectionIndicator then
						obj.SelectionIndicator:Show()
						if obj.IndicatorFrame then
							obj.IndicatorFrame:Show()
						end
					end
				else
					if obj.SelectionIndicator then
						obj.SelectionIndicator:Hide()
						if obj.IndicatorFrame then
							obj.IndicatorFrame:Hide()
						end
					end
				end
				
				local iconAtlas,iconTexture,iconVirtual,iconGray = nil
				local ajustSize,ajustMask = 0
				local amount,amountIcon,amountColor = 0

				local money = GetQuestLogRewardMoney(obj.questID)
				local goldAmount = 0
				local hasGoldReward = false
				local goldOnly = false
				
				if money > 0 then
					goldAmount = floor(money / 10000 * (warMode and C_QuestLog.QuestCanHaveWarModeBonus(obj.questID) and warModeBonus or 1))
					local numItems = GetNumQuestLogRewards(obj.questID)
					local numCurrencies = GetNumQuestLogRewardCurrencies(obj.questID)
					if goldAmount > 500 then
						hasGoldReward = true
					elseif numItems == 0 and numCurrencies == 0 then
						hasGoldReward = true
						goldOnly = true
					end
					if hasGoldReward then
						iconAtlas = "Auctioneer"
						amount = goldAmount
					end
				end

				local currencies = {}
				local items = {}
				if not goldOnly then
					for i = 1, GetNumQuestLogRewardCurrencies(obj.questID) do
						local name, texture, numItems, currencyID = GetQuestLogRewardCurrencyInfo(i, obj.questID)
						if numItems and numItems > 0 then
							local warModeMultiplier = (warMode and C_QuestLog.QuestCanHaveWarModeBonus(obj.questID) and C_CurrencyInfo.DoesWarModeBonusApply(currencyID) and warModeBonus or 1)
							local finalAmount = floor(numItems * warModeMultiplier)
							currencies[#currencies+1] = {
								texture = texture,
								amount = finalAmount,
							}
						end
					end

					for i = 1, GetNumQuestLogRewards(obj.questID) do
						local name, icon, numItems, quality, _, itemID = GetQuestLogRewardInfo(i, obj.questID)
						if itemID then
							local itemLink = CacheQuestItemReward[obj.questID]
							if not itemLink then
								local tooltipData = C_TooltipInfo.GetQuestLogItem("reward", i, obj.questID)
								if tooltipData then
									itemLink = tooltipData.hyperlink
								end
								CacheQuestItemReward[obj.questID] = itemLink
							end
							local realItemLevel, realItemQuality = GetItemInfoFromLink(itemLink)
							if realItemLevel == 0 then
								realItemLevel = select(4, C_Item.GetItemInfo(itemID)) or 0
							end
							if realItemQuality == 0 then
								realItemQuality = quality
							end

							local isEquippable = C_Item.IsEquippableItem(itemID)
							
							local itemData = {
								itemID = itemID,
								icon = icon,
								numItems = numItems or 1,
								quality = realItemQuality,
								itemLevel = realItemLevel,
								iconTexture = icon,
								ajustMask = true,
								ajustSize = 4,
								amount = realItemLevel,
								equippable = isEquippable,
							}

							if isEquippable then
								itemData.amount = realItemLevel
							else
								itemData.amount = itemData.numItems
							end

							if itemID == 245653 then
								itemData.iconTexture = 133016
								itemData.amount = numItems
							elseif itemID == 124124 or itemID == 151568 then
								itemData.amount = numItems
							elseif itemID == 152668 and numItems and numItems > 1 then
								itemData.amount = numItems
							elseif itemID == 198048 or itemID == 198056 or itemID == 198058 or itemID == 198059 or itemID == 204673 then
								itemData.amount = (itemID == 198048 and "I" or itemID == 198056 and "II" or itemID == 198058 and "III" or itemID == 204673 and "V" or "IV")
							elseif itemID == 228339 or itemID == 228338 then
								itemData.amount = (itemID == 228338 and "I" or itemID == 228339 and "II" or "III")
							end

							if CacheIsAnimaItem[itemID] then
								itemData.iconTexture = 613397
								itemData.ajustMask = true
								itemData.ajustSize = 10
								local animaAmount = numItems * CacheIsAnimaItem[itemID]
								if warMode and C_QuestLog.QuestCanHaveWarModeBonus(obj.questID) then
									local bonus = floor(animaAmount * (warModeBonus - 1) + .5)
									bonus = bonus - bonus % 3
									animaAmount = animaAmount + bonus
								end
								itemData.amount = animaAmount
							elseif select(2, C_Item.GetItemInfoInstant(itemID)) == MISCELLANEOUS then
								local tooltipData = C_TooltipInfo.GetQuestLogItem("reward", i, obj.questID)
								if tooltipData then
									local isAnima
									for j=2, #tooltipData.lines do
										local tooltipLine = tooltipData.lines[j]
										local text = tooltipLine.leftText
										if text and text:find(WORLD_QUEST_REWARD_FILTERS_ANIMA.."|r$") then
											isAnima = 1
										elseif text and isAnima and text:find("^"..LE.ITEM_SPELL_TRIGGER_ONUSE) then
											local num = text:gsub("(%d+)[ %.,]+(%d+)","%1%2"):match("%d+")
											isAnima = tonumber(num or "") or 1
											break
										end 
									end
									if isAnima then
										if isAnima ~= 1 then
											CacheIsAnimaItem[itemID] = isAnima
										end
										itemData.iconTexture = 613397
										itemData.ajustMask = true
										itemData.ajustSize = 10
										local animaAmount = numItems * isAnima
										if warMode and C_QuestLog.QuestCanHaveWarModeBonus(obj.questID) then
											local bonus = floor(animaAmount * (warModeBonus - 1) + .5)
											bonus = bonus - bonus % 3
											animaAmount = animaAmount + bonus
										end
										itemData.amount = animaAmount
									end
								end
							end

							items[#items+1] = itemData
						end
					end
				end

				local selected = nil
				if hasGoldReward then
					selected = { type = "gold", iconAtlas = iconAtlas, amount = amount }
				elseif #items > 0 then
					table.sort(items, function(a, b)
						if a.itemLevel ~= b.itemLevel then return a.itemLevel > b.itemLevel end
						return (a.numItems or 0) > (b.numItems or 0)
					end)
					selected = items[1]
					selected.type = "item"
				elseif #currencies > 0 then
					table.sort(currencies, function(a, b) return a.amount > b.amount end)
					selected = currencies[1]
					selected.type = "currency"
				end

				if worldQuestType == LE.LE_QUEST_TAG_TYPE_PET_BATTLE then
					iconVirtual = true
					if selected and selected.type == "item" then
						amountIcon = selected.icon
						amount = selected.amount
						if selected.iconTexture then
							amountIcon = selected.iconTexture
						end
					elseif selected and selected.type == "currency" then
						amountIcon = selected.texture
						amount = selected.amount
					elseif selected and selected.type == "gold" then
						amountIcon = nil
						amount = selected.amount
					end
					selected = nil
					iconTexture = nil
					iconAtlas = nil

					if obj.WQL_rewardIcon then
						obj.WQL_rewardIcon:SetTexture(nil)
						obj.WQL_rewardIcon:SetAtlas(nil)
					end
					if obj.WQL_rewardIconWMask then
						obj.WQL_rewardIconWMask:SetTexture(nil)
					end
				end

				if selected and selected.type == "gold" then
					iconAtlas = selected.iconAtlas
					amount = selected.amount
					iconTexture = nil
					iconVirtual = nil
					iconGray = nil
					ajustSize = 0
					ajustMask = false
				elseif selected and selected.type == "item" then
					iconAtlas = selected.iconAtlas
					iconTexture = selected.iconTexture
					ajustMask = selected.ajustMask
					ajustSize = selected.ajustSize
					amount = selected.amount
					amountIcon = nil
					amountColor = nil
					if selected.equippable and selected.quality and selected.quality > 1 then
						local r, g, b = C_Item.GetItemQualityColor(selected.quality)
						if r and g and b then
							amountColor = "|cff"..string.format("%02x%02x%02x", r*255, g*255, b*255)
						end
					end
				elseif selected and selected.type == "currency" then
					iconAtlas = nil
					iconTexture = selected.texture
					ajustMask = true
					ajustSize = 0
					amount = selected.amount
					amountIcon = nil
					iconGray = nil
				end

					if worldQuestType == LE.LE_QUEST_TAG_TYPE_PVP then
						if obj.WQL_iconTopRight.curr ~= "worldquest-icon-pvp-ffa" then
							obj.WQL_iconTopRight:SetSize(RewardIcons_Size*0.5,RewardIcons_Size*0.5)
							obj.WQL_iconTopRight:SetPoint("TOPLEFT", obj, "TOPLEFT", 0, 22)
							obj.WQL_iconTopRight:SetAtlas("worldquest-icon-pvp-ffa")
							obj.WQL_iconTopRight.curr = "worldquest-icon-pvp-ffa"
						end
					elseif worldQuestType == LE.LE_QUEST_TAG_TYPE_FACTION_ASSAULT then
						local icon = UnitFactionGroup("player") == "Alliance" and "worldquest-icon-horde" or "worldquest-icon-alliance"
						if obj.WQL_iconTopRight.curr ~= icon then
							obj.WQL_iconTopRight:SetSize(RewardIcons_Size*0.5,RewardIcons_Size*0.5)
							obj.WQL_iconTopRight:SetPoint("TOPLEFT", obj, "TOPLEFT", 0, 22)
							obj.WQL_iconTopRight:SetAtlas("worldquest-icon-pvp-ffa")
							obj.WQL_iconTopRight.curr = "worldquest-icon-pvp-ffa"
						end
					else
						if obj.WQL_iconTopRight.curr then
							obj.WQL_iconTopRight:SetSize(RewardIcons_Size,RewardIcons_Size)
							obj.WQL_iconTopRight:SetTexture()
							obj.WQL_iconTopRight.curr = nil
						end						
					end

				if not iconVirtual and (iconTexture or iconAtlas) then
					local res_size = (RewardIcons_Size+ajustSize) * 0.5
					icon:SetSize(res_size,res_size)
					obj.WQL_rewardIconWMask:SetSize(res_size,res_size)
					if iconTexture then
						if ajustMask then
							if obj.WQL_rewardIconWMask.curr ~= iconTexture then
								obj.WQL_rewardIconWMask:SetTexture(iconTexture)
								obj.WQL_rewardIconWMask.curr = iconTexture
							end
							if icon.curr then
								icon:SetTexture()
								icon.curr = nil
							end
						else
							if obj.WQL_rewardIconWMask.curr then
								obj.WQL_rewardIconWMask:SetTexture()
								obj.WQL_rewardIconWMask.curr = nil
							end
							if icon.curr ~= iconTexture then
								icon:SetTexture(iconTexture)
								icon.curr = iconTexture
								if iconGray then
									icon:SetDesaturated(true)
								else
									icon:SetDesaturated(false)
								end
							end
						end
					else
						if obj.WQL_rewardIconWMask.curr then
							obj.WQL_rewardIconWMask:SetTexture()
							obj.WQL_rewardIconWMask.curr = nil
						end
						if icon.curr ~= iconAtlas then
							icon:SetAtlas(iconAtlas)
							icon.curr = iconAtlas
							if iconGray then
								icon:SetDesaturated(true)
							else
								icon:SetDesaturated(false)
							end
						end
					end
					if obj.Display then
						obj.Display.Icon:SetTexture()
						obj.WQL_rewardIcon:SetParent(obj.Display.Icon:GetParent())
						obj.WQL_rewardIcon:SetDrawLayer("ARTWORK",7)
						obj.WQL_rewardIconWMask:SetParent(obj.Display.Icon:GetParent())
						obj.WQL_rewardIconWMask:SetDrawLayer("ARTWORK",7)
					end
				elseif not iconVirtual then
					if obj.WQL_rewardIconWMask.curr then
						obj.WQL_rewardIconWMask:SetTexture()
						obj.WQL_rewardIconWMask.curr = nil
					end
					if icon.curr then
						icon:SetTexture()
						icon.curr = nil
					end
				end

				local showRibbon = false
				local ribbonText = ""
				if iconVirtual then
					showRibbon = true
					ribbonText = (amountIcon and "|T"..amountIcon..":0|t" or "")..(amountColor or "")..amount
				elseif selected and selected.type == "item" and ((type(amount)=="number" and amount > 0) or type(amount) == "string") then
					showRibbon = true
					ribbonText = (amountIcon and "|T"..amountIcon..":0|t" or "")..(amountColor or "")..amount
				elseif selected and selected.type == "currency" and amount > 0 then
					showRibbon = true
					ribbonText = (amountIcon and "|T"..amountIcon..":0|t" or "")..(amountColor or "")..amount
				elseif selected and selected.type == "gold" and amount > 0 then
					showRibbon = true
					ribbonText = amount
				end

				if showRibbon and not isRibbonDisabled then
					if not obj.WQL_rewardRibbon:IsShown() then obj.WQL_rewardRibbon:Show() end
					if not isWorldMapFrame then
						obj.WQL_rewardRibbonText:SetFont(STANDARD_TEXT_FONT,12,"OUTLINE")
						obj.WQL_rewardRibbonText:SetTextColor(1,1,1,1)
					end
					obj.WQL_rewardRibbon:SetAlpha(1)
					if not isWorldMapFrame then
						obj.WQL_rewardRibbonText:SetText(ribbonText)
					end
					obj.WQL_rewardRibbon:SetWidth( ((#tostring(amount) + (amountIcon and 1.5 or 0)) * RewardIcons_Size * 2) * 0.6 )

					local ribbonXOffset = 0
					if worldQuestType == LE.LE_QUEST_TAG_TYPE_PET_BATTLE then
						ribbonXOffset = 12
					end
					obj.WQL_rewardRibbon:ClearAllPoints()
					obj.WQL_rewardRibbon:SetPoint("TOP", obj, "BOTTOM", ribbonXOffset, 16)

					obj.TimeLowFrame:SetPoint("CENTER",-8,-8)
					if isWorldMapFrame then
						tCount = AddText(WorldMapFrame_TextTable,obj.WQL_rewardRibbon,tCount,ribbonText)							
					end
				else
					if obj.WQL_rewardRibbon:IsShown() then
						obj.WQL_rewardRibbon:Hide()
						if not isWorldMapFrame then
							obj.WQL_rewardRibbonText:SetText("")
						end
						obj.TimeLowFrame:SetPoint("CENTER",8,-8)				
					end
				end
				obj.WQL_questID = obj.questID

				if obj.BountyRing then
				obj.BountyRing:SetVertexColor(1,1,1)
				obj.BountyRing:SetSize(obj.WQL_BountyRing_defSize,obj.WQL_BountyRing_defSize)
				obj.BountyRing.WQL_color = 4
				if not RewardIcons_DisableBountyColors then
					obj.BountyRing:Hide()
					for _,bountyData in pairs(bounties) do
						if IsQuestCriteriaForBounty(obj.questID, bountyData.questID) and not bountyData.completed then
							obj.BountyRing:SetSize(RewardIcons_Size*2.5,RewardIcons_Size*2.5)
							obj.BountyRing:Show()
							if bountyData.lowTime and obj.BountyRing.WQL_color > 1 then
								obj.BountyRing:SetVertexColor(1,0,0)
								obj.BountyRing.WQL_color = 1
							elseif bountyData.middleTime and obj.BountyRing.WQL_color > 2 then
								obj.BountyRing:SetVertexColor(1,.5,0)
								obj.BountyRing.WQL_color = 2
							elseif not bountyData.lowTime and not bountyData.middleTime and obj.BountyRing.WQL_color > 3 then
								obj.BountyRing:SetVertexColor(.3,1,.3)
								obj.BountyRing.WQL_color = 3
								end
							end
						end
						local mapID = WorldQuestList_QuestIDtoMapID[obj.questID or 0]
						if mapID then
							for i=1,#mapsToHighlightCallings do
								local callingData = mapsToHighlightCallings[i]
								if callingData and callingData.mapID == mapID and (callingData.worldQuests or (callingData.worldQuestsElite and isElite)) and not callingData.completed then
									obj.BountyRing:SetSize(RewardIcons_Size*2.5,RewardIcons_Size*2.5)
									obj.BountyRing:Show()
									if callingData.lowTime and obj.BountyRing.WQL_color > 1 then
										obj.BountyRing:SetVertexColor(1,0,0)
										obj.BountyRing.WQL_color = 1
									elseif callingData.middleTime and obj.BountyRing.WQL_color > 2 then
										obj.BountyRing:SetVertexColor(1,.5,0)
										obj.BountyRing.WQL_color = 2
									elseif not callingData.lowTime and not callingData.middleTime and obj.BountyRing.WQL_color > 3 then
										obj.BountyRing:SetVertexColor(.3,1,.3)
										obj.BountyRing.WQL_color = 3
									end
							end
						end
					end
				end
		end
			else
			if obj.WQL_rewardIcon then
				if obj.WQL_rewardIconWMask.curr then
					obj.WQL_rewardIconWMask:SetTexture()
					obj.WQL_rewardIconWMask.curr = nil
				end
				if obj.WQL_rewardIcon.curr then
					obj.WQL_rewardIcon:SetTexture()
					obj.WQL_rewardIcon.curr = nil
				end
				if obj.WQL_iconTopRight.curr then
					obj.WQL_iconTopRight:SetTexture()
					obj.WQL_iconTopRight.curr = nil
				end
				obj.WQL_rewardRibbon:Hide()
				if not isWorldMapFrame then
					obj.WQL_rewardRibbonText:SetText("")
				end
				obj.TimeLowFrame:SetPoint("CENTER",8,-8)
					if obj.BountyRing then
				obj.BountyRing:SetSize(obj.WQL_BountyRing_defSize,obj.WQL_BountyRing_defSize)
				obj.BountyRing:SetVertexColor(1,1,1)
				end
			end
			obj.WQL_questID = nil
			if obj.SelectionIndicator then
				obj.SelectionIndicator:Hide()
			end
			end
		end
		if isWorldMapFrame then
			for i=tCount+1,#WorldMapFrame_TextTable do
				WorldMapFrame_TextTable[i]:Hide()
			end
			if WorldMapFrame_TextTable then
				WorldMapFrame_TextTable.prevScale = nil
				WorldMapFrame_TextTable.prevZoom = nil
			end
		end

	elseif frame == WorldMapFrame then
		for i=1,#WorldMapFrame_TextTable do
			WorldMapFrame_TextTable[i]:Hide()
		end
	end

	WorldQuestList_WQUpdateWMIcons(frame)
end

function WorldQuestList_WQUpdateWMIcons(frame)
		frame = frame or WorldMapFrame
		local isEnabled = false
		if frame.EnumeratePinsByTemplate then
			local currNum, questsNum = 0
			if isEnabled then
				for i = 1, C_QuestLog.GetNumQuestLogEntries() do
					local info = C_QuestLog.GetInfo(i)
					if info.questID and not C_QuestLog.IsComplete(info.questID) and not info.isHeader then
						if not questsNum then
							questsNum = {}
						end
						currNum = currNum + 1
						questsNum[info.questID] = currNum
					end
				end
			end
			for obj in frame:EnumeratePinsByTemplate("QuestPinTemplate") do
				if not obj.Display then

				elseif questsNum and questsNum[obj.questID] then
					obj.Display.Icon:SetAlpha(0)
					if not obj.Display.WQL_Text then
						obj.Display.WQL_Text = obj:CreateFontString(nil,"OVERLAY","GameFontNormal")
						local a1,a2 = obj.Display.WQL_Text:GetFont()
						obj.Display.WQL_Text:SetFont(a1,12,"OUTLINE")
						obj.Display.WQL_Text:SetPoint("CENTER",0,0)
					end
					obj.Display.WQL_Text:SetText(questsNum[obj.questID])
					obj.Display.WQL_Text:Show()
				elseif obj.Display.WQL_Text then
					obj.Display.Icon:SetAlpha(1)
					obj.Display.WQL_Text:Hide()
				end
			end
			for obj in QuestScrollFrame.Contents.buttonPool:EnumerateActive() do
				if not obj.Display then

				elseif obj.questID and questsNum and questsNum[obj.questID] then
					obj.Display.Icon:SetAlpha(0)
					if not obj.Display.WQL_Text then
						obj.Display.WQL_Text = obj:CreateFontString(nil,"OVERLAY","GameFontNormal")
						local a1,a2 = obj.Display.WQL_Text:GetFont()
						obj.Display.WQL_Text:SetFont(a1,12,"OUTLINE")
						obj.Display.WQL_Text:SetPoint("CENTER",0,0)
					end
					obj.Display.WQL_Text:SetText(questsNum[obj.questID])
					obj.Display.WQL_Text:Show()
				elseif obj.Display and obj.Display.WQL_Text then
					obj.Display.Icon:SetAlpha(1)
					obj.Display.WQL_Text:Hide()
				end
			end
		end
end


WorldMapFrame:RegisterCallback("WorldQuestsUpdate", function()
	WorldQuestList_WQIcons_AddIcons()
end)

local WQIcons_FlightMapLoad = CreateFrame("Frame")
WQIcons_FlightMapLoad:RegisterEvent("ADDON_LOADED")
WQIcons_FlightMapLoad:SetScript("OnEvent",function (self, event, arg)
	if arg == "Blizzard_FlightMap" then
		self:UnregisterAllEvents()
		FlightMapFrame:RegisterCallback("WorldQuestsUpdate", function()
			WorldQuestList_WQIcons_AddIcons(FlightMapFrame,"FlightMap_WorldQuestPinTemplate")
		end, self)
	end
end)

local function SetupSelectionTracking()
	WorldMapFrame:HookScript("OnShow", function()
		WorldMapFrame:RegisterEvent("QUEST_ACCEPTED")
		WorldMapFrame:RegisterEvent("QUEST_REMOVED")
		WorldMapFrame:RegisterEvent("SUPER_TRACKING_CHANGED")
	end)
	
	WorldMapFrame:HookScript("OnHide", function()
		WorldMapFrame:UnregisterEvent("QUEST_ACCEPTED")
		WorldMapFrame:UnregisterEvent("QUEST_REMOVED")
		WorldMapFrame:UnregisterEvent("SUPER_TRACKING_CHANGED")
		collectgarbage("collect")
	end)
	
	WorldMapFrame:HookScript("OnEvent", function(self, event, ...)
		if event == "QUEST_ACCEPTED" or event == "QUEST_REMOVED" or event == "SUPER_TRACKING_CHANGED" then
			C_Timer.After(0, function()
				WorldQuestList_WQIcons_AddIcons()
			end)
		end
	end)
end

SetupSelectionTracking()