local _, privateDB = ...

-- ============================================================================
-- PROFESSION SIDEBAR (left rail of the Recipes tab)
-- Owns the expansion filter dropdown, the "All Professions" button, and the
-- per-profession buttons with collection/recipe-known badges. Extracted from
-- HDG_RecipesTab.lua during the v2.42.x code-smell sweep.
-- ============================================================================

local CONFIG = privateDB.CONFIG
local L = HDG_L or {}
local HDG = _G.HousingDecorGuide

local HDG_ProfessionSidebar = {}
privateDB.HDG_ProfessionSidebar = HDG_ProfessionSidebar

local function GetScheme() return HDG.Theme.GetCurrentScheme() end
local function ApplyFont(fs, s, ft) HDG.Theme.ApplyFont(fs, s, ft) end
local function Data() return HDG_UIHelpers.Data() end

local mainFrame = nil

local professionList = { "Alchemy", "Blacksmithing", "Cooking", "Enchanting", "Engineering",
    "Inscription", "Jewelcrafting", "Leatherworking", "Tailoring" }

local COLLECTION_COL_RIGHT = -6
local RECIPES_COL_RIGHT = -68
local COL_WIDTH = 60

function HDG_ProfessionSidebar.Init(frame)
    mainFrame = frame
end

-- Enumerate expansions that have at least one loaded recipe, in canonical EXPANSION_ORDER.
local function GetAvailableRecipeExpansions()
    local present = {}
    if HDG_ProfessionsDB then
        for _, recipe in pairs(HDG_ProfessionsDB) do
            local norm = HDG_ExpansionData.NormalizeToDisplayName(recipe.expansion)
            if norm and norm ~= "Unknown" then
                present[norm] = true
            end
        end
    end
    local ordered = {}
    for _, name in ipairs(HDG_ExpansionData.EXPANSION_ORDER or {}) do
        if present[name] then
            table.insert(ordered, name)
        end
    end
    return ordered
end

local function EnsureFrames()
    if mainFrame.profTabsCreated then return end

    local scheme = GetScheme()
    local yOffset = 0

    -- Expansion filter dropdown (first row, above "All Professions")
    local expansionDropdown = HDG.UI:Dropdown(mainFrame.professionTabs, {
        width = CONFIG.LEFT_PANEL_WIDTH - 16,
        items = GetAvailableRecipeExpansions(),
        currentValue = HDG.Store:GetConfig("expansionFilter") or "All",
        allLabel = L["FILTER_ALL_EXPANSIONS"] or "All Expansions",
        colorFn = function(v)
            if not v or v == "All" then return nil end
            return HDG_ExpansionData.GetColor(v)
        end,
        onChange = function(v)
            HDG.Store:Dispatch("SET_CONFIG", { key = "expansionFilter", value = v or "All" })
            HDG_UI.RefreshUI()
        end,
    })
    expansionDropdown:SetPoint("TOPLEFT", 0, yOffset)
    mainFrame.expansionDropdown = expansionDropdown
    do
        local current = HDG.Store:GetConfig("expansionFilter") or "All"
        if current and current ~= "All" and expansionDropdown._text then
            local c = HDG_ExpansionData.GetColor(current)
            if c then expansionDropdown._text:SetTextColor(c[1], c[2], c[3], 1) end
        end
    end
    yOffset = yOffset - 26

    -- "All Professions" button
    local allBtn = CreateFrame("Button", nil, mainFrame.professionTabs, "BackdropTemplate")
    allBtn:SetSize(CONFIG.LEFT_PANEL_WIDTH - 16, 18)
    allBtn:SetPoint("TOPLEFT", 0, yOffset)
    allBtn:SetBackdrop({ bgFile = CONFIG.TEXTURES.WHITE_BG, tile = false })
    allBtn:SetBackdropColor(scheme.button_normal.r, scheme.button_normal.g, scheme.button_normal.b, 0.2)

    local allHighlight = allBtn:CreateTexture(nil, "HIGHLIGHT")
    allHighlight:SetAllPoints()
    allHighlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
    allHighlight:SetBlendMode("ADD")
    allHighlight:Hide()

    local allText = allBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    allText:SetPoint("LEFT", 6, 0)
    ApplyFont(allText, scheme, "small")

    allBtn.highlight = allHighlight
    allBtn.textLabel = allText
    mainFrame.allProfBtn = allBtn

    allBtn:SetScript("OnClick", function()
        HDG.Store:SetCharacterProfessionFilter("All")
        HDG_UI.RefreshUI()
    end)
    allBtn:SetScript("OnEnter", function(self)
        if not self.isSelected then
            local s = GetScheme()
            self:SetBackdropColor(s.button_hover.r, s.button_hover.g, s.button_hover.b, 0.4)
        end
        GameTooltip:SetOwner(self, HDG_UIHelpers.TOOLTIP_ANCHOR)
        local label = L["FILTER_ALL_PROFESSIONS"] or "All Professions"
        GameTooltip:AddLine(label, 1, 0.84, 0)
        GameTooltip:AddLine(HDG.Theme.C_Dim() .. "Show recipes from all professions|r")
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine(HDG.Theme.C_Warning() .. "Tip:|r Use search to find recipes", 0.7, 0.7, 0.7)
        GameTooltip:Show()
    end)
    allBtn:SetScript("OnLeave", function(self)
        local s = GetScheme()
        if self.isSelected then
            self:SetBackdropColor(s.accent.r, s.accent.g, s.accent.b, 0.3)
        else
            self:SetBackdropColor(s.button_normal.r, s.button_normal.g, s.button_normal.b, 0.2)
        end
        GameTooltip:Hide()
    end)

    yOffset = yOffset - 20

    -- Separator line after "All Professions"
    local separator = mainFrame.professionTabs:CreateTexture(nil, "ARTWORK")
    separator:SetHeight(1)
    separator:SetPoint("TOPLEFT", 0, yOffset - 2)
    separator:SetPoint("TOPRIGHT", 0, yOffset - 2)
    separator:SetColorTexture(0.3, 0.3, 0.35, 0.5)
    mainFrame.profSeparator = separator
    yOffset = yOffset - 6

    -- Per-profession buttons
    mainFrame.profBtns = {}
    for _, profName in ipairs(professionList) do
        local btn = CreateFrame("Button", nil, mainFrame.professionTabs, "BackdropTemplate")
        btn:SetSize(CONFIG.LEFT_PANEL_WIDTH - 16, 18)
        btn:SetPoint("TOPLEFT", 0, yOffset)
        btn:SetBackdrop({ bgFile = CONFIG.TEXTURES.WHITE_BG, tile = false })
        btn:SetBackdropColor(scheme.button_normal.r, scheme.button_normal.g, scheme.button_normal.b, 0.2)

        local highlight = btn:CreateTexture(nil, "HIGHLIGHT")
        highlight:SetAllPoints()
        highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
        highlight:SetBlendMode("ADD")
        highlight:Hide()

        local text = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        text:SetPoint("LEFT", 6, 0)
        ApplyFont(text, scheme, "small")

        local collectionBadge = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        collectionBadge:SetPoint("RIGHT", COLLECTION_COL_RIGHT, 0)
        collectionBadge:SetWidth(COL_WIDTH)
        collectionBadge:SetJustifyH("LEFT")
        ApplyFont(collectionBadge, scheme, "small")

        local recipesBadge = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        recipesBadge:SetPoint("RIGHT", RECIPES_COL_RIGHT, 0)
        recipesBadge:SetWidth(COL_WIDTH)
        recipesBadge:SetJustifyH("LEFT")
        ApplyFont(recipesBadge, scheme, "small")

        -- Open profession window button (right edge, shown only if player has the profession)
        local openBtn = CreateFrame("Button", nil, btn)
        openBtn:SetSize(14, 14)
        openBtn:SetPoint("RIGHT", btn, "RIGHT", -2, 0)
        local openIcon = openBtn:CreateTexture(nil, "ARTWORK")
        openIcon:SetAllPoints()
        openIcon:SetAtlas("Profession")
        openIcon:SetAlpha(0.6)
        openBtn:SetScript("OnClick", function(self)
            local parent = self:GetParent()
            HDG_Data.OpenProfessionAtRecipe(parent.professionName)
        end)
        openBtn:SetScript("OnEnter", function(self)
            openIcon:SetAlpha(1.0)
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:AddLine("Open Profession Window", 1, 0.84, 0)
            GameTooltip:Show()
        end)
        openBtn:SetScript("OnLeave", function(self)
            openIcon:SetAlpha(0.6)
            GameTooltip:Hide()
        end)
        openBtn:Hide()
        btn.openProfBtn = openBtn

        btn.highlight = highlight
        btn.textLabel = text
        btn.collectionBadge = collectionBadge
        btn.recipesBadge = recipesBadge
        btn.professionName = profName

        btn:SetScript("OnClick", function(self)
            HDG.Store:SetCharacterProfessionFilter(self.professionName)
            HDG_UI.RefreshUI()
        end)
        btn:SetScript("OnEnter", function(self)
            if not self.isSelected then
                local s = GetScheme()
                self:SetBackdropColor(s.button_hover.r, s.button_hover.g, s.button_hover.b, 0.4)
            end
            GameTooltip:SetOwner(self, HDG_UIHelpers.TOOLTIP_ANCHOR)
            GameTooltip:AddLine(self.localizedProfName or profName, 1, 0.84, 0)
            GameTooltip:AddLine(self.hasProf and (HDG.Theme.C_Success() .. "You have this profession|r") or
                HDG.Theme.C_Dim() .. "You don't have this profession|r")
            GameTooltip:AddLine(" ")
            if self.hasProf then
                GameTooltip:AddLine(
                    string.format(HDG.Theme.C_Accent() .. "Recipes Known:|r %d / %d (%.0f%%)", self.recipesKnown or 0, self.totalCount or 0,
                        self.recipesPercentage or 0), 1, 1, 1)
                if self.altKnown and self.altKnown > (self.recipesKnown or 0) then
                    GameTooltip:AddLine(string.format(HDG.Theme.C_Dim() .. "Known by alts: %d/%d|r", self.altKnown, self.altTotal or 0), 0.78, 0.78, 0.78)
                end
            elseif self.altCharacter then
                GameTooltip:AddLine(HDG.Theme.C_Dim() .. "Known by alts|r", 0.78, 0.78, 0.78)
            end
            GameTooltip:AddLine(
                string.format(HDG.Theme.C_Warning() .. "Decor Collected:|r %d / %d (%.0f%%)", self.collectedCount or 0, self.totalCount or 0,
                    self.collectionPercentage or 0), 1, 1, 1)
            GameTooltip:Show()
        end)
        btn:SetScript("OnLeave", function(self)
            local s = GetScheme()
            if self.isSelected then
                self:SetBackdropColor(s.accent.r, s.accent.g, s.accent.b, 0.3)
            else
                self:SetBackdropColor(s.button_normal.r, s.button_normal.g, s.button_normal.b, 0.2)
            end
            GameTooltip:Hide()
        end)

        mainFrame.profBtns[profName] = btn
        yOffset = yOffset - 20
    end

    mainFrame.profTabsCreated = true
end

function HDG_ProfessionSidebar.Refresh()
    if not mainFrame or not mainFrame.professionTabs then return end

    EnsureFrames()

    local currentFilter = HDG.Store:GetCharacterProfessionFilter()
    local filtescheme = GetScheme()
    local allProfsLabel = L["FILTER_ALL_PROFESSIONS"] or "All Professions"

    -- Update "All Professions" button
    local allBtn = mainFrame.allProfBtn
    local isAllSelected = (currentFilter == "All")
    allBtn.isSelected = isAllSelected
    if isAllSelected then
        allBtn:SetBackdropColor(filtescheme.accent.r, filtescheme.accent.g, filtescheme.accent.b, 0.3)
        allBtn.highlight:SetVertexColor(1, 1, 1, 0.5); allBtn.highlight:Show()
        allBtn.textLabel:SetText(HDG.Theme.C_Warning() .. allProfsLabel .. "|r")
    else
        allBtn:SetBackdropColor(filtescheme.button_normal.r, filtescheme.button_normal.g, filtescheme.button_normal.b, 0.2)
        allBtn.highlight:Hide()
        allBtn.textLabel:SetText(HDG.Theme.C_Text() .. allProfsLabel .. "|r")
    end

    -- Update per-profession buttons (also accumulate grand totals in one pass)
    local grandTotalRecipes, grandKnownRecipes, grandTotalDecor, grandCollectedDecor = 0, 0, 0, 0
    local D = Data()
    for _, profName in ipairs(professionList) do
        local btn = mainFrame.profBtns[profName]
        local localizedProfName = HDG_ExpansionData.GetLocalizedProfessionName(profName)
        local hasProf = D.PlayerHasProfession(profName)
        local recipesKnown, collectedCount, totalCount = 0, 0, 0

        for _, profData in ipairs(privateDB.professions or {}) do
            if profData.name == profName and profData.items then
                for _, recipe in ipairs(profData.items) do
                    totalCount = totalCount + 1
                    if D.PlayerKnowsRecipeBySpellID and D.PlayerKnowsRecipeBySpellID(recipe.spellID) then
                        recipesKnown = recipesKnown + 1
                    end
                    if D.IsItemCollected(recipe.itemID) then
                        collectedCount = collectedCount + 1
                    end
                end
                break
            end
        end
        grandTotalRecipes = grandTotalRecipes + totalCount
        grandTotalDecor = grandTotalDecor + totalCount
        grandCollectedDecor = grandCollectedDecor + collectedCount
        local bestAltKnown = D.GetBestAltRecipeCount(profName)
        grandKnownRecipes = grandKnownRecipes + math.max(recipesKnown, bestAltKnown)

        local recipesPercentage = totalCount > 0 and (recipesKnown / totalCount * 100) or 0
        local collectionPercentage = totalCount > 0 and (collectedCount / totalCount * 100) or 0
        local isSelected = (currentFilter == profName)
        btn.isSelected = isSelected

        if isSelected then
            btn:SetBackdropColor(filtescheme.accent.r, filtescheme.accent.g, filtescheme.accent.b, 0.3)
            btn.highlight:SetVertexColor(1, 1, 1, 0.5); btn.highlight:Show()
        else
            btn:SetBackdropColor(filtescheme.button_normal.r, filtescheme.button_normal.g, filtescheme.button_normal.b, 0.2)
            btn.highlight:Hide()
        end

        btn.textLabel:SetText(profName) -- English only (layout policy)

        local collectionColor = collectionPercentage >= 100 and HDG.Theme.C_Success() or HDG.Theme.C_Warning()
        btn.collectionBadge:SetText(string.format("%s%d/%d|r", collectionColor, collectedCount, totalCount))

        local altKnown, altTotal, altChar = D.GetBestAltRecipeCount(profName)
        if hasProf and altKnown > recipesKnown then
            btn.recipesBadge:SetText(string.format(HDG.Theme.C_Text() .. "%d/%d|r", altKnown, altTotal))
            btn.altCharacter = altChar
        elseif hasProf then
            local recipesColor = recipesPercentage >= 100 and HDG.Theme.C_Success() or HDG.Theme.C_Accent()
            btn.recipesBadge:SetText(string.format("%s%d/%d|r", recipesColor, recipesKnown, totalCount))
            btn.altCharacter = nil
        elseif altKnown > 0 then
            btn.recipesBadge:SetText(string.format(HDG.Theme.C_Text() .. "%d/%d|r", altKnown, altTotal))
            btn.altCharacter = altChar
        else
            btn.recipesBadge:SetText(HDG.Theme.C_Dim() .. "--|r")
            btn.altCharacter = nil
        end

        local profColor
        if isSelected or hasProf then
            profColor = filtescheme.text_recipe_known or {r=0.80, g=0.29, b=0.09, a=1}
        elseif altKnown > 0 then
            profColor = filtescheme.text_recipe_alt or {r=1, g=1, b=1, a=1}
        else
            profColor = filtescheme.text_recipe_no_prof or {r=0.56, g=0.56, b=0.56, a=1}
        end
        btn.textLabel:SetTextColor(profColor.r, profColor.g, profColor.b, profColor.a)

        btn.localizedProfName = localizedProfName
        btn.hasProf = hasProf
        if btn.openProfBtn then btn.openProfBtn:SetShown(hasProf) end
        btn.recipesKnown = recipesKnown
        btn.collectedCount = collectedCount
        btn.totalCount = totalCount
        btn.recipesPercentage = recipesPercentage
        btn.collectionPercentage = collectionPercentage
        btn.altKnown = altKnown
        btn.altTotal = altTotal
    end

    local collectionPct = grandTotalDecor > 0 and (grandCollectedDecor / grandTotalDecor * 100) or 0
    local recipesPct = grandTotalRecipes > 0 and (grandKnownRecipes / grandTotalRecipes * 100) or 0

    -- Update header percentages
    if mainFrame.headerCollectionPct then
        mainFrame.headerCollectionPct:SetText(string.format("%s%.0f%%|r",
            collectionPct >= 100 and HDG.Theme.C_Success() or HDG.Theme.C_Warning(), collectionPct))
    end
    if mainFrame.headerRecipesPct then
        mainFrame.headerRecipesPct:SetText(string.format("%s%.0f%%|r", recipesPct >= 100 and HDG.Theme.C_Success() or HDG.Theme.C_Accent(),
            recipesPct))
    end

    -- Set up tooltips on header frames with totals
    if mainFrame.recipesHeaderFrame then
        HDG_UIHelpers.SetupTooltip(mainFrame.recipesHeaderFrame, {
            title = HDG.Theme.C_Accent() .. "Recipes Known|r",
            desc  = {
                { text = string.format("Total: %d / %d (%.0f%%)", grandKnownRecipes, grandTotalRecipes, recipesPct), color = {0.9, 0.9, 0.9} },
                " ",
                { text = "Includes recipes known by you and alts", color = {0.6, 0.6, 0.6} },
            },
        })
    end

    if mainFrame.collectionHeaderFrame then
        HDG_UIHelpers.SetupTooltip(mainFrame.collectionHeaderFrame, {
            title = HDG.Theme.C_Warning() .. "Decor Collected|r",
            desc  = {
                { text = string.format("Total: %d / %d (%.0f%%)", grandCollectedDecor, grandTotalDecor, collectionPct), color = {0.9, 0.9, 0.9} },
                " ",
                { text = "Account-wide decor collection progress", color = {0.6, 0.6, 0.6} },
            },
        })
    end

    -- Update title based on selection
    if mainFrame.recipeTitle then
        if HDG.Store:GetCharacterProfessionFilter() == "All" then
            mainFrame.recipeTitle:SetText(allProfsLabel)
        else
            mainFrame.recipeTitle:SetText(L["RECIPE_PROFESSIONS"] or "Professions")
        end
    end
end
