-------------------------
-- AiB Hearthstone Toy Selector
-------------------------

AiB.HearthstoneToys = {}
local HT = AiB.HearthstoneToys

-- Liste aller Hearthstone-Toys (Icons werden dynamisch via GetSpellTexture geladen)
HT.TOYS = {
    -- Toy Hearthstones (Item-ID für PlayerHasToy, Spell-ID für Benutzen + Icon)
    {itemID = 54452, spellID = 75136, name = "Ethereal Portal", type = "toy"},
    {itemID = 64488, spellID = 94719, name = "The Innkeeper's Daughter", type = "toy"},
    {itemID = 93672, spellID = 136508, name = "Dark Portal", type = "toy"},
    {itemID = 110560, spellID = 171253, name = "Garrison Hearthstone", type = "toy", excludeFromRandom = true}, -- Quest-abhängig
    {itemID = 140192, spellID = 224869, name = "Dalaran Hearthstone", type = "toy", excludeFromRandom = true}, -- Quest-abhängig
    {itemID = 142542, spellID = 193759, name = "Tome of Town Portal", type = "toy"},
    {itemID = 162973, spellID = 278559, name = "Greatfather Winter's Hearthstone", type = "toy"},
    {itemID = 163045, spellID = 278244, name = "Headless Horseman's Hearthstone", type = "toy"},
    {itemID = 165669, spellID = 278979, name = "Lunar Elder's Hearthstone", type = "toy"},
    {itemID = 165670, spellID = 285362, name = "Peddlefeet's Lovely Hearthstone", type = "toy"},
    {itemID = 165802, spellID = 285424, name = "Noble Gardener's Hearthstone", type = "toy"},
    {itemID = 166746, spellID = 286331, name = "Fire Eater's Hearthstone", type = "toy"},
    {itemID = 166747, spellID = 286353, name = "Brewfest Reveler's Hearthstone", type = "toy"},
    {itemID = 168907, spellID = 298068, name = "Holographic Digitalization Hearthstone", type = "toy"},
    {itemID = 172179, spellID = 308742, name = "Eternal Traveler's Hearthstone", type = "toy"},
    {itemID = 180290, spellID = 325933, name = "Night Fae Hearthstone", type = "toy"},
    {itemID = 182773, spellID = 326064, name = "Necrolord Hearthstone", type = "toy"},
    {itemID = 183716, spellID = 327708, name = "Venthyr Sinstone", type = "toy"},
    {itemID = 184353, spellID = 340200, name = "Kyrian Hearthstone", type = "toy"},
    {itemID = 188952, spellID = 367013, name = "Dominated Hearthstone", type = "toy"},
    {itemID = 190196, spellID = 363799, name = "Enlightened Hearthstone", type = "toy"},
    {itemID = 190237, spellID = 366945, name = "Broker Translocation Matrix", type = "toy"},
    {itemID = 193588, spellID = 375357, name = "Timewalker's Hearthstone", type = "toy"},
    {itemID = 200630, spellID = 391042, name = "Ohn'ir Windsage's Hearthstone", type = "toy"},
    {itemID = 206195, spellID = 401802, name = "Path of the Naaru", type = "toy"},
    {itemID = 208704, spellID = 412555, name = "Deepdweller's Earthen Hearthstone", type = "toy"},
    {itemID = 209035, spellID = 420418, name = "Hearthstone of the Flame", type = "toy"},
    {itemID = 210455, spellID = 422284, name = "Draenic Hologem", type = "toy"},
    {itemID = 212337, spellID = 430913, name = "Stone of the Hearth", type = "toy"},
    {itemID = 228940, spellID = 446424, name = "Notorious Thread's Hearthstone", type = "toy"},
    {itemID = 236687, spellID = 458604, name = "Explosive Hearthstone", type = "toy"},
    {itemID = 246565, spellID = 465004, name = "Cosmic Hearthstone", type = "toy"},
}

-- Hole Icon für ein Toy (cached, lädt aus Item-Daten - zuverlässiger!)
local iconCache = {}
function HT:GetToyIcon(toy)
    -- Cache prüfen
    if iconCache[toy.itemID] then
        return iconCache[toy.itemID]
    end
    
    local icon
    
    -- Alle sind jetzt Toys - hole vom ITEM!
    -- Items haben die richtigen High-Res Icons
    
    -- Methode 1: GetItemIconByID (beste Methode für Toys!)
    icon = C_Item.GetItemIconByID(toy.itemID)
    
    -- Methode 2: GetItemInfo (Fallback wenn Item im Cache)
    if not icon then
        local itemIcon = select(10, GetItemInfo(toy.itemID))
        if itemIcon then
            icon = itemIcon
        end
    end
    
    -- Methode 3: GetSpellTexture (letzter Fallback)
    if not icon and toy.spellID then
        icon = C_Spell.GetSpellTexture(toy.spellID)
    end
    
    -- Methode 4: GetSpellInfo (äußerster Fallback)
    if not icon and toy.spellID then
        local spellName, _, spellIcon = GetSpellInfo(toy.spellID)
        if spellIcon then
            icon = spellIcon
        end
    end
    
    -- Cache speichern
    if icon then
        iconCache[toy.itemID] = icon
    end
    
    return icon
end

-- Ensure AiB_Settings exists
AiB_Settings = AiB_Settings or {}

-- Initialisiere Settings
function HT:Init()
    -- Set default toy wenn noch nicht gesetzt
    if not AiB_Settings.hearthstone_toy then
        -- Finde erstes verfügbares Toy als Default
        local available = self:GetAvailableToys()
        if #available > 0 then
            AiB_Settings.hearthstone_toy = available[1].itemID
        else
            -- Fallback: Erstes Toy aus Liste
            AiB_Settings.hearthstone_toy = self.TOYS[1].itemID
        end
    end
    
    -- Set default random mode
    if AiB_Settings.hearthstone_random == nil then
        AiB_Settings.hearthstone_random = false
    end
end

-- Scanne welche Toys der Char hat (wie HearthstoneToys)
function HT:GetAvailableToys()
    local available = {}
    
    for _, toy in ipairs(self.TOYS) do
        -- Alle Einträge sind jetzt Toys - prüfe mit PlayerHasToy!
        if PlayerHasToy(toy.itemID) then
            table.insert(available, toy)
        end
    end
    
    return available
end

-- Hole aktuell ausgewähltes Toy (mit Random-Support)
function HT:GetSelectedToy()
    -- Random Mode?
    if AiB_Settings.hearthstone_random then
        local available = self:GetAvailableToys()
        if #available > 0 then
            local randomToy = available[math.random(1, #available)]
            return randomToy, true -- true = ist random
        end
    end
    
    -- Fixed Toy - Suche nach itemID!
    local selectedID = AiB_Settings.hearthstone_toy
    
    -- Default: Erstes verfügbares Toy
    if not selectedID then
        local available = self:GetAvailableToys()
        if #available > 0 then
            return available[1], false
        else
            -- Notfall: Erstes Toy aus Liste (auch wenn nicht verfügbar)
            return self.TOYS[1], false
        end
    end
    
    for _, toy in ipairs(self.TOYS) do
        if toy.itemID == selectedID then
            return toy, false
        end
    end
    
    -- Fallback zu erstem Toy
    return self.TOYS[1], false
end

-- Setze ausgewähltes Toy
function HT:SetSelectedToy(toyID)
    AiB_Settings.hearthstone_toy = toyID
    AiB_Settings.hearthstone_random = false -- Deaktiviere Random wenn manuell gewählt
    
    -- Update Button wenn vorhanden
    if self.button then
        self:UpdateButton()
    end
    
    -- Force refresh wenn Season Frame offen ist
    local seasonFrame = _G["AiB_SeasonPortalsFrame"]
    if seasonFrame and seasonFrame:IsVisible() then
        C_Timer.After(0.1, function()
            if self.button then
                self:UpdateButton()
            end
        end)
    end
end

-- Toggle Random Mode
function HT:ToggleRandomMode(enabled)
    AiB_Settings.hearthstone_random = enabled
    
    -- Update Button
    if self.button then
        self:UpdateButton()
    end
    
    -- Force refresh wenn Season Frame offen ist
    local seasonFrame = _G["AiB_SeasonPortalsFrame"]
    if seasonFrame and seasonFrame:IsVisible() then
        C_Timer.After(0.1, function()
            if self.button then
                self:UpdateButton()
            end
        end)
    end
end

-- Zeige Auswahl-Menü
function HT:ShowSelectionMenu(button)
    local available = self:GetAvailableToys()
    
    if #available == 0 then
        print("|cFFFF0000AiB:|r Du hast keine Hearthstone-Toys!")
        return
    end
    
    -- Erstelle Menu mit MenuUtil (moderne API)
    local menu = CreateFrame("Frame", "AiBHearthstoneMenu", UIParent, "UIDropDownMenuTemplate")
    
    local function InitializeMenu(self, level)
        local info = UIDropDownMenu_CreateInfo()
        
        if level == 1 then
            -- Random Option
            info.text = "🎲 Zufälliges Toy"
            info.checked = AiB_Settings.hearthstone_random
            info.func = function()
                HT:ToggleRandomMode(not AiB_Settings.hearthstone_random)
                if AiB_Settings.hearthstone_random then
                    print("|cFF00FF00AiB:|r Hearthstone: Zufallsmodus aktiviert!")
                else
                    print("|cFF00FF00AiB:|r Hearthstone: Zufallsmodus deaktiviert")
                end
                CloseDropDownMenus()
            end
            info.keepShownOnClick = false
            UIDropDownMenu_AddButton(info, level)
            
            -- Separator
            info = UIDropDownMenu_CreateInfo()
            info.isTitle = true
            info.notCheckable = true
            info.text = " "
            UIDropDownMenu_AddButton(info, level)
            
            -- Alle Toys
            for _, toy in ipairs(available) do
                info = UIDropDownMenu_CreateInfo()
                info.text = toy.name
                info.checked = (toy.itemID == AiB_Settings.hearthstone_toy and not AiB_Settings.hearthstone_random)
                info.func = function()
                    HT:SetSelectedToy(toy.itemID)
                    CloseDropDownMenus()
                end
                info.keepShownOnClick = false
                UIDropDownMenu_AddButton(info, level)
            end
        end
    end
    
    UIDropDownMenu_Initialize(menu, InitializeMenu, "MENU")
    ToggleDropDownMenu(1, nil, menu, "cursor", 0, 0)
end

-- Update Button (wird vom Season Frame aufgerufen)
function HT:UpdateButton()
    if not self.button then return end
    
    local toy, isRandom = self:GetSelectedToy()
    
    -- Update Icon
    if self.button.icon then
        if isRandom then
            -- Würfel-Icon für Random
            self.button.icon:SetTexture("Interface\\Icons\\inv_misc_dice_01")
        else
            -- Lade Icon via GetToyIcon!
            local iconTexture = self:GetToyIcon(toy)
            if iconTexture then
                self.button.icon:SetTexture(iconTexture)
            end
        end
    end
    
    -- Update SecureActionButton - IMMER als MACRO mit /use item:ID!
    self.button:SetAttribute("type", "macro")
    
    if isRandom then
        -- Random Mode: Erstelle Macro mit allen verfügbaren Toys (außer excludeFromRandom)
        local available = self:GetAvailableToys()
        local macroText = "/castrandom "
        
        for i, t in ipairs(available) do
            -- Skip Toys die von Random ausgeschlossen sind (Garrison, Dalaran)
            if not t.excludeFromRandom then
                -- Verwende IMMER item:ID (funktioniert für Items UND Toys!)
                macroText = macroText .. "item:" .. t.itemID
                if i < #available then
                    macroText = macroText .. ", "
                end
            end
        end
        
        self.button:SetAttribute("macrotext", macroText)
    else
        -- Festes Toy: /use item:ID
        local macroText = "/use item:" .. toy.itemID
        self.button:SetAttribute("macrotext", macroText)
    end
    
    -- Update Tooltip
    if isRandom then
        self.button.toyName = "Zufälliges Hearthstone"
    else
        self.button.toyName = toy.name
    end
end

-- Setup Handler für Rechtsklick-Menu
function HT:SetupMenuHandler(button)
    -- PostClick (nicht-secure, wird NACH dem Cast ausgeführt)
    button:SetScript("PostClick", function(self, mouseButton)
        if mouseButton == "RightButton" then
            -- Rechtsklick: Öffne Menu
            if AiB.HearthstoneToys then
                AiB.HearthstoneToys:ShowSelectionMenu(self)
            end
        end
    end)
end

-- Registriere Button
function HT:RegisterButton(button)
    self.button = button
    
    -- Setup Menu Handler (Rechtsklick)
    self:SetupMenuHandler(button)
    
    -- Update Button sofort
    C_Timer.After(0.1, function()
        self:UpdateButton()
    end)
end

-- Settings UI (wird in Settings-Tab angezeigt)
function HT:LoadSettings(parent)
    local FONT = "Fonts\\FRIZQT__.TTF"
    local yOffset = -20
    
    -- Header
    local header = parent:CreateFontString(nil, "OVERLAY")
    header:SetFont(FONT, 14, "OUTLINE")
    header:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    header:SetText("Hearthstone Toy Auswahl")
    header:SetTextColor(1, 0.8, 0, 1)
    yOffset = yOffset - 40
    
    -- Info
    local info = parent:CreateFontString(nil, "OVERLAY")
    info:SetFont(FONT, 11)
    info:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    info:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, yOffset)
    info:SetJustifyH("LEFT")
    info:SetWordWrap(true)
    info:SetText("Wähle welches Hearthstone-Toy beim Portal-Fenster benutzt werden soll. Du kannst auch den Zufallsmodus aktivieren.")
    info:SetTextColor(0.7, 0.7, 0.7, 1)
    yOffset = yOffset - 40
    
    -- Random Mode Checkbox
    local randomCB = AiB.Utils:CreateCheckbox(parent, "Zufälliges Toy bei jeder Benutzung",
        AiB_Settings.hearthstone_random or false,
        function(checked)
            self:ToggleRandomMode(checked)
        end
    )
    randomCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    yOffset = yOffset - 40
    
    -- Aktuell gewähltes Toy anzeigen
    local currentLabel = parent:CreateFontString(nil, "OVERLAY")
    currentLabel:SetFont(FONT, 12)
    currentLabel:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    currentLabel:SetText("Aktuell gewählt:")
    currentLabel:SetTextColor(0.9, 0.9, 0.9, 1)
    yOffset = yOffset - 25
    
    -- Toy Icon + Name
    local toyDisplay = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    toyDisplay:SetSize(350, 40)  -- Breiter! (war 200)
    toyDisplay:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    toyDisplay:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\Buttons\\WHITE8X8",
        tile = false,
        edgeSize = 1,
    })
    toyDisplay:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
    toyDisplay:SetBackdropBorderColor(0.4, 0.4, 0.4, 1)
    
    local toyIcon = toyDisplay:CreateTexture(nil, "ARTWORK")
    toyIcon:SetSize(32, 32)
    toyIcon:SetPoint("LEFT", toyDisplay, "LEFT", 5, 0)
    
    local toyName = toyDisplay:CreateFontString(nil, "OVERLAY")
    toyName:SetFont(FONT, 12)
    toyName:SetPoint("LEFT", toyIcon, "RIGHT", 10, 0)
    toyName:SetPoint("RIGHT", toyDisplay, "RIGHT", -5, 0)  -- Begrenzt Breite
    toyName:SetJustifyH("LEFT")
    toyName:SetTextColor(1, 1, 1, 1)
    
    -- Update Display
    local function UpdateDisplay()
        local toy, isRandom = self:GetSelectedToy()
        if isRandom then
            toyIcon:SetTexture("Interface\\Icons\\inv_misc_dice_01")
            toyIcon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
            toyName:SetText("Zufälliges Toy")
        else
            -- Lade Icon via GetToyIcon!
            local iconTexture = self:GetToyIcon(toy)
            if iconTexture then
                toyIcon:SetTexture(iconTexture)
                toyIcon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
            end
            toyName:SetText(toy.name)
        end
    end
    
    -- Initial Update (sofort)
    UpdateDisplay()
    
    -- Nochmal nach 0.5s wenn Toy-DB geladen
    C_Timer.After(0.5, function()
        UpdateDisplay()
    end)
    
    yOffset = yOffset - 50
    
    -- Liste aller verfügbaren Toys (wird später gefüllt)
    local listStartY = yOffset
    
    -- Lazy-Load: Warte bis Toy-Datenbank bereit ist
    C_Timer.After(0.5, function()
        if not parent:IsVisible() then return end
        
        -- Update "Aktuell gewählt" Display
        UpdateDisplay()
        
        local available = self:GetAvailableToys()
        
        -- Header für verfügbare Toys
        local listHeader = parent:CreateFontString(nil, "OVERLAY")
        listHeader:SetFont(FONT, 12)
        listHeader:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, listStartY)
        listHeader:SetText("Verfügbare Toys:")
        listHeader:SetTextColor(0.9, 0.9, 0.9, 1)
        
        if #available == 0 then
            local noToysText = parent:CreateFontString(nil, "OVERLAY")
            noToysText:SetFont(FONT, 11)
            noToysText:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, listStartY - 25)
            noToysText:SetText("Keine Hearthstone-Toys gefunden.\nStelle sicher dass du mindestens ein Hearthstone-Toy besitzt!")
            noToysText:SetTextColor(1, 0.5, 0.5, 1)
            return
        end
        
        -- 3-Spalten Grid Layout
        local columns = 3
        local buttonWidth = 280
        local buttonHeight = 28
        local columnSpacing = 10
        local rowSpacing = 2
        local startY = listStartY - 30
        
        for i, toy in ipairs(available) do
            local col = (i - 1) % columns
            local row = math.floor((i - 1) / columns)
            
            local xPos = 20 + (col * (buttonWidth + columnSpacing))
            local yPos = startY - (row * (buttonHeight + rowSpacing))
            
            local btn = CreateFrame("Button", nil, parent)
            btn:SetSize(buttonWidth, buttonHeight)
            btn:SetPoint("TOPLEFT", parent, "TOPLEFT", xPos, yPos)
            
            -- Hover Background
            local bg = btn:CreateTexture(nil, "BACKGROUND")
            bg:SetAllPoints()
            bg:SetColorTexture(0.15, 0.15, 0.15, 0)
            btn.bg = bg
            
            -- Icon - Lade via GetToyIcon!
            local icon = btn:CreateTexture(nil, "ARTWORK")
            icon:SetSize(24, 24)
            icon:SetPoint("LEFT", btn, "LEFT", 2, 0)
            
            local iconTexture = self:GetToyIcon(toy)
            if iconTexture then
                icon:SetTexture(iconTexture)
                icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
            end
            
            -- Name
            local name = btn:CreateFontString(nil, "OVERLAY")
            name:SetFont(FONT, 11)
            name:SetPoint("LEFT", icon, "RIGHT", 5, 0)
            name:SetPoint("RIGHT", btn, "RIGHT", -5, 0)
            name:SetJustifyH("LEFT")
            name:SetText(toy.name)
            name:SetTextColor(0.8, 0.8, 0.8, 1)
            
            -- Click Handler
            btn:SetScript("OnClick", function()
                self:SetSelectedToy(toy.itemID)
                UpdateDisplay()
            end)
            
            -- Hover
            btn:SetScript("OnEnter", function(self)
                self.bg:SetColorTexture(0.25, 0.25, 0.25, 0.5)
                name:SetTextColor(1, 1, 1, 1)
                
                -- Tooltip
                GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                GameTooltip:AddLine(toy.name, 1, 1, 1)
                GameTooltip:Show()
            end)
            
            btn:SetScript("OnLeave", function(self)
                self.bg:SetColorTexture(0.15, 0.15, 0.15, 0)
                name:SetTextColor(0.8, 0.8, 0.8, 1)
                GameTooltip:Hide()
            end)
        end
        
        -- Info-Text
        local rows = math.ceil(#available / columns)
        local infoY = startY - (rows * (buttonHeight + rowSpacing)) - 15
        
        local infoText = parent:CreateFontString(nil, "OVERLAY")
        infoText:SetFont(FONT, 10)
        infoText:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, infoY)
        infoText:SetText(string.format("%d Hearthstone-Toys gefunden", #available))
        infoText:SetTextColor(0.6, 0.6, 0.6, 1)
        
        -- WICHTIG: Aktualisiere ScrollChild Höhe nach Toy-Loading!
        C_Timer.After(0.1, function()
            local scrollChild = parent.scrollChild
            if not scrollChild then return end
            
            local contentFrame = scrollChild:GetParent()
            if not contentFrame then return end
            
            -- Berechne tatsächliche Content-Höhe:
            -- Portal Visibility Section: Header + Checkbox + Info = ~180px
            -- Hearthstone Header + Random Checkbox + Current Selection Box = ~200px
            -- "Verfügbare Toys" Header = ~30px
            -- Grid: rows * rowHeight
            -- Info Text: ~30px
            local portalVisibilityHeight = 180
            local hearthstoneHeaderHeight = 200
            local availableToysHeader = 30
            local gridHeight = rows * (buttonHeight + rowSpacing)
            local infoHeight = 30
            
            local contentHeight = portalVisibilityHeight + hearthstoneHeaderHeight + availableToysHeader + gridHeight + infoHeight
            scrollChild:SetHeight(contentHeight)
            
            -- Update ScrollBar
            if contentFrame.ScrollBar then
                local frameHeight = contentFrame:GetHeight()
                local scrollRange = math.max(0, contentHeight - frameHeight)
                contentFrame.ScrollBar:SetMinMaxValues(0, scrollRange)
            end
        end)
    end)
end

------------------------------------------------------------------------
-- Auto-Init mit Delay
------------------------------------------------------------------------
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_LOGIN")
initFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        C_Timer.After(0.5, function()
            if AiB.HearthstoneToys then
                AiB.HearthstoneToys:Init()
            end
        end)
        self:UnregisterEvent("PLAYER_LOGIN")
    end
end)
