-- Housing Item Tracker
-- Markiert Items, die für Housing-Crafting benötigt werden

local addonName = "HousingItemTracker"
local HousingItemTracker = CreateFrame("Frame")

-- Localization
local L = {}

-- English (Default)
L["HOUSING"] = "Housing"
L["USED_IN_CRAFTING"] = "Used in Housing recipes"
L["DECOR_COST"] = "Decor Cost"
L["CATEGORY"] = "Category"
L["SOURCE"] = "Source"
L["VENDORS"] = "Vendors"
L["MAP_AVAILABLE"] = "<Map available>"
L["MATERIALS"] = "Materials"
L["PROFESSION"] = "Profession"
L["ACHIEVEMENT"] = "Achievement"
L["QUEST"] = "Quest"

-- Source Types
L["SOURCE_CRAFTING"] = "Crafting"
L["SOURCE_VENDOR"] = "Vendor"
L["SOURCE_QUEST"] = "Quest"
L["SOURCE_ACHIEVEMENT"] = "Achievement"
L["SOURCE_DROP"] = "Drop"
L["SOURCE_TREASURE"] = "Treasure"
L["SOURCE_ENCOUNTER"] = "Encounter"

-- Professions
L["PROF_ALCHEMY"] = "Alchemy"
L["PROF_BLACKSMITHING"] = "Blacksmithing"
L["PROF_COOKING"] = "Cooking"
L["PROF_ENCHANTING"] = "Enchanting"
L["PROF_ENGINEERING"] = "Engineering"
L["PROF_INSCRIPTION"] = "Inscription"
L["PROF_JEWELCRAFTING"] = "Jewelcrafting"
L["PROF_LEATHERWORKING"] = "Leatherworking"
L["PROF_TAILORING"] = "Tailoring"

-- Login Messages
L["LOADED_SUCCESSFULLY"] = "Successfully loaded!"
L["DECOR_ITEMS"] = "Decor Items"
L["CRAFTING_MATERIALS"] = "Crafting Materials"
L["NEW_ADDON_IDEAS"] = "New AddOn ideas?"
L["VISIT"] = "Visit:"

-- German
if GetLocale() == "deDE" then
    L["HOUSING"] = "Behausung"
    L["USED_IN_CRAFTING"] = "Verwendet für Behausung-Rezepte"
    L["DECOR_COST"] = "Deko-Kosten"
    L["CATEGORY"] = "Kategorie"
    L["SOURCE"] = "Quelle"
    L["VENDORS"] = "Händler"
    L["MAP_AVAILABLE"] = "<Karte verfügbar>"
    L["MATERIALS"] = "Materialien"
    L["PROFESSION"] = "Beruf"
    L["ACHIEVEMENT"] = "Erfolg"
    L["QUEST"] = "Quest"
    
    -- Source Types
    L["SOURCE_CRAFTING"] = "Herstellung"
    L["SOURCE_VENDOR"] = "Händler"
    L["SOURCE_QUEST"] = "Quest"
    L["SOURCE_ACHIEVEMENT"] = "Erfolg"
    L["SOURCE_DROP"] = "Beute"
    L["SOURCE_TREASURE"] = "Schatz"
    L["SOURCE_ENCOUNTER"] = "Begegnung"
    
    -- Professions
    L["PROF_ALCHEMY"] = "Alchemie"
    L["PROF_BLACKSMITHING"] = "Schmiedekunst"
    L["PROF_COOKING"] = "Kochkunst"
    L["PROF_ENCHANTING"] = "Verzauberkunst"
    L["PROF_ENGINEERING"] = "Ingenieurskunst"
    L["PROF_INSCRIPTION"] = "Inschriftenkunde"
    L["PROF_JEWELCRAFTING"] = "Juwelenschleifen"
    L["PROF_LEATHERWORKING"] = "Lederverarbeitung"
    L["PROF_TAILORING"] = "Schneiderei"
    
    -- Login Messages
    L["LOADED_SUCCESSFULLY"] = "Erfolgreich geladen!"
    L["DECOR_ITEMS"] = "Decor-Items"
    L["CRAFTING_MATERIALS"] = "Crafting-Materialien"
    L["NEW_ADDON_IDEAS"] = "Neue AddOn-Ideen?"
    L["VISIT"] = "Besuche:"
end

-- French
if GetLocale() == "frFR" then
    L["HOUSING"] = "Logement"
    L["USED_IN_CRAFTING"] = "Utilisé dans les recettes de logement"
    L["DECOR_COST"] = "Coût de décoration"
    L["CATEGORY"] = "Catégorie"
    L["SOURCE"] = "Source"
    L["VENDORS"] = "Vendeurs"
    L["MAP_AVAILABLE"] = "<Carte disponible>"
    L["MATERIALS"] = "Matériaux"
    L["PROFESSION"] = "Métier"
    L["ACHIEVEMENT"] = "Haut fait"
    L["QUEST"] = "Quête"
    
    L["SOURCE_CRAFTING"] = "Artisanat"
    L["SOURCE_VENDOR"] = "Vendeur"
    L["SOURCE_QUEST"] = "Quête"
    L["SOURCE_ACHIEVEMENT"] = "Haut fait"
    L["SOURCE_DROP"] = "Butin"
    L["SOURCE_TREASURE"] = "Trésor"
    L["SOURCE_ENCOUNTER"] = "Rencontre"
    
    L["PROF_ALCHEMY"] = "Alchimie"
    L["PROF_BLACKSMITHING"] = "Forge"
    L["PROF_COOKING"] = "Cuisine"
    L["PROF_ENCHANTING"] = "Enchantement"
    L["PROF_ENGINEERING"] = "Ingénierie"
    L["PROF_INSCRIPTION"] = "Calligraphie"
    L["PROF_JEWELCRAFTING"] = "Joaillerie"
    L["PROF_LEATHERWORKING"] = "Travail du cuir"
    L["PROF_TAILORING"] = "Couture"
    
    -- Login Messages
    L["LOADED_SUCCESSFULLY"] = "Chargé avec succès !"
    L["DECOR_ITEMS"] = "Objets de décoration"
    L["CRAFTING_MATERIALS"] = "Matériaux d'artisanat"
    L["NEW_ADDON_IDEAS"] = "Nouvelles idées d'addon ?"
    L["VISIT"] = "Visitez :"
end

-- Spanish
if GetLocale() == "esES" or GetLocale() == "esMX" then
    L["HOUSING"] = "Vivienda"
    L["USED_IN_CRAFTING"] = "Usado en recetas de vivienda"
    L["DECOR_COST"] = "Coste de decoración"
    L["CATEGORY"] = "Categoría"
    L["SOURCE"] = "Fuente"
    L["VENDORS"] = "Vendedores"
    L["MAP_AVAILABLE"] = "<Mapa disponible>"
    L["MATERIALS"] = "Materiales"
    L["PROFESSION"] = "Profesión"
    L["ACHIEVEMENT"] = "Logro"
    L["QUEST"] = "Misión"
    
    L["SOURCE_CRAFTING"] = "Fabricación"
    L["SOURCE_VENDOR"] = "Vendedor"
    L["SOURCE_QUEST"] = "Misión"
    L["SOURCE_ACHIEVEMENT"] = "Logro"
    L["SOURCE_DROP"] = "Botín"
    L["SOURCE_TREASURE"] = "Tesoro"
    L["SOURCE_ENCOUNTER"] = "Encuentro"
    
    L["PROF_ALCHEMY"] = "Alquimia"
    L["PROF_BLACKSMITHING"] = "Herrería"
    L["PROF_COOKING"] = "Cocina"
    L["PROF_ENCHANTING"] = "Encantamiento"
    L["PROF_ENGINEERING"] = "Ingeniería"
    L["PROF_INSCRIPTION"] = "Inscripción"
    L["PROF_JEWELCRAFTING"] = "Joyería"
    L["PROF_LEATHERWORKING"] = "Peletería"
    L["PROF_TAILORING"] = "Sastrería"
    
    -- Login Messages
    L["LOADED_SUCCESSFULLY"] = "¡Cargado con éxito!"
    L["DECOR_ITEMS"] = "Objetos de decoración"
    L["CRAFTING_MATERIALS"] = "Materiales de fabricación"
    L["NEW_ADDON_IDEAS"] = "¿Nuevas ideas de complementos?"
    L["VISIT"] = "Visita:"
end

-- Frame für Vendor-Karten-Anzeige
local VendorMapFrame = CreateFrame("Frame", "HousingVendorMapFrame", UIParent)
VendorMapFrame:SetSize(256, 256)
VendorMapFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 100, -100)
VendorMapFrame:Hide()
VendorMapFrame:SetFrameStrata("TOOLTIP")
VendorMapFrame:SetFrameLevel(1000)

-- Background
VendorMapFrame.bg = VendorMapFrame:CreateTexture(nil, "BACKGROUND")
VendorMapFrame.bg:SetAllPoints()
VendorMapFrame.bg:SetColorTexture(0, 0, 0, 0.8)

-- Border
VendorMapFrame.border = VendorMapFrame:CreateTexture(nil, "BORDER")
VendorMapFrame.border:SetAllPoints()
VendorMapFrame.border:SetColorTexture(0.3, 0.3, 0.3, 1)
VendorMapFrame.border:SetPoint("TOPLEFT", -1, 1)
VendorMapFrame.border:SetPoint("BOTTOMRIGHT", 1, -1)

-- Map Texture
VendorMapFrame.texture = VendorMapFrame:CreateTexture(nil, "ARTWORK")
VendorMapFrame.texture:SetPoint("TOPLEFT", 4, -4)
VendorMapFrame.texture:SetPoint("BOTTOMRIGHT", -4, 4)

-- Map Pin (eigene Texture)
VendorMapFrame.pin = VendorMapFrame:CreateTexture(nil, "OVERLAY")
VendorMapFrame.pin:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\map-pin")
VendorMapFrame.pin:SetSize(32, 32)  -- Etwas größer für bessere Sichtbarkeit
VendorMapFrame.pin:Hide()

-- Title
VendorMapFrame.title = VendorMapFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
VendorMapFrame.title:SetPoint("TOP", 0, -8)
VendorMapFrame.title:SetTextColor(1, 0.82, 0)

-- Close Button
VendorMapFrame.close = CreateFrame("Button", nil, VendorMapFrame, "UIPanelCloseButton")
VendorMapFrame.close:SetPoint("TOPRIGHT", 2, 2)

-- Funktion zum Anzeigen der Karte
function VendorMapFrame:ShowMap(mapTexture, locationName, coordX, coordY)
    if not mapTexture then return end
    
    self.texture:SetTexture(mapTexture)
    self.title:SetText(locationName or "Vendor Location")
    
    -- Intelligente Positionierung neben dem GameTooltip
    local tooltip = GameTooltip

   -- Speichere Tooltip-Referenz
   self.anchoredTooltip = GameTooltip
    
   -- Intelligente Positionierung
   self:UpdatePosition()
    
    -- Zeige Map Pin falls Koordinaten vorhanden
    if coordX and coordY then
        -- Konvertiere % Koordinaten (0-100) zu Pixel-Position auf der Karte
        -- Die Karte ist 256x256, aber wir haben 4px Padding
        local mapWidth = 256 - 8  -- 4px links + 4px rechts
        local mapHeight = 256 - 8  -- 4px oben + 4px unten
        
        -- X/Y sind in Prozent (0-100), konvertiere zu Pixel-Offset
        local pixelX = (coordX / 100) * mapWidth
        local pixelY = (coordY / 100) * mapHeight
        
        -- Setze Pin-Position (relativ zur Karte)
        -- Y muss invertiert werden (0 = oben in WoW)
        self.pin:ClearAllPoints()
        self.pin:SetPoint("CENTER", self.texture, "TOPLEFT", pixelX, -pixelY)
        self.pin:Show()
    else
        self.pin:Hide()
    end
    
    self:Show()
end

-- Update Position Funktion
function VendorMapFrame:UpdatePosition()
    local tooltip = self.anchoredTooltip or GameTooltip
    
    if not tooltip or not tooltip:IsShown() then
        return
    end
    
    self:ClearAllPoints()
    
    -- Hole Tooltip-Position und Größe
    local tooltipLeft = tooltip:GetLeft()
    local tooltipRight = tooltip:GetRight()
    local tooltipTop = tooltip:GetTop()
    
    if not tooltipLeft or not tooltipRight or not tooltipTop then
        -- Fallback Position
        self:SetPoint("CENTER", UIParent, "CENTER", 300, 0)
        return
    end
    
    -- Bildschirm-Breite
    local screenWidth = GetScreenWidth()
    
    -- Map-Breite
    local mapWidth = self:GetWidth()
    
    -- Prüfe ob Platz rechts vom Tooltip ist
    local spaceOnRight = screenWidth - tooltipRight
    
    if spaceOnRight >= (mapWidth + 20) then
        -- Genug Platz rechts - zeige rechts
        self:SetPoint("TOPLEFT", tooltip, "TOPRIGHT", 15, 0)
    else
        -- Kein Platz rechts - versuche links
        local spaceOnLeft = tooltipLeft
        
        if spaceOnLeft >= (mapWidth + 20) then
            -- Platz links - zeige links
            self:SetPoint("TOPRIGHT", tooltip, "TOPLEFT", -15, 0)
        else
            -- Kein Platz links oder rechts - zeige unterhalb
            self:SetPoint("TOP", tooltip, "BOTTOM", 0, -15)
        end
    end
end

-- OnUpdate: Verstecke wenn Tooltip verschwindet und aktualisiere Position
VendorMapFrame:SetScript("OnUpdate", function(self, elapsed)
    if not self.anchoredTooltip or not self.anchoredTooltip:IsShown() then
        self:Hide()
        self.anchoredTooltip = nil
    else
        -- Aktualisiere Position falls Tooltip sich bewegt hat
        if not self.updateTimer then
            self.updateTimer = 0
        end
        
        self.updateTimer = self.updateTimer + elapsed
        
        -- Aktualisiere Position alle 0.1 Sekunden
        if self.updateTimer >= 0.1 then
            self.updateTimer = 0
            self:UpdatePosition()
        end
    end
end)

-- Lade die Datenbank (wird vom Scraper generiert)
if not HousingItemTrackerDB then
    HousingItemTrackerDB = {
        version = 2,
        items = {
            materials = {},
            decorItems = {},
            achievements = {},
            quests = {},
        },
    }
end

-- Settings/Optionen (Saved Variables)
if not HousingItemTrackerSettings then
    HousingItemTrackerSettings = {
        showMaterialTooltips = true,   -- Tooltips für Materials in Bags anzeigen
        showVendorMaps = true,          -- Vendor-Karten anzeigen
        showBagIcons = true,            -- Icons in Bags anzeigen
        showDashboardTooltips = true,   -- Tooltips im Housing Dashboard anzeigen
    }
end

local DB = HousingItemTrackerDB.items
local Settings = HousingItemTrackerSettings

-- Prüft ob ein Item in irgendeinem Decor-Item als Material verwendet wird
local function IsUsedInCrafting(itemId)
    if not itemId or not DB.decorItems then return false end
    
    for decorId, decorInfo in pairs(DB.decorItems) do
        if decorInfo.materials then
            for _, material in ipairs(decorInfo.materials) do
                if material.id == itemId then
                    return true
                end
            end
        end
    end
    
    return false
end

-- Kombinierte Prüfung: Ist es ein Housing-relevantes Item?
local function IsHousingRelated(itemId)
    return IsUsedInCrafting(itemId)
end

-- Prüft ob ein Item ein Decor-Item ist (optional, für zukünftige Erweiterungen)
local function IsDecorItem(itemId)
    if not itemId then return false end
    return DB.decorItems and DB.decorItems[itemId] ~= nil
end

-- Holt den lokalisierten Namen für eine Currency (falls ID vorhanden)
local function GetLocalizedCurrencyName(currencyId, fallbackName)
    if currencyId and C_CurrencyInfo and C_CurrencyInfo.GetCurrencyInfo then
        local currencyInfo = C_CurrencyInfo.GetCurrencyInfo(currencyId)
        if currencyInfo and currencyInfo.name then
            return currencyInfo.name
        end
    end
    return fallbackName or "Currency"
end

-- Holt den lokalisierten Namen für einen NPC (automatisch via WoW API)
local function GetLocalizedNPCName(npcId, fallbackName)
    if npcId and C_TooltipInfo and C_TooltipInfo.GetHyperlink then
        -- Erstelle NPC-Hyperlink und hole Tooltip-Info
        local hyperlink = "unit:Creature-0-0-0-0-" .. npcId
        local tooltipInfo = C_TooltipInfo.GetHyperlink(hyperlink)
        
        if tooltipInfo and tooltipInfo.lines and tooltipInfo.lines[1] then
            local npcName = tooltipInfo.lines[1].leftText
            if npcName and npcName ~= "" then
                return npcName
            end
        end
    end
    
    -- Fallback auf englischen Namen
    return fallbackName or ("NPC " .. (npcId or ""))
end

-- Holt den lokalisierten Achievement-Namen (automatisch via WoW API)
local function GetLocalizedAchievementName(achievementId, fallbackName)
    if achievementId then

        if GetAchievementInfo then
            local id, name = GetAchievementInfo(achievementId)
            if name and name ~= "" then
                return name
            end
        end
    end
    
    -- Fallback auf englischen Namen oder ID
    return fallbackName or ("Achievement " .. (achievementId or ""))
end

-- Holt den lokalisierten Quest-Namen (automatisch via WoW API)
local function GetLocalizedQuestName(questId, fallbackName)
    if questId then
        -- Nutze WoW API für automatische Localization
        if C_QuestLog and C_QuestLog.GetTitleForQuestID then
            local questName = C_QuestLog.GetTitleForQuestID(questId)
            if questName and questName ~= "" then
                return questName
            end
        end
    end
    
    -- Fallback auf englischen Namen oder ID
    return fallbackName or ("Quest " .. (questId or ""))
end

-- Lokalisiert Source-Namen
local function LocalizeSource(source)
    local sourceMap = {
        ["Crafting"] = L["SOURCE_CRAFTING"],
        ["Vendor"] = L["SOURCE_VENDOR"],
        ["Quest"] = L["SOURCE_QUEST"],
        ["Achievement"] = L["SOURCE_ACHIEVEMENT"],
        ["Drop"] = L["SOURCE_DROP"],
        ["Treasure"] = L["SOURCE_TREASURE"],
        ["Encounter"] = L["SOURCE_ENCOUNTER"],
    }
    return sourceMap[source] or source
end

-- Lokalisiert Profession-Namen
local function LocalizeProfession(profession)
    local profMap = {
        ["Alchemy"] = L["PROF_ALCHEMY"],
        ["Blacksmithing"] = L["PROF_BLACKSMITHING"],
        ["Cooking"] = L["PROF_COOKING"],
        ["Enchanting"] = L["PROF_ENCHANTING"],
        ["Engineering"] = L["PROF_ENGINEERING"],
        ["Inscription"] = L["PROF_INSCRIPTION"],
        ["Jewelcrafting"] = L["PROF_JEWELCRAFTING"],
        ["Leatherworking"] = L["PROF_LEATHERWORKING"],
        ["Tailoring"] = L["PROF_TAILORING"],
    }
    return profMap[profession] or profession
end

-- Holt den lokalisierten Item-Namen (Materials/Decors)
local function GetLocalizedItemName(itemId, fallbackName)
    if itemId then
        if C_Item and C_Item.GetItemInfo then
            local name = C_Item.GetItemInfo(itemId)
            if name and name ~= "" then
                return name
            end
        end
        if GetItemInfo then
            local name = GetItemInfo(itemId)
            if name and name ~= "" then
                return name
            end
        end
    end
    return fallbackName or ("Item " .. (itemId or ""))
end

-- Fügt Tooltip-Text hinzu
local function AddTooltipInfo(tooltip, itemId)
    if not itemId then return end
    
    local isDecor = IsDecorItem(itemId)
    local isUsedInCrafting = IsUsedInCrafting(itemId)
    local decorInfo = DB.decorItems and DB.decorItems[itemId]
    
    if isDecor or isUsedInCrafting then
        tooltip:AddLine(" ") -- Leerzeile
        tooltip:AddLine("|cFF00FF00" .. L["HOUSING"] .. ":|r", 1, 1, 1)
        
        if isUsedInCrafting then
            -- Zeige in welchen Decor-Items dieses Material verwendet wird
            tooltip:AddLine(L["USED_IN_CRAFTING"], 0.8, 0.8, 0.8)
        end
        
        if decorInfo then
                    
            -- -- Zeige Kategorie
            -- if decorInfo.category then
            --     local categoryText = decorInfo.category
            --     if decorInfo.subcategory then
            --         categoryText = categoryText .. " > " .. decorInfo.subcategory
            --     end
            --     tooltip:AddDoubleLine("Category:", categoryText, 0.8, 0.8, 0.8, 0.7, 0.7, 0.7)
            -- end
            
            -- Zeige Sources (lokalisiert)
            if decorInfo.sources and #decorInfo.sources > 0 then
                local localizedSources = {}
                for _, source in ipairs(decorInfo.sources) do
                    table.insert(localizedSources, LocalizeSource(source))
                end
                local sourcesText = table.concat(localizedSources, ", ")
                tooltip:AddDoubleLine(L["SOURCE"] .. ":", sourcesText, 0.8, 0.8, 0.8, 0.7, 0.9, 1)
            end
            
            -- Zeige Vendor-Informationen
            if decorInfo.vendors and #decorInfo.vendors > 0 then
                tooltip:AddLine(" ")
                tooltip:AddLine("|cFFFFD700" .. L["VENDORS"] .. ":|r", 0.9, 0.9, 0.9)
                
                local firstVendorWithMap = nil
                
                for _, vendor in ipairs(decorInfo.vendors) do
                    -- Nutze lokalisierte Namen falls IDs vorhanden
                    local vendorName = GetLocalizedNPCName(vendor.npcId, vendor.name)
                    local vendorText = "  " .. vendorName
                    if vendor.location then
                        vendorText = vendorText .. " (" .. vendor.location .. ")"
                    end
                    tooltip:AddLine(vendorText, 0.7, 0.7, 0.7)
                    
                    if vendor.price then
                        -- Nutze lokalisierte Currency-Namen
                        local currencyName = GetLocalizedCurrencyName(vendor.currencyId, vendor.currency)
                        local priceText = "  " .. vendor.price .. " " .. currencyName
                        tooltip:AddLine(priceText, 1, 0.82, 0)
                    end
                    
                    -- Zeige Waypoint falls vorhanden
                    if vendor.waypoint then
                        tooltip:AddLine("  |cFF90EE90" .. vendor.waypoint .. "|r", 0.5, 0.9, 0.5)
                    end
                    
                    -- Merke ersten Vendor mit Karte (nur einmal)
                    if vendor.mapTexture and not firstVendorWithMap then
                        firstVendorWithMap = vendor
                    end
                end
                
                -- Zeige "Karte verfügbar" Hinweis nur einmal
                if firstVendorWithMap and firstVendorWithMap.mapTexture then
                                        
                    -- Zeige Karte vom ersten Vendor
                    VendorMapFrame:ShowMap(
                        firstVendorWithMap.mapTexture, 
                        firstVendorWithMap.location,
                        firstVendorWithMap.coordX,
                        firstVendorWithMap.coordY
                    )
                else
                    -- Verstecke Karte wenn keine vorhanden
                    VendorMapFrame:Hide()
                end
            else
                -- Keine Vendors - Karte verstecken
                VendorMapFrame:Hide()
            end
            
            -- Zeige Materials (für Crafting-Items)
            if decorInfo.materials and #decorInfo.materials > 0 then
                tooltip:AddLine(" ")
                tooltip:AddLine("|cFF00CCFF" .. L["MATERIALS"] .. ":|r", 0.9, 0.9, 0.9)
                
                for _, material in ipairs(decorInfo.materials) do
                    local localizedMatName = GetLocalizedItemName(material.id, material.name or ("Item " .. material.id))
                    local quantity = material.quantity or 1
                    local matText = "  " .. quantity .. "x " .. localizedMatName
                    tooltip:AddLine(matText, 0.8, 0.8, 0.8)
                end
            end
            
            -- Zeige Profession (falls Crafting) - lokalisiert
            if decorInfo.profession then
                local localizedProf = LocalizeProfession(decorInfo.profession)
                tooltip:AddDoubleLine(L["PROFESSION"] .. ":", localizedProf, 0.8, 0.8, 0.8, 0.7, 0.9, 1)
            end
            
            -- Zeige Achievement (falls vorhanden)
            if decorInfo.achievementId or decorInfo.achievement then
                local achievementName = GetLocalizedAchievementName(decorInfo.achievementId, decorInfo.achievement)
                tooltip:AddDoubleLine(L["ACHIEVEMENT"] .. ":", achievementName, 0.8, 0.8, 0.8, 1, 0.5, 0)
            end
            
            -- Zeige Quest (falls vorhanden)
            if decorInfo.questId or decorInfo.quest then
                local questName = GetLocalizedQuestName(decorInfo.questId, decorInfo.quest)
                tooltip:AddDoubleLine(L["QUEST"] .. ":", questName, 0.8, 0.8, 0.8, 1, 0.8, 0)
            end
        end
    end
end

-- Extrahiert Item-ID aus Item-Link
local function GetItemIdFromLink(itemLink)
    if not itemLink then return nil end
    -- Item-Link Format: |cff9d9d9d|Hitem:12345:0:0:0:0:0:0:0:0|h[Item Name]|h|r
    local itemId = itemLink:match("item:(%d+)")
    return itemId and tonumber(itemId) or nil
end

-- Hook für GameTooltip (moderner Ansatz für Retail WoW)
-- Dieser Hook ist für normale Tooltips (Bags, Inventar, etc.)
local function OnTooltipSetItem(tooltip)
    if not tooltip then return end
    
    -- Prüfe Settings
    if not Settings.showMaterialTooltips then
        return
    end
    
    -- Prüfe ob der Tooltip die GetItem Methode hat
    if tooltip.GetItem then
        local _, itemLink = tooltip:GetItem()
        if itemLink then
            local itemId = GetItemIdFromLink(itemLink)
            if itemId then
                -- NUR für Materials anzeigen (nicht für Decor-Items in Bags)
                -- Das verhindert Probleme wenn Material-IDs und Decor-IDs überlappen
                if IsUsedInCrafting(itemId) then
                    -- Es ist ein Material oder wird in Crafting verwendet
                    AddTooltipInfo(tooltip, itemId)
                end
            end
        end
    end
end

-- Tooltip-Hook Setup (kompatibel mit modernem WoW)
local function SetupTooltipHooks()
    -- Verwende TooltipDataProcessor für moderne WoW-Versionen (Dragonflight+)
    if TooltipDataProcessor and Enum.TooltipDataType then
        TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Item, function(tooltip)
            if tooltip == GameTooltip or tooltip == ItemRefTooltip then
                OnTooltipSetItem(tooltip)
            end
        end)
    else
        -- Fallback für ältere Versionen (funktioniert aber nicht in Midnight)
        -- Diese Events existieren nicht mehr
    end
end

-- Hook für Bag-Slots (Icon-Markierung) - Vereinfachtes System mit eigener Texture
local function UpdateBagSlotIcon(button)
    if not button then return end
    
    local bagID = button.GetBagID and button:GetBagID()
    local slotID = button.GetID and button:GetID()
    
    if not bagID or not slotID then return end
    
    local itemId = C_Container.GetContainerItemID(bagID, slotID)
    
    -- Zeige Icon für Materialien UND für Items die in Crafting verwendet werden
    if itemId and IsHousingRelated(itemId) and Settings.showBagIcons then
        -- Erstelle Icon wenn noch nicht vorhanden
        if not button.housingIcon then
            -- Erstelle die Texture als Kind des Buttons
            button.housingIcon = button:CreateTexture(nil, "OVERLAY")
            -- Verwende unsere eigene TGA-Datei
            button.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
            button.housingIcon:SetSize(16, 16)
            button.housingIcon:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
            
            -- Setze einen goldenen Farbfilter
            button.housingIcon:SetVertexColor(1, 0.82, 0, 1)  -- Gold
            
            -- Stelle sicher, dass die Texture über allem anderen liegt
            button.housingIcon:SetDrawLayer("OVERLAY", 7)
        end
        button.housingIcon:Show()
    else
        if button.housingIcon then
            button.housingIcon:Hide()
        end
    end
end

-- Update Bank-Buttons (TWW Combined Bank System)
local function UpdateBankItemButton(button)
    if not button or not button.isInitialized then return end
    
    -- Prüfe Settings
    if not Settings.showBagIcons then
        if button.housingIcon then
            button.housingIcon:Hide()
        end
        return
    end
    
    -- Hole Item-ID über BankPanelItemButtonMixin Methoden
    local bankTabID = button.GetBankTabID and button:GetBankTabID()
    local containerSlotID = button.GetContainerSlotID and button:GetContainerSlotID()
    
    if not bankTabID or not containerSlotID then return end
    
    local itemId = C_Container.GetContainerItemID(bankTabID, containerSlotID)
    
    -- Zeige Icon für Housing-relevante Items
    if itemId and IsHousingRelated(itemId) then
        -- Erstelle Icon wenn noch nicht vorhanden
        if not button.housingIcon then
            button.housingIcon = button:CreateTexture(nil, "OVERLAY")
            button.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
            button.housingIcon:SetSize(16, 16)
            button.housingIcon:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
            button.housingIcon:SetVertexColor(1, 0.82, 0, 1)  -- Gold
            button.housingIcon:SetDrawLayer("OVERLAY", 7)
        end
        button.housingIcon:Show()
    else
        if button.housingIcon then
            button.housingIcon:Hide()
        end
    end
end

-- Update Bank-Buttons (TWW Combined Bank System)
local function UpdateBankSlots()
    -- Versuche über BankPanel (neues TWW System)
    if BankFrame and BankFrame.BankPanel then
        local bankPanel = BankFrame.BankPanel
        if bankPanel:IsShown() and bankPanel.EnumerateValidItems then
            for itemButton in bankPanel:EnumerateValidItems() do
                UpdateBankItemButton(itemButton)
            end
        end
    end
    
    -- Fallback: Versuche über Container-Frames
    if ContainerFrameUtil_EnumerateContainerFrames then
        ContainerFrameUtil_EnumerateContainerFrames(function(frame)
            if not frame or not frame:IsShown() then return end
            
            -- Wenn das Frame EnumerateValidItems hat, nutze es
            if frame.EnumerateValidItems then
                for _, itemButton in frame:EnumerateValidItems() do
                    -- Update alle Buttons, egal welcher Bag
                    UpdateBagSlotIcon(itemButton)
                end
            end
        end)
    end
end

-- Einfache direkte Update-Funktion
local function UpdateAllBagSlots()
    -- Methode 1: Versuche ContainerFrameUtil (TWW+)
    if ContainerFrameUtil_EnumerateContainerFrames then
        ContainerFrameUtil_EnumerateContainerFrames(function(frame)
            if frame and frame.EnumerateValidItems then
                for _, itemButton in frame:EnumerateValidItems() do
                    UpdateBagSlotIcon(itemButton)
                end
            end
        end)
    end
    
    -- Methode 2: Update Bank-Slots separat
    UpdateBankSlots()
end

-- Hook für einzelne Bag-Buttons
local function HookBagButton(button)
    if not button or button.housingHooked then return end
    
    -- Hook Update-Events
    if button.UpdateTooltip then
        hooksecurefunc(button, "UpdateTooltip", function(self)
            UpdateBagSlotIcon(self)
        end)
    end
    
    button.housingHooked = true
    UpdateBagSlotIcon(button)
end

-- Hook für Inventar-Slots
local function UpdateInventorySlotIcon(slotId)
    local itemId = GetInventoryItemID("player", slotId)
    local button = _G["CharacterSlot" .. slotId]
    
    if not button then
        -- Versuche alternative Button-Namen
        local slotNames = {
            [1] = "Head", [2] = "Neck", [3] = "Shoulder", [4] = "Shirt", [5] = "Chest",
            [6] = "Waist", [7] = "Legs", [8] = "Feet", [9] = "Wrist", [10] = "Hands",
            [11] = "Finger0", [12] = "Finger1", [13] = "Trinket0", [14] = "Trinket1",
            [15] = "Back", [16] = "MainHand", [17] = "SecondaryHand", [18] = "Ranged", [19] = "Tabard"
        }
        if slotNames[slotId] then
            button = _G["Character" .. slotNames[slotId] .. "Slot"]
        end
    end
    
    if button then
        if itemId and IsUsedInCrafting(itemId) then
            if not button.housingIcon then
                button.housingIcon = button:CreateTexture(nil, "OVERLAY", nil, 7)
                button.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
                button.housingIcon:SetSize(16, 16)
                button.housingIcon:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
                button.housingIcon:SetVertexColor(1, 0.82, 0, 1)  -- Gold
                button.housingIcon:SetDrawLayer("OVERLAY", 7)
            end
            button.housingIcon:Show()
        else
            if button.housingIcon then
                button.housingIcon:Hide()
            end
        end
    end
end

-- Event-Handler
HousingItemTracker:RegisterEvent("ADDON_LOADED")
HousingItemTracker:RegisterEvent("BAG_UPDATE_DELAYED")
HousingItemTracker:RegisterEvent("UNIT_INVENTORY_CHANGED")
HousingItemTracker:RegisterEvent("PLAYER_EQUIPMENT_CHANGED")
HousingItemTracker:RegisterEvent("PLAYERBANKSLOTS_CHANGED")
HousingItemTracker:RegisterEvent("BANKFRAME_OPENED")

-- Hook für Housing Dashboard und andere UI-Tooltips
local function SetupHousingDashboardHooks()
    -- Hook für das Housing Dashboard Catalog Entry Event
    -- Dies ist der offizielle Event-Hook für Housing Catalog Tooltips
    -- Parameter Signatur: caller (CallbackRegistry), catalogEntryFrame, tooltip
    if EventRegistry and not _G.HousingItemTrackerCatalogHooked then
        EventRegistry:RegisterCallback("HousingCatalogEntry.TooltipCreated", function(caller, catalogEntryFrame, tooltip)
            -- caller = die CallbackRegistry (ignorieren)
            -- catalogEntryFrame = der HousingCatalogEntry Frame
            -- tooltip = GameTooltip
            
            -- Prüfe Settings
            if not Settings.showDashboardTooltips then
                return
            end
            
            -- NUR im Housing Dashboard Catalog anzeigen, NICHT im Editor Mode
            -- Prüfe ob wir im House Editor sind
            if C_HouseEditor and C_HouseEditor.IsHouseEditorActive() then
                -- Im Editor Mode - KEINE zusätzlichen Infos anzeigen
                return
            end
            
            if catalogEntryFrame and catalogEntryFrame.entryInfo then
                -- Das entryInfo hat eine decorID für Decor-Items
                local decorID = catalogEntryFrame.entryInfo.entryID and catalogEntryFrame.entryInfo.entryID.recordID
                
                -- Debug: Zeige die decorID
                if decorID then
                    -- Temporäres Debug (kann später entfernt werden)
                    -- print("[Housing] Catalog Entry decorID:", decorID, "Name:", catalogEntryFrame.entryInfo.name)
                    
                    -- Für Decor-Items: Zeige Source-Informationen
                    if DB.decorItems and DB.decorItems[decorID] then
                        AddTooltipInfo(tooltip, decorID)
                    else
                        -- Debug: Item nicht in DB gefunden
                        -- print("[Housing] DecorID", decorID, "nicht in Datenbank gefunden")
                        
                        -- Zeige zumindest eine Basis-Info dass wir es erkannt haben
                        tooltip:AddLine(" ")
                        tooltip:AddLine("|cFF00FF00[Housing Item]|r", 1, 1, 1)
                        tooltip:AddLine("DecorID: " .. decorID, 0.6, 0.6, 0.6)
                    end
                end
            end
        end)
        _G.HousingItemTrackerCatalogHooked = true
    end
    
    -- Hook für Hyperlinks (z.B. im Chat oder anderen UIs)
    if GameTooltip and GameTooltip.SetHyperlink and not GameTooltip.housingHyperlinkHooked then
        hooksecurefunc(GameTooltip, "SetHyperlink", function(self, link)
            if link then
                local itemId = GetItemIdFromLink(link)
                if itemId then
                    -- Kleine Verzögerung damit der Tooltip zuerst gerendert wird
                    C_Timer.After(0.01, function()
                        AddTooltipInfo(self, itemId)
                    end)
                end
            end
        end)
        GameTooltip.housingHyperlinkHooked = true
    end
    
    -- Hook für ItemRefTooltip (wird für Item-Links verwendet)
    if ItemRefTooltip and ItemRefTooltip.SetHyperlink and not ItemRefTooltip.housingHyperlinkHooked then
        hooksecurefunc(ItemRefTooltip, "SetHyperlink", function(self, link)
            if link then
                local itemId = GetItemIdFromLink(link)
                if itemId then
                    C_Timer.After(0.01, function()
                        AddTooltipInfo(self, itemId)
                    end)
                end
            end
        end)
        ItemRefTooltip.housingHyperlinkHooked = true
    end
end

-- Hook für BankPanelItemButtonMixin (Bank und Warband-Bank)
local function SetupBankPanelHooks()
    if not BankPanelItemButtonMixin or _G.HousingItemTrackerBankPanelHooked then
        return
    end
    
    -- Hook für Refresh-Methode der Bank-Buttons
    if BankPanelItemButtonMixin.Refresh then
        hooksecurefunc(BankPanelItemButtonMixin, "Refresh", function(self)
            -- Update Icon wenn Button aktualisiert wird
            UpdateBankItemButton(self)
        end)
    end
    
    -- Hook für BankPanel Refresh (wenn Tab gewechselt wird)
    if BankPanelMixin and BankPanelMixin.RefreshBankPanel then
        hooksecurefunc(BankPanelMixin, "RefreshBankPanel", function(self)
            -- Update alle Bank-Buttons nach kurzer Verzögerung
            C_Timer.After(0.1, function()
                if self:IsShown() and self.EnumerateValidItems then
                    for itemButton in self:EnumerateValidItems() do
                        UpdateBankItemButton(itemButton)
                    end
                end
            end)
        end)
    end
    
    -- Hook für GenerateItemSlotsForSelectedTab (wenn neue Buttons erstellt werden)
    if BankPanelMixin and BankPanelMixin.GenerateItemSlotsForSelectedTab then
        hooksecurefunc(BankPanelMixin, "GenerateItemSlotsForSelectedTab", function(self)
            -- Update alle Bank-Buttons nach kurzer Verzögerung
            C_Timer.After(0.1, function()
                if self:IsShown() and self.EnumerateValidItems then
                    for itemButton in self:EnumerateValidItems() do
                        UpdateBankItemButton(itemButton)
                    end
                end
            end)
        end)
    end
    
    -- Hook für BankFrame OnShow (wenn Bank geöffnet wird)
    if BankFrame and BankFrame.SetScript then
        BankFrame:HookScript("OnShow", function(self)
            -- Update alle Bank-Buttons nach kurzer Verzögerung
            C_Timer.After(0.2, function()
                UpdateBankSlots()
            end)
        end)
    end
    
    -- Hook für BankPanel OnShow (wenn Panel angezeigt wird)
    if BankPanelMixin and BankPanelMixin.OnShow then
        -- Versuche BankPanel zu finden
        if BankFrame and BankFrame.BankPanel then
            local bankPanel = BankFrame.BankPanel
            if bankPanel.SetScript then
                bankPanel:HookScript("OnShow", function(self)
                    -- Update alle Bank-Buttons nach kurzer Verzögerung
                    C_Timer.After(0.2, function()
                        if self:IsShown() and self.EnumerateValidItems then
                            for itemButton in self:EnumerateValidItems() do
                                UpdateBankItemButton(itemButton)
                            end
                        end
                    end)
                end)
            end
        end
    end
    
    _G.HousingItemTrackerBankPanelHooked = true
end

-- Hook für MerchantFrame (Händler) - Zeige Housing-Icons
local function SetupMerchantFrameHooks()
    if not MerchantFrame or _G.HousingItemTrackerMerchantHooked then
        return
    end
    
    -- Definiere Konstanten falls nicht vorhanden (Fallback)
    local merchantItemsPerPage = MERCHANT_ITEMS_PER_PAGE or 10
    local buybackItemsPerPage = BUYBACK_ITEMS_PER_PAGE or 12
    
    -- Hook MerchantFrame_UpdateMerchantInfo um Icons hinzuzufügen
    hooksecurefunc("MerchantFrame_UpdateMerchantInfo", function()
        if not Settings.showBagIcons then
            -- Verstecke alle Icons wenn deaktiviert
            for i = 1, merchantItemsPerPage do
                local itemButton = _G["MerchantItem"..i.."ItemButton"]
                if itemButton and itemButton.housingIcon then
                    itemButton.housingIcon:Hide()
                end
            end
            return
        end
        
        local numMerchantItems = GetMerchantNumItems()
        
        for i = 1, merchantItemsPerPage do
            local index = (((MerchantFrame.page - 1) * merchantItemsPerPage) + i)
            local itemButton = _G["MerchantItem"..i.."ItemButton"]
            
            if itemButton and index <= numMerchantItems then
                local itemLink = GetMerchantItemLink(index)
                if itemLink then
                    local itemId = GetItemIdFromLink(itemLink)
                    
                    if itemId and IsHousingRelated(itemId) then
                        -- Erstelle Icon wenn noch nicht vorhanden
                        if not itemButton.housingIcon then
                            itemButton.housingIcon = itemButton:CreateTexture(nil, "OVERLAY")
                            itemButton.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
                            itemButton.housingIcon:SetSize(16, 16)
                            -- Positioniere es oben rechts, ähnlich wie das Quest-Icon
                            itemButton.housingIcon:SetPoint("TOPRIGHT", itemButton, "TOPRIGHT", 0, 0)
                            itemButton.housingIcon:SetVertexColor(1, 0.82, 0, 1)  -- Gold
                            itemButton.housingIcon:SetDrawLayer("OVERLAY", 7)
                        end
                        itemButton.housingIcon:Show()
                    else
                        if itemButton.housingIcon then
                            itemButton.housingIcon:Hide()
                        end
                    end
                else
                    if itemButton.housingIcon then
                        itemButton.housingIcon:Hide()
                    end
                end
            else
                if itemButton and itemButton.housingIcon then
                    itemButton.housingIcon:Hide()
                end
            end
        end
    end)
    
    -- Hook auch für Buyback-Items
    hooksecurefunc("MerchantFrame_UpdateBuybackInfo", function()
        if not Settings.showBagIcons then
            return
        end
        
        local numBuybackItems = GetNumBuybackItems()
        
        for i = 1, buybackItemsPerPage do
            local itemButton = _G["MerchantItem"..i.."ItemButton"]
            
            if itemButton and i <= numBuybackItems then
                local itemLink = GetBuybackItemLink(i)
                if itemLink then
                    local itemId = GetItemIdFromLink(itemLink)
                    
                    if itemId and IsHousingRelated(itemId) then
                        if not itemButton.housingIcon then
                            itemButton.housingIcon = itemButton:CreateTexture(nil, "OVERLAY")
                            itemButton.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
                            itemButton.housingIcon:SetSize(16, 16)
                            itemButton.housingIcon:SetPoint("TOPRIGHT", itemButton, "TOPRIGHT", 0, 0)
                            itemButton.housingIcon:SetVertexColor(1, 0.82, 0, 1)  -- Gold
                            itemButton.housingIcon:SetDrawLayer("OVERLAY", 7)
                        end
                        itemButton.housingIcon:Show()
                    else
                        if itemButton.housingIcon then
                            itemButton.housingIcon:Hide()
                        end
                    end
                else
                    if itemButton.housingIcon then
                        itemButton.housingIcon:Hide()
                    end
                end
            else
                if itemButton and itemButton.housingIcon then
                    itemButton.housingIcon:Hide()
                end
            end
        end
    end)
    
    _G.HousingItemTrackerMerchantHooked = true
end

HousingItemTracker:SetScript("OnEvent", function(self, event, ...)
    if event == "ADDON_LOADED" then
        local loadedAddon = select(1, ...)
        
        if loadedAddon == addonName then
            -- Setup Tooltip-Hooks
            SetupTooltipHooks()
            
            -- Setup Housing Dashboard Hooks (verzögert)
            C_Timer.After(1, SetupHousingDashboardHooks)
            C_Timer.After(3, SetupHousingDashboardHooks) -- Nochmal später für sicheren Hook
            
            -- Setup MerchantFrame Hooks (verzögert, damit MerchantFrame geladen ist)
            C_Timer.After(1, SetupMerchantFrameHooks)
            C_Timer.After(3, SetupMerchantFrameHooks) -- Nochmal später für sicheren Hook
            
            -- Setup BankPanel Hooks (verzögert, damit BankFrame geladen ist)
            C_Timer.After(1, SetupBankPanelHooks)
            C_Timer.After(3, SetupBankPanelHooks) -- Nochmal später für sicheren Hook
            
            -- Zähle Items in der Datenbank
            local materialCount = 0
            for _ in pairs(DB.materials) do
                materialCount = materialCount + 1
            end
            
            local decorCount = 0
            if DB.decorItems then
                for _ in pairs(DB.decorItems) do
                    decorCount = decorCount + 1
                end
            end
            
            -- Zeige Lade-Nachricht im Chat
            print("|cFF00FF00===================================|r")
            print("|cFF00FF00Housing Item Tracker|r |cFFFFFFFFv" .. HousingItemTrackerDB.version .. "|r")
            print("|cFFFFFFFF" .. L["LOADED_SUCCESSFULLY"] .. "|r")
            print("|cFFFFFFFF" .. decorCount .. " " .. L["DECOR_ITEMS"] .. "|r")
            print("|cFFFFFFFF" .. materialCount .. " " .. L["CRAFTING_MATERIALS"] .. "|r")
            print("|cFF00FF00===================================|r")
            print(" ")
            print("|cFF88AAFF" .. L["NEW_ADDON_IDEAS"] .. "|r")
            print("|cFFFFFFFF" .. L["VISIT"] .. "|r |cFF00FF00https://www.addon-forge.de/|r")
            print(" ")
            
            -- Initiales Update nach kurzer Verzögerung
            C_Timer.After(1, function()
                UpdateAllBagSlots()
                for slotId = 1, 19 do
                    UpdateInventorySlotIcon(slotId)
                end
            end)
        end
    elseif event == "BAG_UPDATE_DELAYED" then
        -- Update alle Bag-Slots wenn sich was ändert
        -- Warte einen kurzen Moment, damit andere Addons ihre Frames aktualisieren können
        C_Timer.After(0.1, function()
            if ContainerFrameUtil_EnumerateContainerFrames then
                ContainerFrameUtil_EnumerateContainerFrames(function(frame)
                    if frame and frame:IsShown() then
                        for _, itemButton in frame:EnumerateValidItems() do
                            UpdateBagSlotIcon(itemButton)
                        end
                    end
                end)
            end
            
            -- Update auch Bank-Slots
            UpdateBankSlots()
        end)
    elseif event == "UNIT_INVENTORY_CHANGED" then
        local unit = select(1, ...)
        if unit == "player" then
            -- Update alle Inventar-Slots
            for slotId = 1, 19 do
                UpdateInventorySlotIcon(slotId)
            end
        end
    elseif event == "PLAYER_EQUIPMENT_CHANGED" then
        local slotId = select(1, ...)
        if slotId then
            UpdateInventorySlotIcon(slotId)
        end
    elseif event == "PLAYERBANKSLOTS_CHANGED" or event == "BANKFRAME_OPENED" then
        -- Update Bank-Icons mit mehreren Versuchen
        C_Timer.After(0.1, UpdateBankSlots)
        C_Timer.After(0.3, UpdateBankSlots)
        C_Timer.After(0.5, UpdateBankSlots)
    end
end)

-- Hook für Container-Frames (modernes System wie Pawn)
local function HookContainerFrame(frame)
    if not frame or frame.housingHooked then return end
    
    if frame.UpdateItems then
        hooksecurefunc(frame, "UpdateItems", function(self)
            if self.EnumerateValidItems then
                for _, itemButton in self:EnumerateValidItems() do
                    UpdateBagSlotIcon(itemButton)
                end
            end
        end)
    end
    
    -- Zusätzlicher Hook für Show-Event (wichtig für Bank)
    if frame.SetScript then
        frame:HookScript("OnShow", function(self)
            C_Timer.After(0.1, function()
                if self:IsShown() and self.EnumerateValidItems then
                    for _, itemButton in self:EnumerateValidItems() do
                        UpdateBagSlotIcon(itemButton)
                    end
                end
            end)
        end)
    end
    
    frame.housingHooked = true
end

-- Hook alle Container-Frames und Combined Bags
C_Timer.After(1, function()
    -- Hook Combined Bags (TWW+)
    if ContainerFrameCombinedBags then
        HookContainerFrame(ContainerFrameCombinedBags)
    end
    
    -- Hook Reagent Bag (ContainerFrame6)
    if _G["ContainerFrame6"] then
        HookContainerFrame(_G["ContainerFrame6"])
    end
    
    -- Hook Bank Frames (ContainerFrame7-13 sind Bank-Slots)
    -- ContainerFrame7 = Bank Hauptfach, ContainerFrame8-13 = Bank Bag Slots 1-6
    for i = 7, 13 do
        local frame = _G["ContainerFrame" .. i]
        if frame then
            HookContainerFrame(frame)
        end
    end
    
    -- Hook Combined Bank Frame (TWW+)
    if BankFrame then
        HookContainerFrame(BankFrame)
    end
    
    -- Hook einzelne Bag-Frames (ContainerFrame1-5)
    for i = 1, 5 do
        local frame = _G["ContainerFrame" .. i]
        if frame then
            HookContainerFrame(frame)
        end
    end
    
    -- Hook auch über ContainerFrameUtil falls verfügbar
    if ContainerFrameUtil_EnumerateContainerFrames then
        ContainerFrameUtil_EnumerateContainerFrames(HookContainerFrame)
    end
    
    -- Initiales Update
    UpdateAllBagSlots()
end)


-- Slash-Command zum manuellen Update
SLASH_HOUSINGITEMTRACKER1 = "/hit"
SLASH_HOUSINGITEMTRACKER2 = "/housingitemtracker"
SlashCmdList["HOUSINGITEMTRACKER"] = function(msg)
    if msg == "update" or msg == "" then
        print("|cFF00FF00Housing Item Tracker:|r Aktualisiere Icons...")
        UpdateAllBagSlots()
        for slotId = 1, 19 do
            UpdateInventorySlotIcon(slotId)
        end
    elseif msg == "debug" then
        print("|cFF00FF00Housing Item Tracker Debug:|r")
        print("ContainerFrameUtil_EnumerateContainerFrames: " .. tostring(ContainerFrameUtil_EnumerateContainerFrames ~= nil))
        print("DB.materials hat Einträge: " .. tostring(next(DB.materials) ~= nil))
        
        -- Teste ein bekanntes Item
        local testItemId = 2325 -- Erstes Item in der DB
        print("Test Item 2325 ist Housing Item: " .. tostring(IsUsedInCrafting(testItemId)))
    elseif msg == "test" then
        print("|cFF00FF00Housing Item Tracker:|r Teste Icon-System...")
        UpdateAllBagSlots()
        print("Icons aktualisiert!")
    elseif msg == "bank" then
        print("|cFF00FF00Housing Item Tracker:|r Teste Bank-Buttons...")
        
        -- Teste Bank Hauptfach
        for slotID = 1, 28 do
            local button = _G["BankFrameItem" .. slotID]
            if button then
                print("BankFrameItem" .. slotID .. " gefunden")
                local itemId = C_Container.GetContainerItemID(-1, slotID)
                if itemId then
                    print("  Item: " .. itemId .. " - Housing: " .. tostring(IsUsedInCrafting(itemId)))
                end
            else
                print("BankFrameItem" .. slotID .. " NICHT gefunden")
            end
        end
        
        -- Teste Bank Bags
        for bagID = 5, 11 do
            local numSlots = C_Container.GetContainerNumSlots(bagID)
            if numSlots and numSlots > 0 then
                print("Bank Bag " .. bagID .. " hat " .. numSlots .. " Slots")
                for slotID = 1, math.min(5, numSlots) do
                    local buttonName = "ContainerFrame" .. (bagID + 2) .. "Item" .. slotID
                    local button = _G[buttonName]
                    if button then
                        print("  " .. buttonName .. " gefunden")
                    else
                        print("  " .. buttonName .. " NICHT gefunden")
                    end
                end
            end
        end
        
        UpdateBankSlots()
        print("Bank-Icons aktualisiert!")
    else
        print("|cFF00FF00Housing Item Tracker Befehle:|r")
        print("/hit update - Icons aktualisieren")
        print("/hit debug - Debug-Informationen anzeigen")
        print("/hit test - Test-Icon auf erstem Bag-Slot erstellen")
        print("/hit bank - Bank-Buttons testen und Icons aktualisieren")
    end
end

