local _, WN = ...

local defaults = {
    dbVersion = 15,
    activeSection = "overview",
    settings = {
        language = "auto",
        uiScale = 100,
        opacity = 100,
        theme = "ulathek",
        customAccent = {0.07, 0.82, 0.815},
        showTracker = true,
        lockTracker = false,
        showMinimap = true,
        openOnLogin = false,
        autoRefresh = true,
        showStatusBar = false,
        checkEnchants = true,
        privateTooltips = true,
        lockWindow = false,
        smartNotifications = true,
        notifyLogin = true,
        autoSnapshot = true,
        showSearch = true,
        showFavorites = true,
        enableIntegrations = true,
        safeMode = false,
        widgetPerformance = false,
        widgetCharacter = false,
        widgetCurrency = false,
        widgetWeekly = false,
        widgetBags = false,
    },
    positions = {},
    dailyGoals = {},
    goalCycles = {},
    customTasks = {},
    characters = {},
    favorites = {},
    minimapAngle = 2.35,
    firstRun11 = true,
    addonFilter = nil,
    altSort = "lastSeen",
}

local eventFrame = CreateFrame("Frame")

function WN:InitializeDatabase()
    local previous = WoWNextDB or {}
    WoWNextDB = self:CopyDefaults(defaults, previous)
    self.db = WoWNextDB

    if previous.settings and previous.settings.windowOpacity and previous.settings.opacity == nil then
        self.db.settings.opacity = self:Clamp(previous.settings.windowOpacity, 60, 100)
    end
    if self.db.activeSection == "home" or self.db.activeSection == "adventure" or self.db.activeSection == "professions" then
        local migration = { home = "overview", adventure = "activities", professions = "tools" }
        self.db.activeSection = migration[self.db.activeSection] or "overview"
    end
    local validSections = { overview=true, planner=true, character=true, gear=true, activities=true, endgame=true, alts=true, collections=true, tools=true, settings=true }
    if not validSections[self.db.activeSection] then self.db.activeSection = "overview" end

    if (tonumber(previous.dbVersion) or 0) < 14 then
        local oldTheme = self.db.settings and self.db.settings.theme
        if oldTheme == nil or oldTheme == "midnight" or oldTheme == "minimal" or oldTheme == "transparent" then
            self.db.settings.theme = "ulathek"
        end
    end

    if (tonumber(previous.dbVersion) or 0) < 15 then
        local oldTheme = self.db.settings and self.db.settings.theme
        if oldTheme == nil or oldTheme == "midnight" or oldTheme == "ulathek" then
            self.db.settings.theme = "ulathek"
        end
    end

    self.db.dbVersion = 15
    self:ApplyLocale()
    self:ApplyTheme(self.db.settings.theme or "midnight", false)
    self:InitDiagnostics()
end

function WN:ResetAllSettings()
    WoWNextDB = self:CopyDefaults(defaults, {})
    WoWNextDB.firstRun11 = false
    self.db = WoWNextDB
    self:ApplyLocale(); self:ApplyTheme(self.db.settings.theme, true); self:ResetPositions(); self:ResetHUDPositions(); self:ApplySettings(); self:UpdateStaticTexts(); self:RefreshAll(); self:Print(self:T("SETTINGS_RESET_DONE"))
end

function WN:ScheduleRefresh()
    if not self.db or not self.db.settings.autoRefresh or self.db.settings.safeMode or self.refreshScheduled then return end
    if not self.frame or not self.frame:IsShown() then return end
    self.refreshScheduled = true
    C_Timer.After(0.65, function()
        WN.refreshScheduled = false
        if WN.frame and WN.frame:IsShown() then WN:RefreshActiveSection() end
    end)
end

function WN:OnPlayerLogin()
    self:InitializeDatabase()
    self:RequestEndgameData(true)
    self:CreateMainFrame()
    self:CheckGoalResets()
    self:RefreshAll()
    C_Timer.After(2.0, function()
        if WN.frame then
            WN:RefreshAll()
            if WN.cachedOverview then
                WN:SaveCharacterSnapshot(WN.cachedOverview, true)
                if type(GetTime) == "function" then WN.lastAltDetailedSnapshot = GetTime() end
            end
            WN:ShowLoginSummary(WN.cachedOverview)
        end
    end)
    if self.db.firstRun11 then
        self.db.firstRun11 = false
        C_Timer.After(1.0, function()
            if WN.frame then WN.frame:Show(); WN:ShowSection("overview"); WN:Print(WN:T("FIRST_RUN")) end
        end)
    elseif self.db.settings.openOnLogin then
        C_Timer.After(0.8, function() if WN.frame then WN.frame:Show(); WN:RefreshAll() end end)
    end
end

function WoWNext_OnAddonCompartmentClick(_, mouseButton)
    if mouseButton == "RightButton" then WN:OpenSettings() else WN:Toggle() end
end

function WoWNext_OnAddonCompartmentEnter(button)
    local owner = type(button)=="table" and button or AddonCompartmentFrame or UIParent
    local tip = WN:PrepareHoverTooltip(owner, "ANCHOR_LEFT")
    tip:SetText("WoWNext",1,1,1)
    tip:AddLine(WN:T("TOOLTIP_OPEN"),0.7,0.85,0.9)
    tip:AddLine(WN:T("TOOLTIP_SETTINGS"),0.7,0.85,0.9)
    tip:Show()
end
function WoWNext_OnAddonCompartmentLeave() WN:HideHoverTooltip() end

local events = {
    "ADDON_LOADED","PLAYER_LOGIN","PLAYER_LOGOUT","PLAYER_ENTERING_WORLD","PLAYER_EQUIPMENT_CHANGED","PLAYER_SPECIALIZATION_CHANGED","PLAYER_LEVEL_UP",
    "BAG_UPDATE_DELAYED","QUEST_LOG_UPDATE","CURRENCY_DISPLAY_UPDATE","UPDATE_FACTION","WEEKLY_REWARDS_UPDATE","CHALLENGE_MODE_COMPLETED","CHALLENGE_MODE_MAPS_UPDATE",
    "UPDATE_INSTANCE_INFO","PLAYER_MONEY","GET_ITEM_INFO_RECEIVED","MYTHIC_PLUS_CURRENT_AFFIX_UPDATE","MYTHIC_PLUS_NEW_WEEKLY_RECORD","ADDON_ACTION_BLOCKED","ADDON_ACTION_FORBIDDEN",
}
for _, event in ipairs(events) do pcall(eventFrame.RegisterEvent, eventFrame, event) end

eventFrame:SetScript("OnEvent", function(_, event, arg1, arg2)
    if event == "ADDON_LOADED" then
        if arg1 == WN.name then WN:InitializeDatabase() end
        return
    end
    if event == "PLAYER_LOGIN" then WN:OnPlayerLogin(); return end
    if event == "PLAYER_LOGOUT" then if WN.cachedOverview then WN:SaveCharacterSnapshot(WN.cachedOverview, true) end; return end
    if event == "ADDON_ACTION_BLOCKED" or event == "ADDON_ACTION_FORBIDDEN" then WN:RecordBlockedAction(arg1,arg2); return end
    if event == "CHALLENGE_MODE_MAPS_UPDATE" or event == "MYTHIC_PLUS_CURRENT_AFFIX_UPDATE" then WN:RequestEndgameData() end
    WN:ScheduleRefresh()
end)

SLASH_WOWNEXT1 = "/wnext"
SLASH_WOWNEXT2 = "/wn"
SlashCmdList.WOWNEXT = function(message)
    message = strtrim(message or "")
    local lower = string.lower(message)
    if lower == "settings" then WN:OpenSettings()
    elseif lower == "overview" or lower == "home" then WN.frame:Show(); WN:ShowSection("overview")
    elseif lower == "planner" or lower == "planer" then WN.frame:Show(); WN:ShowSection("planner")
    elseif lower == "character" or lower == "char" then WN.frame:Show(); WN:ShowSection("character")
    elseif lower == "gear" then WN.frame:Show(); WN:ShowSection("gear")
    elseif lower == "activities" or lower == "activity" then WN.frame:Show(); WN:ShowSection("activities")
    elseif lower == "endgame" or lower == "mythic" or lower == "raid" or lower == "delves" then WN.frame:Show(); WN:ShowSection("endgame")
    elseif lower == "alts" or lower == "characters" then WN.frame:Show(); WN:ShowSection("alts")
    elseif lower == "collections" or lower == "collection" then WN.frame:Show(); WN:ShowSection("collections")
    elseif lower == "tools" or lower == "addons" then WN.frame:Show(); WN:ShowSection("tools")
    elseif lower == "diagnostics" or lower == "diag" then WN:OpenDiagnosticDialog()
    elseif lower == "reset" then WN:RequestResetSettings()
    elseif lower == "editor" then WN:ToggleEditorMode()
    elseif lower == "color" or lower == "farbe" then WN:ApplyTheme("custom", true); WN:OpenCustomColorPicker()
    elseif lower == "safe" then WN:SetSafeMode(not WN.db.settings.safeMode)
    elseif lower == "export" then WN:OpenProfileDialog("export")
    elseif lower == "import" then WN:OpenProfileDialog("import")
    elseif string.sub(lower,1,7) == "search " then WN:SearchNavigate(string.sub(message,8))
    else WN:Toggle() end
end
