--[[
============================================================================
ETB - ProfileSelector.lua
============================================================================
UI Component for switching between character profiles.

Shows a dropdown with all characters on the account, allows switching
the "viewing as" profile to filter items for different classes.
============================================================================
]]--

local ADDON_NAME, NS = ...
local ETB = NS.ETB

ETB.ProfileSelector = {
    frame = nil,
    dropdown = nil,
    isOpen = false,
}

local PS = ETB.ProfileSelector

-- Class colors for display
local CLASS_COLORS = {
    WARRIOR     = "|cffc79c6e",
    PALADIN     = "|cfff58cba",
    DEATHKNIGHT = "|cffc41e3a",
    HUNTER      = "|cffabd473",
    SHAMAN      = "|cff0070de",
    ROGUE       = "|cfffff569",
    DRUID       = "|cffff7d0a",
    MONK        = "|cff00ff96",
    MAGE        = "|cff69ccf0",
    WARLOCK     = "|cff9482c9",
    PRIEST      = "|cffffffff",
}

-- =============================================================================
-- CREATE SELECTOR
-- =============================================================================

function PS:Create(parent)
    if self.frame then return self.frame end
    
    local f = CreateFrame("Frame", "ETBProfileSelector", parent, "BackdropTemplate")
    f:SetSize(200, 28)
    f:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 12,
        insets = { left = 3, right = 3, top = 3, bottom = 3 }
    })
    
    -- Label
    local label = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    label:SetPoint("LEFT", 5, 0)
    label:SetText("|cff00ffffViewing As:|r")
    f.label = label
    
    -- Current profile display
    local currentText = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    currentText:SetPoint("LEFT", label, "RIGHT", 5, 0)
    currentText:SetWidth(100)
    currentText:SetJustifyH("LEFT")
    f.currentText = currentText
    
    -- Dropdown button
    local dropBtn = CreateFrame("Button", nil, f)
    dropBtn:SetSize(20, 20)
    dropBtn:SetPoint("RIGHT", -3, 0)
    dropBtn:SetNormalTexture("Interface\\ChatFrame\\UI-ChatIcon-ScrollDown-Up")
    dropBtn:SetPushedTexture("Interface\\ChatFrame\\UI-ChatIcon-ScrollDown-Down")
    dropBtn:SetHighlightTexture("Interface\\Buttons\\UI-Common-MouseHilight", "ADD")
    dropBtn:SetScript("OnClick", function()
        PS:ToggleDropdown()
    end)
    f.dropBtn = dropBtn
    
    -- Make the whole frame clickable
    f:EnableMouse(true)
    f:SetScript("OnMouseDown", function()
        PS:ToggleDropdown()
    end)
    
    -- Create dropdown menu (hidden by default)
    self:CreateDropdownMenu(f)
    
    self.frame = f
    self:Update()
    
    return f
end

function PS:CreateDropdownMenu(parent)
    local menu = CreateFrame("Frame", "ETBProfileDropdown", parent, "BackdropTemplate")
    menu:SetSize(220, 200)
    menu:SetPoint("TOPLEFT", parent, "BOTTOMLEFT", 0, -2)
    menu:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, tileSize = 32, edgeSize = 16,
        insets = { left = 5, right = 5, top = 5, bottom = 5 }
    })
    menu:SetFrameStrata("DIALOG")
    menu:Hide()
    
    -- Title
    local title = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    title:SetPoint("TOP", 0, -10)
    title:SetText("|cffffd100Select Character|r")
    menu.title = title
    
    -- Scroll frame for character list
    local scrollFrame = CreateFrame("ScrollFrame", nil, menu, "UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT", 8, -30)
    scrollFrame:SetPoint("BOTTOMRIGHT", -28, 8)
    
    local content = CreateFrame("Frame", nil, scrollFrame)
    content:SetSize(180, 400)
    scrollFrame:SetScrollChild(content)
    menu.content = content
    
    self.dropdown = menu
end

-- =============================================================================
-- UPDATE DISPLAY
-- =============================================================================

function PS:Update()
    if not self.frame then return end
    
    local PM = ETB.ProfileManager
    if not PM then return end
    
    local activeProfile = PM:GetActiveProfile()
    if activeProfile then
        local classColor = CLASS_COLORS[activeProfile.classID] or "|cffffffff"
        local displayText = string.format("%s%s|r", classColor, activeProfile.name)
        self.frame.currentText:SetText(displayText)
        
        -- Add indicator if viewing different character
        if PM.activeProfileKey ~= PM.currentCharacterKey then
            self.frame.label:SetText("|cffff8800Viewing As:|r")
        else
            self.frame.label:SetText("|cff00ffffViewing As:|r")
        end
    else
        self.frame.currentText:SetText("Unknown")
    end
end

function PS:PopulateDropdown()
    if not self.dropdown then return end
    
    local content = self.dropdown.content
    local PM = ETB.ProfileManager
    
    -- Clear existing buttons
    for _, child in pairs({content:GetChildren()}) do
        child:Hide()
        child:SetParent(nil)
    end
    
    local profiles = PM:GetAllProfiles()
    local yOffset = 0
    
    for i, profile in ipairs(profiles) do
        local btn = CreateFrame("Button", nil, content)
        btn:SetSize(175, 24)
        btn:SetPoint("TOPLEFT", 0, -yOffset)
        
        -- Background
        local bg = btn:CreateTexture(nil, "BACKGROUND")
        bg:SetAllPoints()
        bg:SetColorTexture(0.2, 0.2, 0.2, 0.5)
        btn.bg = bg
        
        -- Highlight
        local hl = btn:CreateTexture(nil, "HIGHLIGHT")
        hl:SetAllPoints()
        hl:SetColorTexture(0.4, 0.4, 0.4, 0.5)
        
        -- v15.8.0: Class icon — use Blizzard's standard class-icon texture
        -- (Interface\TargetingFrame\UI-Classes-Circles) with per-class
        -- texture coordinates from CLASS_ICON_TCOORDS. This replaces the
        -- prior emoji FontString that didn't render correctly on MoP 5.4.8's
        -- default fonts.
        local classIcon = btn:CreateTexture(nil, "OVERLAY")
        classIcon:SetSize(20, 20)
        classIcon:SetPoint("LEFT", 5, 0)
        classIcon:SetTexture("Interface\\TargetingFrame\\UI-Classes-Circles")
        local tcoords = CLASS_ICON_TCOORDS and CLASS_ICON_TCOORDS[profile.classID or ""]
        if tcoords then
            classIcon:SetTexCoord(tcoords[1], tcoords[2], tcoords[3], tcoords[4])
        else
            -- Unknown class fallback: faded question-mark-ish look
            classIcon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
            classIcon:SetTexCoord(0, 1, 0, 1)
        end

        -- Name
        local classColor = CLASS_COLORS[profile.classID] or "|cffffffff"
        local nameText = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        nameText:SetPoint("LEFT", classIcon, "RIGHT", 5, 0)
        nameText:SetText(string.format("%s%s|r", classColor, profile.name))
        
        -- Level
        local levelText = btn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        levelText:SetPoint("RIGHT", -5, 0)
        levelText:SetText("|cff888888Lv" .. (profile.level or "?") .. "|r")
        
        -- Current indicator
        if profile.isCurrent then
            local current = btn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
            current:SetPoint("RIGHT", levelText, "LEFT", -5, 0)
            current:SetText("|cff00ff00(You)|r")
        end
        
        -- Active indicator
        if profile.isActive then
            bg:SetColorTexture(0.1, 0.4, 0.1, 0.5)
        end
        
        -- Click handler
        btn:SetScript("OnClick", function()
            PM:SetActiveProfile(profile.key)
            PS:Update()
            PS:HideDropdown()
            
            -- Trigger refresh of item display
            if ETB.MainFrame and ETB.MainFrame.RefreshItems then
                ETB.MainFrame:RefreshItems()
            end
        end)
        
        yOffset = yOffset + 26
    end
    
    -- Resize content
    content:SetHeight(math.max(yOffset, 50))
    
    -- Add "Reset to Current" button at bottom
    local resetBtn = CreateFrame("Button", nil, content, "UIPanelButtonTemplate")
    resetBtn:SetSize(160, 22)
    resetBtn:SetPoint("TOPLEFT", 5, -(yOffset + 10))
    resetBtn:SetText("Reset to Current Character")
    resetBtn:SetScript("OnClick", function()
        PM:SetActiveProfile(PM.currentCharacterKey)
        PS:Update()
        PS:HideDropdown()
        if ETB.MainFrame and ETB.MainFrame.RefreshItems then
            ETB.MainFrame:RefreshItems()
        end
    end)
    
    -- Update content height
    content:SetHeight(yOffset + 40)
end

-- v15.8.0: GetClassIcon now returns the standard class-icon texture path
-- + texture-coordinate tuple. Previously returned emoji glyphs that didn't
-- render on MoP 5.4.8's default fonts. Existing callers that just wanted
-- a short text label have all been migrated to the texture-based render
-- in PS:PopulateDropdown; this helper is preserved for any third-party
-- code that may still call it.
function PS:GetClassIcon(classID)
    local tcoords = CLASS_ICON_TCOORDS and CLASS_ICON_TCOORDS[classID or ""]
    if not tcoords then
        return "Interface\\Icons\\INV_Misc_QuestionMark", 0, 1, 0, 1
    end
    return "Interface\\TargetingFrame\\UI-Classes-Circles",
           tcoords[1], tcoords[2], tcoords[3], tcoords[4]
end

-- =============================================================================
-- DROPDOWN TOGGLE
-- =============================================================================

function PS:ToggleDropdown()
    if self.isOpen then
        self:HideDropdown()
    else
        self:ShowDropdown()
    end
end

function PS:ShowDropdown()
    if not self.dropdown then return end
    self:PopulateDropdown()
    self.dropdown:Show()
    self.isOpen = true
end

function PS:HideDropdown()
    if not self.dropdown then return end
    self.dropdown:Hide()
    self.isOpen = false
end

-- =============================================================================
-- EVENT HANDLING
-- =============================================================================

ETB.EventBus:Register("ETB_PROFILE_CHANGED", function(event, key, profile)
    PS:Update()
end)

ETB:Debug("ProfileSelector", "ProfileSelector.lua loaded")
