local baseUrl = "https://www.wowhead.com/"
local keybind = "CTRL-C"
local popupText = "Wowhead %s Link\n" .. keybind .. " to copy"

local typeAttributeMap = {
	quest = { "id", "questId", "questID" },
	item = { info = { "id" } },
}

local function ShowUrlPopup(id, type)
	if not (id or type) then return end
	local url = baseUrl .. type .. "=" .. id
	StaticPopup_Show("WowheadQuestLinkUrl", type:sub(1, 1):upper() .. type:sub(2), _, url)
end

local function getIdAndType(focus)
	local function loop(focus, keys)
		if not focus then return end
		for key, value in pairs(keys) do
			if type(value) == "table" then return loop(focus[key], value) end
			local id = focus[value]
			if id then return id end
		end
	end
	if not focus then return end
	for type, keys in pairs(typeAttributeMap) do
		local id = loop(focus, keys)
		if id then return id, type end
	end
	return getIdAndType(focus:GetParent())
end

local function run()
	local focus = GetMouseFocus()
	local id, type = getIdAndType(focus)
	ShowUrlPopup(id, type)
end

StaticPopupDialogs["WowheadQuestLinkUrl"] = {
	text = popupText,
	button1 = "Close",
	OnShow = function(self, data)
		local function HidePopup(self) self:GetParent():Hide() end
		self.editBox:SetScript("OnEscapePressed", HidePopup)
		self.editBox:SetScript("OnEnterPressed", HidePopup)
		self.editBox:SetMaxLetters(0)
		self.editBox:SetText(data)
		self.editBox:HighlightText(0, self.editBox:GetNumLetters())
	end,
	hasEditBox = true,
	editBoxWidth = 233,
	timeout = 0,
	whileDead = true,
	hideOnEscape = true,
	preferredIndex = 3,
}

local btn = CreateFrame("BUTTON", "KeybindBtn")
SetBindingClick(keybind, btn:GetName())
btn:SetScript("OnClick", run)
