local addonName, NS = ...
local GR = NS.GR

-- =========================================================================
-- UI: STRUCTURE & TABS
-- =========================================================================

function GR:UpdateResizeBounds()
    local currentScale = self:GetScale() or 1
    
    -- General Constraints adjusted for scale
    local maxWidth = 1980 / currentScale
    local maxHeight = 750 / currentScale 
    
    -- Determine Minimum Width based on Active Tab
    local minWidth = 1280
    if self.activeTab == 5 then
        minWidth = 1640 -- Enforce 1640 minimum for Guild Roster
    end

    -- Safety: MaxWidth must never be less than MinWidth (e.g., if scale is very high)
    if maxWidth < minWidth then 
        maxWidth = minWidth 
    end

    -- Apply Bounds: (minWidth, minHeight, maxWidth, maxHeight)
    self:SetResizeBounds(minWidth, 750, maxWidth, maxHeight) 
    
    -- Auto-Correct: If current width is invalid for the new constraints, snap it.
    local w = self:GetWidth()
    if w < minWidth then self:SetWidth(minWidth) end
    if w > maxWidth then self:SetWidth(maxWidth) end
end

function GR:BuildStructuralUI()
    self:SetFrameStrata("DIALOG") 
    self:SetToplevel(true)
    self:EnableMouse(true)
    self:SetMovable(true)
    self:SetResizable(true)
    self:SetClampedToScreen(true)
    self:SetSize(1280, 750) -- Increased height to accommodate new header
    self:SetPoint("CENTER")

    NS.CreateBg(self, 0, 0, 0, 0.85)
    NS.CreateBorder(self, 0.3, 0.3, 0.3, 1)

    self:RegisterForDrag("LeftButton")
    self:SetScript("OnDragStart", self.StartMoving)
    self:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
    end)
    
    self:UpdateResizeBounds()

    local resize = CreateFrame("Button", nil, self)
    resize:SetSize(16, 16); resize:SetPoint("BOTTOMRIGHT")
    resize:SetNormalTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Up")
    resize:SetHighlightTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Highlight")
    resize:SetScript("OnMouseDown", function() self:StartSizing("BOTTOMRIGHT") end)
    resize:SetScript("OnMouseUp", function() 
        self:StopMovingOrSizing() 
        if self.db then
            self.db.windowWidth = self:GetWidth()
            self.db.windowHeight = self:GetHeight()
        end
    end)
    
    table.insert(UISpecialFrames, self:GetName()) 
    
    -- =========================================================================
    -- AXIOM GLOBAL HEADER
    -- =========================================================================
    local axiomHeader = CreateFrame("Frame", "GRS_AxiomHeader", self)
    axiomHeader:SetHeight(30)
    axiomHeader:SetPoint("TOPLEFT", 0, 0)
    axiomHeader:SetPoint("TOPRIGHT", 0, 0)
    NS.CreateBg(axiomHeader, 0.1, 0.1, 0.1, 1) -- Consistent dark background
    NS.CreateBorder(axiomHeader, 0, 0, 0, 1)
    
    local axTitle = axiomHeader:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    axTitle:SetPoint("CENTER", 0, 0)
    axTitle:SetText("A.X.I.O.M.")
    axTitle:SetTextColor(0.4, 0.8, 1) -- Slight blue tint for branding
    
    -- Close Button (Moved to Global Header)
    local close = CreateFrame("Button", nil, axiomHeader)
    close:SetPoint("TOPRIGHT", -5, -3) 
    close:SetSize(24, 24)
    close:SetNormalFontObject("GameFontNormal")
    close:SetText("X")
    close:SetScript("OnClick", function() GR:Hide() end)
    NS.SkinButton(close)
    
    -- [[ NEW: Minimize Button ]]
    local minimize = CreateFrame("Button", nil, axiomHeader)
    minimize:SetPoint("RIGHT", close, "LEFT", -2, 0) 
    minimize:SetSize(24, 24)
    minimize:SetNormalFontObject("GameFontNormal")
    minimize:SetText("_")
    minimize:SetScript("OnClick", function() GR:ToggleMiniMode(true) end)
    NS.SkinButton(minimize)

-- [[ DEV: Officer Mode Override Button - DISABLED ]]
    --[[
    local devOverride = CreateFrame("Button", nil, axiomHeader)
    devOverride:SetPoint("RIGHT", minimize, "LEFT", -2, 0)
    devOverride:SetSize(24, 24)
    devOverride:SetNormalFontObject("GameFontNormalSmall")
    devOverride:SetText("OFF")
    devOverride:SetScript("OnClick", function(s)
        GR.devOfficerMode = not GR.devOfficerMode
        if GR.devOfficerMode then
            s:SetText("ON")
            s.bg:SetColorTexture(0.1, 0.8, 0.1, 1) 
            print("|cff00ff00GRS: Officer Override Enabled (Developer Mode)|r")
        else
            s:SetText("OFF")
            s.bg:SetColorTexture(0.2, 0.2, 0.2, 1) 
            print("|cffff0000GRS: Officer Override Disabled|r")
        end
        
        if GR.RR and GR.RR.Initialized then
            if (IsInGuild() and (C_GuildInfo.CanEditOfficerNote() or IsGuildLeader())) or GR.devOfficerMode then
                GR.RR.viewMode = "OFFICER"
            else
                GR.RR.viewMode = "MEMBER"
            end
            
            if GR.RR.Frame and GR.RR.Frame:IsShown() then
                GR:RR_BuildUI()
            end
        end

        if GR.UpdateRaiderIOStatus then GR:UpdateRaiderIOStatus() end
        if GR.UpdateOfficerStatus then GR:UpdateOfficerStatus() end
    end)
    NS.SkinButton(devOverride)
    devOverride:SetScript("OnEnter", function(s)
        GameTooltip:SetOwner(s, "ANCHOR_TOP")
        GameTooltip:SetText("Dev: Officer Override")
        GameTooltip:AddLine("Toggles artificial officer status for UI development.", 1, 1, 1)
        GameTooltip:Show()
    end)
    devOverride:SetScript("OnLeave", function() GameTooltip:Hide() end)
    ]]
    
    -- Initialize Minimap Button
    if self.BuildMinimapButton then self:BuildMinimapButton() end

    -- =========================================================================
    -- SIDEBAR & CONTENT LAYOUT
    -- =========================================================================
    
    local sideBar = CreateFrame("Frame", "GRS_SideBar", self)
    sideBar:SetWidth(40)
    sideBar:SetPoint("TOPLEFT", 0, -30) -- Shifted down below Axiom Header
    sideBar:SetPoint("BOTTOMLEFT", 0, 0)
    NS.CreateBg(sideBar, 0.15, 0.15, 0.15, 1)
    NS.CreateBorder(sideBar, 0, 0, 0, 1)
    self.SideBar = sideBar
    
    local container = CreateFrame("Frame", "GRS_ViewContainer", self)
    container:SetPoint("TOPLEFT", sideBar, "TOPRIGHT", 0, 0)
    container:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", 0, 0)
    self.ViewContainer = container

    -- Original Title Bar (Preserved as Sub-Header)
    local top = CreateFrame("Frame", nil, container)
    NS.CreateBg(top, 0.1, 0.1, 0.1, 1)
    top:SetHeight(30); top:SetPoint("TOPLEFT"); top:SetPoint("TOPRIGHT")
    self.TitleBar = top
    
    local title = top:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("LEFT", 10, 0); title:SetText("Guild Recruiter System")
    self.MainTitle = title
    
    local ioStatus = top:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    ioStatus:SetPoint("LEFT", title, "RIGHT", 10, 0)
    self.ioStatus = ioStatus; 
    -- Call UpdateRaiderIOStatus if it exists, logic handled in Engine usually
    if self.UpdateRaiderIOStatus then self:UpdateRaiderIOStatus() end
    
    local offStatus = top:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    offStatus:SetPoint("LEFT", ioStatus, "RIGHT", 10, 0)
    self.officerStatus = offStatus
    
    -- Tabs Generation
    self.Tabs = {}
    local tabsData = NS.Constants.TABS
    
    for i, data in ipairs(tabsData) do
        local tab = CreateFrame("Button", nil, sideBar)
        tab:SetSize(32, 32)
        tab:SetPoint("TOP", sideBar, "TOP", 0, -10 - ((i-1) * 40))
        
        local tex = tab:CreateTexture(nil, "ARTWORK")
        tex:SetAllPoints()
        tex:SetTexture(data.icon)
        tab.icon = tex
        
        tab:SetScript("OnEnter", function(s)
            GameTooltip:SetOwner(s, "ANCHOR_CURSOR")
            GameTooltip:SetText(data.title)
            GameTooltip:Show()
            if s.timer then s.timer:Cancel() end
            s.timer = C_Timer.NewTimer(5, function()
                GameTooltip:Hide()
            end)
            if s.bg then s.bg:SetColorTexture(0.3, 0.3, 0.3, 1) end
        end)
        
        tab:SetScript("OnLeave", function(s)
            GameTooltip:Hide()
            if s.timer then s.timer:Cancel() end
            if s.bg then 
                 if GR.activeTab == i then
                     s.bg:SetColorTexture(1, 1, 1, 0.2)
                 else
                     s.bg:SetColorTexture(0, 0, 0, 0)
                 end
            end
        end)
        
        tab:SetScript("OnClick", function()
            if data.id == 7 and GR.OpenSettings then
                GR:OpenSettings()
            else
                GR:SwitchView(data.id)
            end
        end)
        
        local selBg = tab:CreateTexture(nil, "BACKGROUND")
        selBg:SetAllPoints()
        selBg:SetColorTexture(1, 1, 1, 0.2)
        selBg:Hide()
        tab.selBg = selBg
        
        self.Tabs[i] = tab
    end
    
    -- [[ Build the Mini Frame Logic ]]
    self:BuildMiniFrame()
end

function GR:BuildMinimapButton()
    local btn = CreateFrame("Button", "GRS_MinimapButton", Minimap)
    btn:SetSize(32, 32)
    btn:SetFrameLevel(8)
    
    -- Highlight
    btn:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
    
    -- Icon (Background Layer)
    local bg = btn:CreateTexture(nil, "BACKGROUND")
    bg:SetSize(20, 20)
    bg:SetPoint("CENTER")
    bg:SetTexture("Interface\\AddOns\\" .. addonName .. "\\Icons\\Guild Recruitment System.tga")
    btn.icon = bg

    -- Border (Overlay Layer)
    local border = btn:CreateTexture(nil, "OVERLAY")
    border:SetSize(52, 52)
    border:SetPoint("TOPLEFT", 0, 0)
    border:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
    
    btn:RegisterForClicks("AnyUp")
    
    btn:SetScript("OnClick", function(self, button)
        if IsShiftKeyDown() then
            ReloadUI()
        else
            if GR:IsShown() then GR:Hide() else GR:Show() end
        end
    end)
    
    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:SetText("A.X.I.O.M.")
        GameTooltip:AddLine("Click to open A.X.I.O.M.", 1, 1, 1)
        GameTooltip:AddLine("SHIFT+CLICK to reload UI.", 0.7, 0.7, 0.7)
        GameTooltip:Show()
    end)
    
    btn:SetScript("OnLeave", function() GameTooltip:Hide() end)
    
    -- Drag Logic
    btn:SetMovable(true)
    btn:RegisterForDrag("LeftButton")
    
    local function UpdatePos()
        local angle = GR.db.minimapAngle or 45
        local radians = math.rad(angle)
        local radius = 100 -- Requested Radius
        local x = math.cos(radians) * radius
        local y = math.sin(radians) * radius
        btn:SetPoint("CENTER", Minimap, "CENTER", x, y)
    end
    
    btn:SetScript("OnDragStart", function(self)
        self:SetScript("OnUpdate", function()
            local mx, my = Minimap:GetCenter()
            local cx, cy = GetCursorPosition()
            local scale = Minimap:GetEffectiveScale()
            cx, cy = cx/scale, cy/scale
            
            local dx, dy = cx - mx, cy - my
            local angle = math.deg(math.atan2(dy, dx))
            GR.db.minimapAngle = angle
            UpdatePos()
        end)
    end)
    
    btn:SetScript("OnDragStop", function(self)
        self:SetScript("OnUpdate", nil)
    end)
    
    UpdatePos()
end

function GR:SwitchView(id)
    self.activeTab = id
    self:UpdateResizeBounds() -- DYNAMIC CHECK: Re-evaluate lock on tab switch
    for i, tab in ipairs(self.Tabs) do
        if i == id then
            tab:SetAlpha(1.0)
            tab.selBg:Show()
        else
            tab:SetAlpha(0.6)
            tab.selBg:Hide()
        end
    end
    if not self.views then self.views = {} end
    for viewId, frame in pairs(self.views) do
        if viewId == id then
            frame:Show()
            -- Note: Blacklist refresh logic is now handled in Blacklist.lua via OnShow or explicit calls
            -- We no longer call GR:RefreshBlacklistViews() here to avoid nil errors if logic is moved.
        else
            frame:Hide()
        end
    end
    if self.MainTitle and NS.Constants.TABS[id] then
        self.MainTitle:SetText(NS.Constants.TABS[id].title)
    end
end

function GR:BuildModuleContainers()
    -- Standard Modules (Requirements, History, Guild, Raid)
    -- Note: Blacklist (ID 2) is handled by Blacklist.lua attachment.
    if not self.views then self.views = {} end
    for i = 3, 6 do
        local f = CreateFrame("Frame", nil, self.ViewContainer)
        f:SetAllPoints()
        f:Hide()
        self.views[i] = f
    end
    -- Initialize the MVP Module
    if self.BuildMVPView then self:BuildMVPView() end
end

-- =========================================================================
-- UI: MINI MODE LOGIC (COMPACT 155x45)
-- =========================================================================

function GR:BuildMiniFrame()
    if self.MiniFrame then return end
    
    local f = CreateFrame("Frame", "GRS_MiniFrame", UIParent)
    f:SetSize(155, 45) -- Compact Dimensions
    f:SetPoint("CENTER")
    f:SetFrameStrata("DIALOG")
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
    f:Hide()
    
    NS.CreateBg(f, 0, 0, 0, 1) -- Pure Black
    NS.CreateBorder(f, 0, 0, 0, 1) -- Black Border
    
    -- CONTROLS
    local btnClose = CreateFrame("Button", nil, f)
    btnClose:SetSize(12, 12); btnClose:SetPoint("TOPRIGHT", -2, -2)
    btnClose:SetNormalFontObject("GameFontNormalSmall"); btnClose:SetText("X")
    btnClose:SetScript("OnClick", function() GR:Hide() end)
    
    local btnMax = CreateFrame("Button", nil, f)
    btnMax:SetSize(12, 12); btnMax:SetPoint("RIGHT", btnClose, "LEFT", -2, 0)
    btnMax:SetNormalFontObject("GameFontNormalSmall"); btnMax:SetText("+")
    btnMax:SetScript("OnClick", function() GR:ToggleMiniMode(false) end)
    
    -- SINGLE LINE TEXT LAYOUT
    local container = CreateFrame("Frame", nil, f)
    container:SetPoint("LEFT", 5, 0)
    container:SetPoint("RIGHT", -5, 0)
    container:SetHeight(20)
    container:SetPoint("CENTER")
    
    -- AXIOM
    local t1 = container:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    t1:SetPoint("LEFT", 0, 0)
    t1:SetText("|cff66CCFFA.X.I.O.M.|r")
    
    -- SEPARATOR
    local t2 = container:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    t2:SetPoint("LEFT", t1, "RIGHT", 2, 0)
    t2:SetText("|cffffd100|||r") -- Gold Pipe
    
    -- ACTIVE LABEL (Dynamic Color)
    local t3 = container:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    t3:SetPoint("LEFT", t2, "RIGHT", 2, 0)
    t3:SetText("Active:")
    f.ActiveLabel = t3
    
    -- COUNT
    local t4 = container:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    t4:SetPoint("LEFT", t3, "RIGHT", 2, 0)
    t4:SetText("0/0")
    f.CountLabel = t4
    
    -- ANIMATION LOGIC (Green <-> Gold Fade over 3s)
    local totalTime = 0
    f:SetScript("OnUpdate", function(self, elapsed)
        totalTime = totalTime + elapsed
        local phase = totalTime % 6
        local r, g, b
        
        -- Green: 0, 1, 0
        -- Gold:  1, 0.82, 0
        
        if phase < 3 then
            -- Fading Green to Gold
            local p = phase / 3
            r = 0 + (1 - 0) * p
            g = 1 + (0.82 - 1) * p
            b = 0
        else
            -- Fading Gold to Green
            local p = (phase - 3) / 3
            r = 1 + (0 - 1) * p
            g = 0.82 + (1 - 0.82) * p
            b = 0
        end
        
        if f.ActiveLabel then f.ActiveLabel:SetTextColor(r, g, b) end
    end)
    
    self.MiniFrame = f
end

function GR:UpdateMiniStatus()
    if not self.MiniFrame then return end
    local sent = self.batchSent or 0
    local total = self.batchTotal or 0
    -- Just update the number part to fit the single line
    self.MiniFrame.CountLabel:SetText(string.format("%d/%d", sent, total))
end

-- [[ FIXED: MISSING TOGGLE FUNCTION ]]
function GR:ToggleMiniMode(enable)
    if enable then
        self:Hide()
        if not self.MiniFrame then self:BuildMiniFrame() end
        self.MiniFrame:Show()
        self:UpdateMiniStatus()
    else
        if self.MiniFrame then self.MiniFrame:Hide() end
        self:Show()
    end
end