-- HDG_Favorites.lua
-- Per-account favorite-decor set. Persists in HDG_DB.favorites = { [itemID] = true }.
-- Survives catalog cache rebuilds because it lives in SavedVariables and is keyed
-- by itemID (not catalog index). Pass-through preserved by HDG_Store:SaveToSavedVariables.

local HDG = _G.HousingDecorGuide
HDG.Favorites = HDG.Favorites or {}
local F = HDG.Favorites

local _subscribers = {}

local function ensureTable()
    HDG_DB = HDG_DB or {}
    HDG_DB.favorites = HDG_DB.favorites or {}
    return HDG_DB.favorites
end

function F.IsFavorited(itemID)
    if not itemID then return false end
    return ensureTable()[itemID] == true
end

function F.GetAll()
    return ensureTable()
end

function F.Count()
    local n = 0
    for _ in pairs(ensureTable()) do n = n + 1 end
    return n
end

local function notify(itemID, state)
    for _, fn in ipairs(_subscribers) do
        local ok, err = pcall(fn, itemID, state)
        if not ok then print("|cFFFF0000[HDG Favorites]|r subscriber error: " .. tostring(err)) end
    end
end

function F.Set(itemID, on)
    if not itemID then return end
    local t = ensureTable()
    local newState = on and true or nil
    if t[itemID] == newState then return end
    t[itemID] = newState
    if HDG.EventBus and HDG.EventBus.Fire then
        HDG.EventBus:Fire("HDG_FAVORITES_UPDATED", itemID, on and true or false)
    end
    notify(itemID, on and true or false)
end

function F.Toggle(itemID)
    if not itemID then return false end
    local t = ensureTable()
    local newState = not t[itemID]
    F.Set(itemID, newState)
    return newState
end

-- Local subscribe — direct callback (avoids EventBus init order on early load)
function F.Subscribe(fn)
    for _, existing in ipairs(_subscribers) do
        if existing == fn then return end
    end
    _subscribers[#_subscribers + 1] = fn
end
