--[[
============================================================================
ETB v11.0 - ProfileSelector.lua (PROTOTYPE)
============================================================================
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)
        
        -- Class icon (placeholder)
        local classIcon = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        classIcon:SetPoint("LEFT", 5, 0)
        classIcon:SetText(self:GetClassIcon(profile.classID))
        
        -- 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

function PS:GetClassIcon(classID)
    local icons = {
        WARRIOR = "⚔️",
        PALADIN = "✝️",
        DEATHKNIGHT = "💀",
        HUNTER = "🏹",
        SHAMAN = "⚡",
        ROGUE = "🗡️",
        DRUID = "🐻",
        MONK = "☯️",
        MAGE = "❄️",
        WARLOCK = "🔥",
        PRIEST = "✨",
    }
    return icons[classID] or "❓"
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(key, profile)
    PS:Update()
end)

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