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 COMMANDS: /axi or /grs
SLASH_AXI_ADDON1 = "/axi"
SLASH_AXI_ADDON2 = "/grs"
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")
-- Classic fallback: Use GUILD_ROSTER_UPDATE mostly, but keep PLAYER_GUILD_UPDATE if available
GR:RegisterEvent("GUILD_ROSTER_UPDATE")
if (C_EventUtils and C_EventUtils.IsEventValid and C_EventUtils.IsEventValid("PLAYER_GUILD_UPDATE")) or (not C_EventUtils) then
    pcall(function() GR:RegisterEvent("PLAYER_GUILD_UPDATE") end)
end

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
        
        -- API Compat Check for Prefix Registration
        if C_ChatInfo and C_ChatInfo.RegisterAddonMessagePrefix then
            C_ChatInfo.RegisterAddonMessagePrefix("GRS_SYNC")
        else
            RegisterAddonMessagePrefix("GRS_SYNC")
        end
        
        local blSize = self.db and self.db.blacklist and NS.Engine and NS.Engine.GetTableSize(self.db.blacklist) or 0
        print("|cff00ff00GRS V1.2.2 (Vanilla) Loaded.|r")
        print("|cff00ffff[System]: Blacklist integrity check: " .. blSize .. " entries found.|r")
        
    elseif event == "PLAYER_ENTERING_WORLD" then
        if self.isInitialized then 
            self:UpdateRaiderIOStatus() 
            self:UpdateOfficerStatus()
        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" or event == "GUILD_ROSTER_UPDATE" then
        if self.isInitialized then self:UpdateOfficerStatus() 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.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
    for k, v in pairs(self.db.blacklist) do
        if type(v) == "boolean" then
            self.db.blacklist[k] = {
                name = k,
                rio = 0,
                heroic = "-",
                mythic = "-",
                race = "Unknown",
                fullClass = "Unknown",
                level = 0,
                zone = "Unknown"
            }
        end
    end
end