local _, addonTable = ...
local WipedQoL = addonTable.WipedQoL
local UI = addonTable.UI
local TRANSLATE = addonTable.TRANSLATE or function(msg) return msg end

local function FindLegacyWordRange(text)
    for _, word in ipairs({ "legacy", "altem" }) do
        local startIndex = text:find(word, 1, true)
        if startIndex then
            return text:sub(1, startIndex - 1), word
        end
    end
    return nil, nil
end

local function AddTextRangeUnderline(section, fontString, fontSize, yOffset, r, g, b, a)
    local prefix, phrase = FindLegacyWordRange(fontString:GetText() or "")
    if not prefix then
        return
    end

    local prefixMeasure = section:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    prefixMeasure:SetText(prefix)
    prefixMeasure:SetAlpha(0)
    UI.ApplyFont(prefixMeasure, fontSize, "")

    local phraseMeasure = section:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    phraseMeasure:SetText(phrase)
    phraseMeasure:SetAlpha(0)
    UI.ApplyFont(phraseMeasure, fontSize, "")

    local underline = section:CreateTexture(nil, "OVERLAY")
    underline:SetColorTexture(r, g, b, a)
    underline:SetPoint(
        "TOPLEFT",
        fontString,
        "TOPLEFT",
        prefixMeasure:GetStringWidth(),
        yOffset
    )
    underline:SetSize(math.max(phraseMeasure:GetStringWidth(), 1), 1)
end

local AUTO_LOOT_ROLL_OPTIONS = {
    { value = "need", label = "Need" },
    { value = "transmog", label = "Transmog" },
    { value = "greed", label = "Greed" },
    { value = "pass", label = "Pass" },
}

local function CreateTextButton(parent, width, label)
    local button = CreateFrame("Button", nil, parent)
    button:SetSize(width or 80, 26)
    UI.SkinButton(button)

    button.text = UI.CreateLabel(button, label, 12)
    button.text:SetPoint("CENTER", button, "CENTER", 0, 0)
    button.text:SetTextColor(0.88, 0.88, 0.88)

    function button:SetLabel(text)
        self.text:SetText(text)
    end

    return button
end

local function CreateReloadButton(parent)
    local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    button:SetSize(72, 24)
    button:SetText("/reload")
    button:SetScript("OnClick", ReloadUI)
    UI.SkinButton(button)
    button:Hide()

    local flashFrame = CreateFrame("Frame", nil, button)
    flashFrame:SetPoint("TOPLEFT", button, "TOPLEFT", -2, 2)
    flashFrame:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 2, -2)
    flashFrame:SetAlpha(0)

    local flashEdges = {
        top = flashFrame:CreateTexture(nil, "OVERLAY"),
        bottom = flashFrame:CreateTexture(nil, "OVERLAY"),
        left = flashFrame:CreateTexture(nil, "OVERLAY"),
        right = flashFrame:CreateTexture(nil, "OVERLAY"),
    }
    flashEdges.top:SetPoint("TOPLEFT")
    flashEdges.top:SetPoint("TOPRIGHT")
    flashEdges.top:SetHeight(1)
    flashEdges.bottom:SetPoint("BOTTOMLEFT")
    flashEdges.bottom:SetPoint("BOTTOMRIGHT")
    flashEdges.bottom:SetHeight(1)
    flashEdges.left:SetPoint("TOPLEFT")
    flashEdges.left:SetPoint("BOTTOMLEFT")
    flashEdges.left:SetWidth(1)
    flashEdges.right:SetPoint("TOPRIGHT")
    flashEdges.right:SetPoint("BOTTOMRIGHT")
    flashEdges.right:SetWidth(1)

    for _, edge in pairs(flashEdges) do
        edge:SetTexture("Interface\\Buttons\\WHITE8X8")
        UI.SetAddonColor(edge, "SetVertexColor")
    end

    local flashAnimation = flashFrame:CreateAnimationGroup()
    local flashIn = flashAnimation:CreateAnimation("Alpha")
    flashIn:SetFromAlpha(0)
    flashIn:SetToAlpha(1)
    flashIn:SetDuration(0.08)
    flashIn:SetOrder(1)

    local flashOut = flashAnimation:CreateAnimation("Alpha")
    flashOut:SetFromAlpha(1)
    flashOut:SetToAlpha(0)
    flashOut:SetDuration(0.42)
    flashOut:SetOrder(2)

    local function ResetAttention()
        flashAnimation:Stop()
        flashFrame:SetAlpha(0)
    end

    flashAnimation:SetScript("OnFinished", ResetAttention)

    function button:SetReloadSuggested(suggested)
        local shouldShow = suggested == true
        local wasShown = self:IsShown()
        self:SetShown(shouldShow)

        if shouldShow and not wasShown then
            self:SetAlpha(1)
            ResetAttention()
            flashAnimation:Play()
        elseif not shouldShow then
            self:SetAlpha(1)
            ResetAttention()
        end
    end

    return button
end

local function CreateModeButton(parent, label)
    local button = CreateFrame("Button", nil, parent)
    button:SetSize(76, 28)
    UI.SkinButton(button)

    local text = UI.CreateLabel(button, label, 12)
    text:SetPoint("CENTER", button, "CENTER", 0, 0)
    text:SetTextColor(0.88, 0.88, 0.88)
    button.text = text

    button.activeBorder = {}
    button.activeBorder.top = button:CreateTexture(nil, "OVERLAY")
    button.activeBorder.top:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0)
    button.activeBorder.top:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
    button.activeBorder.top:SetHeight(1)
    button.activeBorder.bottom = button:CreateTexture(nil, "OVERLAY")
    button.activeBorder.bottom:SetPoint("BOTTOMLEFT", button, "BOTTOMLEFT", 0, 0)
    button.activeBorder.bottom:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 0, 0)
    button.activeBorder.bottom:SetHeight(1)
    button.activeBorder.left = button:CreateTexture(nil, "OVERLAY")
    button.activeBorder.left:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0)
    button.activeBorder.left:SetPoint("BOTTOMLEFT", button, "BOTTOMLEFT", 0, 0)
    button.activeBorder.left:SetWidth(1)
    button.activeBorder.right = button:CreateTexture(nil, "OVERLAY")
    button.activeBorder.right:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
    button.activeBorder.right:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 0, 0)
    button.activeBorder.right:SetWidth(1)

    function button:SetActive(active)
        local r, g, b = UI.GetClassColor()
        for _, texture in pairs(self.activeBorder) do
            texture:SetColorTexture(r, g, b, active and 1 or 0)
        end
        self.text:SetTextColor(active and r or 0.88, active and g or 0.88, active and b or 0.88)
    end

    button:SetActive(false)
    return button
end

WipedQoL:RegisterTabBuilder("rolling", function(addon, parent)
    local frame = CreateFrame("Frame", nil, parent)
    local autoLootRollSettings = addon:GetAutoLootRollSettings()
    local lootToastSettings = addon:GetLootToastSettings()
    local autoLootRollCheckbox
    local autoLootRollButtons = {}
    local unlockButton
    local resetButton
    local testModeButton
    local lootMoverCheckbox
    local reloadButton

    local autoLootRollSection = UI.CreateSection(
        frame,
        TRANSLATE("Auto roll in legacy content"),
        TRANSLATE("Automatically rolls on loot in legacy content. Priority: Need > Transmog > Greed > Pass. If the selected roll is unavailable, the next lower option is used.")
    )
    autoLootRollSection:SetPoint("TOPLEFT", frame, "TOPLEFT", 14, -14)
    autoLootRollSection:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -14, -14)
    autoLootRollSection:SetHeight(112)
    AddTextRangeUnderline(autoLootRollSection, autoLootRollSection.title, 12, -14, 1, 1, 1, 0.92)
    AddTextRangeUnderline(autoLootRollSection, autoLootRollSection.description, 11, -11, 0.62, 0.62, 0.62, 1)

    local function RefreshAutoLootRollState()
        autoLootRollSettings = addon:GetAutoLootRollSettings()
        local enabled = autoLootRollSettings.enabled == true
        local mode = autoLootRollSettings.mode or "pass"

        if autoLootRollCheckbox and autoLootRollCheckbox.Refresh then
            autoLootRollCheckbox.Refresh()
        end

        for value, button in pairs(autoLootRollButtons) do
            button:SetActive(value == mode)
            button:SetAlpha(enabled and 1 or 0.45)
            button:EnableMouse(enabled)
        end
    end

    function addon:RefreshAutoLootRollRollingUI()
        RefreshAutoLootRollState()
    end

    local function RefreshLootToastState()
        lootToastSettings = addon:GetLootToastSettings()
        local unlocked = lootToastSettings.unlocked == true
        local active = addon:IsLootToastMoverActive()

        if lootMoverCheckbox and lootMoverCheckbox.Refresh then
            lootMoverCheckbox.Refresh()
        end
        if unlockButton then
            unlockButton:SetLabel(TRANSLATE(unlocked and "Lock" or "Configure"))
        end
        if testModeButton then
            local testModeActive = addon:IsLootTestModeActive()
            testModeButton:SetLabel(TRANSLATE(testModeActive and "Stop test mode" or "Test mode"))
        end
        for _, button in pairs({ unlockButton, resetButton, testModeButton }) do
            if button then
                button:SetAlpha(active and 1 or 0.45)
                button:EnableMouse(active)
            end
        end
        if reloadButton then
            reloadButton:SetReloadSuggested(addon.lootMoverReloadSuggested == true)
        end
    end

    function addon:RefreshLootToastRollingUI()
        RefreshLootToastState()
    end

    autoLootRollCheckbox = UI.CreateSectionToggle(autoLootRollSection, function()
        return autoLootRollSettings.enabled == true
    end, function(value)
        addon:SetAutoLootRollEnabled(value)
        RefreshAutoLootRollState()
    end)

    local autoLootRollLabel = UI.CreateLabel(autoLootRollSection, string.format("%s:", TRANSLATE("Roll choice")), 12)
    autoLootRollLabel:SetPoint("TOPLEFT", autoLootRollSection.description, "BOTTOMLEFT", 0, -12)
    autoLootRollLabel:SetTextColor(0.78, 0.78, 0.78)

    for index, option in ipairs(AUTO_LOOT_ROLL_OPTIONS) do
        local button = CreateModeButton(autoLootRollSection, TRANSLATE(option.label))
        button:SetPoint("LEFT", autoLootRollLabel, "RIGHT", 10 + ((index - 1) * 82), 0)
        button:SetScript("OnClick", function()
            addon:SetAutoLootRollMode(option.value)
            RefreshAutoLootRollState()
        end)
        autoLootRollButtons[option.value] = button
    end

    RefreshAutoLootRollState()

    local lootToastSection = UI.CreateSection(
        frame,
        TRANSLATE("Loot, roll, achievement and completion popups"),
        TRANSLATE("Moves and scales Blizzard's loot, roll, achievement, completion and activity popups. Enabling or disabling takes effect after reloading the UI.")
            .. "\n|cffff5555"
            .. TRANSLATE("Do not use this if another addon such as ElvUI already provides this feature.")
            .. "|r"
    )
    lootToastSection:SetPoint("TOPLEFT", autoLootRollSection, "BOTTOMLEFT", 0, -12)
    lootToastSection:SetPoint("TOPRIGHT", autoLootRollSection, "BOTTOMRIGHT", 0, -12)
    lootToastSection:SetHeight(134)

    lootMoverCheckbox = UI.CreateSectionToggle(lootToastSection, function()
        return lootToastSettings.enabled == true
    end, function(value)
        addon:SetLootToastMoverEnabled(value)
        RefreshLootToastState()
    end)

    unlockButton = CreateTextButton(lootToastSection, 110, TRANSLATE("Configure"))
    unlockButton:SetPoint("TOPLEFT", lootToastSection.description, "BOTTOMLEFT", 0, -12)
    unlockButton:SetScript("OnClick", function()
        addon:SetLootToastMoverUnlocked(not (lootToastSettings.unlocked == true))
        RefreshLootToastState()
    end)

    resetButton = CreateTextButton(lootToastSection, 76, TRANSLATE("Reset"))
    resetButton:SetPoint("LEFT", unlockButton, "RIGHT", 8, 0)
    resetButton:SetScript("OnClick", function()
        addon:ResetLootToastMover()
        RefreshLootToastState()
    end)

    testModeButton = CreateTextButton(lootToastSection, 140, TRANSLATE("Test mode"))
    testModeButton:SetPoint("LEFT", resetButton, "RIGHT", 8, 0)
    testModeButton:SetScript("OnClick", function()
        addon:SetLootTestModeEnabled(not addon:IsLootTestModeActive())
        RefreshLootToastState()
    end)

    reloadButton = CreateReloadButton(lootToastSection)
    reloadButton:SetPoint("LEFT", testModeButton, "RIGHT", 8, 0)

    RefreshLootToastState()

    return frame
end)
