local addonName, addon = ...

addon.UI = addon.UI or {}
addon.TankAssistant = addon.TankAssistant or {}

local UI = addon.UI
local Tank = addon.TankAssistant

Tank.SEASON = "Midnight Season 2"
Tank.PATCH = "12.1"
Tank.DUNGEONS = {
    {
        id = "altar_of_fangs",
        name = "Altar of Fangs",
        nameRU = "Алтарь Клыков",
        nameUK = "Вівтар Іклів",
        bosses = { "Rav'i", "The Writhing Coil", "Zul'jan" },
        bossesRU = { "Рав'и", "Извивающийся виток", "Зул'джан" },
    },
    {
        id = "murder_row",
        name = "Murder Row",
        nameRU = "Закоулок душегубов",
        nameUK = "Провулок душогубів",
        bosses = { "Kystia Manaheart", "Zaen Bladesorrow", "Xathuux the Annihilator", "Lithiel Cinderfury" },
        bossesRU = { "Кистия Сердце Маны", "Заэн Траурный Клинок", "Затуукс Разрушитель", "Литиэль Пепельная Ярость" },
    },
    {
        id = "den_of_nalorakk",
        name = "Den of Nalorakk",
        nameRU = "Берлога Налоракка",
        nameUK = "Барліг Налоракка",
        bosses = { "The Hoardmonger", "Sentinel of Winter", "Nalorakk" },
        bossesRU = { "Прозапасник", "Часовой зимы", "Налоракк" },
    },
    {
        id = "the_blinding_vale",
        name = "The Blinding Vale",
        nameRU = "Слепящая долина",
        nameUK = "Сліпуча долина",
        bosses = { "Lightblossom Trinity", "Ikuzz the Light Hunter", "Lightwarden Ruia", "Ziekket" },
        bossesRU = { "Светоцветное трио", "Икузз Охотник Света", "Страж Света Руйя", "Зиккет" },
    },
    {
        id = "voidscar_arena",
        name = "Voidscar Arena",
        nameRU = "Арена Шрама Бездны",
        nameUK = "Арена Шраму Безодні",
        bosses = { "Taz'Rah", "Atroxus", "Charonus" },
        bossesRU = { "Таз'ра", "Атрокс", "Харон" },
    },
    {
        id = "ruby_life_pools",
        name = "Ruby Life Pools",
        nameRU = "Рубиновые Омуты Жизни",
        nameUK = "Рубінові Вири Життя",
        bosses = { "Melidrussa Chillworn", "Kokia Blazehoof", "Kyrakka and Erkhart Stormvein" },
        bossesRU = { "Мелидрусса Истощенная Холодом", "Кокия Пламенное Копыто", "Киракка и Эркхарт Кровь Бури" },
    },
    {
        id = "temple_of_sethraliss",
        name = "Temple of Sethraliss",
        nameRU = "Храм Сетралисс",
        nameUK = "Храм Сетралісс",
        bosses = { "Adderis and Aspix", "Merektha", "Galvazzt", "Avatar of Sethraliss" },
        bossesRU = { "Гюрзис и Аспидис", "Меректа", "Гальваззт", "Аватара Сетралисс" },
    },
    {
        id = "kings_rest",
        name = "King's Rest",
        nameRU = "Гробница королей",
        nameUK = "Гробниця королів",
        bosses = { "The Golden Serpent", "Mchimba the Embalmer", "The Council of Tribes", "Dazar, The First King" },
        bossesRU = { "Золотой Змей", "Мчимба Бальзамировщик", "Совет племен", "Дазар, первый король" },
    },
}

local function AddonLanguage()
    return addon.Localization and addon.Localization:GetLanguage() or "en"
end

function Tank:GetDungeonDisplayName(dungeon)
    local language = AddonLanguage()
    if language == "ru" and dungeon.nameRU and dungeon.nameRU ~= "" then
        return dungeon.nameRU
    elseif language == "uk" and dungeon.nameUK and dungeon.nameUK ~= "" then
        return dungeon.nameUK
    end
    return dungeon.name
end

function Tank:GetBossDisplayName(dungeon, bossIndex)
    local englishName = dungeon.bosses[bossIndex] or ""
    local russianName = dungeon.bossesRU and dungeon.bossesRU[bossIndex]
    if AddonLanguage() == "ru" and russianName and russianName ~= "" then
        return russianName
    end
    return englishName
end

local function EnsureStorage()
    WhatsNextUserData = WhatsNextUserData or {}
    WhatsNextUserData.tankAssistant = WhatsNextUserData.tankAssistant or {}
    WhatsNextUserData.tankAssistant.routes = WhatsNextUserData.tankAssistant.routes or {}
    WhatsNextUserData.tankAssistant.selectedDungeon = WhatsNextUserData.tankAssistant.selectedDungeon or Tank.DUNGEONS[1].id
    WhatsNextUserData.settings = WhatsNextUserData.settings or {}
    if WhatsNextUserData.settings.showTankAssistantWindow == nil then
        WhatsNextUserData.settings.showTankAssistantWindow = true
    end
    if WhatsNextUserData.settings.lockTankAssistantWindow == nil then
        WhatsNextUserData.settings.lockTankAssistantWindow = false
    end
end

function Tank:GetDungeon(id)
    for _, dungeon in ipairs(self.DUNGEONS) do
        if dungeon.id == id then
            return dungeon
        end
    end
    return self.DUNGEONS[1]
end

function Tank:GetSelectedDungeon()
    EnsureStorage()
    local dungeon = self:GetDungeon(WhatsNextUserData.tankAssistant.selectedDungeon)
    WhatsNextUserData.tankAssistant.selectedDungeon = dungeon.id
    return dungeon
end

function Tank:SetSelectedDungeon(id)
    EnsureStorage()
    local dungeon = self:GetDungeon(id)
    WhatsNextUserData.tankAssistant.selectedDungeon = dungeon.id
end

function Tank:GetBossPercent(dungeonID, bossIndex)
    EnsureStorage()
    local route = WhatsNextUserData.tankAssistant.routes[dungeonID]
    if not route then return nil end
    local value = tonumber(route[bossIndex])
    if not value then return nil end
    return math.max(0, math.min(100, math.floor(value + 0.5)))
end

function Tank:SetBossPercent(dungeonID, bossIndex, value)
    EnsureStorage()
    WhatsNextUserData.tankAssistant.routes[dungeonID] = WhatsNextUserData.tankAssistant.routes[dungeonID] or {}
    if value == nil or tostring(value) == "" then
        WhatsNextUserData.tankAssistant.routes[dungeonID][bossIndex] = nil
        return
    end
    local number = tonumber(value)
    if not number then return end
    number = math.max(0, math.min(100, math.floor(number + 0.5)))
    WhatsNextUserData.tankAssistant.routes[dungeonID][bossIndex] = number
end

local function CreateNativeDropdown(parent, width, defaultText, generator)
    local dropdown = UI:CreateBlizzardDropdown(parent, width, defaultText, generator)
    dropdown:SetHeight(30)
    return dropdown
end

local function CreatePercentEdit(parent, width)
    local edit = CreateFrame("EditBox", nil, parent, "InputBoxTemplate")
    edit:SetSize(width or 64, 28)
    edit:SetAutoFocus(false)
    edit:SetNumeric(true)
    edit:SetMaxLetters(3)
    edit:SetJustifyH("CENTER")
    edit:SetFontObject(GameFontHighlight)
    return edit
end

local function SetPercentEditValue(edit, value)
    if not edit then return end
    edit:SetText(value ~= nil and tostring(value) or "")
end

local function CommitPercentEdit(edit, dungeonID, bossIndex)
    local text = edit:GetText() or ""
    if text == "" then
        Tank:SetBossPercent(dungeonID, bossIndex, nil)
        return
    end
    local value = tonumber(text)
    if not value then
        SetPercentEditValue(edit, Tank:GetBossPercent(dungeonID, bossIndex))
        return
    end
    value = math.max(0, math.min(100, value))
    Tank:SetBossPercent(dungeonID, bossIndex, value)
    SetPercentEditValue(edit, Tank:GetBossPercent(dungeonID, bossIndex))
end

-- Keep the detached Tank Assistant visually identical to TODAY TASKS/TODAY TIMERS.
local function ApplyTaskWindowBackdrop(frame)
    frame:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        edgeSize = 10,
    })
    frame:SetBackdropColor(0.025, 0.025, 0.035, 0.82)
    frame:SetBackdropBorderColor(0.25, 0.25, 0.30, 0.95)
end

local function MakeTaskWindowTitle(frame, text)
    local title = frame:CreateFontString(nil, "OVERLAY")
    title:SetFontObject(GameFontNormal)
    title:SetPoint("TOPLEFT", frame, "TOPLEFT", 12, -10)
    title:SetText(text)
    title:SetTextColor(1.0, 0.82, 0.15, 1)
    return title
end

local function AddTankResizeGrip(frame)
    frame:SetResizable(true)
    frame:SetResizeBounds(440, 210, 900, 900)

    local grip = CreateFrame("Button", nil, frame)
    grip:SetSize(18, 18)
    grip:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -2, 2)
    grip:SetNormalTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Up")
    grip:SetHighlightTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Highlight")
    grip:SetPushedTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Down")

    grip:SetScript("OnMouseDown", function()
        if WhatsNextUserData.settings.lockTankAssistantWindow then return end
        if not InCombatLockdown() then
            frame:StartSizing("BOTTOMRIGHT")
        end
    end)

    grip:SetScript("OnMouseUp", function()
        frame:StopMovingOrSizing()
        WhatsNextUserData.settings.tankAssistantWidth = math.floor(frame:GetWidth() + 0.5)
        WhatsNextUserData.settings.tankAssistantHeight = math.floor(frame:GetHeight() + 0.5)
        UI:RefreshTankAssistantFloatingWindow()
    end)

    frame.ResizeGrip = grip
end

function UI:InitializeTankAssistant()
    if self.TankAssistantPage then return end
    EnsureStorage()

    local parent = self.PageHost or self.MainFrame
    if not parent then return end

    --------------------------------------------------------
    -- MAIN PAGE
    --------------------------------------------------------
    local page = CreateFrame("Frame", "WhatsNextTankAssistantPage", parent, "BackdropTemplate")
    self.TankAssistantPage = page
    page:SetAllPoints(parent)
    self:ApplyPanelBackdrop(page)
    page:Hide()

    local title = page:CreateFontString(nil, "OVERLAY")
    title:SetFontObject(GameFontNormalLarge)
    title:SetPoint("TOPLEFT", page, "TOPLEFT", 18, -18)
    title:SetText(self:T("TANK_ASSISTANT", "TANK ASSISTANT"))
    title:SetTextColor(unpack(self.COLORS.gold))

    local subtitle = page:CreateFontString(nil, "OVERLAY")
    subtitle:SetFontObject(GameFontHighlightSmall)
    subtitle:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -6)
    subtitle:SetPoint("RIGHT", page, "RIGHT", -20, 0)
    subtitle:SetJustifyH("LEFT")
    subtitle:SetText(Tank.SEASON .. "  •  Patch " .. Tank.PATCH)
    subtitle:SetTextColor(unpack(self.COLORS.muted))

    -- Short onboarding block. It uses normal Blizzard fonts and the same panel
    -- backdrop as the rest of the addon, so it scales with UIParent.
    local help = CreateFrame("Frame", nil, page, "BackdropTemplate")
    help:SetPoint("TOPLEFT", page, "TOPLEFT", 18, -60)
    help:SetPoint("TOPRIGHT", page, "TOPRIGHT", -18, -60)
    help:SetHeight(62)
    help:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
    help:SetBackdropColor(unpack(self.COLORS.panelAlt))

    local helpTitle = help:CreateFontString(nil, "OVERLAY")
    helpTitle:SetFontObject(GameFontNormal)
    helpTitle:SetPoint("TOPLEFT", help, "TOPLEFT", 12, -9)
    helpTitle:SetText(self:T("TANK_HELP_TITLE", "HOW TO USE TANK ASSISTANT"))
    helpTitle:SetTextColor(unpack(self.COLORS.gold))

    local helpText = help:CreateFontString(nil, "OVERLAY")
    helpText:SetFontObject(GameFontHighlightSmall)
    helpText:SetPoint("TOPLEFT", helpTitle, "BOTTOMLEFT", 0, -5)
    helpText:SetPoint("RIGHT", help, "RIGHT", -12, 0)
    helpText:SetJustifyH("LEFT")
    helpText:SetText(UI:T("TANK_HELP", "Choose a Mythic+ dungeon and enter the Enemy Forces percentage you want reached at each boss. The detached window shows these checkpoints during the run."))
    helpText:SetTextColor(unpack(self.COLORS.text))

    local dungeonLabel = page:CreateFontString(nil, "OVERLAY")
    dungeonLabel:SetFontObject(GameFontNormalSmall)
    dungeonLabel:SetPoint("TOPLEFT", help, "BOTTOMLEFT", 0, -18)
    dungeonLabel:SetText(self:T("MYTHIC_DUNGEON", "MYTHIC+ DUNGEON"))
    dungeonLabel:SetTextColor(unpack(self.COLORS.muted))

    local dungeonDropdown = CreateNativeDropdown(page, 340, self:T("SELECT_DUNGEON", "SELECT DUNGEON"), function(_, rootDescription)
        for _, dungeon in ipairs(Tank.DUNGEONS) do
            UI:AddBlizzardMenuEntry(rootDescription, {
                text = Tank:GetDungeonDisplayName(dungeon),
                func = function()
                    Tank:SetSelectedDungeon(dungeon.id)
                    UI:RefreshTankAssistant()
                end,
            })
        end
    end)
    self.TankAssistantDungeonDropdown = dungeonDropdown
    dungeonDropdown:SetPoint("TOPLEFT", dungeonLabel, "BOTTOMLEFT", 0, -6)

    local bossCount = page:CreateFontString(nil, "OVERLAY")
    self.TankAssistantBossCount = bossCount
    bossCount:SetFontObject(GameFontHighlight)
    bossCount:SetPoint("LEFT", dungeonDropdown, "RIGHT", 18, 0)
    bossCount:SetTextColor(unpack(self.COLORS.text))

    local showWindow = CreateFrame("CheckButton", nil, page, "UICheckButtonTemplate")
    self.TankAssistantShowWindowCheck = showWindow
    showWindow:SetSize(28, 28)
    showWindow:SetPoint("TOPRIGHT", page, "TOPRIGHT", -190, -142)

    local showWindowLabel = page:CreateFontString(nil, "OVERLAY")
    showWindowLabel:SetFontObject(GameFontHighlight)
    showWindowLabel:SetPoint("LEFT", showWindow, "RIGHT", 4, 0)
    showWindowLabel:SetText(self:T("SHOW_WINDOW", "SHOW WINDOW"))

    showWindow:SetScript("OnClick", function(button)
        WhatsNextUserData.settings.showTankAssistantWindow = button:GetChecked() == true
        UI:ApplyTankAssistantWindowSettings()
    end)

    local lockWindow = CreateFrame("CheckButton", nil, page, "UICheckButtonTemplate")
    self.TankAssistantLockWindowCheck = lockWindow
    lockWindow:SetSize(28, 28)
    lockWindow:SetPoint("TOPLEFT", showWindow, "BOTTOMLEFT", 0, -3)

    local lockWindowLabel = page:CreateFontString(nil, "OVERLAY")
    lockWindowLabel:SetFontObject(GameFontHighlight)
    lockWindowLabel:SetPoint("LEFT", lockWindow, "RIGHT", 4, 0)
    lockWindowLabel:SetText(self:T("LOCK_WINDOW", "LOCK WINDOW"))

    lockWindow:SetScript("OnClick", function(button)
        WhatsNextUserData.settings.lockTankAssistantWindow = button:GetChecked() == true
        UI:ApplyTankAssistantWindowSettings()
    end)

    local header = CreateFrame("Frame", nil, page, "BackdropTemplate")
    header:SetPoint("TOPLEFT", page, "TOPLEFT", 18, -212)
    header:SetPoint("TOPRIGHT", page, "TOPRIGHT", -18, -212)
    header:SetHeight(32)
    header:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
    header:SetBackdropColor(unpack(self.COLORS.panelAlt))

    local hBoss = header:CreateFontString(nil, "OVERLAY")
    hBoss:SetFontObject(GameFontNormalSmall)
    hBoss:SetPoint("LEFT", header, "LEFT", 14, 0)
    hBoss:SetText(self:T("BOSS", "BOSS"))

    local hPercent = header:CreateFontString(nil, "OVERLAY")
    hPercent:SetFontObject(GameFontNormalSmall)
    hPercent:SetPoint("RIGHT", header, "RIGHT", -34, 0)
    hPercent:SetText(self:T("ENEMY_FORCES", "ENEMY FORCES %"))

    local scroll = CreateFrame("ScrollFrame", "WhatsNextTankAssistantScrollFrame", page, "UIPanelScrollFrameTemplate")
    self.TankAssistantScroll = scroll
    scroll:SetPoint("TOPLEFT", header, "BOTTOMLEFT", 0, -6)
    scroll:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", -34, 18)

    local content = CreateFrame("Frame", nil, scroll)
    self.TankAssistantContent = content
    content:SetWidth(900)
    content:SetHeight(100)
    scroll:SetScrollChild(content)

    --------------------------------------------------------
    -- FLOATING WINDOW - same visual style as TODAY TASKS
    --------------------------------------------------------
    local floating = CreateFrame("Frame", "WhatsNextTankAssistantWindow", UIParent, "BackdropTemplate")
    self.TankAssistantWindow = floating
    floating:SetSize(
        WhatsNextUserData.settings.tankAssistantWidth or 440,
        WhatsNextUserData.settings.tankAssistantHeight or 285
    )
    floating:SetPoint("CENTER", UIParent, "CENTER", 370, 0)
    floating:SetFrameStrata("MEDIUM")
    floating:SetClampedToScreen(true)
    floating:SetMovable(true)
    floating:EnableMouse(true)
    floating:RegisterForDrag("LeftButton")

    ApplyTaskWindowBackdrop(floating)
    AddTankResizeGrip(floating)

    local floatingTitle = MakeTaskWindowTitle(floating, "TANK ASSISTANT")
    self.TankAssistantFloatingTitle = floatingTitle

    floating:SetScript("OnDragStart", function(selfFrame)
        if WhatsNextUserData.settings.lockTankAssistantWindow then return end
        if not InCombatLockdown() then selfFrame:StartMoving() end
    end)
    floating:SetScript("OnDragStop", function(selfFrame)
        selfFrame:StopMovingOrSizing()
    end)

    local floatingLabel = floating:CreateFontString(nil, "OVERLAY")
    floatingLabel:SetFontObject(GameFontNormalSmall)
    floatingLabel:SetPoint("TOPLEFT", floating, "TOPLEFT", 12, -36)
    floatingLabel:SetText(self:T("CURRENT_KEY", "CURRENT KEY"))

    local floatingDropdown = CreateNativeDropdown(floating, 300, self:T("SELECT_DUNGEON", "SELECT DUNGEON"), function(_, rootDescription)
        for _, dungeon in ipairs(Tank.DUNGEONS) do
            UI:AddBlizzardMenuEntry(rootDescription, {
                text = Tank:GetDungeonDisplayName(dungeon),
                func = function()
                    Tank:SetSelectedDungeon(dungeon.id)
                    UI:RefreshTankAssistant()
                end,
            })
        end
    end)
    self.TankAssistantFloatingDropdown = floatingDropdown
    floatingDropdown:SetPoint("TOPLEFT", floatingLabel, "BOTTOMLEFT", 0, -4)

    local floatingCount = floating:CreateFontString(nil, "OVERLAY")
    self.TankAssistantFloatingBossCount = floatingCount
    floatingCount:SetFontObject(GameFontHighlightSmall)
    floatingCount:SetPoint("TOPRIGHT", floating, "TOPRIGHT", -28, -36)
    floatingCount:SetTextColor(unpack(self.COLORS.muted))

    local floatingScroll = CreateFrame("ScrollFrame", nil, floating, "UIPanelScrollFrameTemplate")
    floatingScroll:SetPoint("TOPLEFT", floatingDropdown, "BOTTOMLEFT", 0, -10)
    floatingScroll:SetPoint("BOTTOMRIGHT", floating, "BOTTOMRIGHT", -28, 10)

    local floatingContent = CreateFrame("Frame", nil, floatingScroll)
    self.TankAssistantFloatingContent = floatingContent
    floatingContent:SetSize(380, 120)
    floatingScroll:SetScrollChild(floatingContent)

    self:ApplyTankAssistantWindowSettings()
    self:RefreshTankAssistant()
end

function UI:ApplyTankAssistantWindowSettings()
    EnsureStorage()
    if self.TankAssistantWindow then
        self.TankAssistantWindow:SetShown(WhatsNextUserData.settings.showTankAssistantWindow ~= false)
        if self.TankAssistantWindow.ResizeGrip then
            self.TankAssistantWindow.ResizeGrip:SetShown(WhatsNextUserData.settings.lockTankAssistantWindow ~= true)
        end
    end
    if self.TankAssistantShowWindowCheck then
        self.TankAssistantShowWindowCheck:SetChecked(WhatsNextUserData.settings.showTankAssistantWindow ~= false)
    end
    if self.TankAssistantLockWindowCheck then
        self.TankAssistantLockWindowCheck:SetChecked(WhatsNextUserData.settings.lockTankAssistantWindow == true)
    end
end

function UI:RefreshTankAssistantPage()
    if not self.TankAssistantContent then return end
    EnsureStorage()
    self:ClearFrame(self.TankAssistantContent)

    local dungeon = Tank:GetSelectedDungeon()
    self:SetBlizzardDropdownText(self.TankAssistantDungeonDropdown, Tank:GetDungeonDisplayName(dungeon))
    self.TankAssistantBossCount:SetText(string.format("%d %s", #dungeon.bosses, self:T("BOSSES", "BOSSES")))

    local y = 0
    local rowHeight = 52
    local width = math.max(700, (self.TankAssistantScroll and self.TankAssistantScroll:GetWidth() or 900) - 10)

    for index, bossName in ipairs(dungeon.bosses) do
        local row = CreateFrame("Frame", nil, self.TankAssistantContent, "BackdropTemplate")
        row:SetSize(width, 44)
        row:SetPoint("TOPLEFT", self.TankAssistantContent, "TOPLEFT", 0, y)
        row:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
        if index % 2 == 0 then
            row:SetBackdropColor(0.05, 0.05, 0.06, 0.55)
        else
            row:SetBackdropColor(0.025, 0.025, 0.03, 0.35)
        end

        local number = row:CreateFontString(nil, "OVERLAY")
        number:SetFontObject(GameFontNormal)
        number:SetPoint("LEFT", row, "LEFT", 12, 0)
        number:SetWidth(30)
        number:SetJustifyH("LEFT")
        number:SetText(index .. ".")
        number:SetTextColor(unpack(self.COLORS.gold))

        local boss = row:CreateFontString(nil, "OVERLAY")
        boss:SetFontObject(GameFontHighlight)
        boss:SetPoint("LEFT", number, "RIGHT", 4, 0)
        boss:SetPoint("RIGHT", row, "RIGHT", -150, 0)
        boss:SetJustifyH("LEFT")
        boss:SetWordWrap(false)
        boss:SetText(Tank:GetBossDisplayName(dungeon, index))

        local percent = CreatePercentEdit(row, 62)
        percent:SetPoint("RIGHT", row, "RIGHT", -48, 0)
        SetPercentEditValue(percent, Tank:GetBossPercent(dungeon.id, index))

        local percentSign = row:CreateFontString(nil, "OVERLAY")
        percentSign:SetFontObject(GameFontHighlight)
        percentSign:SetPoint("LEFT", percent, "RIGHT", 5, 0)
        percentSign:SetText("%")

        percent:SetScript("OnEnterPressed", function(edit)
            CommitPercentEdit(edit, dungeon.id, index)
            edit:ClearFocus()
            UI:RefreshTankAssistantFloatingWindow()
        end)
        percent:SetScript("OnEditFocusLost", function(edit)
            CommitPercentEdit(edit, dungeon.id, index)
            UI:RefreshTankAssistantFloatingWindow()
        end)

        y = y - rowHeight
    end

    self.TankAssistantContent:SetHeight(math.max(100, math.abs(y) + 10))
end

function UI:RefreshTankAssistantFloatingWindow()
    if not self.TankAssistantFloatingContent then return end
    EnsureStorage()
    self:ClearFrame(self.TankAssistantFloatingContent)

    local dungeon = Tank:GetSelectedDungeon()
    self:SetBlizzardDropdownText(self.TankAssistantFloatingDropdown, Tank:GetDungeonDisplayName(dungeon))
    self.TankAssistantFloatingBossCount:SetText(string.format("%d %s", #dungeon.bosses, self:T("BOSSES", "BOSSES")))

    local y = 0
    local rowHeight = 38
    local width = math.max(320, (self.TankAssistantWindow and self.TankAssistantWindow:GetWidth() or 440) - 58)

    for index, bossName in ipairs(dungeon.bosses) do
        local row = CreateFrame("Frame", nil, self.TankAssistantFloatingContent)
        row:SetSize(width, 34)
        row:SetPoint("TOPLEFT", self.TankAssistantFloatingContent, "TOPLEFT", 0, y)

        local boss = row:CreateFontString(nil, "OVERLAY")
        boss:SetFontObject(GameFontHighlight)
        boss:SetPoint("LEFT", row, "LEFT", 2, 0)
        boss:SetPoint("RIGHT", row, "RIGHT", -72, 0)
        boss:SetJustifyH("LEFT")
        boss:SetWordWrap(false)
        boss:SetText(index .. ".  " .. Tank:GetBossDisplayName(dungeon, index))

        local value = Tank:GetBossPercent(dungeon.id, index)
        local percent = row:CreateFontString(nil, "OVERLAY")
        percent:SetFontObject(GameFontNormal)
        percent:SetPoint("RIGHT", row, "RIGHT", -4, 0)
        percent:SetWidth(64)
        percent:SetJustifyH("RIGHT")
        percent:SetText(value ~= nil and (tostring(value) .. "%") or "--%")
        if value ~= nil then
            percent:SetTextColor(unpack(self.COLORS.gold))
        else
            percent:SetTextColor(unpack(self.COLORS.muted))
        end

        y = y - rowHeight
    end

    self.TankAssistantFloatingContent:SetHeight(math.max(80, math.abs(y) + 8))
end

function UI:RefreshTankAssistant()
    self:ApplyTankAssistantWindowSettings()
    self:RefreshTankAssistantPage()
    self:RefreshTankAssistantFloatingWindow()
end
