--[[
============================================================================
Enhanced Toy Tracker  -  EToy/Core/Init.lua
============================================================================
Namespace bootstrap for the toy browser. Mirrors EMT/EPT exactly: every
file does `local ADDON_NAME, NS = ...` and reaches the addon table via
NS.ETT. The toy *data* (NS.ETT.ToyData, 167 toys) ships in Data/ToyData.lua
and loads earlier; this module adds the API, UI, and launcher hookup so the
toys are actually browsable — previously the data was stored but unsurfaced.

Nothing is written to _G except the slash-command globals (required by the
WoW API). Namespace key is ETT ("Enhanced Toy Tracker") to match the table
ToyData.lua already populates.
============================================================================
]]--

local ADDON_NAME, NS = ...

NS.ETT = NS.ETT or {}
local ETT = NS.ETT
local ETB = NS.ETB

ETT.version = "1.0.0"
ETT.debug   = false

-- ============================================================================
-- C_TIMER FALLBACK (defensive; the retail-engine client has it, but guard anyway)
-- ============================================================================
if not C_Timer then
    C_Timer = {}
    function C_Timer.After(delay, callback)
        local f = CreateFrame("Frame")
        f.elapsed = 0
        f:SetScript("OnUpdate", function(self, e)
            self.elapsed = self.elapsed + e
            if self.elapsed >= delay then
                self:SetScript("OnUpdate", nil)
                callback()
            end
        end)
    end
end

-- ============================================================================
-- OUTPUT HELPERS
-- ============================================================================
local PREFIX = "|cffffcc33EToy|r "

function ETT:Print(msg)
    DEFAULT_CHAT_FRAME:AddMessage(PREFIX .. tostring(msg))
end

function ETT:Printf(fmt, ...)
    DEFAULT_CHAT_FRAME:AddMessage(PREFIX .. string.format(fmt, ...))
end

function ETT:Debug(tag, msg)
    if not self.debug then return end
    DEFAULT_CHAT_FRAME:AddMessage(PREFIX .. "|cff888888[" .. tostring(tag) .. "]|r " .. tostring(msg))
end

function ETT:Error(msg)
    DEFAULT_CHAT_FRAME:AddMessage(PREFIX .. "|cffff4444Error:|r " .. tostring(msg))
end

-- ============================================================================
-- TINY EVENT BUS (collection-changed signal so the browser refreshes live)
-- ============================================================================
local listeners = {}

function ETT:On(signal, fn)
    listeners[signal] = listeners[signal] or {}
    table.insert(listeners[signal], fn)
end

function ETT:Emit(signal, ...)
    local list = listeners[signal]
    if not list then return end
    for _, fn in ipairs(list) do
        local ok, err = pcall(fn, ...)
        if not ok then ETT:Debug("EventBus", "listener error: " .. tostring(err)) end
    end
end

-- ============================================================================
-- DEFERRED INIT (run after PLAYER_ENTERING_WORLD; never block the load screen)
-- ============================================================================
local initFns = {}
function ETT:RegisterInit(fn) table.insert(initFns, fn) end

local bootFrame = CreateFrame("Frame")
bootFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
bootFrame:RegisterEvent("TOYS_UPDATED")
bootFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_ENTERING_WORLD" then
        self:UnregisterEvent("PLAYER_ENTERING_WORLD")
        local function runInit()
            for _, fn in ipairs(initFns) do
                local ok, err = pcall(fn)
                if not ok then ETT:Error("init failed: " .. tostring(err)) end
            end
            ETT.initialized = true
            ETT:Debug("Init", "Enhanced Toy Tracker v" .. ETT.version .. " ready.")
        end
        if ETB and ETB.RunWhenStartupIdle then
            ETB:RunWhenStartupIdle("etoy.init", runInit, { delay = 2, interval = 2, maxWait = 180 })
        else
            C_Timer.After(0, runInit)
        end
    elseif event == "TOYS_UPDATED" then
        ETT:Emit("ETT_COLLECTION_CHANGED")
    end
end)

BINDING_HEADER_EToyBINDING = "Enhanced Toy Tracker"
