local addonName, NS = ...

-- =========================================================================
-- CORE: INITIALIZATION & EVENTS
-- =========================================================================

-- Create the Main Frame Object
local GR = CreateFrame("Frame", "GRS_MainFrame", UIParent)
GR:Hide()
NS.GR = GR -- Expose to Namespace for other files

-- Global reference for legacy support if needed
_G["GRS_MainFrame"] = GR

-- Core Properties
GR.isInitialized = false
GR.activeTab = 1
GR.views = {}
GR.db = {}

-- SLASH COMMAND: /axi
SLASH_AXI_ADDON1 = "/axi"
SLASH_AXI_ADDON2 = "/grs"
SLASH_AXI_ADDON1 = "/axi"
SlashCmdList["AXI_ADDON"] = function(msg) 
    if not GR.isInitialized then
        GR:Initialize()
    end
    if msg == "rio" then
        print("|cff00ffff--- GRS (AXI) RIO DIAGNOSTIC ---|r")
        return
    end
    if GR:IsShown() then GR:Hide() else GR:Show() end 
end

-- Event Registration
GR:RegisterEvent("ADDON_LOADED")
GR:RegisterEvent("WHO_LIST_UPDATE")
GR:RegisterEvent("CHAT_MSG_WHISPER")
GR:RegisterEvent("CHAT_MSG_WHISPER_INFORM")
GR:RegisterEvent("PLAYER_ENTERING_WORLD") 
GR:RegisterEvent("CHAT_MSG_ADDON")
GR:RegisterEvent("PLAYER_GUILD_UPDATE") 
GR:RegisterEvent("GUILD_ROSTER_UPDATE") -- [[ NEW: For Blacklist Guild Check ]]

GR:SetScript("OnEvent", function(self, event, ...)
    if event == "ADDON_LOADED" and ... == addonName then
        if not self.isInitialized then self:Initialize() end
        
        if self.db.scale then 
            self:SetScale(self.db.scale) 
            self:UpdateResizeBounds() 
        end
        if self.db.alpha then
            self:SetAlpha(self.db.alpha)
        end
        if self.db.windowWidth and self.db.windowHeight then
            self:SetSize(self.db.windowWidth, self.db.windowHeight)
        end
        
        -- Safety check for recent list update
        if self.UpdateRecentList then self:UpdateRecentList() end
        
        C_ChatInfo.RegisterAddonMessagePrefix("GRS_SYNC")
        
        local blSize = self.db and self.db.blacklist and NS.Engine.GetTableSize(self.db.blacklist) or 0
        local pblSize = self.db and self.db.permaBlacklist and NS.Engine.GetTableSize(self.db.permaBlacklist) or 0
        
        print("|cff00ff00GRS V1.2.3 (Perma-Blacklist) Loaded.|r")
        print("|cff00ffff[System]: Blacklist: " .. blSize .. " | Perma: " .. pblSize .. "|r")
        
    elseif event == "PLAYER_ENTERING_WORLD" then
        if self.isInitialized then 
            self:UpdateRaiderIOStatus() 
            self:UpdateOfficerStatus()
            if self.ScanGuildForBlacklistMatches then self:ScanGuildForBlacklistMatches() end
        end
    elseif event == "WHO_LIST_UPDATE" then
        self:ProcessWhoResults()
    elseif event == "CHAT_MSG_WHISPER" or event == "CHAT_MSG_WHISPER_INFORM" then
        self:HandleChatEvent(event, ...)
    elseif event == "CHAT_MSG_ADDON" then
        if self.HandleComm then self:HandleComm(...) end
    elseif event == "PLAYER_GUILD_UPDATE" then
        if self.isInitialized then self:UpdateOfficerStatus() end
    elseif event == "GUILD_ROSTER_UPDATE" then
        if self.isInitialized and self.ScanGuildForBlacklistMatches then self:ScanGuildForBlacklistMatches() end
    end
end)

function GR:Initialize()
    self:InitDB()
    self.db.debugMode = false 
    
    -- UI Initialization (Methods in Ui.lua)
    if self.BuildStructuralUI then self:BuildStructuralUI() end
    if self.BuildHomeView then self:BuildHomeView() end

    if NS and NS.Blacklist and NS.Blacklist.Attach then
        NS.Blacklist.Attach(self)
    end
    if self.BuildBlacklistView then
        self:BuildBlacklistView() 
    end
    
    if self.BuildModuleContainers then self:BuildModuleContainers() end
    if self.BuildSettingsView then
        self:BuildSettingsView() 
    end
    
    -- Engine Initialization (Methods in Engine.lua)
    if self.InjectGlobalMenus then self:InjectGlobalMenus() end
    
    -- CRITICAL FIX: Check if function exists before call
    if self.UpdateRecentList then 
        self:UpdateRecentList() 
    end
    
    if self.SwitchView then self:SwitchView(1) end
    
    self.isInitialized = true
    if self.UpdateOfficerStatus then self:UpdateOfficerStatus() end
end

function GR:InitDB()
    if not _G.GRS_DB then _G.GRS_DB = {} end
    if not _G.GRS_DB.blacklist then _G.GRS_DB.blacklist = {} end
    if not _G.GRS_DB.permaBlacklist then _G.GRS_DB.permaBlacklist = {} end -- [[ NEW ]]
    if not _G.GRS_DB.recentHistory then _G.GRS_DB.recentHistory = {} end
    if not _G.GRS_DB.templates then _G.GRS_DB.templates = {["Default"] = "Hi there!"} end
    if not _G.GRS_DB.customFilters then _G.GRS_DB.customFilters = {} end

    -- Load Defaults from Constants
    local defaults = NS.Constants.DEFAULTS
    for k, v in pairs(defaults) do
        if _G.GRS_DB[k] == nil then _G.GRS_DB[k] = v end
    end
    self.db = _G.GRS_DB
    
    -- Sanitize Blacklist
    local function Sanitize(tbl)
        for k, v in pairs(tbl) do
            if type(v) == "boolean" then
                tbl[k] = {
                    name = k,
                    rio = 0,
                    heroic = "-",
                    mythic = "-",
                    race = "Unknown",
                    fullClass = "Unknown",
                    level = 0,
                    zone = "Unknown"
                }
            end
        end
    end
    Sanitize(self.db.blacklist)
    Sanitize(self.db.permaBlacklist)
end