--## Title: |c000EEE00地下堡助手|r|cFFFFA500 By|r|c000EEEEE DFCN ## Notes: DFCN的地下堡助手，提供自动选择层数，自动进入地下堡，宿敌及藏宝图监控等功能。 ## Author: DFCN ## Version: 1.51
local DFCN =  {
    scoreboardUpdateTimer = nil,
    isAbundant = nil,
    delveTimer = nil,
    delveStartServerTime = nil,
    delveCompleted = false,
    delveCompletionTime = nil,
    showScoreboardTimer = nil,
    treasureMapAlert = nil,
    inDelveWithMap = false,
    checkTreasureMapPending = false,
    treasureBuffAlert = nil,
    lastTreasureBuffState = nil,
    medicineBar = nil,
    medicineUpdateTimer = nil,
    playerChoiceUpdateTimer = nil,
    expectingCinematic = false,
    cinematicTimer = nil,
	playerChoiceTicker = nil,
    periodicUpdateTimer = nil,
	flashingDoorCheckTimer = nil,
    flashingDoorActivated = nil,
	lastBrannSetup = nil,
    merchantFrame = nil,
}

DFCN_DelveHelperDB = DFCN_DelveHelperDB or {
    autoEnter = true,
    autoActivateDelve = true,
    difficultyLevel = 11,
    autoLeaveShip = true,
    scoreboardEnabled = true,
    treasureMapAlertEnabled = true,
    scoreboardLocked = false,
    scoreboardPosition = nil,
	minimapIcon = {},
    minimapIconShown = true,
    characters = {},
    exitCooldown = false,
    exitTime = 0,
    fastExitMode = false,
    backgroundAlpha = 0.4,
    autoTokenExchange = true,
}

local AUTO_CONFIRM_NPC_IDS = {
    [223594] = {
        confirmText = "你确定要离开副本吗？",
        yesText = "是的！",
        checkInstance = true,
        difficultyID = 205,
        leaveParty = true,
        printText = "|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 已自动退队离开破晨号（追随者难度）|r"
    },
    [229022] = {
        confirmText = "弄到合适的安德麦文件了吗？",
        yesText = "<搭乘钻机前往安德麦。>",
        checkInstance = false,
        printText = "|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 已自动搭乘钻机前往安德麦|r"
    },
    [233626] = {
        confirmText = "这坏小子马上就要开往深沟镇！",
        yesText = "<搭乘钻机前往喧鸣深窟。>",
        checkInstance = false,
        printText = "|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 已自动搭乘钻机前往喧鸣深窟|r"
    },
    [233719] = {
        confirmText = "<控制台喇叭里传出预录语音。>",
        yesText = "<搭乘钻机前往安德麦。>",
        checkInstance = false,
        printText = "|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 已自动搭乘钻机前往安德麦|r"
    },
    [233625] = {
        confirmText = "嘿，之前的事儿我很抱歉。",
        yesText = "<搭乘钻机前往卡亚海滨。>",
        checkInstance = false,
        printText = "|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 已自动搭乘钻机前往祖达萨|r"
    }
}

local MERCHANT_ITEMS = {
	{itemID = 238386, name = "虚触碎片", schedule = {2, 3}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1582:10255:1:28:2462:::::"},
	{itemID = 238390, name = "碎魂者的印记", schedule = {2, 3}, offset = 2, suffix = "::::::::80:66::110:4:6652:12355:1582:10255:1:28:2462:::::"},
	{itemID = 240213, name = "朦胧的法力帷纱", schedule = {3, 2}, offset = 1, suffix = "::::::::80:66::110:4:6652:12355:3239:10255:1:28:2462:::::"},
	{itemID = 242867, name = "自动化足球炸弹分发器", schedule = {3, 2}, offset = 1, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246824, name = "影卫的扭曲收获者", schedule = {1}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246825, name = "混乱虚空之门", schedule = {1}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246939, name = "精华猎手的镜片", schedule = {3, 2}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246940, name = "法力熔炉以太电池", schedule = {3, 2}, offset = 1, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246941, name = "共生以太薄纱", schedule = {3, 2}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246944, name = "心智溃解之祸", schedule = {3, 2}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246945, name = "虚体精华吞噬者", schedule = {2, 3}, offset = 1, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"},
	{itemID = 246947, name = "扭曲的法力之魂", schedule = {3, 2}, offset = 0, suffix = "::::::::80:66::110:4:6652:12355:1572:10255:1:28:2462:::::"}
}

local function GetMerchantItemsForDate(targetDate)
    local targetTime = time(targetDate)
    if targetDate.hour < 7 then
        targetTime = targetTime - 86400
        targetDate = date("*t", targetTime)
    end
    
    local baseDate = time({year=2025, month=8, day=16, hour=7, min=0, sec=0})
    local daysDiff = floor((targetTime - baseDate) / 86400)
    
    local availableItems = {}
    
    for _, item in ipairs(MERCHANT_ITEMS) do
        local adjustedDaysDiff = daysDiff - item.offset
        if adjustedDaysDiff >= 0 then
            local totalDays = 0
            for _, days in ipairs(item.schedule) do
                totalDays = totalDays + days
            end
            
            if totalDays > 0 then
                local cyclePosition = adjustedDaysDiff % totalDays
                local cumulativeDays = 0
                local isAvailable = false
                
                if cyclePosition == 0 then
                    isAvailable = true
                else
                    for i, days in ipairs(item.schedule) do
                        cumulativeDays = cumulativeDays + days
                        if cyclePosition == cumulativeDays then
                            isAvailable = true
                            break
                        end
                        if cyclePosition < cumulativeDays then
                            break
                        end
                    end
                end
                
                if isAvailable then
                    table.insert(availableItems, item)
                end
            else
                table.insert(availableItems, item)
            end
        end
    end
    
    return availableItems
end

local function IsInDelvesScenario()
    local scenarioName = select(1, C_Scenario.GetInfo())
    return scenarioName == "地下堡"
end

local function UpdateExitCooldownDuration()
    DFCN.exitCooldownDuration = DFCN_DelveHelperDB.fastExitMode and 0 or 10
end

local function GetCharacterKey()
    local realm = GetRealmName()
    local name = UnitName("player")
    return realm .. "-" .. name
end

local function FormatTime(seconds, completed)
    local hours = floor(seconds / 3600)
    local minutes = floor((seconds % 3600) / 60)
    local seconds = seconds % 60
    
    if hours > 0 then
        if completed then
            return format("%d:%02d:%02d（已完成）", hours, minutes, seconds)
        else
            return format("%d:%02d:%02d", hours, minutes, seconds)
        end
    else
        if completed then
            return format("%02d:%02d（已完成）", minutes, seconds)
        else
            return format("%02d:%02d", minutes, seconds)
        end
    end
end

local function GetDelveInfo()
    local widgetInfo = C_UIWidgetManager and C_UIWidgetManager.GetScenarioHeaderDelvesWidgetVisualizationInfo(6183)
    if not widgetInfo then
        return nil, nil, nil, nil
    end

    local info = widgetInfo
    local difficultyLevel = tonumber(info.tierText)
    local remainingLives = nil
    
    if info.currencies and info.currencies[1] then
        remainingLives = tonumber(info.currencies[1].text)
    end
    
    local delveName = info.headerText
    local isSpecialDelve = delveName == "虚空之锋庇护所"
    
    local isAbundant = false
    if info.spells then
        for _, spell in ipairs(info.spells) do
            if spell.spellID == 462940 then
                isAbundant = true
                break
            end
        end
    end
    
    return difficultyLevel, remainingLives, isAbundant, delveName, isSpecialDelve
end

function DFCN.IsBountifulDelveVisible()
    local _, _, isAbundant = GetDelveInfo()
    return isAbundant or false
end

local function StripColorCodes(text)
    if not text then return "" end
    return text:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", "")
end

function DFCN.CreateScoreboard()
    if DFCN.scoreboardFrame then
        return DFCN.scoreboardFrame
    end

    local frame = CreateFrame("Frame", "DFCN_DelveHelperScoreboard", UIParent, "BackdropTemplate")
    frame:SetSize(260, 185)
    
    if DFCN_DelveHelperDB.scoreboardPosition then
        frame:SetPoint(
            DFCN_DelveHelperDB.scoreboardPosition.point,
            UIParent,
            DFCN_DelveHelperDB.scoreboardPosition.relativePoint,
            DFCN_DelveHelperDB.scoreboardPosition.x,
            DFCN_DelveHelperDB.scoreboardPosition.y
        )
    else
        frame:SetPoint("CENTER", 0, 150)
    end
    
    frame:SetMovable(true)
    frame:EnableMouse(true)
    frame:RegisterForDrag("LeftButton")
    
    frame:SetScript("OnDragStart", function(self)
        if not DFCN_DelveHelperDB.scoreboardLocked then
            self:StartMoving()
        end
    end)
    
    frame:SetScript("OnDragStop", function(self)
        if not DFCN_DelveHelperDB.scoreboardLocked then
            self:StopMovingOrSizing()
            
            local point, _, relativePoint, x, y = self:GetPoint()
            
            DFCN_DelveHelperDB.scoreboardPosition = {
                x = x, 
                y = y,
                point = point,
                relativePoint = relativePoint
            }
        end
    end)
    
    frame:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, 
        tileSize = 16, 
        edgeSize = 4,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    
    frame.title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    frame.title:SetPoint("TOP", 0, -15)
    frame.title:SetText("地下堡监控")
    frame.title:SetTextColor(0.95, 0.95, 0.32)
    
    frame.lockBtn = CreateFrame("Button", nil, frame)
    frame.lockBtn:SetPoint("TOPRIGHT", -20, -3)
    frame.lockBtn:SetSize(20, 20)
    
    frame.lockBtn.text = frame.lockBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    frame.lockBtn.text:SetPoint("CENTER")

    frame.closeBtn = CreateFrame("Button", nil, frame)
    frame.closeBtn:SetPoint("TOPRIGHT", -2, -2)
    frame.closeBtn:SetSize(20, 20)
    
    frame.closeBtn.text = frame.closeBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    frame.closeBtn.text:SetPoint("CENTER")
    frame.closeBtn.text:SetText("x")
    frame.closeBtn.text:SetTextColor(1, 1, 1)
    
    frame.closeBtn:SetScript("OnEnter", function(self)
        self.text:SetTextColor(1, 0.82, 0) 
    end)
    
    frame.closeBtn:SetScript("OnLeave", function(self)
        self.text:SetTextColor(1, 1, 1) 
    end)
    
    frame.closeBtn:SetScript("OnClick", function() 
        DFCN_DelveHelperDB.scoreboardEnabled = false
        frame:Hide() 
    end)

    local bgAlpha = DFCN_DelveHelperDB.backgroundAlpha or 0.4

    frame:SetBackdropColor(0.1, 0.1, 0.1, bgAlpha)
    frame:SetBackdropBorderColor(0.4, 0.4, 0.4, bgAlpha)

    frame.transparencyBtn = CreateFrame("Button", nil, frame)
    frame.transparencyBtn:SetPoint("TOPRIGHT", frame.lockBtn, "TOPLEFT", 0, 0)
    frame.transparencyBtn:SetSize(20, 20)
    
    frame.transparencyBtn.text = frame.transparencyBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    frame.transparencyBtn.text:SetPoint("CENTER")
    frame.transparencyBtn.text:SetText("T")
    frame.transparencyBtn.text:SetTextColor(1, 1, 1)

    frame.bgAlphaSlider = CreateFrame("Slider", "DFCN_DelveHelperScoreboardBgAlphaSlider", frame, "OptionsSliderTemplate")
    frame.bgAlphaSlider:SetPoint("TOP", frame, "TOP", 0, 30)
    frame.bgAlphaSlider:SetSize(250, 20)
    frame.bgAlphaSlider:SetMinMaxValues(0, 1)
    frame.bgAlphaSlider:SetValueStep(0.1)
    frame.bgAlphaSlider:SetObeyStepOnDrag(true)
    frame.bgAlphaSlider:SetValue(bgAlpha)
    frame.bgAlphaSlider:Hide()
    
    frame.bgAlphaSlider.Low = _G[frame.bgAlphaSlider:GetName().."Low"]
    frame.bgAlphaSlider.High = _G[frame.bgAlphaSlider:GetName().."High"]
    frame.bgAlphaSlider.Text = _G[frame.bgAlphaSlider:GetName().."Text"]
    
    frame.bgAlphaSlider.Low:SetText("0")
    frame.bgAlphaSlider.High:SetText("1")
    frame.bgAlphaSlider.Text:SetText("背景透明度")
    
    frame.transparencyBtn:SetScript("OnClick", function()
        if frame.bgAlphaSlider:IsShown() then
            frame.bgAlphaSlider:Hide()
        else
            frame.bgAlphaSlider:Show()
        end
    end)

    frame.bgAlphaSlider:SetScript("OnValueChanged", function(self, value)
        value = tonumber(string.format("%.1f", value))
        frame:SetBackdropColor(0.1, 0.1, 0.1, value)
        frame:SetBackdropBorderColor(0.4, 0.4, 0.4, value)        
        frame:Show()        
        DFCN_DelveHelperDB.backgroundAlpha = value
    end)

    frame:SetScript("OnHide", function()
        if frame.bgAlphaSlider and frame.bgAlphaSlider:IsShown() then
            frame.bgAlphaSlider:Hide()
        end
    end)
    
    frame.exitBtn = CreateFrame("Button", nil, frame)
    frame.exitBtn:SetPoint("TOPLEFT", 5, -5)
    frame.exitBtn:SetSize(24, 24)
    
    frame.exitBtn.icon = frame.exitBtn:CreateTexture(nil, "ARTWORK")
    frame.exitBtn.icon:SetAllPoints()
    frame.exitBtn.icon:SetTexture("interface\\vehicles\\ui-vehicles-button-exit-up")    
    frame.exitBtn.icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
    frame.exitBtn.tooltipText = "点击立刻离开地下堡"

    frame.exitBtn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:SetText(self.tooltipText, 1, 0, 0)
        GameTooltip:Show()
    end)
    
    frame.exitBtn:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
    
    frame.exitBtn:SetScript("OnClick", function() 
        C_PartyInfo.DelveTeleportOut()
    end)
    
    local function UpdateLockState()
        if DFCN_DelveHelperDB.scoreboardLocked then
            frame.lockBtn.text:SetText("L")
            frame.lockBtn.text:SetTextColor(1, 0.2, 0.2)

            frame:EnableMouse(false)
            frame.lockBtn:EnableMouse(true)
            frame.closeBtn:EnableMouse(true)
            frame.exitBtn:EnableMouse(true)
        else
            frame.lockBtn.text:SetText("U")
            frame.lockBtn.text:SetTextColor(0.2, 1, 0.2)
            
            frame:EnableMouse(true)
        end
    end
    
    frame.lockBtn:SetScript("OnClick", function()
        DFCN_DelveHelperDB.scoreboardLocked = not DFCN_DelveHelperDB.scoreboardLocked
        UpdateLockState()
    end)
    
    UpdateLockState()
      
    local function CreateInfoLineWithIcon(parent, yOffset, label, iconPath)
        local line = CreateFrame("Frame", nil, parent)
        line:SetSize(230, 20)
        line:SetPoint("TOPLEFT", 10, yOffset)
        
        line.icon = line:CreateTexture(nil, "ARTWORK")
        line.icon:SetTexture(iconPath)
        line.icon:SetSize(18, 18)
        line.icon:SetPoint("LEFT", 10, 0)

        line.label = line:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        line.label:SetPoint("LEFT", line.icon, "RIGHT", 5, 0)
		line.label:SetFont(GameFontNormal:GetFont(), 13)
        line.label:SetText(label.."")
        line.label:SetTextColor(1, 1, 0.8)
        
        line.value = line:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        line.value:SetPoint("RIGHT", line, "RIGHT", 0, 0)
		line.value:SetFont(GameFontNormal:GetFont(), 13)
        line.value:SetText("Loading...")
        
        return line
    end

    frame.delveName = CreateInfoLineWithIcon(frame, -65, " 场景", "Interface\\icons\\ui_delves")
    frame.difficultyLevel = CreateInfoLineWithIcon(frame, -87, " 难度等级", "Interface\\icons\\achievement_garrisonfollower_levelup")
    frame.remainingLives = CreateInfoLineWithIcon(frame, -109, " 剩余生命", "Interface\\icons\\delves-scenario-heart-icon")
    frame.remainingEnemies = CreateInfoLineWithIcon(frame, -131, " 剩余宿敌", "Interface\\delves\\delves-scenario-treasure-available")
    frame.duration = CreateInfoLineWithIcon(frame, -153, " 总用时", "Interface\\icons\\spell_holy_borrowedtime")

    frame.companionIcons = CreateFrame("Frame", nil, frame)
    frame.companionIcons:SetSize(80, 22)
    frame.companionIcons:SetPoint("TOPLEFT", 18, -40)
    
    frame.roleIcon = frame.companionIcons:CreateTexture(nil, "ARTWORK")
    frame.roleIcon:SetSize(22, 22)
    frame.roleIcon:SetPoint("LEFT", 0, 0)
    
    frame.combatIcon = frame.companionIcons:CreateTexture(nil, "ARTWORK")
    frame.combatIcon:SetSize(18, 18)
    frame.combatIcon:SetPoint("LEFT", frame.roleIcon, "RIGHT", 4, 0)
    
    frame.utilityIcon = frame.companionIcons:CreateTexture(nil, "ARTWORK")
    frame.utilityIcon:SetSize(18, 18)
    frame.utilityIcon:SetPoint("LEFT", frame.combatIcon, "RIGHT", 4, 0)   
    
    frame.flashingDoorText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    frame.flashingDoorText:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -20, -45)
    frame.flashingDoorText:SetFont(GameFontNormal:GetFont(), 14)
    frame.flashingDoorText:SetText(" 闪烁之门")
    frame.flashingDoorText:Hide()

    frame.flashingDoorIcon = frame:CreateTexture(nil, "OVERLAY")
    frame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_RaidTrinkets_BlobOfSwirlingVoid_purple")
    frame.flashingDoorIcon:SetSize(18, 18)
    frame.flashingDoorIcon:SetPoint("RIGHT", frame.flashingDoorText, "LEFT", -3, 0)
    frame.flashingDoorIcon:Hide()
    
    local key = GetCharacterKey()
    local charData = DFCN_DelveHelperDB.characters[key] or {}
    
    if charData.flashingDoorDetected then
        frame.flashingDoorIcon:Show()
        frame.flashingDoorText:Show()
        
        if charData.flashingDoorActivated then
            frame.flashingDoorText:SetText(" 已使用")
            frame.flashingDoorText:SetTextColor(0.5, 0.5, 0.5)
            frame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_Achievement_Zone_Karesh")
        else
            frame.flashingDoorText:SetText(" 闪烁之门")
            frame.flashingDoorText:SetTextColor(0.1, 0.4, 0.9)
            frame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_RaidTrinkets_BlobOfSwirlingVoid_purple")
        end
    else
        frame.flashingDoorIcon:Hide()
        frame.flashingDoorText:Hide()
    end
    
    DFCN.CreatemedicineBar(frame)
	
    frame:Hide()
    DFCN.scoreboardFrame = frame
	
    return frame
end

function GetBrannCurrentSetup()
    local companionInfoID = C_DelvesUI.GetCompanionInfoForActivePlayer()    
    local treeID = C_DelvesUI.GetTraitTreeForCompanion(companionInfoID)    
    local configID = C_Traits.GetConfigIDByTreeID(treeID)
    local roleNodeID = C_DelvesUI.GetRoleNodeForCompanion(companionInfoID)
    
    local roleName, combatTrinket, utilityTrinket = "未设置", "未设置", "未设置"
    local roleIcon, combatIcon, utilityIcon = "Interface\\Icons\\INV_Misc_QuestionMark", "Interface\\Icons\\INV_Misc_QuestionMark", "Interface\\Icons\\INV_Misc_QuestionMark"
    local combatSpellID, utilitySpellID

    if subTreeInfo and subTreeInfo.iconElementID then
        roleIcon = subTreeInfo.iconElementID
    end
    
    if roleNodeID then
        local roleNodeInfo = C_Traits.GetNodeInfo(configID, roleNodeID)
        if roleNodeInfo and roleNodeInfo.activeEntry then
            local entryInfo = C_Traits.GetEntryInfo(configID, roleNodeInfo.activeEntry.entryID)
            if entryInfo then
                local subTreeInfo = C_Traits.GetSubTreeInfo(configID, entryInfo.subTreeID)
                if subTreeInfo then
                    roleName = subTreeInfo.name
                    roleIcon = subTreeInfo.iconElementID and CreateAtlasMarkup(subTreeInfo.iconElementID, 20, 20) or roleIcon
                end
            end
        end
    end

    local combatTrinketNodeID = C_DelvesUI.GetCurioNodeForCompanion(Enum.CurioType.Combat, companionInfoID)
    if combatTrinketNodeID then
        local combatNodeInfo = C_Traits.GetNodeInfo(configID, combatTrinketNodeID)
        if combatNodeInfo and combatNodeInfo.activeEntry then
            local entryInfo = C_Traits.GetEntryInfo(configID, combatNodeInfo.activeEntry.entryID)
            if entryInfo then
                local definitionInfo = C_Traits.GetDefinitionInfo(entryInfo.definitionID)
                if definitionInfo then
                    local spellID = definitionInfo.overriddenSpellID or definitionInfo.spellID
                    local spellInfo = C_Spell.GetSpellInfo(spellID)
                    if spellInfo then
                        combatTrinket = C_Spell.GetSpellLink(spellID) or spellInfo.name
                        combatIcon = spellInfo.iconID and spellInfo.iconID or combatIcon
                        combatSpellID = spellID
                    end
                end
            end
        end
    end
    
    local utilityTrinketNodeID = C_DelvesUI.GetCurioNodeForCompanion(Enum.CurioType.Utility, companionInfoID)
    if utilityTrinketNodeID then
        local utilityNodeInfo = C_Traits.GetNodeInfo(configID, utilityTrinketNodeID)
        if utilityNodeInfo and utilityNodeInfo.activeEntry then
            local entryInfo = C_Traits.GetEntryInfo(configID, utilityNodeInfo.activeEntry.entryID)
            if entryInfo then
                local definitionInfo = C_Traits.GetDefinitionInfo(entryInfo.definitionID)
                if definitionInfo then
                    local spellID = definitionInfo.overriddenSpellID or definitionInfo.spellID
                    local spellInfo = C_Spell.GetSpellInfo(spellID)
                    if spellInfo then
                        utilityTrinket = C_Spell.GetSpellLink(spellID) or spellInfo.name
                        utilityIcon = spellInfo.iconID and spellInfo.iconID or utilityIcon
                        utilitySpellID = spellID
                    end
                end
            end
        end
    end
    
    return {
        role = {name = roleName, icon = roleIcon},
        combat = {name = combatTrinket, icon = combatIcon, spellID = combatSpellID},
        utility = {name = utilityTrinket, icon = utilityIcon, spellID = utilitySpellID},
		hash = tostring(roleName) .. "|" .. tostring(combatSpellID) .. "|" .. tostring(utilitySpellID)
    }
end

function DFCN.UpdateCompanionIcons(forceUpdate)
    if not DFCN.scoreboardFrame or not DFCN.scoreboardFrame:IsShown() then 
        return 
    end
    
    local setup = GetBrannCurrentSetup()

    local shouldUpdate = forceUpdate or not DFCN.lastBrannSetup or DFCN.lastBrannSetup.hash ~= setup.hash

    if not shouldUpdate then
        return
    end

    DFCN.lastBrannSetup = setup
    
     if type(setup.role.icon) == "string" and setup.role.icon:match("^|A:") then
        local atlasName = setup.role.icon:match("|A:([^:]+)")
        if atlasName then
            DFCN.scoreboardFrame.roleIcon:SetAtlas(atlasName)
            DFCN.scoreboardFrame.roleIcon:SetTexCoord(0, 1, 0, 1)
        else
            DFCN.scoreboardFrame.roleIcon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
        end
    else
        DFCN.scoreboardFrame.roleIcon:SetTexture(setup.role.icon or "Interface\\Icons\\INV_Misc_QuestionMark")
    end

    if type(setup.combat.icon) == "number" then
        DFCN.scoreboardFrame.combatIcon:SetTexture(setup.combat.icon)
        DFCN.scoreboardFrame.combatIcon:SetTexCoord(0, 1, 0, 1)
    elseif type(setup.combat.icon) == "string" then
        DFCN.scoreboardFrame.combatIcon:SetTexture(setup.combat.icon)
    else
        DFCN.scoreboardFrame.combatIcon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
    end

    if type(setup.utility.icon) == "number" then
        DFCN.scoreboardFrame.utilityIcon:SetTexture(setup.utility.icon)
        DFCN.scoreboardFrame.utilityIcon:SetTexCoord(0, 1, 0, 1)
    elseif type(setup.utility.icon) == "string" then
        DFCN.scoreboardFrame.utilityIcon:SetTexture(setup.utility.icon)
    else
        DFCN.scoreboardFrame.utilityIcon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
    end
    
    DFCN.scoreboardFrame.roleIcon:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText("铜须职责: "..setup.role.name, 1, 1, 1)
        GameTooltip:Show()
    end)
    DFCN.scoreboardFrame.roleIcon:SetScript("OnLeave", GameTooltip_Hide)
    
	DFCN.scoreboardFrame.combatIcon:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		if setup.combat.spellID then
			GameTooltip:SetSpellByID(setup.combat.spellID)
		else
			GameTooltip:SetText("战斗珍玩: "..setup.combat.name, 1, 1, 1)
		end
		GameTooltip:Show()
	end)
	DFCN.scoreboardFrame.combatIcon:SetScript("OnLeave", GameTooltip_Hide)
	DFCN.scoreboardFrame.utilityIcon:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		if setup.utility.spellID then
			GameTooltip:SetSpellByID(setup.utility.spellID)
		else
			GameTooltip:SetText("效能珍玩: "..setup.utility.name, 1, 1, 1)
		end
		GameTooltip:Show()
	end)
	DFCN.scoreboardFrame.utilityIcon:SetScript("OnLeave", GameTooltip_Hide)

    DFCN.scoreboardFrame.roleIcon:Show()
    DFCN.scoreboardFrame.combatIcon:Show()
    DFCN.scoreboardFrame.utilityIcon:Show()
end


function DFCN.CreatemedicineBar(parent)
    if DFCN.medicineBar then return end
    
    local bar = CreateFrame("Frame", nil, parent)
    bar:SetSize(parent:GetWidth(), 24)
    bar:SetPoint("TOP", parent, "BOTTOM", 0, -2)
    bar:Hide()
    
    bar.icon = bar:CreateTexture(nil, "ARTWORK")
    bar.icon:SetSize(24, 24)
    bar.icon:SetPoint("LEFT", bar, "LEFT", 0, 0)
    bar.icon:SetTexture(C_Spell.GetSpellTexture(416224) or "Interface\\Icons\\INV_Misc_QuestionMark")

    bar.nameText = bar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    bar.nameText:SetPoint("LEFT", bar.icon, "RIGHT", 5, 0)
    bar.nameText:SetText("")
    bar.nameText:SetTextColor(1, 1, 1)
    
    bar.background = bar:CreateTexture(nil, "BACKGROUND")
    bar.background:SetColorTexture(0.2, 0.2, 0.2, 0.2)
    bar.background:SetPoint("LEFT", bar.icon, "RIGHT", 2, 0)
    bar.background:SetPoint("RIGHT", bar, "RIGHT", 0, 0)
    bar.background:SetHeight(20)
    
    bar.statusBar = bar:CreateTexture(nil, "ARTWORK")
    bar.statusBar:SetColorTexture(0.8, 0.2, 0.8, 0.8)
    bar.statusBar:SetPoint("LEFT", bar.background, "LEFT")
    bar.statusBar:SetHeight(25)
    bar.statusBar:SetWidth(0)

    bar.timeText = bar:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    bar.timeText:SetPoint("CENTER", bar.background, "CENTER")
    bar.timeText:SetText("0.0s")
    bar.timeText:SetTextColor(1, 1, 1)
    
    bar.stackText = bar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    bar.stackText:SetPoint("BOTTOMRIGHT", bar.background, "BOTTOMRIGHT", -2, 2)
    bar.stackText:SetTextColor(1, 1, 1)
    
    DFCN.medicineBar = bar
end

function DFCN.UpdatemedicineBar()
    if not DFCN.medicineBar then return end
    
    local auraInfo = C_UnitAuras and C_UnitAuras.GetPlayerAuraBySpellID(416224)
    
    if not auraInfo then
        DFCN.medicineBar:Hide()
        if DFCN.medicineUpdateTimer then
            DFCN.medicineUpdateTimer:Cancel()
            DFCN.medicineUpdateTimer = nil
        end
        return
    end
    
    DFCN.medicineBar:Show()

    DFCN.medicineBar.nameText:SetText(auraInfo.name or "")
    
    local applications = auraInfo.applications or 1
    DFCN.medicineBar.stackText:SetText(applications.."层")
    
    local duration = auraInfo.duration or 10
    local expirationTime = auraInfo.expirationTime or 0
    local remaining = expirationTime - GetTime()

    local remainingText = string.format("%.1fs", remaining > 0 and remaining or 0)
    DFCN.medicineBar.timeText:SetText(remainingText)
    
    if remaining >= 6 then
        DFCN.medicineBar.timeText:SetTextColor(0, 1, 0)
    elseif remaining >= 2 then
        DFCN.medicineBar.timeText:SetTextColor(1, 0.65, 0)
    else
        DFCN.medicineBar.timeText:SetTextColor(1, 0, 0)
    end
    
    if remaining > 0 then
        local width = DFCN.medicineBar.background:GetWidth() * (remaining / duration)
        DFCN.medicineBar.statusBar:SetWidth(width)
        
        if remaining >= 6 then
            DFCN.medicineBar.statusBar:SetColorTexture(0, 0.7, 0, 0.7)
        elseif remaining >= 2 then
            DFCN.medicineBar.statusBar:SetColorTexture(1, 0.4, 0, 0.7)
        else
            DFCN.medicineBar.statusBar:SetColorTexture(0.7, 0, 0, 0.7)
        end
    else
        DFCN.medicineBar.statusBar:SetWidth(0)
    end
    
    if not DFCN.medicineUpdateTimer then
        DFCN.medicineUpdateTimer = C_Timer.NewTicker(0.1, function()
            DFCN.UpdatemedicineBar()
        end)
    end
end

function DFCN.StartDelveTimer()
    if DFCN.delveCompleted then return end
    if DFCN.delveTimer then
        DFCN.delveTimer:Cancel()
        DFCN.delveTimer = nil
    end
    DFCN.delveStartServerTime = GetServerTime()
    
    local key = GetCharacterKey()
    DFCN_DelveHelperDB.characters[key] = DFCN_DelveHelperDB.characters[key] or {}
    DFCN_DelveHelperDB.characters[key].delveStartTime = DFCN.delveStartServerTime
    DFCN_DelveHelperDB.characters[key].delveCompleted = false
    
    DFCN.delveTimer = C_Timer.NewTicker(1, function()
        if not DFCN.scoreboardFrame or not DFCN.scoreboardFrame:IsShown() then return end
        
        local now = GetServerTime()
        local duration = now - DFCN.delveStartServerTime
        
        DFCN.scoreboardFrame.duration.value:SetText(FormatTime(duration, false))
    end)
end

function DFCN.PauseDelveTimer()
    if DFCN.delveTimer then
        DFCN.delveTimer:Cancel()
        DFCN.delveTimer = nil
    end
    
    if DFCN.delveStartServerTime and not DFCN.delveCompletionTime then
        DFCN.delveCompletionTime = GetServerTime() - DFCN.delveStartServerTime
    end
end

function DFCN.ResetDelveTimer()
    DFCN.PauseDelveTimer()
    
    DFCN.delveStartServerTime = nil
    DFCN.delveCompleted = false
    DFCN.delveCompletionTime = nil
    
    local key = GetCharacterKey()
    if DFCN_DelveHelperDB.characters[key] then
        DFCN_DelveHelperDB.characters[key].delveStartTime = nil
        DFCN_DelveHelperDB.characters[key].delveCompleted = false
    end
    
    if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
        DFCN.scoreboardFrame.duration.value:SetText("00:00")
        DFCN.scoreboardFrame.duration.value:SetTextColor(0, 1, 0)
    end
end

local function ExtractEnemiesFromTooltip()
    local tooltipData = C_TooltipInfo and C_TooltipInfo.GetSpellByID(1239535)
    if not tooltipData then
        return nil
    end

    for _, line in ipairs(tooltipData.lines) do
        if line.leftText and line.leftText:find("剩余敌群") then
            local lineText = line.leftText
            local lineNumbers = {}
            for num in lineText:gmatch("%d+") do
                table.insert(lineNumbers, tonumber(num))
            end
            
            if #lineNumbers >= 2 then
                return lineNumbers[1].." / "..lineNumbers[2]
            end
            break
        end
    end
    
    return nil
end

function DFCN.UpdateScoreboard()
    if not IsInDelvesScenario() then
        if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
            DFCN.scoreboardFrame:Hide()
        end
        DFCN.StopPeriodicUpdateTimer()
        return
    end
    if not DFCN.scoreboardFrame or not DFCN.scoreboardFrame:IsShown() then return end

    local key = GetCharacterKey()
    local charDB = DFCN_DelveHelperDB.characters[key] or {}
    local delveCompleted = DFCN.delveCompleted or charDB.delveCompleted
    local delveCompletionTime = DFCN.delveCompletionTime or charDB.delveCompletionTime

	if DFCN.delveCompleted and DFCN.delveCompletionTime then
		local duration = DFCN.delveCompletionTime
		
		local minutes = floor(duration / 60)
		if minutes < 10 then
			DFCN.scoreboardFrame.duration.value:SetTextColor(0, 1, 0)
		elseif minutes <= 15 then
			DFCN.scoreboardFrame.duration.value:SetTextColor(1, 1, 0)
		elseif minutes <= 20 then
			DFCN.scoreboardFrame.duration.value:SetTextColor(1, 0.5, 0)
		else
			DFCN.scoreboardFrame.duration.value:SetTextColor(0, 1, 0)
		end
		
		DFCN.scoreboardFrame.duration.value:SetText(FormatTime(duration, true))
	elseif DFCN.delveStartServerTime then
		local now = GetServerTime()
		local duration = now - DFCN.delveStartServerTime

		local minutes = floor(duration / 60)
		if minutes < 10 then
			DFCN.scoreboardFrame.duration.value:SetTextColor(0, 1, 0)
		elseif minutes <= 15 then
			DFCN.scoreboardFrame.duration.value:SetTextColor(1, 1, 0)
		elseif minutes <= 20 then
			DFCN.scoreboardFrame.duration.value:SetTextColor(1, 0.5, 0)
		else
			DFCN.scoreboardFrame.duration.value:SetTextColor(0, 1, 0)
		end
		
		DFCN.scoreboardFrame.duration.value:SetText(FormatTime(duration, false))
	else
		DFCN.scoreboardFrame.duration.value:SetText("00:00")
		DFCN.scoreboardFrame.duration.value:SetTextColor(0, 1, 0)
	end

     local difficultyLevel, remainingLives, isAbundant, delveName, isSpecialDelve = GetDelveInfo()

    if isSpecialDelve then
        DFCN.scoreboardFrame.delveName.value:SetText(delveName)
        DFCN.scoreboardFrame.delveName.value:SetTextColor(1, 0, 0)
        
        if difficultyLevel == 8 then
            DFCN.scoreboardFrame.difficultyLevel.value:SetText("？")
            DFCN.scoreboardFrame.difficultyLevel.value:SetTextColor(1, 0, 0)
        elseif difficultyLevel == 11 then
            DFCN.scoreboardFrame.difficultyLevel.value:SetText("？？")
            DFCN.scoreboardFrame.difficultyLevel.value:SetTextColor(1, 0, 0)
        else
            DFCN.scoreboardFrame.difficultyLevel.value:SetText(tostring(difficultyLevel))
            DFCN.scoreboardFrame.difficultyLevel.value:SetTextColor(1, 0, 0)
        end
        
        DFCN.scoreboardFrame.remainingLives.value:SetText("N/A")
        DFCN.scoreboardFrame.remainingLives.value:SetTextColor(1, 1, 1)
        
        DFCN.scoreboardFrame.remainingEnemies.value:SetText("N/A")
        DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 1)
        
        return
    end
    
	if delveName then
		if isAbundant then
			local displayText = delveName .. " (丰裕)"
			DFCN.scoreboardFrame.delveName.value:SetText(displayText)
			DFCN.scoreboardFrame.delveName.value:SetTextColor(0, 1, 0)
		else
			DFCN.scoreboardFrame.delveName.value:SetText(delveName)
			DFCN.scoreboardFrame.delveName.value:SetTextColor(1, 1, 1)
		end
	else
		DFCN.scoreboardFrame.delveName.value:SetText("未知")
		DFCN.scoreboardFrame.delveName.value:SetTextColor(1, 1, 1)
	end
    
    if difficultyLevel then
        local hasTreasureBuff = false
        if DFCN_DelveHelperDB.treasureMapAlertEnabled then
            hasTreasureBuff = C_UnitAuras and C_UnitAuras.GetPlayerAuraBySpellID(1246363) ~= nil
        end

        local difficultyText = tostring(difficultyLevel)
        if hasTreasureBuff then
            if difficultyLevel == 11 then
                difficultyText = difficultyText .."（藏宝图激活）|r"
            else
                if not DFCN.treasureBuffAlert then
                    DFCN.CreateTreasureBuffAlert()
                end
                DFCN.treasureBuffAlert:Show()
            end
        else
            if DFCN.treasureBuffAlert then
                DFCN.treasureBuffAlert:Hide()
            end
        end

        DFCN.scoreboardFrame.difficultyLevel.value:SetText(difficultyText)
        
		if difficultyLevel <= 7 then
			DFCN.scoreboardFrame.difficultyLevel.value:SetTextColor(1, 0, 0)
		else
			DFCN.scoreboardFrame.difficultyLevel.value:SetTextColor(0, 1, 0)
		end
	else
		DFCN.scoreboardFrame.difficultyLevel.value:SetText("未知")
		DFCN.scoreboardFrame.difficultyLevel.value:SetTextColor(1, 1, 1)
	end

    if difficultyLevel and difficultyLevel < 4 then
        DFCN.scoreboardFrame.remainingLives.value:SetText("N/A")
        DFCN.scoreboardFrame.remainingLives.value:SetTextColor(0, 1, 0.5)
    else
        if remainingLives == nil then
            DFCN.scoreboardFrame.remainingLives.value:SetText("未知")
            DFCN.scoreboardFrame.remainingLives.value:SetTextColor(1, 1, 1)
        else
            DFCN.scoreboardFrame.remainingLives.value:SetText(tostring(remainingLives))
            
            if remainingLives == 0 then
                DFCN.scoreboardFrame.remainingLives.value:SetTextColor(0.5, 0.5, 0.5)
            elseif remainingLives == 1 then
                DFCN.scoreboardFrame.remainingLives.value:SetTextColor(1, 0, 0)
            elseif remainingLives == 2 then
                DFCN.scoreboardFrame.remainingLives.value:SetTextColor(1, 0.5, 0)
            else
                DFCN.scoreboardFrame.remainingLives.value:SetTextColor(0, 1, 0)
            end
        end
    end

    local enemiesText = "0/0"
    if difficultyLevel and difficultyLevel >= 4 then
        local retryCount = 0
        local maxRetries = 3
        local success = false
        
        local function TryGetEnemies()
            local text = ExtractEnemiesFromTooltip()
            if text then
                enemiesText = text
                success = true
                DFCN.scoreboardFrame.remainingEnemies.value:SetText(text)

                local current, total = text:match("(%d+)[^%d]*(%d+)")
                if current and total then
                    current = tonumber(current)
                    total = tonumber(total)

                    if total == 1 then
                        if current == 1 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 0, 0)
                        else
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(0, 1, 0)
                        end
                    elseif total == 2 then
                        if current == 2 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 0, 0)
                        elseif current == 1 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 0)
                        else
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(0, 1, 0)
                        end
                    elseif total == 3 then
                        if current == 3 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 0, 0)
                        elseif current == 2 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 0.5, 0)
                        elseif current == 1 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 0)
                        else
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(0, 1, 0)
                        end
                    elseif total >= 4 then
                        if current == total then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 0, 0)
                        elseif current == total - 1 or current == total - 2 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 0.5, 0)
                        elseif current == total - 3 then
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 0)
                        else
                            DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(0, 1, 0)
                        end
                    end
                else
                     DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 1)
                end
            elseif retryCount < maxRetries then
                retryCount = retryCount + 1
                DFCN.scoreboardFrame.remainingEnemies.value:SetText("重试："..retryCount.."/3")
                DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 1)
                C_Timer.After(2, TryGetEnemies)
                return
            else
                enemiesText = "N/A"
                success = true
                DFCN.scoreboardFrame.remainingEnemies.value:SetText(enemiesText)
                DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(1, 1, 1)
            end
        end
        
        TryGetEnemies()
    else
        DFCN.scoreboardFrame.remainingEnemies.value:SetText("N/A")
        DFCN.scoreboardFrame.remainingEnemies.value:SetTextColor(0, 1, 0)
    end

    if DFCN.scoreboardFrame and DFCN.scoreboardFrame.flashingDoorIcon then
        local key = GetCharacterKey()
        local charData = DFCN_DelveHelperDB.characters[key] or {}
        
        if charData.flashingDoorDetected then
            DFCN.scoreboardFrame.flashingDoorIcon:Show()
            DFCN.scoreboardFrame.flashingDoorText:Show()
            
            if charData.flashingDoorActivated then
                DFCN.scoreboardFrame.flashingDoorText:SetText(" 已使用")
                DFCN.scoreboardFrame.flashingDoorText:SetTextColor(0.5, 0.5, 0.5)
                DFCN.scoreboardFrame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_Achievement_Zone_Karesh")
            else
                DFCN.scoreboardFrame.flashingDoorText:SetText(" 闪烁之门")
                DFCN.scoreboardFrame.flashingDoorText:SetTextColor(0.1, 0.4, 0.9)
                DFCN.scoreboardFrame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_RaidTrinkets_BlobOfSwirlingVoid_purple")
            end
        else
            DFCN.scoreboardFrame.flashingDoorIcon:Hide()
            DFCN.scoreboardFrame.flashingDoorText:Hide()
        end
    end
    
    DFCN.UpdatemedicineBar()
end

local LDB, LibDBIcon
local ldbLoaded = false

local function LoadLibraries()
    LDB = LibStub("LibDataBroker-1.1", true)
    LibDBIcon = LibStub("LibDBIcon-1.0", true)    
    if LDB and LibDBIcon then
        ldbLoaded = true
    end
end

local function CreateLDBObject()
    if not ldbLoaded then return nil end
    
    local ldb = LDB:NewDataObject("DFCN_DelveHelper", {
        type = "data source",
        text = "地下堡助手",
        icon = "Interface\\ICONS\\UI_Delves",
        OnClick = function(self, button)
            if button == "LeftButton" then
                DFCN.ToggleSettingsFrame()
            end
        end,
        OnTooltipShow = function(tooltip)
            tooltip:AddLine("|c000EEE00地下堡助手|r|cFFFFA500 By|r|c000EEEEE DFCN")
            tooltip:AddLine(" ")
			tooltip:AddLine("左键|r: 打开设置面板", 1, 1, 1)
			tooltip:AddLine("宏命令: |cFFFFFF00/dfcndelve|r", 0.5, 1, 1)
            tooltip:AddLine("小地图图标: |cFFFFFF00/dfcndelve minimap on/off|r", 0.5, 1, 1)
        end,
    })
    
    return ldb
end

function DFCN.InitMinimapIcon()   
    local ldb = CreateLDBObject()
    if not ldb then return end
	
    DFCN_DelveHelperDB.minimapIcon = DFCN_DelveHelperDB.minimapIcon or {}    
    LibDBIcon:Register("DFCN_DelveHelper", ldb, DFCN_DelveHelperDB.minimapIcon)
    
    if DFCN_DelveHelperDB.minimapIconShown then
        LibDBIcon:Show("DFCN_DelveHelper")
    else
        LibDBIcon:Hide("DFCN_DelveHelper")
    end
    
    if not DFCN_DelveHelperDB.minimapIcon.position then
        DFCN_DelveHelperDB.minimapIcon.position = 150
        LibDBIcon:Refresh("DFCN_DelveHelper", DFCN_DelveHelperDB.minimapIcon)
    end
end

function DFCN.ToggleSettingsFrame()
    if not DFCN.settingsFrame then
        DFCN.CreateSettingsFrame()
    end
    if DFCN.settingsFrame:IsShown() then
        DFCN.settingsFrame:Hide()
    else
        DFCN.settingsFrame:Show()
        DFCN.RefreshSettingsFrame()
    end
end

function DFCN.RefreshSettingsFrame()
    if not DFCN.settingsFrame then return end    
    DFCN.autoEnterCheckbox:Show()
    DFCN.autoEnterCheckbox:SetEnabled(true)
    DFCN.autoEnterCheckbox.text:SetTextColor(1, 1, 1)
end

function DFCN.CreateSettingsFrame()
    local frame = CreateFrame("Frame", "DFCN_DelveHelperSettingsFrame", UIParent, "BackdropTemplate")
    frame:SetSize(230, 350)
    frame:SetPoint("CENTER")
    frame:SetMovable(true)
    frame:EnableMouse(true)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", frame.StartMoving)
    frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
    tinsert(UISpecialFrames, frame:GetName())
    frame:SetScript("OnHide", function(self)
        if DFCN.merchantFrame and DFCN.merchantFrame:IsShown() then
            DFCN.merchantFrame:Hide()
			collectgarbage("collect")
        end
    end)

    frame:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, 
        tileSize = 16, 
        edgeSize = 4,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    frame:SetBackdropColor(0.1, 0.1, 0.1, 0.7)
    frame:SetBackdropBorderColor(0.4, 0.4, 0.4)
    
    local titleBg = frame:CreateTexture(nil, "BACKGROUND")
    titleBg:SetColorTexture(0.3, 0.3, 0.3, 0)
    titleBg:SetPoint("TOPLEFT", frame, "TOPLEFT", 2, -2)
    titleBg:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -2, -2)
    titleBg:SetHeight(24)
    
    frame.title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    frame.title:SetPoint("TOP", 0, -18)
    frame.title:SetText("|TInterface\\icons\\ui_delves:16:16|t 助手设置")
    frame.title:SetTextColor(0.95, 0.95, 0.32) 
    
    local closeButton = CreateFrame("Button", nil, frame)
    closeButton:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -2, -2)
    closeButton:SetSize(24, 24)

    local closeText = closeButton:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    closeText:SetPoint("CENTER", closeButton, "CENTER")
    closeText:SetText("x")
    closeText:SetTextColor(1, 1, 1)

    closeButton:SetScript("OnEnter", function(self)
        closeText:SetTextColor(1, 0.82, 0)
    end)

    closeButton:SetScript("OnLeave", function(self)
        closeText:SetTextColor(1, 1, 1)
    end)

    closeButton:SetScript("OnClick", function()
        if DFCN.merchantFrame and DFCN.merchantFrame:IsShown() then
            DFCN.merchantFrame:Hide()
			collectgarbage("collect")
        end
        frame:Hide()
    end)

    local autoEnterCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    autoEnterCheckbox:SetPoint("TOPLEFT", 30, -45)
    autoEnterCheckbox:SetChecked(DFCN_DelveHelperDB.autoEnter)
    autoEnterCheckbox:SetScript("OnClick", function(self)
        if not self:IsEnabled() then return end
        
        DFCN_DelveHelperDB.autoEnter = self:GetChecked()
        
        if DFCN_DelveHelperDB.autoEnter then
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动进入地下堡功能已启用|r")
        else
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动进入地下堡功能已禁用|r")
        end
    end)
    
    autoEnterCheckbox.text = autoEnterCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    autoEnterCheckbox.text:SetPoint("LEFT", autoEnterCheckbox, "RIGHT", 5, 0)
    autoEnterCheckbox.text:SetText("自动进入地下堡")
    autoEnterCheckbox.text:SetTextColor(1, 1, 1) 
    
    DFCN.autoEnterCheckbox = autoEnterCheckbox    

    local difficultyLabel = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    difficultyLabel:SetPoint("TOPLEFT", 35, -85)
    difficultyLabel:SetText("难度：")
    difficultyLabel:SetTextColor(1, 1, 1) 

    local fastExitCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    fastExitCheckbox:SetPoint("LEFT", difficultyLabel, "RIGHT", 15, 0)
    fastExitCheckbox:SetChecked(DFCN_DelveHelperDB.fastExitMode)
    fastExitCheckbox:SetScript("OnClick", function(self)
        DFCN_DelveHelperDB.fastExitMode = self:GetChecked()
        UpdateExitCooldownDuration()
        
        if self:GetChecked() then
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 刷蓝门模式已启用，现在进出地下堡无CD|r")
        else
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 刷蓝门模式已禁用，离开地下堡5秒后才再次触发自动进入|r")
        end
    end)

    fastExitCheckbox.text = fastExitCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    fastExitCheckbox.text:SetPoint("LEFT", fastExitCheckbox, "RIGHT", 5, 0)
    fastExitCheckbox.text:SetText("速刷蓝门")
    fastExitCheckbox.text:SetTextColor(1, 1, 1)
    
    local dropdown = CreateFrame("Frame", "DFCN_DelveHelperDifficultyDropdown", frame, "UIDropDownMenuTemplate")
    dropdown:SetPoint("TOPLEFT", difficultyLabel, "BOTTOMLEFT", -20, -10)
    
    UIDropDownMenu_SetWidth(dropdown, 140) 
    
    UIDropDownMenu_SetText(dropdown, DFCN_DelveHelperDB.difficultyLevel and "难度 "..DFCN_DelveHelperDB.difficultyLevel or "关闭")
    
    local function Difficulty_OnClick(self, arg1, arg2, checked)
        DFCN_DelveHelperDB.difficultyLevel = arg1
        UIDropDownMenu_SetText(dropdown, arg1 and "难度 "..arg1 or "关闭")
        
        if arg1 then
            print(string.format("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 已设置自动选择难度等级为 %d|r", arg1))
        else
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 已关闭自动选择难度等级，自动进入地下堡功能已禁用|r")
        end
    end
    
    UIDropDownMenu_Initialize(dropdown, function(self, level)
        UIDropDownMenu_SetWidth(self, 140)
        
        local info = UIDropDownMenu_CreateInfo()
        info.text = "关闭"
        info.arg1 = nil
        info.func = Difficulty_OnClick
        info.minWidth = 130
        info.notCheckable = true
        info.leftPadding = 10
        UIDropDownMenu_AddButton(info)
        
        for i = 1, 11 do
            info = UIDropDownMenu_CreateInfo()
            info.text = "难度 "..i
            info.arg1 = i
            info.func = Difficulty_OnClick
            info.minWidth = 130
            info.notCheckable = true
            info.leftPadding = 10
            UIDropDownMenu_AddButton(info)
        end
        
        local listFrame = _G[self:GetName().."List"]
        if listFrame then
            listFrame:SetWidth(150)
        end
    end)

    local scoreboardCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
	scoreboardCheckbox:SetPoint("TOPLEFT", dropdown, "BOTTOMLEFT", 15, 0)
	scoreboardCheckbox:SetChecked(DFCN_DelveHelperDB.scoreboardEnabled)
	scoreboardCheckbox:SetScript("OnClick", function(self)
		DFCN_DelveHelperDB.scoreboardEnabled = self:GetChecked()
		if self:GetChecked() then
            DFCN.CreateScoreboard()
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 地下堡监控已启用，进入地下堡后自动显示监控面板|r")
			if IsInDelvesScenario() then
				DFCN.scoreboardFrame:Show()
			end
		else
            if DFCN.scoreboardFrame then
                DFCN.scoreboardFrame:Hide()
            end
			print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 地下堡监控功能已禁用|r")
		end
	end)

	scoreboardCheckbox.text = scoreboardCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	scoreboardCheckbox.text:SetPoint("LEFT", scoreboardCheckbox, "RIGHT", 5, 0)
	scoreboardCheckbox.text:SetText("显示地下堡监控")
	scoreboardCheckbox.text:SetTextColor(1, 1, 1)

    local treasureMapCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    treasureMapCheckbox:SetPoint("TOPLEFT", scoreboardCheckbox, "BOTTOMLEFT", 0, 0) 
    treasureMapCheckbox:SetChecked(DFCN_DelveHelperDB.treasureMapAlertEnabled)
    treasureMapCheckbox:SetScript("OnClick", function(self)
        DFCN_DelveHelperDB.treasureMapAlertEnabled = self:GetChecked()
        if self:GetChecked() then
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动检测藏宝图功能已启用|r")
        else
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动检测藏宝图功能已禁用|r")
        end
    end)

    treasureMapCheckbox.text = treasureMapCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    treasureMapCheckbox.text:SetPoint("LEFT", treasureMapCheckbox, "RIGHT", 5, 0)
    treasureMapCheckbox.text:SetText("自动检测藏宝图")
    treasureMapCheckbox.text:SetTextColor(1, 1, 1)

    local autoActivateCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    autoActivateCheckbox:SetPoint("TOPLEFT", treasureMapCheckbox, "BOTTOMLEFT", 0, 0)
    autoActivateCheckbox:SetChecked(DFCN_DelveHelperDB.autoActivateDelve)
    autoActivateCheckbox:SetScript("OnClick", function(self)
        DFCN_DelveHelperDB.autoActivateDelve = self:GetChecked()
        if self:GetChecked() then
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动与NPC对话功能已启用|r")
        else
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动与NPC对话功能已禁用|r")
        end
    end)

    autoActivateCheckbox.text = autoActivateCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    autoActivateCheckbox.text:SetPoint("LEFT", autoActivateCheckbox, "RIGHT", 5, 0)
    autoActivateCheckbox.text:SetText("自动与NPC对话")
    autoActivateCheckbox.text:SetTextColor(1, 1, 1)
    
    local autoLeaveCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    autoLeaveCheckbox:SetPoint("TOPLEFT", autoActivateCheckbox, "BOTTOMLEFT", 0, 0)
	autoLeaveCheckbox:SetChecked(DFCN_DelveHelperDB.autoLeaveShip)
	autoLeaveCheckbox:SetScript("OnClick", function(self)
		DFCN_DelveHelperDB.autoLeaveShip = self:GetChecked()
		
		if DFCN_DelveHelperDB.autoLeaveShip then
			print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动离开破晨号（追随者难度）及自动跳过安德麦钻机功能已启用|r")
		else
			print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动离开破晨号（追随者难度）及自动跳过安德麦钻机功能已禁用|r")
		end
	end)

	autoLeaveCheckbox.text = autoLeaveCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	autoLeaveCheckbox.text:SetPoint("LEFT", autoLeaveCheckbox, "RIGHT", 5, 0)
	autoLeaveCheckbox.text:SetText("自动破晨号钻机")
	autoLeaveCheckbox.text:SetTextColor(1, 1, 1)

    local autoTokenConfirmCheckbox = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    autoTokenConfirmCheckbox:SetPoint("TOPLEFT", autoLeaveCheckbox, "BOTTOMLEFT", 0, 0)
    autoTokenConfirmCheckbox:SetChecked(DFCN_DelveHelperDB.autoTokenExchange)
    autoTokenConfirmCheckbox:SetScript("OnClick", function(self)
        DFCN_DelveHelperDB.autoTokenExchange = self:GetChecked()
        if self:GetChecked() then
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动确认兑换纹章功能已启用，仅自动确认45低级纹章换15高级纹章。|r")
        else
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[设置修改] 自动确认兑换纹章功能已禁用|r")
        end
    end)

    autoTokenConfirmCheckbox.text = autoTokenConfirmCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    autoTokenConfirmCheckbox.text:SetPoint("LEFT", autoTokenConfirmCheckbox, "RIGHT", 5, 0)
    autoTokenConfirmCheckbox.text:SetText("自动确认兑换纹章")
    autoTokenConfirmCheckbox.text:SetTextColor(1, 1, 1)

    local merchantBtn = CreateFrame("Button", nil, frame)
    merchantBtn:SetSize(150, 24	)
    merchantBtn:SetPoint("BOTTOM", 0, 18)

    merchantBtn.BorderTop = merchantBtn:CreateTexture(nil, "BORDER")
    merchantBtn.BorderTop:SetPoint("TOPLEFT", 0, 0)
    merchantBtn.BorderTop:SetPoint("TOPRIGHT", 0, 0)
    merchantBtn.BorderTop:SetHeight(1)
    merchantBtn.BorderTop:SetColorTexture(1, 1, 1, 0.7)
    
    merchantBtn.BorderBottom = merchantBtn:CreateTexture(nil, "BORDER")
    merchantBtn.BorderBottom:SetPoint("BOTTOMLEFT", 0, 0)
    merchantBtn.BorderBottom:SetPoint("BOTTOMRIGHT", 0, 0)
    merchantBtn.BorderBottom:SetHeight(1)
    merchantBtn.BorderBottom:SetColorTexture(1, 1, 1, 0.7)
    
    merchantBtn.BorderLeft = merchantBtn:CreateTexture(nil, "BORDER")
    merchantBtn.BorderLeft:SetPoint("TOPLEFT", 0, 0)
    merchantBtn.BorderLeft:SetPoint("BOTTOMLEFT", 0, 0)
    merchantBtn.BorderLeft:SetWidth(1)
    merchantBtn.BorderLeft:SetColorTexture(1, 1, 1, 0.7)
    
    merchantBtn.BorderRight = merchantBtn:CreateTexture(nil, "BORDER")
    merchantBtn.BorderRight:SetPoint("TOPRIGHT", 0, 0)
    merchantBtn.BorderRight:SetPoint("BOTTOMRIGHT", 0, 0)
    merchantBtn.BorderRight:SetWidth(1)
    merchantBtn.BorderRight:SetColorTexture(1, 1, 1, 0.7)
    
    merchantBtn.text = merchantBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    merchantBtn.text:SetPoint("CENTER")
	merchantBtn.text:SetFont(GameFontNormal:GetFont(), 13)
    merchantBtn.text:SetText("查看地下堡商人")
    merchantBtn.text:SetTextColor(1, 1, 1)

    merchantBtn:SetScript("OnMouseDown", function(self)
        self.text:SetPoint("CENTER", 1, -1)
    end)
    
    merchantBtn:SetScript("OnMouseUp", function(self)
        self.text:SetPoint("CENTER", 0, 0)
    end)
    
	merchantBtn:SetScript("OnEnter", function(self)
		self.BorderTop:SetColorTexture(1, 0.8, 0)
		self.BorderBottom:SetColorTexture(1, 0.8, 0)
		self.BorderLeft:SetColorTexture(1, 0.8, 0)
		self.BorderRight:SetColorTexture(1, 0.8, 0)
		self.text:SetTextColor(1, 0.8, 0)
	end)
    
	merchantBtn:SetScript("OnLeave", function(self)
		self.BorderTop:SetColorTexture(1, 1, 1, 0.7)
		self.BorderBottom:SetColorTexture(1, 1, 1, 0.7)
		self.BorderLeft:SetColorTexture(1, 1, 1, 0.7)
		self.BorderRight:SetColorTexture(1, 1, 1, 0.7)
		self.text:SetTextColor(1, 1, 1)
	end)
    
	merchantBtn:SetScript("OnClick", function()
		DFCN.ToggleMerchantFrame()
		
		if DFCN.merchantFrame and DFCN.merchantFrame:IsShown() then
			C_Timer.After(0, function()
				DFCN.UpdateMerchantItems(DFCN.merchantFrame.currentDate or date("*t"))
			end)
		end
	end)

	frame:Hide()
    DFCN.settingsFrame = frame
    DFCN.RefreshSettingsFrame()
end

function DFCN.CreateMerchantFrame()
    if DFCN.merchantFrame then return end
    
    local parent = DFCN.settingsFrame
    local frame = CreateFrame("Frame", "DFCN_DelveHelperMerchantFrame", UIParent, "BackdropTemplate")
    frame:SetSize(240, 350)
    frame:SetPoint("RIGHT", parent, "LEFT", 2, 0)
    frame:SetFrameLevel(parent:GetFrameLevel() + 10)
    
    frame:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, 
        tileSize = 16, 
        edgeSize = 4,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    frame:SetBackdropColor(0.1, 0.1, 0.1, 0.7)
    frame:SetBackdropBorderColor(0.4, 0.4, 0.4)
    frame.dateLabel = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    frame.dateLabel:SetPoint("TOPLEFT", 10, -18)
    frame.dateLabel:SetText("日期：")
    frame.dateLabel:SetTextColor(1, 1, 1)
    
    frame.datePicker = CreateFrame("Frame", "DFCN_DelveHelperMerchantDatePicker", frame, "UIDropDownMenuTemplate")
    frame.datePicker:SetPoint("LEFT", frame.dateLabel, "RIGHT", 10, 0)
    UIDropDownMenu_SetWidth(frame.datePicker, 120)
    
    UIDropDownMenu_Initialize(frame.datePicker, function(self, level)
        local today = date("*t")
        local info = UIDropDownMenu_CreateInfo()
        
        local todayText = format("今天 (%02d-%02d)", today.month, today.day)
        info.text = todayText
        info.arg1 = today
        info.func = function(_, arg) 
            UIDropDownMenu_SetText(frame.datePicker, todayText)
            DFCN.UpdateMerchantItems(arg)
			C_Timer.After(0, function()
				DFCN.UpdateMerchantItems(arg)
			end)
        end
        UIDropDownMenu_AddButton(info)
        
        for i = 1, 4 do
            local dateInfo = date("*t", time() + 86400 * i)
            local dateStr = format("%02d-%02d", dateInfo.month, dateInfo.day)
            
            local info = UIDropDownMenu_CreateInfo()
            info.text = dateStr
            info.arg1 = dateInfo
            
            info.func = (function(dateText)
                return function(_, arg)
                    UIDropDownMenu_SetText(frame.datePicker, dateText)
                    DFCN.UpdateMerchantItems(arg)
                end
            end)(dateStr)
            
            UIDropDownMenu_AddButton(info)
        end
    end)
    
    local today = date("*t")
    UIDropDownMenu_SetText(frame.datePicker, format("今天 (%02d-%02d)", today.month, today.day))
    
    frame.itemsFrame = CreateFrame("Frame", nil, frame)
    frame.itemsFrame:SetPoint("TOPLEFT", 10, -40)
    frame.itemsFrame:SetPoint("BOTTOMRIGHT", -10, 10)
    
    frame.items = {}
    for i = 1, 7 do
        local item = CreateFrame("Button", "DFCN_DelveHelperMerchantItem"..i, frame.itemsFrame)
        item:SetSize(260, 42)
        item:SetPoint("TOPLEFT", 0, -((i-1) * 42))
        item.icon = item:CreateTexture(nil, "ARTWORK")
        item.icon:SetSize(32, 32)
        item.icon:SetPoint("LEFT", 5, 0)
        
        item.name = item:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        item.name:SetPoint("LEFT", item.icon, "RIGHT", 8, 0)
        item.name:SetSize(250, 36)
        item.name:SetFont(GameFontNormal:GetFont(), 14)
        item.name:SetTextColor(1, 1, 1)
        item.name:SetJustifyH("LEFT")
        
        item.bg = item:CreateTexture(nil, "BACKGROUND")
        if i % 2 == 1 then
            item.bg:SetColorTexture(0.15, 0.15, 0.15, 0.3)
        else
            item.bg:SetColorTexture(0.2, 0.2, 0.2, 0.3)
        end
        item.bg:SetAllPoints()
        
        frame.items[i] = item
    end
    
    frame:Hide()
    DFCN.merchantFrame = frame
    
    DFCN.UpdateMerchantItems(today)
end

local function CreateFullItemLink(itemID, suffix, itemName)
    local r, g, b = GetItemQualityColor(4)
    local hexColor = format("%02x%02x%02x", r*255, g*255, b*255)
    return format("|cff%s|Hitem:%d%s|h%s|h|r", 
                 hexColor,
                 itemID, 
                 suffix, 
                 itemName)
end

function DFCN.UpdateMerchantItems(dateTable)
    if not DFCN.merchantFrame then return end
    
    local availableItems = GetMerchantItemsForDate(dateTable)
    
    for _, itemFrame in ipairs(DFCN.merchantFrame.items) do
        itemFrame:Hide()
    end

	for i, item in ipairs(availableItems) do
        if i > 8 then break end
        
        local itemFrame = DFCN.merchantFrame.items[i]        
        local fullLink = CreateFullItemLink(item.itemID, item.suffix, item.name)
        itemFrame.name:SetText(fullLink)
        itemFrame.name:SetFont(GameFontNormal:GetFont(), 14)
        local icon = select(10, GetItemInfo(item.itemID))
        itemFrame.icon:SetTexture(icon or "Interface\\Icons\\INV_Misc_QuestionMark")

        itemFrame:SetScript("OnClick", function(self, button)
            if IsShiftKeyDown() then
                HandleModifiedItemClick(fullLink)
            end
        end)
        
        itemFrame:SetScript("OnEnter", function(self)
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetHyperlink(fullLink)
            GameTooltip:Show()
        end)
        
        itemFrame:SetScript("OnLeave", GameTooltip_Hide)
        
        itemFrame:Show()
    end
    
    C_Timer.After(0, function()
        for i, item in ipairs(availableItems) do
            if i > 8 then break end
            
            local itemFrame = DFCN.merchantFrame.items[i]
			local updatedLink = CreateFullItemLink(item.itemID, item.suffix, item.name)
			itemFrame.name:SetText(updatedLink)
            
            local icon = select(10, GetItemInfo(item.itemID))
            if icon then
                itemFrame.icon:SetTexture(icon)
            end
        end
    end)
end

function DFCN.ToggleMerchantFrame()
    if not DFCN.merchantFrame then
        DFCN.CreateMerchantFrame()
    end
    
    if DFCN.merchantFrame:IsShown() then
        DFCN.merchantFrame:Hide()
    else
        DFCN.merchantFrame:Show()
    end
end

local function FindAndClickSelectButton()
    local function FindButtonRecursive(frame)
	if not frame or frame:IsForbidden() then return false end
        
        if frame:GetObjectType() == "Button" and frame:IsVisible() and frame:IsEnabled() and frame.GetText then
            local text = frame:GetText()
            if text and text:find("选择") then
                frame:Click()

                if PlayerChoiceFrame and PlayerChoiceFrame:IsShown() then
                    PlayerChoiceFrame:Hide()
                end

                return true
            end
        end
        
        if frame.GetNumChildren then
            local children = {frame:GetChildren()}
            for _, child in ipairs(children) do
                if FindButtonRecursive(child) then
                    return true
                end
            end
        end
        
        return false
    end
    
    return FindButtonRecursive(PlayerChoiceFrame)
end

local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_LOGIN")
frame:RegisterEvent("SCENARIO_UPDATE")
frame:RegisterEvent("SCENARIO_COMPLETED")
frame:RegisterEvent("BAG_UPDATE")
frame:RegisterEvent("UNIT_AURA")
frame:RegisterEvent("PLAYER_CHOICE_UPDATE")
frame:RegisterEvent("PLAYER_CHOICE_CLOSE")
frame:RegisterEvent("CINEMATIC_START")
frame:RegisterEvent("CINEMATIC_STOP")
frame:RegisterEvent("TRAIT_CONFIG_UPDATED")
local function ShouldAutoEnter()
    return DFCN_DelveHelperDB.autoEnter
end

local function IsDelvesGossip()
    if DelvesDifficultyPickerFrame and DelvesDifficultyPickerFrame:IsShown() then
        return true
    end    
    return false
end

local function AutoSelectAndEnter()
    if not ShouldAutoEnter() then return end
    
    local gossipOptions = C_GossipInfo.GetOptions()
    local gossipText = C_GossipInfo.GetText()
    local DelvesName = "未知地下堡"
    
    if gossipText and gossipText ~= "" then
        DelvesName = gossipText
    end
    
    local hasSpecialDifficulty = false
    
    if gossipOptions then
        for _, option in ipairs(gossipOptions) do
            local optionText = StripColorCodes(option.name or "")
            if optionText:find("难度 %？") or optionText:find("赛季") then
                hasSpecialDifficulty = true
                break
            end
        end
    end
    
    if hasSpecialDifficulty then
        print("|TInterface\\icons\\ui_delves:14:14|t |cFFFFA500[警告] 当前为特殊地下堡，自动进入已取消|r")
        return
    end
    
    local level = DFCN_DelveHelperDB.difficultyLevel
    if level and level >= 1 and level <= 11 then
        local targetOrderIndex = level - 1        
        C_GossipInfo.SelectOptionByIndex(targetOrderIndex)
		
        print(string.format("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 自动进入地下堡：%s（%d层）|r", DelvesName, level))
    else
        print("|TInterface\\icons\\ui_delves:14:14|t |cFFFFA500[警告] 请先在设置中选择自动进入的难度等级|r")
    end
end

function DFCN.HandleScenarioUpdate()
	if IsInDelvesScenario() then
        if not DFCN.delveStartTime then
            DFCN.StartDelveTimer()
        end

        local _, _, isAbundant = GetDelveInfo()
        DFCN.isAbundant = isAbundant
        
        if DFCN_DelveHelperDB.scoreboardEnabled then
            local frame = DFCN.CreateScoreboard()            
            frame:Show()            
            DFCN.DelayedScoreboardRefresh(1)
        end
    else
        DFCN.isAbundant = nil
        if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
            DFCN.scoreboardFrame:Hide()
        end
    end
end

function DFCN.DelayedScoreboardRefresh(delay)
    if DFCN.scoreboardUpdateTimer then
        DFCN.scoreboardUpdateTimer:Cancel()
    end
    
    DFCN.scoreboardUpdateTimer = C_Timer.NewTimer(delay, function()
        DFCN.scoreboardUpdateTimer = nil
        DFCN.UpdateScoreboard()	
		DFCN.UpdateCompanionIcons()
    end)
end

function DFCN.StartPeriodicUpdateTimer()
    if DFCN.periodicUpdateTimer then
        DFCN.periodicUpdateTimer:Cancel()
    end
    
    DFCN.periodicUpdateTimer = C_Timer.NewTicker(30, function()
        if not DFCN.scoreboardFrame or not DFCN.scoreboardFrame:IsShown() then return end
        DFCN.UpdateScoreboard()
    end)
end

function DFCN.StopPeriodicUpdateTimer()
    if DFCN.periodicUpdateTimer then
        DFCN.periodicUpdateTimer:Cancel()
        DFCN.periodicUpdateTimer = nil
    end
end

local function CheckForExistingDelveTimer()
    if IsInDelvesScenario() then
        local key = GetCharacterKey()
        local charDB = DFCN_DelveHelperDB.characters[key]
        
        if charDB then
            if charDB.delveCompleted ~= nil then
                DFCN.delveCompleted = charDB.delveCompleted
            end

            if DFCN.delveCompleted then
                if charDB.delveStartTime then
                    DFCN.delveStartServerTime = charDB.delveStartTime
                    DFCN.delveCompletionTime = charDB.delveCompletionTime
                end
                
                if DFCN_DelveHelperDB.scoreboardEnabled then
                    local frame = DFCN.CreateScoreboard()
                    frame:Show()
                    DFCN.UpdateScoreboard()
                end
                return
            end
            
            if charDB.delveStartTime and not DFCN.delveCompleted then
                DFCN.delveStartServerTime = charDB.delveStartTime
                
                if DFCN.delveTimer then
                    DFCN.delveTimer:Cancel()
                end
                
                DFCN.delveTimer = C_Timer.NewTicker(1, function()
                    if not DFCN.scoreboardFrame or not DFCN.scoreboardFrame:IsShown() then return end
                    
                    local now = GetServerTime()
                    local duration = now - DFCN.delveStartServerTime
                    
                    DFCN.scoreboardFrame.duration.value:SetText(FormatTime(duration, false))
                end)
                
                if DFCN_DelveHelperDB.scoreboardEnabled then
                    local frame = DFCN.CreateScoreboard()
                    frame:Show()
                    DFCN.UpdateScoreboard()
                end
            end
        end
    end
end

function DFCN.CreateTreasureMapAlert()
    if DFCN.treasureMapAlert then return end
    
    local alert = CreateFrame("Frame", nil, UIParent)
    alert:SetSize(600, 100)
    alert:SetPoint("CENTER", 0, 350)
    alert:SetFrameStrata("FULLSCREEN_DIALOG")
    
    alert.text = alert:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
    alert.text:SetPoint("CENTER")
    alert.text:SetText("|T1064187:14:14|t |cFFFF0000注意：请使用背包中的地下堡藏宝图！|r")
       
    alert:Hide()
    DFCN.treasureMapAlert = alert
end

function DFCN.CreateTreasureBuffAlert()
    if DFCN.treasureBuffAlert then return end
    
    local alert = CreateFrame("Frame", nil, UIParent)
    alert:SetSize(800, 120)
    alert:SetPoint("CENTER", 0, 350)
    alert:SetFrameStrata("FULLSCREEN_DIALOG")
    
    alert.text = alert:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
    alert.text:SetPoint("CENTER")
    alert.text:SetText("|T1064187:14:14|t |cFFFF0000注意：藏宝图已激活，当前不是11层地下堡！|r")
       
    alert:Hide()
    DFCN.treasureBuffAlert = alert
end

local function HandleTokenExchange(popupName, ...)
    local n = select('#', ...)
    local argParts = {}
    
    for i = 1, n do
        local arg = select(i, ...)
        local argType = type(arg)
        
        if argType == "table" then
            table.insert(argParts, "table")
        else
            table.insert(argParts, tostring(arg))
        end
    end
    
    local argStr = table.concat(argParts, ", ")    
    
    if popupName ~= "CONFIRM_PURCHASE_NONREFUNDABLE_ITEM" then
        return
    end
    
    local itemName = select(1, ...) or ""    
    local itemInfo = select(3, ...)
    local actualItemName = ""
    if type(itemInfo) == "table" and type(itemInfo.name) == "string" then
        actualItemName = itemInfo.name
    end
    
    if actualItemName:find("附魔") then
        return
    end
    
    local isTokenExchange = itemName:find("纹章") ~= nil
    
    if not isTokenExchange then
        return
    end
    
    if not DFCN_DelveHelperDB.autoTokenExchange then
        return
    end
    
    if itemName:match("45") then
        local confirmButton = _G["StaticPopup1Button1"]
        if confirmButton and confirmButton:IsEnabled() then
            confirmButton:Click()
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 自动确认纹章兑换|r")
        end
    elseif itemName:match("15") then
        print("|TInterface\\icons\\ui_delves:14:14|t |cFFFFA500[警告] 你正在使用高级纹章兑换低级纹章，请谨慎操作！|r")        
    end
end

function DFCN.CheckAndShowTreasureMapAlert()
    if not DFCN_DelveHelperDB.treasureMapAlertEnabled then

        if DFCN.treasureMapAlert and DFCN.treasureMapAlert:IsShown() then
            DFCN.treasureMapAlert:Hide()
        end
        DFCN.inDelveWithMap = false
        return
    end
    if not DFCN.treasureMapAlert then
        DFCN.treasureMapAlert = CreateFrame("Frame", nil, UIParent)
        DFCN.treasureMapAlert:SetSize(800, 120)
        DFCN.treasureMapAlert:SetPoint("CENTER", 0, 350)
        DFCN.treasureMapAlert:SetFrameStrata("FULLSCREEN_DIALOG")
        
        DFCN.treasureMapAlert.text = DFCN.treasureMapAlert:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
        DFCN.treasureMapAlert.text:SetPoint("CENTER")
        DFCN.treasureMapAlert.text:SetText("|T1064187:14:14|t |cFFFF0000注意：请使用背包中的地下堡藏宝图！|r")   
        
        DFCN.treasureMapAlert:Hide()
    end

	if IsInDelvesScenario() then
        local mapCount = GetItemCount(248142)
        
        if mapCount > 0 then
            DFCN.treasureMapAlert:Show()
            DFCN.inDelveWithMap = true
        else
            DFCN.treasureMapAlert:Hide()
            DFCN.inDelveWithMap = false
        end
    else
        DFCN.treasureMapAlert:Hide()
        DFCN.inDelveWithMap = false
    end
end

frame:SetScript("OnEvent", function(self, event, ...)
    if event == "ADDON_LOADED" then
        if ... == "OrzUI" then
            frame:UnregisterEvent("ADDON_LOADED")
            frame:RegisterEvent("GOSSIP_SHOW")
			frame:RegisterEvent("DISPLAY_EVENT_TOASTS")
            hooksecurefunc("StaticPopup_Show", HandleTokenExchange)
            LoadLibraries()
            DFCN_DelveHelperDB.characters = DFCN_DelveHelperDB.characters or {}
            UpdateExitCooldownDuration()
			if not IsInDelvesScenario() then
				DFCN.delveCompleted = false
			end
            CheckForExistingDelveTimer()

            local levelInfo = DFCN_DelveHelperDB.difficultyLevel and 
                            string.format("|cFF00FF00%d|r", DFCN_DelveHelperDB.difficultyLevel) or 
                            "|cFFFF0000未设置|r"
            
            local autoStatus = DFCN_DelveHelperDB.autoEnter and "|cFF00FF00开启|r" or "|cFFFF0000关闭|r"

            local fastExitStatus = DFCN_DelveHelperDB.fastExitMode and "|cFF00FF00开启|r" or "|cFFFF0000关闭|r"
            
            print(string.format("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息]|r|cFF00FF00 地下堡助手|cFFFFA500 By|r|c000EEEEE DFCN|r |c000EEE00已加载|r"))
            print(string.format("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[状态] |cFF00FF00自动进入: %s | 难度等级: %s | 速刷蓝门: %s|r", 
                autoStatus, levelInfo, fastExitStatus))
            DFCN.lastScenario = select(1, C_Scenario.GetInfo())
			local currentScenario = select(1, C_Scenario.GetInfo())
			if currentScenario == "地下堡" then
				DFCN.checkTreasureMapPending = true
			end
			if IsInDelvesScenario() and DFCN_DelveHelperDB.scoreboardEnabled then
                local frame = DFCN.CreateScoreboard()
                frame:Show()
				DFCN.StartPeriodicUpdateTimer()
                DFCN.DelayedScoreboardRefresh(1)
			end
        end
    elseif event == "PLAYER_LOGIN" then
		if not IsInDelvesScenario() then
			DFCN.delveCompleted = false
		end
        DFCN.InitMinimapIcon()
        CheckForExistingDelveTimer()
        local currentScenario = select(1, C_Scenario.GetInfo())
        if currentScenario == "地下堡" and DFCN_DelveHelperDB.scoreboardEnabled then
            local frame = DFCN.CreateScoreboard()
            frame:Show()
            DFCN.DelayedScoreboardRefresh(1)
        end
        if DFCN.checkTreasureMapPending then
            DFCN.checkTreasureMapPending = false
            C_Timer.After(1, function()
                DFCN.CheckAndShowTreasureMapAlert()
            end)
        end
    elseif event == "SCENARIO_UPDATE" then
        C_Timer.After(1.5, function()
            local scenarioName = select(1, C_Scenario.GetInfo())
			local isInDelves = IsInDelvesScenario()

			if DFCN.delveCompleted and isInDelves then
				return
			end

            if DFCN.lastScenario == "地下堡" and not isInDelves then
                DFCN.exitCooldown = true
                DFCN.exitTime = GetTime()
                
                C_Timer.After(DFCN.exitCooldownDuration, function()
                    DFCN.exitCooldown = false
                end)
            end
            
            DFCN.lastScenario = scenarioName

			if not isInDelves then
				if DFCN.treasureMapAlert and DFCN.treasureMapAlert:IsShown() then
					DFCN.treasureMapAlert:Hide()
				end
				DFCN.inDelveWithMap = false
				if DFCN.showScoreboardTimer then
					DFCN.showScoreboardTimer:Cancel()
					DFCN.showScoreboardTimer = nil
				end
				DFCN.StopPeriodicUpdateTimer()
				if DFCN.treasureBuffAlert then
					DFCN.treasureBuffAlert:Hide()
				end
				DFCN.isAbundant = nil
				DFCN.ResetDelveTimer()
				if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
					DFCN.scoreboardFrame:Hide()
				end
                
                local key = GetCharacterKey()
                if DFCN_DelveHelperDB.characters[key] then
                    DFCN_DelveHelperDB.characters[key].flashingDoorDetected = false
					DFCN_DelveHelperDB.characters[key].flashingDoorActivated = false
                end
                
                if DFCN.scoreboardFrame then
                    DFCN.scoreboardFrame.flashingDoorIcon:Hide()
                    DFCN.scoreboardFrame.flashingDoorText:Hide()
                end
				return
			end

			if DFCN.delveCompleted then
				if scenarioName == "地下堡" then
					if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
						DFCN.UpdateScoreboard()
					end
				else
					DFCN.delveCompleted = false
					DFCN.delveStartServerTime = nil
					DFCN.delveCompletionTime = nil
				end
				return
			end     

            DFCN.CheckAndShowTreasureMapAlert()
			
            if not DFCN.delveStartServerTime then
                DFCN.StartDelveTimer()
            end
                
            local _, _, isAbundant = GetDelveInfo()
            DFCN.isAbundant = isAbundant
                
            if DFCN_DelveHelperDB.scoreboardEnabled then
                DFCN.StartPeriodicUpdateTimer()
                if DFCN.showScoreboardTimer then
                    DFCN.showScoreboardTimer:Cancel()
                end                
                DFCN.showScoreboardTimer = C_Timer.NewTimer(1, function()
                    DFCN.showScoreboardTimer = nil
                    local frame = DFCN.CreateScoreboard()
                    frame:Show()
                    DFCN.DelayedScoreboardRefresh(1)
                end)
            end
        end)
	elseif event == "GOSSIP_SHOW" then
			if IsInDelvesScenario() then
				if DFCN_DelveHelperDB.autoActivateDelve and 
				   not IsShiftKeyDown() and 
				   not IsControlKeyDown() and 
				   not IsAltKeyDown() then
					
					local gossipOptions = C_GossipInfo.GetOptions()
					if gossipOptions and #gossipOptions > 0 then
						for _, option in ipairs(gossipOptions) do
							if option.name and option.name:find("^|cFF0000FF") then
								local success = pcall(C_GossipInfo.SelectOption, option.gossipOptionID)
								if success then
									print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 自动与NPC对话: "..StripColorCodes(option.name).."|r")
									return
								end
							end
						end

						local taskOptionCount = 0
						local taskOptionID = nil
						for _, option in ipairs(gossipOptions) do
							if option.flags == 1 then
								taskOptionCount = taskOptionCount + 1
								taskOptionID = option.gossipOptionID
							end
						end
						
						if taskOptionCount == 1 then
							local success = pcall(C_GossipInfo.SelectOption, taskOptionID)
							if success then
								local optionName = ""
								for _, option in ipairs(gossipOptions) do
									if option.gossipOptionID == taskOptionID then
										optionName = option.name or ""
										break
									end
								end
								print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 自动与NPC对话: "..StripColorCodes(optionName).."|r")
								return
							end
						end
					end
				end
			end
		if DFCN.exitCooldown then
			return
		end
		if IsDelvesGossip() then
			AutoSelectAndEnter()
		end
		local guid = UnitGUID("npc")
		if guid and DFCN_DelveHelperDB.autoLeaveShip then
			local npcID = select(6, strsplit("-", guid))
			npcID = npcID and tonumber(npcID)
			
			if npcID and AUTO_CONFIRM_NPC_IDS[npcID] then
				local npcInfo = AUTO_CONFIRM_NPC_IDS[npcID]
				local shouldProceed = true
				
				if npcInfo.checkInstance then
					local _, _, difficultyID = GetInstanceInfo()
					shouldProceed = (difficultyID == npcInfo.difficultyID)
				end
				
				if shouldProceed then
					C_Timer.After(0, function()
						local gossipText = C_GossipInfo.GetText()
						if gossipText and gossipText:find(npcInfo.confirmText) then
							local options = C_GossipInfo.GetOptions()
							if options then
								for i, option in ipairs(options) do
									if option.name and option.name:find(npcInfo.yesText) then
										C_GossipInfo.SelectOption(option.gossipOptionID)
										if npcInfo.printText then
											print(npcInfo.printText)
										end
										if npcInfo.leaveParty then
											C_PartyInfo.ConfirmLeaveParty(2)
										end
										DFCN.expectingCinematic = true
										if DFCN.cinematicTimer then
											DFCN.cinematicTimer:Cancel()
										end
										DFCN.cinematicTimer = C_Timer.After(3, function()
											DFCN.expectingCinematic = false
											DFCN.cinematicTimer = nil
										end)										
										break
									end
								end
							end
						end
					end)
				end
			end
		end
	elseif event == "BAG_UPDATE" then
		if DFCN_DelveHelperDB.treasureMapAlertEnabled then
			if IsInDelvesScenario() then
				local mapCount = GetItemCount(248142)				
				if mapCount > 0 and not DFCN.inDelveWithMap then
					DFCN.CheckAndShowTreasureMapAlert()
				elseif mapCount == 0 and DFCN.inDelveWithMap then
					DFCN.treasureMapAlert:Hide()
					DFCN.inDelveWithMap = false
				end
			end
		end
	elseif event == "PLAYER_CHOICE_UPDATE" then
		if PlayerChoiceFrame and PlayerChoiceFrame:IsShown() and IsInDelvesScenario() then
			if DFCN.playerChoiceTicker then
				DFCN.playerChoiceTicker:Cancel()
				DFCN.playerChoiceTicker = nil
			end
			DFCN.playerChoiceTicker = C_Timer.NewTicker(0.1, function()
				local treasureName = "未知珍玩"
				local choiceInfo = C_PlayerChoice.GetCurrentPlayerChoiceInfo()
				if choiceInfo and choiceInfo.options and #choiceInfo.options > 0 then
					treasureName = choiceInfo.options[1].header or treasureName
					treasureName = StripColorCodes(treasureName)
				end

				if FindAndClickSelectButton() then
					if treasureName == "损坏的自动化足球炸弹分发器" then
						print("|TInterface\\icons\\ui_delves:14:14|t |cFFFF8000[信息] 自动选择珍玩宝藏：损坏的自动化足球炸弹分发器|r")
						PlaySoundFile(552503)
					else
						print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 自动选择珍玩宝藏："..treasureName.."|r")
					end
					return
				end
			end)
		end
	elseif event == "PLAYER_CHOICE_CLOSE" then
		if DFCN.playerChoiceTicker then
			DFCN.playerChoiceTicker:Cancel()
			DFCN.playerChoiceTicker = nil
		end
	elseif event == "CINEMATIC_START" then
		if DFCN.expectingCinematic then
			CinematicFrame_CancelCinematic()
			DFCN.expectingCinematic = false
			if DFCN.cinematicTimer then
				DFCN.cinematicTimer:Cancel()
				DFCN.cinematicTimer = nil
			end
		end
	elseif event == "CINEMATIC_STOP" then
		DFCN.expectingCinematic = false
		if DFCN.cinematicTimer then
			DFCN.cinematicTimer:Cancel()
			DFCN.cinematicTimer = nil
		end
	elseif event == "TRAIT_CONFIG_UPDATED" then
		local inDelves = IsInDelvesScenario()		
		if inDelves then
			C_Timer.After(0.1, function()
				if IsInDelvesScenario() and DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
					DFCN.UpdateCompanionIcons(true)
					print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 布莱恩·铜须配置已更新|r")
				end
			end)
		end
	elseif event == "UNIT_AURA" and ... == "player" then
			if IsInDelvesScenario() then
				DFCN.UpdatemedicineBar()
				if DFCN_DelveHelperDB.treasureMapAlertEnabled then
					local currentBuffState = C_UnitAuras and C_UnitAuras.GetPlayerAuraBySpellID(1246363) ~= nil
					if currentBuffState ~= DFCN.lastTreasureBuffState then
						DFCN.lastTreasureBuffState = currentBuffState
						C_Timer.After(1, function()
							DFCN.UpdateScoreboard()
						end)
					end
				end
			end       
	elseif event == "SCENARIO_COMPLETED" then
		DFCN.PauseDelveTimer()		
		DFCN.delveCompleted = true		
		local startTime = DFCN.delveStartServerTime or GetServerTime()
		DFCN.delveCompletionTime = GetServerTime() - startTime			
		local key = GetCharacterKey()
		DFCN_DelveHelperDB.characters[key] = DFCN_DelveHelperDB.characters[key] or {}
		DFCN_DelveHelperDB.characters[key].delveCompleted = true
		DFCN_DelveHelperDB.characters[key].delveCompletionTime = DFCN.delveCompletionTime		
		DFCN.StopPeriodicUpdateTimer()
		C_Timer.After(2.0, function()
			if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
				DFCN.UpdateScoreboard()
			end
		end)
	elseif event == "DISPLAY_EVENT_TOASTS" then
		if not IsInDelvesScenario() then
			return
		end

		if DFCN.delveCompleted then
			return
		end

		if DFCN.scoreboardFrame and DFCN.scoreboardFrame:IsShown() then
			DFCN.UpdateScoreboard()
		end

		if DFCN.flashingDoorCheckTimer then
			DFCN.flashingDoorCheckTimer:Cancel()
			DFCN.flashingDoorCheckTimer = nil
		end
		
		local checkCount = 0
		local maxChecks = 30
		
		local function CheckForFlashingDoor()
			checkCount = checkCount + 1
			local toast = C_EventToastManager.GetNextToastToDisplay()
			
			if toast then
				if toast.eventToastID == 339 then
					local key = GetCharacterKey()
					DFCN_DelveHelperDB.characters[key] = DFCN_DelveHelperDB.characters[key] or {}
					DFCN_DelveHelperDB.characters[key].flashingDoorDetected = true
					
					if DFCN_DelveHelperDB.characters[key].flashingDoorActivated == nil then
						DFCN_DelveHelperDB.characters[key].flashingDoorActivated = false
					end
					
					if DFCN_DelveHelperDB.scoreboardEnabled then
						if not DFCN.scoreboardFrame then
							DFCN.CreateScoreboard()
						end
						DFCN.scoreboardFrame:Show()
						DFCN.scoreboardFrame.flashingDoorIcon:Show()
						DFCN.scoreboardFrame.flashingDoorText:Show()
						
						if DFCN_DelveHelperDB.characters[key].flashingDoorActivated then
							DFCN.scoreboardFrame.flashingDoorText:SetText(" 已使用")
							DFCN.scoreboardFrame.flashingDoorText:SetTextColor(0.5, 0.5, 0.5)
							DFCN.scoreboardFrame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_RaidTrinkets_BlobOfSwirlingVoid_terra")
						else
							DFCN.scoreboardFrame.flashingDoorText:SetText(" 闪烁之门")
							DFCN.scoreboardFrame.flashingDoorText:SetTextColor(0.1, 0.4, 0.9)
							DFCN.scoreboardFrame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_RaidTrinkets_BlobOfSwirlingVoid_purple")
						end
					end
					
					if DFCN.flashingDoorCheckTimer then
						DFCN.flashingDoorCheckTimer:Cancel()
						DFCN.flashingDoorCheckTimer = nil
					end
					return
				end
				
				if toast.eventToastID == 337 or toast.eventToastID == 338 then
					local key = GetCharacterKey()
					DFCN_DelveHelperDB.characters[key] = DFCN_DelveHelperDB.characters[key] or {}
					DFCN_DelveHelperDB.characters[key].flashingDoorDetected = true
					DFCN_DelveHelperDB.characters[key].flashingDoorActivated = true
					
					if DFCN_DelveHelperDB.scoreboardEnabled then
						if not DFCN.scoreboardFrame then
							DFCN.CreateScoreboard()
						end
						DFCN.scoreboardFrame:Show()
						DFCN.scoreboardFrame.flashingDoorIcon:Show()
						DFCN.scoreboardFrame.flashingDoorText:Show()
						DFCN.scoreboardFrame.flashingDoorText:SetText(" 已使用")
						DFCN.scoreboardFrame.flashingDoorText:SetTextColor(0.5, 0.5, 0.5)
						DFCN.scoreboardFrame.flashingDoorIcon:SetTexture("Interface\\Icons\\INV_112_RaidTrinkets_BlobOfSwirlingVoid_terra")
					end                
				   
					if DFCN.flashingDoorCheckTimer then
						DFCN.flashingDoorCheckTimer:Cancel()
						DFCN.flashingDoorCheckTimer = nil
					end
					return
				end
			end
			
			if checkCount >= maxChecks then
				if DFCN.flashingDoorCheckTimer then
					DFCN.flashingDoorCheckTimer:Cancel()
					DFCN.flashingDoorCheckTimer = nil
				end
				return
			end
			
			DFCN.flashingDoorCheckTimer = C_Timer.After(1, CheckForFlashingDoor)
		end
		
		CheckForFlashingDoor()
    end
end)

SLASH_DFCN_DELVEHELPER1 = "/dfcndelve"
SlashCmdList["DFCN_DELVEHELPER"] = function(msg)
    msg = msg and strlower(msg:trim()) or ""
    
    if msg == "minimap on" then
        if LibDBIcon then
            LibDBIcon:Show("DFCN_DelveHelper")
            DFCN_DelveHelperDB.minimapIconShown = true
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 小地图图标已显示|r")
        end
    elseif msg == "minimap off" then
        if LibDBIcon then
            LibDBIcon:Hide("DFCN_DelveHelper")
            DFCN_DelveHelperDB.minimapIconShown = false
            print("|TInterface\\icons\\ui_delves:14:14|t |cFF00BFFF[信息] 小地图图标已隐藏|r")
        end
    elseif msg == "" then
        DFCN.ToggleSettingsFrame()
    else
        print("|cFFFFFF00/dfcndelve|r - 打开设置面板")
        print("|cFFFFFF00/dfcndelve minimap on|r - 显示小地图图标")
        print("|cFFFFFF00/dfcndelve minimap off|r - 隐藏小地图图标")
    end
end