local addonName, nameSpace = ...
local SinsToolkit = nameSpace
if IsRetail() then
    nameSpace.baseWowheadUrl = "https://%swowhead.com/%s=%s%s"
end
if IsClassic() then
    nameSpace.baseWowheadUrl = "https://%swowhead.com/classic/%s=%s%s"
end
if IsBCC() then
    nameSpace.baseWowheadUrl = "https://%swowhead.com/tbc/%s=%s%s"
end
if IsMop() then
    nameSpace.baseWowheadUrl = "https://%swowhead.com/mop-classic/%s=%s%s"
end

nameSpace.baseWowheadAzEsUrl = "https://%swowhead.com/azerite-essence/%s%s"
nameSpace.baseWowheadTradingPostActivityUrl = "https://%swowhead.com/trading-post-activity/%s%s"
nameSpace.baseArmoryUrl = "https://worldofwarcraft.com/%s/character/%s/%s"
nameSpace.baseRaiderIoUrl = "https://raider.io/characters/%s/%s/%s"

local popupText = "%s Link\nCTRL-C to copy"


local function ShowUrlPopup(header, url)
    StaticPopup_Show("SinsToolkitWowheadQuickLinkUrl", header, nil, url)
end


local function CreateUrl(dataSources, strategies)
    for _, strategy in pairs(strategies) do
        local header, url = strategy(dataSources)
        if header and url then
            ShowUrlPopup(header, url)
            return
        end
    end
end

local function GetDataSources()
    local focus = {}
    local foci = GetMouseFoci()
    if foci[1] then
        focus = foci[1]
    end
    local tooltip = GameTooltip
    return {focus = focus, tooltip = tooltip}
end


function RunSinsToolkitWowheadQuickLink()
    if SinsToolkit and SinsToolkit.IsFeatureActive and not SinsToolkit.IsFeatureActive("wowheadSearchEnabled") then return end
    CreateUrl(GetDataSources(), nameSpace.strategies)
end


function RunSinsToolkitAlternativeQuickLink()
    if SinsToolkit and SinsToolkit.IsFeatureActive and not SinsToolkit.IsFeatureActive("wowheadSearchEnabled") then return end
    CreateUrl(GetDataSources(), nameSpace.altStrategies)
end


StaticPopupDialogs["SinsToolkitWowheadQuickLinkUrl"] = {
    text = popupText,
    button1 = "Close",
    OnShow = function(self, data)
        self:SetFrameStrata("FULLSCREEN_DIALOG")
        self:SetFrameLevel(1000)
        local function HidePopup(self) self:GetParent():Hide() end
        
        -- Changed from "if (IsRetail() or IsMop() or IsClassic()) then" to this to make it version agnostic
        local editBox = self.EditBox or self.editBox
        if not editBox then return end

        editBox:SetScript("OnEscapePressed", HidePopup)
        editBox:SetScript("OnEnterPressed", HidePopup)
        editBox:SetScript("OnKeyUp", function(self, key)
            if
                (IsControlKeyDown() and key == "C")
                or (IsKeyDown("C") and (key == "LCTRL" or key == "RCTRL"))
            then
                HidePopup(self)
            end
        end)
        editBox:SetMaxLetters(0)
        editBox:SetText(data)
        editBox:HighlightText()
    end,
    hasEditBox = true,
    editBoxWidth = 240,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

