local addonName, ns = ...
if not ns then return end

-- ============================================================================
-- BrightQoL – Data/Media.lua
-- Single source of truth for all visual constants: colours, alphas, fonts.
-- Replaces scattered magic numbers across every module.
--
-- Usage:
--   local T = ns.Theme
--   frame:SetBackdropColor(T.bgMain.r, T.bgMain.g, T.bgMain.b, T.alpha.windowBg)
--   frame:SetBackdropBorderColor(T.accent.r, T.accent.g, T.accent.b, T.alpha.border)
--   local fontPath = ns.Media.ResolveFont("BrightQoL")
-- ============================================================================

-- ---------------------------------------------------------------------------
-- THEME
-- ---------------------------------------------------------------------------
-- All raw values live here. Nothing else in the addon should hardcode a colour.

ns.Theme = {
    -- ── Primary accent (cyan) ───────────────────────────────────────────────
    accent = { r = 0,        g = 207/255, b = 1.0,   hex = "00cfff" },

    -- ── Background layers (dark → lighter) ─────────────────────────────────
    -- bgDeep   : title bar / extreme-dark chrome                 #020202
    bgDeep   = { r = 0.01,   g = 0.01,   b = 0.01 },
    -- bgMain   : main window fill, sidebar rows                  #050509
    bgMain   = { r = 0.02,   g = 0.02,   b = 0.04 },
    -- bgPanel  : panel backgrounds, GameBar panels               #0D0D14
    bgPanel  = { r = 0.05,   g = 0.05,   b = 0.08 },
    -- bgWidget : buttons, sliders, dropdowns                     #141420
    bgWidget = { r = 0.08,   g = 0.08,   b = 0.12 },
    -- bgGroup  : sidebar group header rows                       #070710
    bgGroup  = { r = 0.03,   g = 0.03,   b = 0.06 },
    -- bgHeader : collapsible section headers                     #1A1A1A
    bgHeader = { r = 0.10,   g = 0.10,   b = 0.10 },

    -- ── Text ────────────────────────────────────────────────────────────────
    textPrimary  = { r = 1.0,  g = 1.0,  b = 1.0  },  -- white
    textMuted    = { r = 0.7,  g = 0.7,  b = 0.7  },  -- inactive labels
    textDim      = { r = 0.65, g = 0.65, b = 0.65 },  -- sidebar inactive
    textDisabled = { r = 0.5,  g = 0.5,  b = 0.5  },  -- greyed-out

    -- ── Alpha presets ───────────────────────────────────────────────────────
    -- Changing a value here updates every consumer automatically.
    alpha = {
        windowBg   = 0.95,  -- main window fill
        titleBg    = 0.90,  -- title bar fill
        contentBg  = 0.30,  -- content area overlay
        border     = 0.60,  -- standard accent border
        borderHi   = 0.90,  -- hover / active border
        separator  = 0.30,  -- thin separator lines
        widgetBg   = 0.95,  -- slider / dropdown / button fills
        glow       = 0.08,  -- inner glow on widgets
    },

    -- ── Fonts ───────────────────────────────────────────────────────────────
    fonts = {
        default = "Interface\\AddOns\\BrightQoL\\Assets\\Fonts\\Bright.ttf",
        bold    = "Interface\\AddOns\\BrightQoL\\Assets\\Fonts\\Metropolis-ExtraBold.otf",
        narrow  = "Interface\\AddOns\\BrightQoL\\Assets\\Fonts\\GothamNarrowUltra.ttf",
    },
}

-- Convenience alias used by older code (ns.THEME_ACCENT_R, etc.)
-- Prefer ns.Theme.accent.r going forward.
local T = ns.Theme
ns.THEME_ACCENT_R = T.accent.r
ns.THEME_ACCENT_G = T.accent.g
ns.THEME_ACCENT_B = T.accent.b

-- ---------------------------------------------------------------------------
-- MEDIA RESOLVER
-- ---------------------------------------------------------------------------
-- Centralises font / statusbar resolution with LibSharedMedia fallback.

ns.Media = {}

local LSM = nil  -- resolved lazily after libs load

local function GetLSM()
    if not LSM then
        LSM = LibStub and LibStub("LibSharedMedia-3.0", true)
    end
    return LSM
end

-- Internal path tables
local ADDON_FONTS = {
    -- name (lower)         → path
    ["brightqol"]           = T.fonts.default,
    ["bright"]              = T.fonts.default,
    ["metropolis extrabold"]= T.fonts.bold,
    ["metropolis-extrabold"]= T.fonts.bold,
    ["gothamnarrowultra"]   = T.fonts.narrow,
    ["gotham narrow ultra"] = T.fonts.narrow,
}

-- Resolve a font: accepts LSM name, addon short-name, or a literal path.
-- Returns a valid WoW font path, or the default addon font as fallback.
function ns.Media.ResolveFont(nameOrPath)
    if not nameOrPath or nameOrPath == "" then
        return T.fonts.default
    end

    -- 1. Already a path (contains backslash or forward slash)?
    if nameOrPath:find("[/\\]") then
        return nameOrPath
    end

    -- 2. Addon internal name lookup (case-insensitive)
    local lower = nameOrPath:lower()
    if ADDON_FONTS[lower] then
        return ADDON_FONTS[lower]
    end

    -- 3. LibSharedMedia lookup
    local lsm = GetLSM()
    if lsm then
        local path = lsm:Fetch("font", nameOrPath)
        if path then return path end
    end

    -- 4. Fallback
    return T.fonts.default
end

-- Resolve a statusbar texture: accepts LSM name or literal path.
-- Returns a valid WoW texture path, or the plain white fallback.
local PLAIN_WHITE = "Interface\\Buttons\\WHITE8x8"
function ns.Media.ResolveBar(nameOrPath)
    if not nameOrPath or nameOrPath == "" then
        return PLAIN_WHITE
    end
    if nameOrPath:find("[/\\]") then
        return nameOrPath
    end
    local lsm = GetLSM()
    if lsm then
        local path = lsm:Fetch("statusbar", nameOrPath)
        if path then return path end
    end
    return PLAIN_WHITE
end

-- Migrate stale saved-variable paths to their LSM names on first login.
-- fontKeys / barKeys: array of key strings to check in db.
-- Example: ns.Media.MigrateDB(db, {"font"}, {"barTexture"})
function ns.Media.MigrateDB(db, fontKeys, barKeys)
    if not db then return end
    local lsm = GetLSM()
    if not lsm then return end

    local function Migrate(keys, mediaType)
        for _, k in ipairs(keys or {}) do
            local v = db[k]
            if v and type(v) == "string" and v:find("[/\\]") then
                -- It's a raw path; try to find its LSM name
                local hashTable = lsm:HashTable(mediaType)
                if hashTable then
                    for name, path in pairs(hashTable) do
                        if path == v then
                            db[k] = name
                            break
                        end
                    end
                end
            end
        end
    end

    Migrate(fontKeys, "font")
    Migrate(barKeys,  "statusbar")
end

-- ---------------------------------------------------------------------------
-- HELPERS  (convenience wrappers used by Widgets.lua and UI files)
-- ---------------------------------------------------------------------------

-- SetBackdrop + fill colour in one call, using theme defaults.
-- bgKey  : key in ns.Theme (e.g. "bgWidget")
-- bgAlpha: overrides theme.alpha.widgetBg when provided
-- Returns the frame for chaining.
function ns.Media.StyledBackdrop(frame, bgKey, bgAlpha)
    local bg = ns.Theme[bgKey] or ns.Theme.bgWidget
    local a  = bgAlpha or ns.Theme.alpha.widgetBg
    frame:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1,
        insets   = { left = 1, right = 1, top = 1, bottom = 1 },
    })
    frame:SetBackdropColor(bg.r, bg.g, bg.b, a)
    local ac = ns.Theme.accent
    frame:SetBackdropBorderColor(ac.r, ac.g, ac.b, ns.Theme.alpha.border)
    return frame
end

-- Apply accent border at a given alpha without touching the fill.
function ns.Media.AccentBorder(frame, alpha)
    local ac = ns.Theme.accent
    frame:SetBackdropBorderColor(ac.r, ac.g, ac.b, alpha or ns.Theme.alpha.border)
end
