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: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
        print("|cff00ff00GRS V1.2.2 (Refactored /axi) Loaded.|r")
        print("|cff00ffff[System]: Blacklist integrity check: " .. blSize .. " entries found.|r")
        
        -- [[ COMPACT MODE INIT: Restore AFTER all geometry is applied ]]
        if self.db.compactMode and self.ToggleCompactMode then
            self:ToggleCompactMode(true)
        end
        
        -- [[ FIX: Force-fill Level Range inputs when addon window becomes visible ]]
        self:HookScript("OnShow", function(s)
            if s.LevelMinInput then
                local minTxt = s.LevelMinInput:GetText()
                if minTxt == "" or minTxt == "0" then
                    s.LevelMinInput:SetText(tostring(s.db.minLevel or 70))
                end
                s.LevelMinInput:SetCursorPosition(0)
            end
            if s.LevelMaxInput then
                local maxTxt = s.LevelMaxInput:GetText()
                if maxTxt == "" or maxTxt == "0" then
                    s.LevelMaxInput:SetText(tostring(s.db.maxLevel or 70))
                end
                s.LevelMaxInput:SetCursorPosition(0)
            end
        end)
        
    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" 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

-- =========================================================================
-- UTILITY: COPY NAME-REALM POPUP
-- =========================================================================

function NS.ShowCopyPopup(nameText)
    if not nameText or nameText == "" then return end

    -- Ensure full Name-Realm format
    if not nameText:find("-") then
        local realm = GetNormalizedRealmName and GetNormalizedRealmName() or GetRealmName() or ""
        nameText = nameText .. "-" .. realm
    end

    if not NS._copyPopup then
        local f = CreateFrame("Frame", "GRS_CopyPopup", UIParent)
        f:SetSize(280, 50)
        f:SetPoint("CENTER")
        f:SetFrameStrata("FULLSCREEN_DIALOG")
        f:SetFrameLevel(500)
        f:EnableMouse(true)
        NS.CreateBg(f, 0, 0, 0, 0.95)
        NS.CreateBorder(f, 0.4, 0.4, 0.4, 1)

        local label = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        label:SetPoint("TOP", 0, -5)
        label:SetText("Ctrl+C to copy, then Escape")
        label:SetTextColor(0.7, 0.7, 0.7)

        local eb = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
        eb:SetSize(250, 20)
        eb:SetPoint("BOTTOM", 0, 8)
        eb:SetAutoFocus(true)
        eb:SetFontObject(ChatFontNormal)

        eb:SetScript("OnEscapePressed", function() f:Hide() end)
        eb:SetScript("OnKeyUp", function(self, key)
            if IsControlKeyDown() and key == "C" then f:Hide() end
        end)

        -- Click-outside catcher
        local catcher = CreateFrame("Button", nil, UIParent)
        catcher:SetFrameStrata("FULLSCREEN_DIALOG")
        catcher:SetFrameLevel(499)
        catcher:SetAllPoints()
        catcher:SetScript("OnClick", function() f:Hide() end)
        catcher:SetNormalTexture("")
        catcher:Hide()

        f:SetScript("OnShow", function() catcher:Show() end)
        f:SetScript("OnHide", function() catcher:Hide() end)

        NS._copyPopup = f
        NS._copyPopupEB = eb
    end

    NS._copyPopupEB:SetText(nameText)
    NS._copyPopup:Show()
    NS._copyPopupEB:HighlightText()
    NS._copyPopupEB:SetFocus()
end