local ADDON_NAME, ns = ...

ns.ADDON_NAME = ADDON_NAME
ns.VERSION = C_AddOns and C_AddOns.GetAddOnMetadata and C_AddOns.GetAddOnMetadata(ADDON_NAME, "Version") or "1.1.0"

local DEFAULTS = {
    selectedExpansion = "all",
    selectedPatchByExpansion = {},
    discovered = {},
    favorites = {},
    showMinimapButton = true,
    showSubtitles = true,
    minimapAngle = 225,
}

local function IsSecret(value)
    return issecretvalue and issecretvalue(value) or false
end

function ns:IsSafeNumber(value)
    return not IsSecret(value) and type(value) == "number"
end

function ns:IsSafeString(value)
    return not IsSecret(value) and type(value) == "string"
end

local function InitializeDatabase()
    if type(MemoriesOfAzerothDB) ~= "table" then MemoriesOfAzerothDB = {} end
    for key, value in pairs(DEFAULTS) do
        if MemoriesOfAzerothDB[key] == nil then
            MemoriesOfAzerothDB[key] = type(value) == "table" and {} or value
        end
    end
    if type(MemoriesOfAzerothDB.discovered) ~= "table" then MemoriesOfAzerothDB.discovered = {} end
    if type(MemoriesOfAzerothDB.favorites) ~= "table" then MemoriesOfAzerothDB.favorites = {} end
    if type(MemoriesOfAzerothDB.selectedPatchByExpansion) ~= "table" then
        MemoriesOfAzerothDB.selectedPatchByExpansion = {}
    end
    -- Thumbnail review data was folded into the locked 0.1.7 manifest. Retire
    -- the temporary chooser state after preserving it in the research archive.
    MemoriesOfAzerothDB.thumbnailSelections = nil
    MemoriesOfAzerothDB.thumbnailCurationSnapshot = nil
    if MemoriesOfAzerothDB.selectedExpansion == "discovered" then
        MemoriesOfAzerothDB.selectedExpansion = "favorites"
    end
    if not ns:IsSafeString(MemoriesOfAzerothDB.selectedExpansion)
        or not ns.IsExpansionKey
        or not ns:IsExpansionKey(MemoriesOfAzerothDB.selectedExpansion) then
        MemoriesOfAzerothDB.selectedExpansion = "all"
    end
    ns.db = MemoriesOfAzerothDB
end

function ns:GetThumbnail(movieID)
    if not self:IsSafeNumber(movieID) then return nil end
    local entry = self.THUMBNAILS and self.THUMBNAILS[movieID]
    if IsSecret(entry) then return nil end
    if self:IsSafeString(entry) then return entry end
    -- Retain read compatibility with development manifests without exposing
    -- their variants in the finished player interface.
    if type(entry) == "table" and not IsSecret(entry) then
        local texture = entry.canon or entry.canonical or entry.default or entry.thumbnail or entry[1]
        if self:IsSafeString(texture) then return texture end
    end
    return nil
end

function ns:SetStatus(message, kind)
    if not self:IsSafeString(message) then return end
    if self.UI and self.UI.SetStatus then self.UI:SetStatus(message, kind) end
end

function ns:RememberMovie(movieID, title)
    if not self.db or not self:IsSafeNumber(movieID) or movieID <= 0 or movieID ~= math.floor(movieID) then return end
    local record = self.db.discovered[movieID]
    if type(record) ~= "table" then
        record = {}
        self.db.discovered[movieID] = record
    end
    if self:IsSafeString(title) and title ~= "" then record.title = title end
    record.seen = true
    if self.UI and self.UI.Refresh then self.UI:Refresh() end
end

function ns:Toggle()
    if self.UI and self.UI.Toggle then self.UI:Toggle() end
end

local function PrintHelp()
    print("|cff7fd5ffMemories of Azeroth|r: /cutscenes, /cin, or /moa opens the library. Add a movie ID to any command to preview it directly.")
end

SLASH_MEMORIESOFAZEROTH1 = "/cutscenes"
SLASH_MEMORIESOFAZEROTH2 = "/cin"
SLASH_MEMORIESOFAZEROTH3 = "/moa"
SlashCmdList.MEMORIESOFAZEROTH = function(input)
    if IsSecret(input) then return end
    input = strtrim(input or "")
    if input == "" then
        ns:Toggle()
        return
    end
    local movieID = tonumber(input)
    if movieID and movieID > 0 and movieID == math.floor(movieID) then
        ns:PlayMovie({ id = movieID, title = "Movie " .. movieID, expansion = "discovered" })
        return
    end
    PrintHelp()
end

function MemoriesOfAzeroth_AddonCompartmentFunction()
    ns:Toggle()
end

local events = CreateFrame("Frame")
events:RegisterEvent("ADDON_LOADED")
events:RegisterEvent("PLAY_MOVIE")
events:SetScript("OnEvent", function(_, event, ...)
    if event == "ADDON_LOADED" then
        local loadedName = ...
        if loadedName ~= ADDON_NAME then return end
        InitializeDatabase()
        local blizzardAvailable = ns.SkinBlizzard
            and (not ns.SkinBlizzard.IsAvailable or ns.SkinBlizzard:IsAvailable())
        if not blizzardAvailable then
            print("|cffff5555Memories of Azeroth:|r the required Retail Spellbook artwork is unavailable on this client.")
            return
        end
        ns.Skin = ns.SkinBlizzard
        if ns.Skin.SetTheme then ns.Skin:SetTheme() end
        if ns.InitializeOptions then ns:InitializeOptions() end
        if ns.InitializeMinimapButton then ns:InitializeMinimapButton() end
        if ns.InitializeUI then ns:InitializeUI() end
    elseif event == "PLAY_MOVIE" then
        local movieID = ...
        ns:RememberMovie(movieID)
    end
end)
