-- 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:"
L["DECOR_ICON_SETTINGS"] = "Decor-Icon Einstellungen"       
L["ICON_SIZE"] = "Icon Size"
L["ICON_BRIGHTNESS"] = "Icon Brightness"
L["ICON_COLOR_R"] = "Icon Color Red"
L["ICON_COLOR_G"] = "Icon Color Green"
L["ICON_COLOR_B"] = "Icon Color Blue"
L["ICON_COLOR"] = "Icon Color"
L["SHOW_BAG_ICONS"] = "Show Icons in Bags"
L["SHOW_MATERIAL_TOOLTIPS"] = "Show Tooltips for Materials"
L["SHOW_VENDOR_MAPS"] = "Show Vendor Maps"
L["SHOW_DASHBOARD_TOOLTIPS"] = "Show Tooltips in Housing Dashboard"
L["SAVE"] = "Save"
L["RELOAD"] = "Reload UI"
L["CLOSE"] = "Close"
L["UPDATE_ICONS"] = "Update Icons"
L["REOPEN_BAGS_HINT"] = "Hinweis: Taschen nach dem Update erneut öffnen"
-- German
if GetLocale() == "deDE" then
    L["HOUSING"] = "Behausung"
    L["USED_IN_CRAFTING"] = "Verwendet für Behausung-Rezepte"
    L["DECOR_COST"] = "Deko-Kosten"
    L["DECOR_ICON_SETTINGS"] = "Decor-Icon Einstellungen"
    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:"
    L["DECOR_ICON_SETTINGS"] = "Decor-Icon Einstellungen"
    L["ICON_SIZE"] = "Icon-Größe"
    L["ICON_BRIGHTNESS"] = "Icon-Helligkeit"
    L["ICON_COLOR_R"] = "Icon-Farbe Rot"
    L["ICON_COLOR_G"] = "Icon-Farbe Grün"
    L["ICON_COLOR_B"] = "Icon-Farbe Blau"
    L["ICON_COLOR"] = "Icon-Farbe"
    L["SHOW_BAG_ICONS"] = "Icons in Taschen anzeigen"
    L["SHOW_MATERIAL_TOOLTIPS"] = "Tooltips für Materials anzeigen"
    L["SHOW_VENDOR_MAPS"] = "Vendor-Karten anzeigen"
    L["SHOW_DASHBOARD_TOOLTIPS"] = "Tooltips im Housing Dashboard anzeigen"
    L["SAVE"] = "Speichern"
    L["RELOAD"] = "UI neu laden"
    L["CLOSE"] = "Schließen"
    L["UPDATE_ICONS"] = "Icons aktualisieren"
    L["REOPEN_BAGS_HINT"] = "Hinweis: Taschen nach dem Update erneut öffnen"
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["DECOR_ICON_SETTINGS"] = "Paramètres des icônes 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 :"
    L["UPDATE_ICONS"] = "Mettre à jour les icônes"
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["DECOR_ICON_SETTINGS"] = "Configuración de iconos 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:"
    L["UPDATE_ICONS"] = "Actualizar iconos"
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
    print("HousingItemTrackerDB not found, creating default database")
    HousingItemTrackerDB = {
        version = 2,
        items = {
            materials = {},
            decorItems = {},
            achievements = {},
            quests = {},
        },
    }
end

-- Settings/Optionen (Saved Variables)
if not HousingItemTrackerSettings then
    print("HousingItemTrackerSettings not found, creating default settings")
    HousingItemTrackerSettings = {}
end

-- Initialisiere Standardwerte falls nicht vorhanden
-- WICHTIG: Diese Funktion wird NUR im ADDON_LOADED Event aufgerufen,
-- damit die SavedVariables bereits geladen sind!
local function InitializeSettings()
    -- Prüfe und setze nur fehlende Werte, überschreibe niemals vorhandene Werte!
    if HousingItemTrackerSettings.showMaterialTooltips == nil then
        HousingItemTrackerSettings.showMaterialTooltips = true
    end
    if HousingItemTrackerSettings.showVendorMaps == nil then
        HousingItemTrackerSettings.showVendorMaps = true
    end
    if HousingItemTrackerSettings.showBagIcons == nil then
        HousingItemTrackerSettings.showBagIcons = true
    end
    if HousingItemTrackerSettings.showDashboardTooltips == nil then
        HousingItemTrackerSettings.showDashboardTooltips = true
    end
    if HousingItemTrackerSettings.iconSize == nil then
        HousingItemTrackerSettings.iconSize = 20
    end
    if HousingItemTrackerSettings.iconColorR == nil then
        HousingItemTrackerSettings.iconColorR = 1.0
    end
    if HousingItemTrackerSettings.iconColorG == nil then
        HousingItemTrackerSettings.iconColorG = 1.0
    end
    if HousingItemTrackerSettings.iconColorB == nil then
        HousingItemTrackerSettings.iconColorB = 1.0
    end
end

local DB = HousingItemTrackerDB.items
-- WICHTIG: Settings wird erst nach ADDON_LOADED korrekt gesetzt
-- Verwende HousingItemTrackerSettings direkt oder warte auf ADDON_LOADED
local Settings = HousingItemTrackerSettings

-- Helper function: Check if an itemId is in the database (any category)
local function IsItemInDatabase(itemId)
    if not itemId then return false end
    
    -- Check materials
    if DB.materials and DB.materials[itemId] == true then
        return true
    end
    
    -- Check manual materials
    if DB.manualMaterials and DB.manualMaterials[itemId] == true then
        return true
    end
    
    -- Check decor items
    if DB.decorItems and DB.decorItems[itemId] ~= nil then
        return true
    end
    
    -- Check if used in crafting
    if DB.decorItems then
        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
    end
    
    return false
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

-- 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

-- Prüft ob ein Item ein manuell hinzugefügtes Material ist
local function IsManualMaterial(itemId)
    if not itemId then return false end

    if DB.manualMaterials then
        -- Zähle Einträge in manualMaterials
        local count = 0
        for k, v in pairs(DB.manualMaterials) do
            count = count + 1
            if count <= 5 then  -- Zeige nur die ersten 5
            end
        end
   
    end
    local result = DB.manualMaterials and DB.manualMaterials[itemId] == true
    
    return result
end

-- Kombinierte Prüfung: Ist es ein Housing-relevantes Item?
-- Prüft auch Quality-Varianten (itemId-1, itemId-2)
local function IsHousingRelated(itemId)
    if not itemId then return false end
    
    if DB.materials then
        -- Zähle Einträge in materials (nur einmal beim ersten Aufruf)
        if not _materialsCountLogged then
            local count = 0
            for k, v in pairs(DB.materials) do
                count = count + 1
                if count <= 5 then  -- Zeige nur die ersten 5
                end
            end

            _materialsCountLogged = true
        end
    end
    
    -- Check the item itself
    if IsItemInDatabase(itemId) then
        return true
    end
    
    -- Check for quality variants (itemId-1, itemId-2)
    -- Items with quality tiers have consecutive IDs (e.g., 222417, 222418, 222419)
    -- If the base item is in DB, the higher quality variants should also be recognized
    for offset = 1, 2 do
        if IsItemInDatabase(itemId - offset) then
            return true
        end
    end
    
    return false
end

-- Prüft ob ein Decor-Item bereits in der Sammlung ist
local function IsDecorCollected(decorId)
    if not decorId then return false end
    
    -- Nutze die WoW API um zu prüfen ob das Item gesammelt wurde
    if C_HouseDecor and C_HouseDecor.IsPlayerDecorCollected then
        return C_HouseDecor.IsPlayerDecorCollected(decorId)
    end
    
    return false
end

-- Gibt die Icon-Farbe basierend auf dem Collection-Status zurück
-- Decor-Items: Grün wenn gesammelt, Orange wenn nicht gesammelt
-- Material-Items: Immer Gold
-- Manuelle Material-Items: Blau
local function GetHousingIconColor(itemId)
    -- Farb-Multiplikatoren aus Settings
    local colorR = Settings.iconColorR or 1.0
    local colorG = Settings.iconColorG or 1.0
    local colorB = Settings.iconColorB or 1.0

    local r, g, b
    
    -- -- Prüfe zuerst ob es ein manuell hinzugefügtes Material ist (höchste Priorität)
    -- if IsManualMaterial(itemId) then
    --     -- Blau für manuell hinzugefügte Material-Items
    --     r, g, b = colorR, colorG, colorB
    -- -- Prüfe ob es ein Decor-Item ist
    -- elseif IsDecorItem(itemId) then
    --     if IsDecorCollected(itemId) then
    --         -- Grün für bereits gesammelte Decor-Items
    --         r, g, b = colorR, colorG, colorB
    --     else
    --         -- Orange für noch nicht gesammelte Decor-Items
    --         r, g, b = colorR, colorG, colorB
    --     end
    -- else
    --     -- Gold für Material-Items (Standard)
    --     r, g, b = colorR, colorG, colorB
    -- end
    
    -- Wende Farb-Multiplikatoren an
    -- return r * colorR, g * colorG, b * colorB, 1
    return colorR, colorG, colorB, 1
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 Collection-Status für Decor-Items
            if C_HouseDecor and C_HouseDecor.IsPlayerDecorCollected then
                local isCollected = C_HouseDecor.IsPlayerDecorCollected(itemId)
                if isCollected then
                    tooltip:AddLine("|cFF00FF00✓ Bereits gesammelt|r", 0.5, 1, 0.5)
                else
                    tooltip:AddLine("|cFFFF6600Noch nicht gesammelt|r", 1, 0.4, 0)
                end
            end
                    
            -- -- 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")
            local iconSize = Settings.iconSize or 20
            button.housingIcon:SetSize(iconSize, iconSize)
            button.housingIcon:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
            
            -- Stelle sicher, dass die Texture über allem anderen liegt
            button.housingIcon:SetDrawLayer("OVERLAY", 7)
            -- WICHTIG: SetBlendMode muss auf BLEND gesetzt sein, damit SetVertexColor funktioniert
            button.housingIcon:SetBlendMode("BLEND")
        end
        
        -- Aktualisiere Größe falls sich geändert hat
        local iconSize = Settings.iconSize or 20
        button.housingIcon:SetSize(iconSize, iconSize)
        
        -- Setze Farbe basierend auf Collection-Status
        local r, g, b, a = GetHousingIconColor(itemId)
        -- WICHTIG: SetVertexColor funktioniert nur, wenn die TGA weiß/grau ist
        -- Wenn die TGA bereits farbig ist, wird die Farbe nicht angewendet
        button.housingIcon:SetVertexColor(r, g, b, a)
        
        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")
            local iconSize = Settings.iconSize or 20
            button.housingIcon:SetSize(iconSize, iconSize)
            button.housingIcon:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
            button.housingIcon:SetDrawLayer("OVERLAY", 7)
            -- WICHTIG: SetBlendMode muss auf BLEND gesetzt sein, damit SetVertexColor funktioniert
            button.housingIcon:SetBlendMode("BLEND")
        end
        
        -- Aktualisiere Größe falls sich geändert hat
        local iconSize = Settings.iconSize or 20
        button.housingIcon:SetSize(iconSize, iconSize)
        
        -- Setze Farbe basierend auf Collection-Status
        local r, g, b, a = GetHousingIconColor(itemId)
        -- WICHTIG: SetVertexColor funktioniert nur, wenn die TGA weiß/grau ist
        button.housingIcon:SetVertexColor(r, g, b, a)
        
        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 IsHousingRelated(itemId) then
            if not button.housingIcon then
                button.housingIcon = button:CreateTexture(nil, "OVERLAY", nil, 7)
                button.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
                local iconSize = Settings.iconSize or 20
                button.housingIcon:SetSize(iconSize, iconSize)
                button.housingIcon:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
                button.housingIcon:SetDrawLayer("OVERLAY", 7)
                -- WICHTIG: SetBlendMode muss auf BLEND gesetzt sein, damit SetVertexColor funktioniert
                button.housingIcon:SetBlendMode("BLEND")
            end
            
            -- Aktualisiere Größe falls sich geändert hat
            local iconSize = Settings.iconSize or 20
            button.housingIcon:SetSize(iconSize, iconSize)
            
            -- Setze Farbe basierend auf Collection-Status
            local r, g, b, a = GetHousingIconColor(itemId)
            -- WICHTIG: SetVertexColor funktioniert nur, wenn die TGA weiß/grau ist
            button.housingIcon:SetVertexColor(r, g, b, a)
        
            button.housingIcon:Show()
        else
            if button.housingIcon then
                button.housingIcon:Hide()
            end
        end
    end
end

-- Zentrale Funktion zum Aktualisieren aller Icons (inkl. Merchant-Frames)
local function UpdateAllIcons()

    UpdateAllBagSlots()
    UpdateBankSlots()
    for slotId = 1, 19 do
        UpdateInventorySlotIcon(slotId)
    end
    
    -- Aktualisiere Merchant-Frames falls geöffnet
    if MerchantFrame and MerchantFrame:IsShown() then
        if MerchantFrame_UpdateMerchantInfo then
            MerchantFrame_UpdateMerchantInfo()
        end
        if MerchantFrame_UpdateBuybackInfo then
            MerchantFrame_UpdateBuybackInfo()
        end
    end
    
    -- Aktualisiere Integration-Bag-Addons (Bagnon, AdiBags, etc.)
    if _G.HousingItemTrackerUpdateIntegrationIcons then
        _G.HousingItemTrackerUpdateIntegrationIcons()
    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")
                            local iconSize = Settings.iconSize or 20
                            itemButton.housingIcon:SetSize(iconSize, iconSize)
                            -- Positioniere es oben rechts, ähnlich wie das Quest-Icon
                            itemButton.housingIcon:SetPoint("TOPRIGHT", itemButton, "TOPRIGHT", 0, 0)
                            itemButton.housingIcon:SetDrawLayer("OVERLAY", 7)
                            -- WICHTIG: SetBlendMode muss auf BLEND gesetzt sein, damit SetVertexColor funktioniert
                            itemButton.housingIcon:SetBlendMode("BLEND")
                        end
                        
                        -- Aktualisiere Größe falls sich geändert hat
                        local iconSize = Settings.iconSize or 20
                        itemButton.housingIcon:SetSize(iconSize, iconSize)
                        
                        -- Setze Farbe basierend auf Collection-Status
                        local r, g, b, a = GetHousingIconColor(itemId)
                        -- WICHTIG: SetVertexColor funktioniert nur, wenn die TGA weiß/grau ist
                        itemButton.housingIcon:SetVertexColor(r, g, b, a)
                        
                        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")
                            local iconSize = Settings.iconSize or 20
                            itemButton.housingIcon:SetSize(iconSize, iconSize)
                            itemButton.housingIcon:SetPoint("TOPRIGHT", itemButton, "TOPRIGHT", 0, 0)
                            itemButton.housingIcon:SetDrawLayer("OVERLAY", 7)
                        end
                        
                        -- Aktualisiere Größe falls sich geändert hat
                        local iconSize = Settings.iconSize or 20
                        itemButton.housingIcon:SetSize(iconSize, iconSize)
                        
                        -- Setze Farbe basierend auf Collection-Status
                        local r, g, b, a = GetHousingIconColor(itemId)
                        itemButton.housingIcon:SetVertexColor(r, g, b, a)
                        
                        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
            -- WICHTIG: Jetzt sind die SavedVariables geladen!
            -- Initialisiere Settings NUR mit Standardwerten für fehlende Einträge
            InitializeSettings()
            
            -- Aktualisiere lokale Referenz nach dem Laden
            Settings = HousingItemTrackerSettings
            
            print("|cFF00FF00[HousingItemTracker] Restoring materials from .lua file...|r")
            
            -- Stelle die materials-Liste aus der .lua Datei wieder her
            -- (SavedVariables könnten die Definitionen überschrieben haben)
            if _HousingItemTrackerMaterialsFromLua and HousingItemTrackerDB.items then
                print("  -> _HousingItemTrackerMaterialsFromLua exists, count:", 0) -- Wir können nicht einfach zählen
                local count = 0
                for k, v in pairs(_HousingItemTrackerMaterialsFromLua) do
                    count = count + 1
                end
                print("  -> _HousingItemTrackerMaterialsFromLua has", count, "entries")
                
                -- Merge: Behalte manuelle Einträge in SavedVariables, füge aber alle aus .lua hinzu
                if not HousingItemTrackerDB.items.materials then
                    HousingItemTrackerDB.items.materials = {}
                    print("  -> Created new materials table")
                end
                -- Kopiere alle Einträge aus der .lua Datei (überschreibt alte Einträge)
                local copied = 0
                for itemId, value in pairs(_HousingItemTrackerMaterialsFromLua) do
                    HousingItemTrackerDB.items.materials[itemId] = value
                    copied = copied + 1
                end
                print("  -> Copied", copied, "entries to DB.materials")
            else
                print("  -> _HousingItemTrackerMaterialsFromLua does NOT exist!")
            end
            
            -- Stelle die manualMaterials-Liste aus der .lua Datei wieder her
            -- (SavedVariables könnten die Definitionen überschrieben haben)
            if _HousingItemTrackerManualMaterialsFromLua and HousingItemTrackerDB.items then
                print("  -> _HousingItemTrackerManualMaterialsFromLua exists")
                local count = 0
                for k, v in pairs(_HousingItemTrackerManualMaterialsFromLua) do
                    count = count + 1
                end
                print("  -> _HousingItemTrackerManualMaterialsFromLua has", count, "entries")
                
                -- Merge: Behalte manuelle Einträge in SavedVariables, füge aber alle aus .lua hinzu
                if not HousingItemTrackerDB.items.manualMaterials then
                    HousingItemTrackerDB.items.manualMaterials = {}
                    print("  -> Created new manualMaterials table")
                end
                -- Kopiere alle Einträge aus der .lua Datei (überschreibt alte Einträge)
                local copied = 0
                for itemId, value in pairs(_HousingItemTrackerManualMaterialsFromLua) do
                    HousingItemTrackerDB.items.manualMaterials[itemId] = value
                    copied = copied + 1
                end
                print("  -> Copied", copied, "entries to DB.manualMaterials")
            else
                print("  -> _HousingItemTrackerManualMaterialsFromLua does NOT exist!")
            end
            
            -- Debug: Zeige DB-Status
            if DB.materials then
                local count = 0
                for k, v in pairs(DB.materials) do
                    count = count + 1
                end

            end
            if DB.manualMaterials then
                local count = 0
                for k, v in pairs(DB.manualMaterials) do
                    count = count + 1
                end
            end

            -- 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)

-- Options-Menü Frame
local OptionsMenuFrame = CreateFrame("Frame", "HousingItemTrackerOptionsMenu", UIParent)
OptionsMenuFrame:SetSize(450, 450)
OptionsMenuFrame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
OptionsMenuFrame:Hide()
OptionsMenuFrame:SetFrameStrata("DIALOG")
OptionsMenuFrame:SetFrameLevel(1000)
OptionsMenuFrame:SetMovable(true)
OptionsMenuFrame:EnableMouse(true)
OptionsMenuFrame:RegisterForDrag("LeftButton")
OptionsMenuFrame:SetScript("OnDragStart", function(self) self:StartMoving() end)
OptionsMenuFrame:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)

-- Background
OptionsMenuFrame.bg = OptionsMenuFrame:CreateTexture(nil, "BACKGROUND")
OptionsMenuFrame.bg:SetAllPoints()
OptionsMenuFrame.bg:SetColorTexture(0.1, 0.1, 0.1, 0.95)

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

-- Title
OptionsMenuFrame.title = OptionsMenuFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
OptionsMenuFrame.title:SetPoint("TOP", 0, -15)
OptionsMenuFrame.title:SetText("|cFF00FF00Housing Item Tracker|r")

-- Subtitle
OptionsMenuFrame.subtitle = OptionsMenuFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
OptionsMenuFrame.subtitle:SetPoint("TOP", OptionsMenuFrame.title, "BOTTOM", 0, -5)
OptionsMenuFrame.subtitle:SetText(L["DECOR_ICON_SETTINGS"])

-- Icon-Größe Label
OptionsMenuFrame.sizeLabel = OptionsMenuFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
OptionsMenuFrame.sizeLabel:SetPoint("TOP", OptionsMenuFrame.subtitle, "BOTTOM", 0, -25)
OptionsMenuFrame.sizeLabel:SetText(L["ICON_SIZE"] .. ":")

-- Icon-Größe Value
OptionsMenuFrame.sizeValue = OptionsMenuFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
OptionsMenuFrame.sizeValue:SetPoint("LEFT", OptionsMenuFrame.sizeLabel, "RIGHT", 10, 0)

-- Icon-Größe Slider
OptionsMenuFrame.sizeSlider = CreateFrame("Slider", nil, OptionsMenuFrame, "OptionsSliderTemplate")
OptionsMenuFrame.sizeSlider:SetPoint("TOP", OptionsMenuFrame.sizeLabel, "BOTTOM", 0, -10)
OptionsMenuFrame.sizeSlider:SetMinMaxValues(10, 40)
OptionsMenuFrame.sizeSlider:SetValueStep(1)
OptionsMenuFrame.sizeSlider:SetObeyStepOnDrag(true)
OptionsMenuFrame.sizeSlider:SetWidth(280)
-- Zentriere den Slider
OptionsMenuFrame.sizeSlider:ClearAllPoints()
OptionsMenuFrame.sizeSlider:SetPoint("TOP", OptionsMenuFrame.sizeLabel, "BOTTOM", 0, -10)
OptionsMenuFrame.sizeSlider.Low:SetText("10")
OptionsMenuFrame.sizeSlider.High:SetText("40")

-- Color Picker Label
OptionsMenuFrame.colorLabel = OptionsMenuFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
OptionsMenuFrame.colorLabel:SetPoint("TOP", OptionsMenuFrame.sizeSlider, "BOTTOM", 0, -30)
OptionsMenuFrame.colorLabel:SetText(L["ICON_COLOR"] .. ":")

-- Color Picker Button
OptionsMenuFrame.colorPickerButton = CreateFrame("Button", nil, OptionsMenuFrame)
OptionsMenuFrame.colorPickerButton:SetSize(200, 30)
OptionsMenuFrame.colorPickerButton:SetPoint("TOP", OptionsMenuFrame.colorLabel, "BOTTOM", 0, -5)

-- Background für Color Picker Button
OptionsMenuFrame.colorPickerButton.bg = OptionsMenuFrame.colorPickerButton:CreateTexture(nil, "BACKGROUND")
OptionsMenuFrame.colorPickerButton.bg:SetAllPoints()
OptionsMenuFrame.colorPickerButton.bg:SetColorTexture(0.2, 0.2, 0.2, 1)

-- Border für Color Picker Button
OptionsMenuFrame.colorPickerButton.border = OptionsMenuFrame.colorPickerButton:CreateTexture(nil, "BORDER")
OptionsMenuFrame.colorPickerButton.border:SetAllPoints()
OptionsMenuFrame.colorPickerButton.border:SetColorTexture(0.5, 0.5, 0.5, 1)
OptionsMenuFrame.colorPickerButton.border:SetPoint("TOPLEFT", -1, 1)
OptionsMenuFrame.colorPickerButton.border:SetPoint("BOTTOMRIGHT", 1, -1)

-- Color Swatch (Farbvorschau)
OptionsMenuFrame.colorPickerButton.swatch = OptionsMenuFrame.colorPickerButton:CreateTexture(nil, "OVERLAY")
OptionsMenuFrame.colorPickerButton.swatch:SetSize(20, 20)
OptionsMenuFrame.colorPickerButton.swatch:SetPoint("LEFT", 5, 0)
OptionsMenuFrame.colorPickerButton.swatch:SetTexture(130939) -- Interface\\ChatFrame\\ChatFrameColorSwatch

-- Checker Pattern Hintergrund
OptionsMenuFrame.colorPickerButton.checkers = OptionsMenuFrame.colorPickerButton:CreateTexture(nil, "BACKGROUND")
OptionsMenuFrame.colorPickerButton.checkers:SetSize(18, 18)
OptionsMenuFrame.colorPickerButton.checkers:SetPoint("CENTER", OptionsMenuFrame.colorPickerButton.swatch)
OptionsMenuFrame.colorPickerButton.checkers:SetTexture(188523) -- Tileset\\Generic\\Checkers
OptionsMenuFrame.colorPickerButton.checkers:SetTexCoord(.25, 0, 0.5, .25)
OptionsMenuFrame.colorPickerButton.checkers:SetDesaturated(true)
OptionsMenuFrame.colorPickerButton.checkers:SetVertexColor(1, 1, 1, 0.75)

-- Text für Color Picker Button
OptionsMenuFrame.colorPickerButton.text = OptionsMenuFrame.colorPickerButton:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
OptionsMenuFrame.colorPickerButton.text:SetPoint("LEFT", OptionsMenuFrame.colorPickerButton.swatch, "RIGHT", 5, 0)
OptionsMenuFrame.colorPickerButton.text:SetText(L["ICON_COLOR"] .. " wählen...")

-- Color Picker Funktion
local function OpenColorPicker()
    local r = Settings.iconColorR or 1.0
    local g = Settings.iconColorG or 1.0
    local b = Settings.iconColorB or 1.0
    
    ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG")
    ColorPickerFrame:SetFrameLevel(OptionsMenuFrame:GetFrameLevel() + 10)
    ColorPickerFrame:SetClampedToScreen(true)
    
    if ColorPickerFrame.SetupColorPickerAndShow then
        local info = {
            swatchFunc = function()
                local newR, newG, newB = ColorPickerFrame:GetColorRGB()
                HousingItemTrackerSettings.iconColorR = newR
                HousingItemTrackerSettings.iconColorG = newG
                HousingItemTrackerSettings.iconColorB = newB
                Settings.iconColorR = newR
                Settings.iconColorG = newG
                Settings.iconColorB = newB
                OptionsMenuFrame.colorPickerButton.swatch:SetVertexColor(newR, newG, newB, 1)
                if OptionsMenuFrame.UpdatePreviewIcons then
                    OptionsMenuFrame.UpdatePreviewIcons()
                end
                UpdateAllIcons()
            end,
            hasOpacity = false,
            r = r,
            g = g,
            b = b,
        }
        ColorPickerFrame:SetupColorPickerAndShow(info)
    else
        ColorPickerFrame.func = function()
            local newR, newG, newB = ColorPickerFrame:GetColorRGB()
            HousingItemTrackerSettings.iconColorR = newR
            HousingItemTrackerSettings.iconColorG = newG
            HousingItemTrackerSettings.iconColorB = newB
            Settings.iconColorR = newR
            Settings.iconColorG = newG
            Settings.iconColorB = newB
            OptionsMenuFrame.colorPickerButton.swatch:SetVertexColor(newR, newG, newB, 1)
            if OptionsMenuFrame.UpdatePreviewIcons then
                OptionsMenuFrame.UpdatePreviewIcons()
            end
            UpdateAllIcons()
        end
        ColorPickerFrame:SetColorRGB(r, g, b)
        ColorPickerFrame:Show()
    end
end

OptionsMenuFrame.colorPickerButton:SetScript("OnClick", OpenColorPicker)
OptionsMenuFrame.colorPickerButton:EnableMouse(true)

-- Checkbox: Icons in Bags anzeigen
OptionsMenuFrame.showBagIconsCheckbox = CreateFrame("CheckButton", nil, OptionsMenuFrame, "InterfaceOptionsCheckButtonTemplate")
OptionsMenuFrame.showBagIconsCheckbox:SetPoint("LEFT", OptionsMenuFrame.subtitle, "RIGHT", -200, 0)
OptionsMenuFrame.showBagIconsCheckbox:SetPoint("TOP", OptionsMenuFrame.subtitle, "BOTTOM", 0, -150)
OptionsMenuFrame.showBagIconsCheckbox.Text:SetText(L["SHOW_BAG_ICONS"])
OptionsMenuFrame.showBagIconsCheckbox:SetChecked(Settings.showBagIcons)
OptionsMenuFrame.showBagIconsCheckbox:SetScript("OnClick", function(self)
    HousingItemTrackerSettings.showBagIcons = self:GetChecked()
    Settings.showBagIcons = self:GetChecked()
    UpdateAllBagSlots()
    UpdateBankSlots()
end)

-- Checkbox: Tooltips für Materials anzeigen
OptionsMenuFrame.showTooltipsCheckbox = CreateFrame("CheckButton", nil, OptionsMenuFrame, "InterfaceOptionsCheckButtonTemplate")
OptionsMenuFrame.showTooltipsCheckbox:SetPoint("TOP", OptionsMenuFrame.showBagIconsCheckbox, "BOTTOM", 0, -5)
OptionsMenuFrame.showTooltipsCheckbox.Text:SetText(L["SHOW_MATERIAL_TOOLTIPS"])
OptionsMenuFrame.showTooltipsCheckbox:SetChecked(Settings.showMaterialTooltips)
OptionsMenuFrame.showTooltipsCheckbox:SetScript("OnClick", function(self)
    HousingItemTrackerSettings.showMaterialTooltips = self:GetChecked()
    Settings.showMaterialTooltips = self:GetChecked()
end)

-- -- Checkbox: Vendor-Karten anzeigen
-- OptionsMenuFrame.showVendorMapsCheckbox = CreateFrame("CheckButton", nil, OptionsMenuFrame, "InterfaceOptionsCheckButtonTemplate")
-- OptionsMenuFrame.showVendorMapsCheckbox:SetPoint("TOP", OptionsMenuFrame.showTooltipsCheckbox, "BOTTOM", 0, -5)
-- OptionsMenuFrame.showVendorMapsCheckbox.Text:SetText(L["SHOW_VENDOR_MAPS"])
-- OptionsMenuFrame.showVendorMapsCheckbox:SetChecked(Settings.showVendorMaps)
-- OptionsMenuFrame.showVendorMapsCheckbox:SetScript("OnClick", function(self)
--     HousingItemTrackerSettings.showVendorMaps = self:GetChecked()
--     Settings.showVendorMaps = self:GetChecked()
-- end)

-- Checkbox: Tooltips im Housing Dashboard anzeigen
OptionsMenuFrame.showDashboardTooltipsCheckbox = CreateFrame("CheckButton", nil, OptionsMenuFrame, "InterfaceOptionsCheckButtonTemplate")
OptionsMenuFrame.showDashboardTooltipsCheckbox:SetPoint("TOP", OptionsMenuFrame.showTooltipsCheckbox, "BOTTOM", 0, -5)
OptionsMenuFrame.showDashboardTooltipsCheckbox.Text:SetText(L["SHOW_DASHBOARD_TOOLTIPS"])
OptionsMenuFrame.showDashboardTooltipsCheckbox:SetChecked(Settings.showDashboardTooltips)
OptionsMenuFrame.showDashboardTooltipsCheckbox:SetScript("OnClick", function(self)
    HousingItemTrackerSettings.showDashboardTooltips = self:GetChecked()
    Settings.showDashboardTooltips = self:GetChecked()
end)

-- Preview Section
OptionsMenuFrame.previewFrame = CreateFrame("Frame", nil, UIParent)
OptionsMenuFrame.previewFrame:SetSize(200, 250)
OptionsMenuFrame.previewFrame:SetPoint("LEFT", OptionsMenuFrame, "RIGHT", 10, 0)
OptionsMenuFrame.previewFrame:SetFrameStrata("DIALOG")
OptionsMenuFrame.previewFrame:SetFrameLevel(1001)
OptionsMenuFrame.previewFrame:Hide() -- Initially hidden

-- Preview Background
OptionsMenuFrame.previewFrame.bg = OptionsMenuFrame.previewFrame:CreateTexture(nil, "BACKGROUND")
OptionsMenuFrame.previewFrame.bg:SetAllPoints()
OptionsMenuFrame.previewFrame.bg:SetColorTexture(0.15, 0.15, 0.15, 0.8)

-- Preview Border
OptionsMenuFrame.previewFrame.border = OptionsMenuFrame.previewFrame:CreateTexture(nil, "BORDER")
OptionsMenuFrame.previewFrame.border:SetAllPoints()
OptionsMenuFrame.previewFrame.border:SetColorTexture(0.4, 0.4, 0.4, 1)
OptionsMenuFrame.previewFrame.border:SetPoint("TOPLEFT", -1, 1)
OptionsMenuFrame.previewFrame.border:SetPoint("BOTTOMRIGHT", 1, -1)

-- Preview Title
OptionsMenuFrame.previewFrame.title = OptionsMenuFrame.previewFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
OptionsMenuFrame.previewFrame.title:SetPoint("TOP", 0, -15)
if GetLocale() == "deDE" then
    OptionsMenuFrame.previewFrame.title:SetText("Vorschau:")
else
    OptionsMenuFrame.previewFrame.title:SetText("Preview:")
end

-- Preview Bag Slot
OptionsMenuFrame.previewFrame.bagSlot = CreateFrame("Button", nil, OptionsMenuFrame.previewFrame)
OptionsMenuFrame.previewFrame.bagSlot:SetSize(42, 42)
OptionsMenuFrame.previewFrame.bagSlot:SetPoint("TOP", 0, -50)

-- Bag Slot Background (standard WoW bag slot texture)
-- OptionsMenuFrame.previewFrame.bagSlot.bg = OptionsMenuFrame.previewFrame.bagSlot:CreateTexture(nil, "BACKGROUND")
-- OptionsMenuFrame.previewFrame.bagSlot.bg:SetAllPoints()
-- OptionsMenuFrame.previewFrame.bagSlot.bg:SetTexture("Interface\\Buttons\\UI-Slot-Background")
-- OptionsMenuFrame.previewFrame.bagSlot.bg:SetTexCoord(0.140625, 0.859375, 0.140625, 0.859375)

-- Item Icon Texture (will be set to actual housing item)
OptionsMenuFrame.previewFrame.bagSlot.itemIcon = OptionsMenuFrame.previewFrame.bagSlot:CreateTexture(nil, "BORDER")
OptionsMenuFrame.previewFrame.bagSlot.itemIcon:SetSize(38, 38)
OptionsMenuFrame.previewFrame.bagSlot.itemIcon:SetPoint("CENTER", 0, 0)
-- Default fallback icon
OptionsMenuFrame.previewFrame.bagSlot.itemIcon:SetTexture(134335) -- Copper Ore icon as fallback

-- Normal Texture (slot border)
OptionsMenuFrame.previewFrame.bagSlot.normalTexture = OptionsMenuFrame.previewFrame.bagSlot:CreateTexture(nil, "ARTWORK")
OptionsMenuFrame.previewFrame.bagSlot.normalTexture:SetAllPoints()
OptionsMenuFrame.previewFrame.bagSlot.normalTexture:SetTexture("Interface\\Buttons\\UI-Quickslot2")
OptionsMenuFrame.previewFrame.bagSlot.normalTexture:SetTexCoord(0.140625, 0.859375, 0.140625, 0.859375)

-- Housing Tracker Icon Overlay
OptionsMenuFrame.previewFrame.bagSlot.housingIcon = OptionsMenuFrame.previewFrame.bagSlot:CreateTexture(nil, "OVERLAY")
OptionsMenuFrame.previewFrame.bagSlot.housingIcon:SetTexture("Interface\\AddOns\\HousingItemTracker\\textures\\decorCost")
OptionsMenuFrame.previewFrame.bagSlot.housingIcon:SetPoint("TOPRIGHT", OptionsMenuFrame.previewFrame.bagSlot, "TOPRIGHT", 0, 0)
OptionsMenuFrame.previewFrame.bagSlot.housingIcon:SetBlendMode("BLEND")
OptionsMenuFrame.previewFrame.bagSlot.housingIcon:SetDrawLayer("OVERLAY", 7)

-- Item Count Text (like in real bags)
OptionsMenuFrame.previewFrame.bagSlot.count = OptionsMenuFrame.previewFrame.bagSlot:CreateFontString(nil, "OVERLAY", "NumberFontNormal")
OptionsMenuFrame.previewFrame.bagSlot.count:SetPoint("BOTTOMRIGHT", -2, 2)
OptionsMenuFrame.previewFrame.bagSlot.count:SetText("42")

-- Item Quality Border
OptionsMenuFrame.previewFrame.bagSlot.qualityBorder = OptionsMenuFrame.previewFrame.bagSlot:CreateTexture(nil, "ARTWORK")
OptionsMenuFrame.previewFrame.bagSlot.qualityBorder:SetAllPoints()
OptionsMenuFrame.previewFrame.bagSlot.qualityBorder:SetTexture("Interface\\Buttons\\UI-ActionButton-Border")
OptionsMenuFrame.previewFrame.bagSlot.qualityBorder:SetBlendMode("ADD")
OptionsMenuFrame.previewFrame.bagSlot.qualityBorder:SetTexCoord(0.140625, 0.859375, 0.140625, 0.859375)
-- Set to white/common quality
OptionsMenuFrame.previewFrame.bagSlot.qualityBorder:SetVertexColor(1, 1, 1, 0.3)

-- Function to update preview icons
local function UpdatePreviewIcons()
    local iconSize = Settings.iconSize or 20
    local colorR = Settings.iconColorR or 1.0
    local colorG = Settings.iconColorG or 1.0
    local colorB = Settings.iconColorB or 1.0
    
    -- Update housing icon size and color
    OptionsMenuFrame.previewFrame.bagSlot.housingIcon:SetSize(iconSize, iconSize)
    OptionsMenuFrame.previewFrame.bagSlot.housingIcon:SetVertexColor(colorR, colorG, colorB, 1)
end

-- Store the function globally for use in slider/color picker
OptionsMenuFrame.UpdatePreviewIcons = UpdatePreviewIcons

-- Hinweis-Text unter dem Update-Button
OptionsMenuFrame.updateHint = OptionsMenuFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
OptionsMenuFrame.updateHint:SetPoint("LEFT", OptionsMenuFrame.showTooltipsCheckbox, "RIGHT", -20, 0)
OptionsMenuFrame.updateHint:SetPoint("TOP", OptionsMenuFrame.showTooltipsCheckbox, "BOTTOM", 0, -50)
OptionsMenuFrame.updateHint:SetText("|cFFFFD700" .. L["REOPEN_BAGS_HINT"] .. "|r")
OptionsMenuFrame.updateHint:SetJustifyH("CENTER")

-- Funktion zum Schließen des Menüs (muss vor den Buttons definiert werden)
local function HideOptionsMenu()
    OptionsMenuFrame:Hide()
    if OptionsMenuFrame.previewFrame then
        OptionsMenuFrame.previewFrame:Hide()
    end
end

-- Buttons zentral am unteren Rand
-- Update Icons Button (links) - Now reloads UI
OptionsMenuFrame.updateButton = CreateFrame("Button", nil, OptionsMenuFrame, "UIPanelButtonTemplate")
OptionsMenuFrame.updateButton:SetSize(120, 30)
OptionsMenuFrame.updateButton:SetPoint("BOTTOM", OptionsMenuFrame, "BOTTOM", -70, 20)
OptionsMenuFrame.updateButton:SetText(L["RELOAD"])
OptionsMenuFrame.updateButton:SetScript("OnClick", function(self)
    UpdateAllIcons()
    -- Reload UI to ensure all changes are applied
    ReloadUI()
end)

-- Close Button (rechts)
OptionsMenuFrame.closeButton = CreateFrame("Button", nil, OptionsMenuFrame, "UIPanelButtonTemplate")
OptionsMenuFrame.closeButton:SetSize(120, 30)
OptionsMenuFrame.closeButton:SetPoint("BOTTOM", OptionsMenuFrame, "BOTTOM", 70, 20)
OptionsMenuFrame.closeButton:SetText(L["CLOSE"])
OptionsMenuFrame.closeButton:SetScript("OnClick", function(self)
    HideOptionsMenu()
end)

-- Funktion zum Öffnen des Menüs
local function ShowOptionsMenu()
    -- Setze aktuelle Werte
    OptionsMenuFrame.sizeSlider:SetValue(Settings.iconSize or 20)
    OptionsMenuFrame.sizeValue:SetText(tostring(Settings.iconSize or 20))
    
    -- Setze Color Picker Farbe
    local r = Settings.iconColorR or 1.0
    local g = Settings.iconColorG or 1.0
    local b = Settings.iconColorB or 1.0
    OptionsMenuFrame.colorPickerButton.swatch:SetVertexColor(r, g, b, 1)
    
    -- Setze Checkbox-Werte
    OptionsMenuFrame.showBagIconsCheckbox:SetChecked(Settings.showBagIcons)
    OptionsMenuFrame.showTooltipsCheckbox:SetChecked(Settings.showMaterialTooltips)
    OptionsMenuFrame.showDashboardTooltipsCheckbox:SetChecked(Settings.showDashboardTooltips)
    
    -- Versuche ein echtes Housing-Item-Icon zu laden für die Preview
    if DB.materials then
        -- Finde das erste Material-Item in der Datenbank
        for itemId, _ in pairs(DB.materials) do
            -- Versuche das Item-Icon zu laden
            local itemTexture = C_Item.GetItemIconByID(itemId)
            if itemTexture then
                OptionsMenuFrame.previewFrame.bagSlot.itemIcon:SetTexture(itemTexture)
                -- Auch den Namen speichern für Tooltip
                C_Item.RequestLoadItemDataByID(itemId)
                break
            end
        end
    end
    
    -- Aktualisiere Preview
    if OptionsMenuFrame.UpdatePreviewIcons then
        OptionsMenuFrame.UpdatePreviewIcons()
    end
    
    -- Zeige Preview Frame
    if OptionsMenuFrame.previewFrame then
        OptionsMenuFrame.previewFrame:Show()
    end
    
    OptionsMenuFrame:Show()
end

-- Slider Event-Handler (direkt auf globale Variable zugreifen)
OptionsMenuFrame.sizeSlider:SetScript("OnValueChanged", function(self, value)
    HousingItemTrackerSettings.iconSize = value
    Settings.iconSize = value  -- Aktualisiere auch lokale Referenz
    OptionsMenuFrame.sizeValue:SetText(tostring(value))
    -- Aktualisiere Preview
    if OptionsMenuFrame.UpdatePreviewIcons then
        OptionsMenuFrame.UpdatePreviewIcons()
    end
    -- Aktualisiere alle Icons sofort
    UpdateAllIcons()
end)


-- Close Button Handler entfernt - verwende jetzt closeButton unten

-- Slash-Command zum manuellen Update
SLASH_HOUSINGITEMTRACKER1 = "/hit"
SLASH_HOUSINGITEMTRACKER2 = "/housingitemtracker"
SlashCmdList["HOUSINGITEMTRACKER"] = function(msg)
    msg = msg:lower():match("^%s*(.-)%s*$") -- Trim whitespace
    
    if msg == "" or msg == "menu" or msg == "options" then
        -- Öffne Options-Menü
        ShowOptionsMenu()
    elseif msg == "update" 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 oder /hit menu - Options-Menü öffnen")
        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

