-- BrightDataTexts/Core.lua
-- BrightDataTexts — native BrightQoL data text system.
-- Removed: AceAddon, AceDB, AceConfig/AceGUI (replaced by BrightQoL GUI).
-- SavedVariables stored in BrightQoL.dataPanels.

local addonName, ns = ...

----------------------------------------------------
-- Create the BDT object and expose it globally
-- All module files access BDT via ns.DataTexts (BrightQoL namespace)
----------------------------------------------------
local BDT = {}
ns.DataTexts = BDT  -- integrated into BrightQoL namespace

----------------------------------------------------
-- Profiler (keep for compatibility)
----------------------------------------------------
BDT.profileData = {}

function BDT:ProfileFunction(name, func)
    func()
end
function BDT:ShowProfileData() end

----------------------------------------------------
-- Libs (all already loaded by BrightQoL TOC)
----------------------------------------------------
BDT.LSM          = LibStub("LibSharedMedia-3.0")
BDT.LDB          = LibStub("LibDataBroker-1.1")
BDT.Icon         = LibStub("LibDBIcon-1.0")
BDT.LibDeflate   = LibStub:GetLibrary("LibDeflate")
BDT.AceSerializer= LibStub("AceSerializer-3.0")


----------------------------------------------------
-- State
----------------------------------------------------
BDT.modules = BDT.modules or {}
BDT.bars    = BDT.bars    or {}
BDT.cache   = BDT.cache   or {}
BDT.cache.locale       = GetLocale()
BDT.cache.moduleNames  = {}
BDT.cache.moduleNamesDirty = true
BDT.cache.version      = "Bright Edition"
BDT.cache.screenWidth  = GetScreenWidth()
BDT.cache.screenHeight = GetScreenHeight()

----------------------------------------------------
-- "db" shim — backed by BrightQoL.dataPanels
-- All BDT code accesses BDT.db.profile.*
----------------------------------------------------
-- Defaults are applied in BrightQoL's Core.lua (BRIGHT_DATAPANELS_DEFAULTS)
BDT.db = {}
BDT.db.char   = { useSpecProfiles = false, chosenProfile = {} }
-- Initialize global immediately so ADDON_LOADED handlers (Ara_Broker) can use it
-- before PLAYER_LOGIN fires. Will be replaced by the real BrightQoL table in SetupDB.
BDT.db.global = { gold = {}, AraBroker = {} }

-- Lazy proxy: BDT.db.profile always points to the live BrightQoL.dataPanels table
-- We set it up after PLAYER_LOGIN when BrightQoL has initialised its DB
local function SetupDB()
    BDT.db.profile = BrightQoL.dataPanels

    -- Global (account-wide) table — backed by a separate BrightQoL saved var key
    -- so Ara_Broker settings and gold data persist across characters.
    if not BrightQoL.dataPanelsGlobal then
        BrightQoL.dataPanelsGlobal = {
            gold     = {},
            AraBroker = {},
        }
    end
    BrightQoL.dataPanelsGlobal.gold      = BrightQoL.dataPanelsGlobal.gold or {}
    BrightQoL.dataPanelsGlobal.AraBroker = BrightQoL.dataPanelsGlobal.AraBroker or {}
    BDT.db.global = BrightQoL.dataPanelsGlobal

    -- AceDB compat stubs used by ProfileManager / import-export
    BDT.db.GetProfiles          = function() return {"Default"} end
    BDT.db.SetProfile           = function() end
    BDT.db.RegisterCallback     = function() end
    BDT.db.UnregisterCallback   = function() end
    BDT.db.keys = { char = "char", realm = "realm", class = "class" }
end

----------------------------------------------------
-- AceEvent shim — RegisterEvent / UnregisterEvent on BDT itself
-- (AceAddon/AceEvent would normally mixin these)
----------------------------------------------------
local eventFrame = CreateFrame("Frame")
local eventHandlers = {}

function BDT:RegisterEvent(event, handler)
    if not eventHandlers[event] then
        eventHandlers[event] = {}
        eventFrame:RegisterEvent(event)
    end
    eventHandlers[event][handler or event] = handler or function(...)
        if type(self[event]) == "function" then self[event](self, event, ...) end
    end
end

function BDT:UnregisterEvent(event)
    eventHandlers[event] = nil
    eventFrame:UnregisterEvent(event)
end

eventFrame:SetScript("OnEvent", function(_, event, ...)
    if eventHandlers[event] then
        for _, fn in pairs(eventHandlers[event]) do
            if type(fn) == "function" then fn(event, ...) end
        end
    end
    -- Also dispatch named method on BDT
    if type(BDT[event]) == "function" then
        BDT[event](BDT, event, ...)
    end
end)

----------------------------------------------------
-- Global Gold tracking (from Core.lua lines 280-340)
----------------------------------------------------
BDT.global = BDT.global or {}
BDT.global.gold = BDT.global.gold or {}

function BDT:UpdateGlobalGold()
    local realmName  = GetRealmName() or "Unknown"
    local charName   = UnitName("player") or "Unknown"
    local money      = GetMoney() or 0
    local _, faction = UnitFactionGroup("player")

    BDT.global.gold[realmName]           = BDT.global.gold[realmName] or {}
    BDT.global.gold[realmName][charName] = {
        amount  = money,
        faction = faction or "Neutral",
    }
end

function BDT:GetTotalGold(faction)
    local total = 0
    for _, realmData in pairs(BDT.global.gold) do
        for _, charData in pairs(realmData) do
            if not faction or charData.faction == faction then
                total = total + (charData.amount or 0)
            end
        end
    end
    return total
end

----------------------------------------------------
-- Localization (enUS inline — no external locale files needed)
----------------------------------------------------
BDT.L = setmetatable({}, {
    __index = function(t, k) rawset(t, k, k); return k end,
    __newindex = function(t, k, v) rawset(t, k, v) end,
})
BDT.L["Simple Datatexts"] = "Simple Datatexts"
BDT.L["(empty)"] = "(empty)"
BDT.L["(spacer)"] = "(spacer)"
BDT.L["Display Font:"] = "Display Font:"
BDT.L["Font Settings"] = "Font Settings"
BDT.L["Font Size"] = "Font Size"
BDT.L["Font Outline"] = "Font Outline"
BDT.L["GOLD"] = "GOLD"
BDT.L["Override Global Font"] = "Override Global Font"
BDT.L["Override Text Color"] = "Override Text Color"
BDT.L["Settings"] = "Settings"
BDT.L["Frame Strata"] = "Frame Strata"
BDT.L["Set the frame strata (layer) for this module. Higher values appear above lower values."] = "Set the frame strata (layer) for this module. Higher values appear above lower values."
BDT.L["Set the frame strata (layer) for this panel. Modules will appear relative to this. Higher values appear above lower values."] = "Set the frame strata (layer) for this panel. Modules will appear relative to this. Higher values appear above lower values."
BDT.L["Slot Controls"] = "Slot Controls"
BDT.L["Anchor Point"] = "Anchor Point"
BDT.L["Set the anchor point for this module."] = "Set the anchor point for this module."
BDT.L["Yes"] = "Yes"
BDT.L["No"] = "No"
BDT.L["Debug Mode Disabled"] = "Debug Mode Disabled"
BDT.L["Debug Mode Enabled"] = "Debug Mode Enabled"
BDT.L["Left Click to open settings"] = "Left Click to open settings"
BDT.L["Lock/Unlock"] = "Lock/Unlock"
BDT.L["Minimap Icon Disabled"] = "Minimap Icon Disabled"
BDT.L["Minimap Icon Enabled"] = "Minimap Icon Enabled"
BDT.L["Not Defined"] = "Not Defined"
BDT.L["Toggle Minimap Icon"] = "Toggle Minimap Icon"
BDT.L["Usage"] = "Usage"
BDT.L["Version"] = "Version"
BDT.L["Error compressing profile data"] = "Error compressing profile data"
BDT.L["Error decoding import string"] = "Error decoding import string"
BDT.L["Error decompressing data"] = "Error decompressing data"
BDT.L["Error deserializing profile data"] = "Error deserializing profile data"
BDT.L["Error serializing profile data"] = "Error serializing profile data"
BDT.L["Import data too large"] = "Import data too large"
BDT.L["Import data too large after decompression"] = "Import data too large after decompression"
BDT.L["Import string is too large"] = "Import string is too large"
BDT.L["Importing profile from version %s"] = "Importing profile from version %s"
BDT.L["Invalid import string format"] = "Invalid import string format"
BDT.L["Invalid profile data"] = "Invalid profile data"
BDT.L["Migrating old settings to new profile system..."] = "Migrating old settings to new profile system..."
BDT.L["Migration complete! All profiles have been migrated."] = "Migration complete! All profiles have been migrated."
BDT.L["No import string provided"] = "No import string provided"
BDT.L["Profile imported successfully!"] = "Profile imported successfully!"
BDT.L["Colors"] = "Colors"
BDT.L["Custom Color"] = "Custom Color"
BDT.L["Enable Per-Spec Profiles"] = "Enable Per-Spec Profiles"
BDT.L["Global"] = "Global"
BDT.L["Global Settings"] = "Global Settings"
BDT.L["Hide Module Title in Tooltip"] = "Hide Module Title in Tooltip"
BDT.L["Lock Panels"] = "Lock Panels"
BDT.L["Prevent panels from being moved"] = "Prevent panels from being moved"
BDT.L["Show Login Message"] = "Show Login Message"
BDT.L["Show Minimap Icon"] = "Show Minimap Icon"
BDT.L["Toggle the minimap button on or off"] = "Toggle the minimap button on or off"
BDT.L["Use 24Hr Clock"] = "Use 24Hr Clock"
BDT.L["Use Class Color"] = "Use Class Color"
BDT.L["Use Custom Color"] = "Use Custom Color"
BDT.L["X Offset"] = "X Offset"
BDT.L["Y Offset"] = "Y Offset"
BDT.L["When enabled, the addon will automatically switch to a different profile each time you change specialization. Pick which profile each spec should use below."] = "When enabled, the addon will automatically switch to a different profile each time you change specialization. Pick which profile each spec should use below."
BDT.L["Enable Font Text Shadow"] = "Enable Font Text Shadow"
BDT.L["Add a subtle shadow to datatexts for better readability"] = "Add a subtle shadow to datatexts for better readability"
BDT.L["Enable Tooltip Text Shadow"] = "Enable Tooltip Text Shadow"
BDT.L["Add a subtle shadow to tooltip text for better readability"] = "Add a subtle shadow to tooltip text for better readability"
BDT.L["Tooltip Settings"] = "Tooltip Settings"
BDT.L["Tooltip Font"] = "Tooltip Font"
BDT.L["Font used for all addon tooltips"] = "Font used for all addon tooltips"
BDT.L["Tooltip Font Outline"] = "Tooltip Font Outline"
BDT.L["Font outline for all addon tooltips"] = "Font outline for all addon tooltips"
BDT.L["Tooltip Header Font Size"] = "Tooltip Header Font Size"
BDT.L["Font size for tooltip headers"] = "Font size for tooltip headers"
BDT.L["Tooltip Line Font Size"] = "Tooltip Line Font Size"
BDT.L["Font size for tooltip content lines"] = "Font size for tooltip content lines"
BDT.L["Show All Panels"] = "Show All Panels"
BDT.L["Toggle visibility of all panels. Individual panels can also be hidden in their own settings."] = "Toggle visibility of all panels. Individual panels can also be hidden in their own settings."
BDT.L["Panels shown"] = "Panels shown"
BDT.L["Panels hidden"] = "Panels hidden"
BDT.L["Toggle All Panels"] = "Toggle All Panels"
BDT.L["Appearance"] = "Appearance"
BDT.L["Apply Slot Changes"] = "Apply Slot Changes"
BDT.L["Are you sure you want to delete this bar?\nThis action cannot be undone."] = "Are you sure you want to delete this bar?\nThis action cannot be undone."
BDT.L["Background Opacity"] = "Background Opacity"
BDT.L["Border Color"] = "Border Color"
BDT.L["Border Size"] = "Border Size"
BDT.L["Create New Panel"] = "Create New Panel"
BDT.L["Height"] = "Height"
BDT.L["Number of Slots"] = "Number of Slots"
BDT.L["Panel Settings"] = "Panel Settings"
BDT.L["Panels"] = "Panels"
BDT.L["Remove Selected Panel"] = "Remove Selected Panel"
BDT.L["Rename Panel:"] = "Rename Panel:"
BDT.L["Scale"] = "Scale"
BDT.L["Select Border:"] = "Select Border:"
BDT.L["Select Panel:"] = "Select Panel:"
BDT.L["Size & Scale"] = "Size & Scale"
BDT.L["Slot Assignments"] = "Slot Assignments"
BDT.L["Slot %d:"] = "Slot %d:"
BDT.L["Slots"] = "Slots"
BDT.L["Update slot assignment dropdowns after changing number of slots"] = "Update slot assignment dropdowns after changing number of slots"
BDT.L["Width"] = "Width"
BDT.L["Hide Panel"] = "Hide Panel"
BDT.L["Hide this panel. Panels are always visible while unlocked."] = "Hide this panel. Panels are always visible while unlocked."
BDT.L["Module Settings"] = "Module Settings"
BDT.L["Hide Decimals"] = "Hide Decimals"
BDT.L["Show Label"] = "Show Label"
BDT.L["Show Short Label"] = "Show Short Label"
BDT.L["1. Click 'Generate Export String' above\n2. Click in this box\n3. Press Ctrl+A to select all\n4. Press Ctrl+C to copy"] = "1. Click 'Generate Export String' above\n2. Click in this box\n3. Press Ctrl+A to select all\n4. Press Ctrl+C to copy"
BDT.L["1. Paste an import string in the box below\n2. Click Accept\n3. Click 'Import Profile'"] = "1. Paste an import string in the box below\n2. Click Accept\n3. Click 'Import Profile'"
BDT.L["Create an export string for your current profile"] = "Create an export string for your current profile"
BDT.L["Export"] = "Export"
BDT.L["Export String"] = "Export String"
BDT.L["Export string generated! Copy it from the box below."] = "Export string generated! Copy it from the box below."
BDT.L["Export your current profile to share with others, or import a profile string.\n"] = "Export your current profile to share with others, or import a profile string.\n"
BDT.L["Generate Export String"] = "Generate Export String"
BDT.L["Import"] = "Import"
BDT.L["Import/Export"] = "Import/Export"
BDT.L["Import Profile"] = "Import Profile"
BDT.L["Import String"] = "Import String"
BDT.L["Import the profile string from above (after clicking Accept)"] = "Import the profile string from above (after clicking Accept)"
BDT.L["Please paste an import string and click Accept first"] = "Please paste an import string and click Accept first"
BDT.L["Profile Import/Export"] = "Profile Import/Export"
BDT.L["This will overwrite your current profile. Are you sure?"] = "This will overwrite your current profile. Are you sure?"
BDT.L["Panels locked"] = "Panels locked"
BDT.L["Panels unlocked"] = "Panels unlocked"
BDT.L["Agi"] = "Agi"
BDT.L["Mitigation By Level:"] = "Mitigation By Level:"
BDT.L["Level %d"] = "Level %d"
BDT.L["Target Mitigation"] = "Target Mitigation"
BDT.L["AP"] = "AP"
BDT.L["Bags"] = "Bags"
BDT.L["Combat"] = "Combat"
BDT.L["combat duration"] = "combat duration"
BDT.L["Combat Timer"] = "Combat Timer"
BDT.L["Current"] = "Current"
BDT.L["Currently out of combat"] = "Currently out of combat"
BDT.L["Display Duration"] = "Display Duration"
BDT.L["Enter combat to start tracking"] = "Enter combat to start tracking"
BDT.L["Last"] = "Last"
BDT.L["Left-click"] = "Left-click"
BDT.L["Out of Combat"] = "Out of Combat"
BDT.L["to reset"] = "to reset"
BDT.L["Crit"] = "Crit"
BDT.L["CURRENCIES"] = "CURRENCIES"
BDT.L["Tracked Currency Qty"] = "Tracked Currency Qty"
BDT.L["Currency Display Order"] = "Currency Display Order"
BDT.L["Position %d"] = "Position %d"
BDT.L["Empty Slot"] = "Empty Slot"
BDT.L["Dur:"] = "Dur:"
BDT.L["Durability:"] = "Durability:"
BDT.L["Max Level"] = "Max Level"
BDT.L["N/A"] = "N/A"
BDT.L["Experience"] = "Experience"
BDT.L["Display Format"] = "Display Format"
BDT.L["Bar Toggles"] = "Bar Toggles"
BDT.L["Show Graphical Bar"] = "Show Graphical Bar"
BDT.L["Hide Blizzard XP Bar"] = "Hide Blizzard XP Bar"
BDT.L["Bar Appearance"] = "Bar Appearance"
BDT.L["Bar Height (%)"] = "Bar Height (%)"
BDT.L["Bar Use Class Color"] = "Bar Use Class Color"
BDT.L["Bar Custom Color"] = "Bar Custom Color"
BDT.L["Bar Texture"] = "Bar Texture"
BDT.L["Text Color"] = "Text Color"
BDT.L["Text Use Class Color"] = "Text Use Class Color"
BDT.L["Text Custom Color"] = "Text Custom Color"
BDT.L["Show Rested XP Bar"] = "Show Rested XP Bar"
BDT.L["Override Default Rested Color"] = "Override Default Rested Color"
BDT.L["Rested Custom Color"] = "Rested Custom Color"
BDT.L["Rested:"] = "Rested:"
BDT.L["Ara Friends LDB object not found! SDT Friends datatext disabled."] = "Ara Friends LDB object not found! SDT Friends datatext disabled."
BDT.L["Show Silver"] = "Show Silver"
BDT.L["Show Copper"] = "Show Copper"
BDT.L["Use Coin Icons"] = "Use Coin Icons"
BDT.L["Display Quantities"] = "Display Quantities"
BDT.L["Characters to Show"] = "Characters to Show"
BDT.L["Servers to Show"] = "Servers to Show"
BDT.L["Session:"] = "Session:"
BDT.L["Earned:"] = "Earned:"
BDT.L["Spent:"] = "Spent:"
BDT.L["Profit:"] = "Profit:"
BDT.L["Deficit:"] = "Deficit:"
BDT.L["Character:"] = "Character:"
BDT.L["Server:"] = "Server:"
BDT.L["Faction:"] = "Faction:"
BDT.L["Alliance:"] = "Alliance:"
BDT.L["Horde:"] = "Horde:"
BDT.L["Total:"] = "Total:"
BDT.L["Warband:"] = "Warband:"
BDT.L["WoW Token:"] = "WoW Token:"
BDT.L["Gold: All data reset!"] = "Gold: All data reset!"
BDT.L["Gold: Data reset for %s!"] = "Gold: Data reset for %s!"
BDT.L["Are you sure you want to delete gold data for:\n\n|cFFFFFF00%s|r"] = "Are you sure you want to delete gold data for:\n\n|cFFFFFF00%s|r"
BDT.L["|cFFFF0000ALL CHARACTERS|r"] = "|cFFFF0000ALL CHARACTERS|r"
BDT.L["|cFF808080No character data found|r"] = "|cFF808080No character data found|r"
BDT.L["Reset Session Data:"] = "Reset Session Data:"
BDT.L["Hold Shift + Right Click"] = "Hold Shift + Right Click"
BDT.L["Reset Character Gold Data:"] = "Reset Character Gold Data:"
BDT.L["Hold Alt + Right Click"] = "Hold Alt + Right Click"
BDT.L["Ara Guild LDB object not found! SDT Guild datatext disabled."] = "Ara Guild LDB object not found! SDT Guild datatext disabled."
BDT.L["Max Guild Name Length"] = "Max Guild Name Length"
BDT.L["Haste:"] = "Haste:"
BDT.L["Hearthstone"] = "Hearthstone"
BDT.L["Selected Hearthstone"] = "Selected Hearthstone"
BDT.L["Random"] = "Random"
BDT.L["Selected:"] = "Selected:"
BDT.L["Available Hearthstones:"] = "Available Hearthstones:"
BDT.L["Left Click: Use Hearthstone"] = "Left Click: Use Hearthstone"
BDT.L["Right Click: Select Hearthstone"] = "Right Click: Select Hearthstone"
BDT.L["Cannot use hearthstone while in combat"] = "Cannot use hearthstone while in combat"
BDT.L["Int"] = "Int"
BDT.L["Item Level"] = "Item Level"
BDT.L["ilvl"] = "ilvl"
BDT.L["Equipped Item Level"] = "Equipped Item Level"
BDT.L["Maximum Item Level"] = "Maximum Item Level"
BDT.L["Show Max Item Level"] = "Show Max Item Level"
BDT.L["NO TEXT"] = "NO TEXT"
BDT.L["New Mail"] = "New Mail"
BDT.L["No Mail"] = "No Mail"
BDT.L["Map Name"] = "Map Name"
BDT.L["Zone Name"] = "Zone Name"
BDT.L["Subzone Name"] = "Subzone Name"
BDT.L["Zone - Subzone"] = "Zone - Subzone"
BDT.L["Zone / Subzone (Two Lines)"] = "Zone / Subzone (Two Lines)"
BDT.L["Minimap Zone"] = "Minimap Zone"
BDT.L["Show Zone on Tooltip"] = "Show Zone on Tooltip"
BDT.L["Show Coordinates on Tooltip"] = "Show Coordinates on Tooltip"
BDT.L["Zone:"] = "Zone:"
BDT.L["Subzone:"] = "Subzone:"
BDT.L["Coordinates:"] = "Coordinates:"
BDT.L["Mastery:"] = "Mastery:"
BDT.L["Mythic+ Keystone"] = "Mythic+ Keystone"
BDT.L["No Mythic+ Keystone"] = "No Mythic+ Keystone"
BDT.L["Current Key:"] = "Current Key:"
BDT.L["Dungeon Teleport is on cooldown for "] = "Dungeon Teleport is on cooldown for "
BDT.L[" more seconds."] = " more seconds."
BDT.L["You do not know the teleport spell for "] = "You do not know the teleport spell for "
BDT.L["Key: "] = "Key: "
BDT.L["None"] = "None"
BDT.L["No Key"] = "No Key"
BDT.L["Left Click: Teleport to Dungeon"] = "Left Click: Teleport to Dungeon"
BDT.L["Right Click: List Group in Finder"] = "Right Click: List Group in Finder"
BDT.L["Quests"] = "Quests"
BDT.L["Left Click: Change Loot Specialization"] = "Left Click: Change Loot Specialization"
BDT.L["Current"] = "Current"
BDT.L["Active"] = "Active"
BDT.L["Inactive"] = "Inactive"
BDT.L["Loadouts"] = "Loadouts"
BDT.L["Failed to load Blizzard_PlayerSpells: %s"] = "Failed to load Blizzard_PlayerSpells: %s"
BDT.L["Starter Build"] = "Starter Build"
BDT.L["Spec"] = "Spec"
BDT.L["Left Click: Change Talent Specialization"] = "Left Click: Change Talent Specialization"
BDT.L["Control + Left Click: Change Loadout"] = "Control + Left Click: Change Loadout"
BDT.L["Shift + Left Click: Show Talent Specialization UI"] = "Shift + Left Click: Show Talent Specialization UI"
BDT.L["Shift + Right Click: Change Loot Specialization"] = "Shift + Right Click: Change Loot Specialization"
BDT.L["Show Specialization Icon"] = "Show Specialization Icon"
BDT.L["Show Specialization Text"] = "Show Specialization Text"
BDT.L["Show Loot Specialization Icon"] = "Show Loot Specialization Icon"
BDT.L["Show Loot Specialization Text"] = "Show Loot Specialization Text"
BDT.L["Show Loot Spec When Current"] = "Show Loot Spec When Current"
BDT.L["Show Loadout"] = "Show Loadout"
BDT.L["Speed: "] = "Speed: "
BDT.L["Stagger Amount:"] = "Stagger Amount:"
BDT.L["Str"] = "Str"
BDT.L["MB_SUFFIX"] = "mb"
BDT.L["KB_SUFFIX"] = "kb"
BDT.L["MIN_SUFFIX"] = "min"
BDT.L["SEC_SUFFIX"] = "sec"
BDT.L["MS_SUFFIX"] = "ms"
BDT.L["SYSTEM"] = "SYSTEM"
BDT.L["FPS:"] = "FPS:"
BDT.L["Home Latency:"] = "Home Latency:"
BDT.L["World Latency:"] = "World Latency:"
BDT.L["Total Memory:"] = "Total Memory:"
BDT.L["(Shift Click) Collect Garbage"] = "(Shift Click) Collect Garbage"
BDT.L["FPS"] = "FPS"
BDT.L["MS"] = "MS"
BDT.L["Top Addons by Memory:"] = "Top Addons by Memory:"
BDT.L["Top Addons in Tooltip"] = "Top Addons in Tooltip"
BDT.L["Total CPU:"] = "Total CPU:"
BDT.L["Top Addons by CPU:"] = "Top Addons by CPU:"
BDT.L["TIME"] = "TIME"
BDT.L["Saved Raid(s)"] = "Saved Raid(s)"
BDT.L["Saved Dungeon(s)"] = "Saved Dungeon(s)"
BDT.L["Display Realm Time"] = "Display Realm Time"
BDT.L["Vers:"] = "Vers:"
BDT.L["Select Volume Stream"] = "Select Volume Stream"
BDT.L["Toggle Volume Stream"] = "Toggle Volume Stream"
BDT.L["Output Audio Device"] = "Output Audio Device"
BDT.L["Active Output Audio Device"] = "Active Output Audio Device"
BDT.L["Volume Streams"] = "Volume Streams"
BDT.L["Left Click: Select Volume Stream"] = "Left Click: Select Volume Stream"
BDT.L["Middle Click: Toggle Mute Master Stream"] = "Middle Click: Toggle Mute Master Stream"
BDT.L["Shift + Middle Click: Toggle Volume Stream"] = "Shift + Middle Click: Toggle Volume Stream"
BDT.L["Shift + Left Click: Open System Audio Panel"] = "Shift + Left Click: Open System Audio Panel"
BDT.L["Shift + Right Click: Select Output Audio Device"] = "Shift + Right Click: Select Output Audio Device"
BDT.L["M. Vol"] = "M. Vol"
BDT.L["FX"] = "FX"
BDT.L["Amb"] = "Amb"
BDT.L["Dlg"] = "Dlg"
BDT.L["Mus"] = "Mus"
BDT.L["Guild"] = "Guild"
BDT.L["No Guild"] = "No Guild"
BDT.L["Friends"] = "Friends"
BDT.L["<Mobile>"] = "<Mobile>"
BDT.L["Hints"] = "Hints"
BDT.L["Block"] = "Block"
BDT.L["Click"] = "Click"
BDT.L["RightClick"] = "RightClick"
BDT.L["MiddleClick"] = "MiddleClick"
BDT.L["Modifier+Click"] = "Modifier+Click"
BDT.L["Shift+Click"] = "Shift+Click"
BDT.L["Shift+RightClick"] = "Shift+RightClick"
BDT.L["Ctrl+Click"] = "Ctrl+Click"
BDT.L["Ctrl+RightClick"] = "Ctrl+RightClick"
BDT.L["Alt+Click"] = "Alt+Click"
BDT.L["Alt+RightClick"] = "Alt+RightClick"
BDT.L["Ctrl+MouseWheel"] = "Ctrl+MouseWheel"
BDT.L["Button4"] = "Button4"
BDT.L["to open panel."] = "to open panel."
BDT.L["to display config menu."] = "to display config menu."
BDT.L["to add a friend."] = "to add a friend."
BDT.L["to toggle notes."] = "to toggle notes."
BDT.L["to whisper."] = "to whisper."
BDT.L["to invite."] = "to invite."
BDT.L["to query information."] = "to query information."
BDT.L["to edit note."] = "to edit note."
BDT.L["to edit officer note."] = "to edit officer note."
BDT.L["to remove friend."] = "to remove friend."
BDT.L["to sort main column."] = "to sort main column."
BDT.L["to sort second column."] = "to sort second column."
BDT.L["to sort third column."] = "to sort third column."
BDT.L["to resize tooltip."] = "to resize tooltip."
BDT.L["Mobile App"] = "Mobile App"
BDT.L["Desktop App"] = "Desktop App"
BDT.L["OFFLINE FAVORITE"] = "OFFLINE FAVORITE"
BDT.L["MOTD"] = "MOTD"
BDT.L["No friends online."] = "No friends online."
BDT.L["Broadcast"] = "Broadcast"
BDT.L["Invalid scale.\nShould be a number between 70 and 200%"] = "Invalid scale.\nShould be a number between 70 and 200%"
BDT.L["Set a custom tooltip scale.\nEnter a value between 70 and 200 (%%)."] = "Set a custom tooltip scale.\nEnter a value between 70 and 200 (%%)."
BDT.L["Guild & Friends"] = "Guild & Friends"
BDT.L["Show guild name"] = "Show guild name"
BDT.L["Show 'Guild' tag"] = "Show 'Guild' tag"
BDT.L["Show total number of guildmates"] = "Show total number of guildmates"
BDT.L["Show 'Friends' tag"] = "Show 'Friends' tag"
BDT.L["Show total number of friends"] = "Show total number of friends"
BDT.L["Show guild XP"] = "Show guild XP"
BDT.L["Show guild XP tooltip"] = "Show guild XP tooltip"
BDT.L["Show own broadcast"] = "Show own broadcast"
BDT.L["Show bnet friends broadcast"] = "Show bnet friends broadcast"
BDT.L["Show guild notes"] = "Show guild notes"
BDT.L["Show friend notes"] = "Show friend notes"
BDT.L["Show class icon when grouped"] = "Show class icon when grouped"
BDT.L["Highlight sorted column"] = "Highlight sorted column"
BDT.L["Simple"] = "Simple"
BDT.L["Gradient"] = "Gradient"
BDT.L["Reverse gradient"] = "Reverse gradient"
BDT.L["Status as..."] = "Status as..."
BDT.L["Class colored text"] = "Class colored text"
BDT.L["Custom colored text"] = "Custom colored text"
BDT.L["Icon"] = "Icon"
BDT.L["Real ID..."] = "Real ID..."
BDT.L["Before nickname"] = "Before nickname"
BDT.L["Instead of nickname"] = "Instead of nickname"
BDT.L["After nickname"] = "After nickname"
BDT.L["Don't show"] = "Don't show"
BDT.L["Column alignments"] = "Column alignments"
BDT.L["Name"] = "Name"
BDT.L["Zone"] = "Zone"
BDT.L["Notes"] = "Notes"
BDT.L["Rank"] = "Rank"
BDT.L["Tooltip Size"] = "Tooltip Size"
BDT.L["90%"] = "90%"
BDT.L["100%"] = "100%"
BDT.L["110%"] = "110%"
BDT.L["120%"] = "120%"
BDT.L["Custom..."] = "Custom..."
BDT.L["Use TipTac skin (requires TipTac)"] = "Use TipTac skin (requires TipTac)"
BDT.L["Colors"] = "Colors"
BDT.L["Background"] = "Background"
BDT.L["Borders"] = "Borders"
BDT.L["Order highlight"] = "Order highlight"
BDT.L["Headers"] = "Headers"
BDT.L["MotD / broadcast"] = "MotD / broadcast"
BDT.L["Friendly zone"] = "Friendly zone"
BDT.L["Contested zone"] = "Contested zone"
BDT.L["Enemy zone"] = "Enemy zone"
BDT.L["Officer notes"] = "Officer notes"
BDT.L["Status"] = "Status"
BDT.L["Ranks"] = "Ranks"
BDT.L["Friends broadcast"] = "Friends broadcast"
BDT.L["Realms"] = "Realms"
BDT.L["Restore default colors"] = "Restore default colors"
BDT.L["Show Block Hints"] = "Show Block Hints"
BDT.L["Open panel"] = "Open panel"
BDT.L["Config menu"] = "Config menu"
BDT.L["Toggle notes"] = "Toggle notes"
BDT.L["Add a friend"] = "Add a friend"
BDT.L["Show Hints"] = "Show Hints"
BDT.L["Whisper"] = "Whisper"
BDT.L["Invite"] = "Invite"
BDT.L["Query"] = "Query"
BDT.L["Edit note"] = "Edit note"
BDT.L["Edit officer note"] = "Edit officer note"
BDT.L["Sort main column"] = "Sort main column"
BDT.L["Sort second column"] = "Sort second column"
BDT.L["Sort third column"] = "Sort third column"
BDT.L["Resize tooltip"] = "Resize tooltip"
BDT.L["Remove friend"] = "Remove friend"

----------------------------------------------------
-- Module settings helpers (from Core.lua)
----------------------------------------------------
function BDT:GetModuleSetting(moduleName, key, default)
    if not BDT.db or not BDT.db.profile then return default end
    local settings = BDT.db.profile.moduleSettings
    if not settings or not settings[moduleName] then return default end
    local val = settings[moduleName][key]
    if val == nil then return default end
    return val
end

function BDT:SetModuleSetting(moduleName, key, value)
    if not BDT.db or not BDT.db.profile then return end
    local settings = BDT.db.profile.moduleSettings
    if not settings then return end
    settings[moduleName] = settings[moduleName] or {}
    settings[moduleName][key] = value
end

function BDT:GetGlobalModuleSetting(key, default)
    return self:GetModuleSetting("__global__", key, default)
end

----------------------------------------------------
-- Print helper
----------------------------------------------------
function BDT:Print(...)
    print("|cffa855f7Bright|r|cff00cfff DataTexts:|r", ...)
end

----------------------------------------------------
-- Spec profile switching (stub — full impl in ProfileManager.lua)
----------------------------------------------------
BDT.ProfileManager = BDT.ProfileManager or {}


----------------------------------------------------
-- Cache
----------------------------------------------------
function BDT:BuildCache()
    self.cache.playerName       = UnitName("player")
    self.cache.playerNameLower  = self.cache.playerName:lower()
    self.cache.playerClass      = select(2, UnitClass("player"))
    self.cache.playerRealmProper= GetRealmName()
    self.cache.playerRealm      = self.cache.playerRealmProper:gsub("[^%w]", ""):lower()
    self.cache.playerFaction    = UnitFactionGroup("player")
    self.cache.playerLevel      = UnitLevel("player")
    self.cache.charKey          = self.cache.playerNameLower.."-"..self.cache.playerRealm

    -- C_ClassColor.GetClassColor returns a ColorMixin; global GetClassColor may return r,g,b directly
    local classColor = C_ClassColor and C_ClassColor.GetClassColor and C_ClassColor.GetClassColor(self.cache.playerClass)
    if classColor and classColor.GetRGB then
        self.cache.colorR, self.cache.colorG, self.cache.colorB = classColor:GetRGB()
        self.cache.colorHex = classColor:GenerateHexColor()
    else
        -- Fallback: RAID_CLASS_COLORS
        local rc = RAID_CLASS_COLORS and RAID_CLASS_COLORS[self.cache.playerClass]
        if rc then
            self.cache.colorR, self.cache.colorG, self.cache.colorB = rc.r, rc.g, rc.b
            self.cache.colorHex = string.format("%02x%02x%02x", rc.r*255, rc.g*255, rc.b*255)
        else
            self.cache.colorR, self.cache.colorG, self.cache.colorB = 1, 1, 1
            self.cache.colorHex = "ffffff"
        end
    end
    self.cache.version  = "Bright Edition"
    self.cache.moduleNames = {}
    self.cache.moduleNamesDirty = false

    self.cache.validStratas = {
        BACKGROUND=true, LOW=true, MEDIUM=true, HIGH=true,
        DIALOG=true, FULLSCREEN=true, FULLSCREEN_DIALOG=true, TOOLTIP=true,
    }
end

function BDT:ScreenCache()
    local w, h = GetPhysicalScreenSize()
    self.cache.screenWidth    = math.floor(GetScreenWidth())
    self.cache.screenHeight   = math.floor(GetScreenHeight())
    self.cache.physicalWidth  = w
    self.cache.physicalHeight = h
end

----------------------------------------------------
-- Tooltip (created at load time so modules can always use BDT.Tooltip)
----------------------------------------------------
BDT.Tooltip = CreateFrame("GameTooltip", "BrightDataTextsTooltip", UIParent, "GameTooltipTemplate")

function BDT:CreateTooltip()
    if self.Tooltip then return end
    local tt = CreateFrame("GameTooltip", "BrightDataTextsTooltip2", UIParent, "GameTooltipTemplate")
    local fontPath   = BDT.LSM:Fetch("font", self.db.profile.tooltipFont or "Friz Quadrata TT")
    local outline    = self.db.profile.tooltipFontOutline or "NONE"
    local headerSize = self.db.profile.tooltipHeaderFontSize or 14
    local lineSize   = self.db.profile.tooltipLineFontSize or 12
    local shadow     = self.db.profile.tooltipShadowEnabled
    -- GameTooltip has no SetFont() method — only child FontStrings do
    for i = 1, 30 do
        local tl = _G["BrightDataTextsTooltipTextLeft"..i]
        local tr = _G["BrightDataTextsTooltipTextRight"..i]
        for _, t in ipairs({ tl, tr }) do
            if t then
                t:SetFont(fontPath, lineSize, (outline ~= "NONE") and outline or nil)
                if shadow then t:SetShadowOffset(1,-1); t:SetShadowColor(0,0,0,1)
                else t:SetShadowOffset(0,0) end
            end
        end
    end
    -- self.Tooltip already created at load time
end

----------------------------------------------------
-- OnInitialize / OnEnable hooks (called manually below)
----------------------------------------------------
function BDT:OnInitialize()
    if self._initialized then return end
    self._initialized = true
    SetupDB()
    self:BuildCache()
    self:InitializeDatabase()
    self:CreateTooltip()
end

function BDT:OnEnable()
    self:ScreenCache()
    self.FontManager:RegisterFonts()
    self.ModuleRegistry:CreateModuleList()
    self.BarManager:CreateFromProfile()

    -- Gold tracking
    for _, ev in ipairs({
        "PLAYER_MONEY","PLAYER_ENTERING_WORLD","SEND_MAIL_MONEY_CHANGED",
        "SEND_MAIL_COD_CHANGED","PLAYER_TRADE_MONEY","TRADE_MONEY_CHANGED",
        "CURRENCY_DISPLAY_UPDATE",
    }) do
        self:RegisterEvent(ev, "UpdateGlobalGold")
    end
    self:UpdateGlobalGold()

    -- Spec switching
    self:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED", function()
        if BDT.ProfileManager and BDT.ProfileManager.SwitchToSpecProfile then
            BDT.ProfileManager:SwitchToSpecProfile()
        end
    end)
    if BDT.ProfileManager and BDT.ProfileManager.SwitchToSpecProfile then
        BDT.ProfileManager:SwitchToSpecProfile()
    end
end

----------------------------------------------------
-- Slash command (optional convenience)
----------------------------------------------------
SLASH_BRIGHTDATATEXTS1 = "/bdt"
SlashCmdList["BRIGHTDATATEXTS"] = function()
    SlashCmdList["BRIGHTQOL"]()  -- open BrightQoL > HUD > DataTexts
end

----------------------------------------------------
-- Bootstrap on PLAYER_LOGIN
-- (BrightQoL's Core.lua has already set up BrightQoL.dataPanels by now)
----------------------------------------------------
local bootFrame = CreateFrame("Frame")
bootFrame:RegisterEvent("PLAYER_LOGIN")
bootFrame:SetScript("OnEvent", function(self)
    self:UnregisterEvent("PLAYER_LOGIN")
    if not BrightQoL.dataPanels or not BrightQoL.dataPanels.enabled then return end
    BDT:OnInitialize()
    BDT:OnEnable()
end)
