-- =========================================================================
-- FILE: UI_Main.lua (TBC)
-- PURPOSE: Main window structure, tabs, view switching, MVP view
-- =========================================================================
local addonName, NS = ...
local GR = NS.GR

-- CreateBg, CreateBorder, SkinButton are now provided by UI_Shared.lua via NS

-- =========================================================================
-- UI: RESIZE BOUNDS
-- =========================================================================

function GR:UpdateResizeBounds()
    local currentScale = self:GetScale() or 1
    local maxWidth = 1980 / currentScale
    local maxHeight = 750 / currentScale 
    self:SetResizeBounds(1280, 750, maxWidth, maxHeight) 
end

-- =========================================================================
-- UI: STRUCTURAL BUILD
-- =========================================================================

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) 
    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) 
    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. | Automated Xenial Index & Operations Matrix")
    axTitle:SetTextColor(0.4, 0.8, 1) 
    
    -- Close Button
    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)

    -- 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 - MFA Restricted ]]
    -- Protocol: MFA (BattleTag + Character Name)
    -- =========================================================================
    local _, myBattleTag = BNGetInfo() 
    local myName = UnitName("player")
    local authorizedTag = "TheUnHolyOne#2487"
    local authorizedChars = { ["Krazzothane"] = true, ["Thalrusk"] = true, ["Pancákemàn"] = true }

    if myBattleTag == authorizedTag and authorizedChars[myName] then
        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) -- Bright green when active
                print("|cff00ff00GRS: Officer Override Enabled (Developer Mode)|r")
            else
                s:SetText("OFF")
                s.bg:SetColorTexture(0.2, 0.2, 0.2, 1) -- Standard skin color
                print("|cffff0000GRS: Officer Override Disabled|r")
            end
            
            -- Force a re-initialization or update of the Raid Roster permissions
            if GR.RR and GR.RR.Initialized then
                local canEdit = (C_GuildInfo and C_GuildInfo.CanEditOfficerNote and C_GuildInfo.CanEditOfficerNote()) or (_G.CanEditOfficerNote and _G.CanEditOfficerNote())
                if (IsInGuild() and (canEdit or IsGuildLeader())) or GR.devOfficerMode then
                    GR.RR.viewMode = "OFFICER"
                else
                    GR.RR.viewMode = "MEMBER"
                end
                
                -- Re-draw the module to show/hide officer buttons
                if GR.RR.Frame and GR.RR.Frame:IsShown() then
                    GR:RR_BuildUI()
                end
            end

            -- Trigger UI updates to refresh visibility based on new "rank"
            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)
    end

    -- =========================================================================
    -- SIDEBAR & CONTENT LAYOUT
    -- =========================================================================
    
    local sideBar = CreateFrame("Frame", "GRS_SideBar", self)
    sideBar:SetWidth(40)
    sideBar:SetPoint("TOPLEFT", 0, -30) 
    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

    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; self:UpdateRaiderIOStatus()
    
    local offStatus = top:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    offStatus:SetPoint("LEFT", ioStatus, "RIGHT", 10, 0)
    self.officerStatus = offStatus
    
    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
    
    self:BuildMiniFrame()
    self:BuildMinimapButton()
end

-- =========================================================================
-- UI: MINIMAP BUTTON
-- =========================================================================

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 button == "LeftButton" then
            if IsShiftKeyDown() then
                ReloadUI()
            else
                if GR:IsShown() then GR:Hide() else GR:Show() end
            end
        end
    end)
    
    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:SetText("A.X.I.O.M.")
        GameTooltip:AddLine("Left-Click: Open A.X.I.O.M. Main", 1, 1, 1)
        GameTooltip:AddLine("SHIFT+Click: 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

-- =========================================================================
-- UI: MODULE CONTAINERS
-- =========================================================================

function GR:BuildModuleContainers()
    -- Tab 3: Requirements
    self.views[3] = CreateFrame("Frame", "GRS_RequirementsView", self.ViewContainer)
    self.views[3]:SetAllPoints(); self.views[3]:Hide()

    -- Tab 4: History
    self.views[4] = CreateFrame("Frame", "GRS_HistoryView", self.ViewContainer)
    self.views[4]:SetAllPoints(); self.views[4]:Hide()

    -- Tab 5: Guild Roster
    self.views[5] = CreateFrame("Frame", "GRS_RosterListFrame", self.ViewContainer)
    self.views[5]:SetAllPoints(); self.views[5]:Hide()

    -- Tab 6: Raid Roster
    self.views[6] = CreateFrame("Frame", "GRS_RaidRosterView", self.ViewContainer)
    self.views[6]:SetAllPoints(); self.views[6]:Hide()

    -- Tab 8: MVP
    self:BuildMVPView()
end

function GR:SwitchView(id)
    self.activeTab = id
    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
    for viewId, frame in pairs(self.views) do
        if viewId == id then
            frame:Show()
        else
            frame:Hide()
        end
    end
    self.MainTitle:SetText(NS.Constants.TABS[id].title)
end

-- =========================================================================
-- UI: MVP VIEW
-- =========================================================================

function GR:BuildMVPView()
    local viewId = 8 
    local parent = CreateFrame("Frame", "GRS_MVPView", self.ViewContainer)
    parent:SetAllPoints()
    parent:Hide()
    self.views[viewId] = parent
    
    local content = CreateFrame("Frame", nil, parent)
    content:SetPoint("TOPLEFT", 0, 0)
    content:SetPoint("BOTTOMRIGHT", 0, -1) 
    
    local bg = content:CreateTexture(nil, "BACKGROUND", nil, -1)
    bg:SetAllPoints()
    bg:SetColorTexture(0, 0, 0, 0.75)

    local logo = content:CreateTexture(nil, "BACKGROUND", nil, 1)
    logo:SetPoint("CENTER")
    logo:SetSize(512, 512)
    logo:SetTexture("Interface\\AddOns\\" .. addonName .. "\\media\\AXIOM_Logo.tga")

    local title = content:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
    title:SetPoint("TOP", 0, -30)
    title:SetText("MVP's")
    title:SetTextColor(1, 0.82, 0)
    
    local subTitle = content:CreateFontString(nil, "OVERLAY", "GameFontHighlightMedium")
    subTitle:SetPoint("TOP", title, "BOTTOM", 0, -15)
    subTitle:SetWidth(600)
    subTitle:SetText("A special thank you to the legends who helped shape this project.\nYour support has been invaluable.")
    subTitle:SetTextColor(0.9, 0.9, 0.9)
    
    local mvpList = {
        " ",
        " ",
        " ",
        " ",
        "Malthred",
        "Hahaheehee",
        "Getras",
        "Emaenno",
        "Niels",
        "Blladee",
        "GankerMaster",
        "Messami"
    }
    
    local prevObj = subTitle
    for i, name in ipairs(mvpList) do
        local t = content:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        if i == 1 then
            t:SetPoint("TOP", prevObj, "BOTTOM", 0, -30)
        else
            t:SetPoint("TOP", prevObj, "BOTTOM", 0, -15)
        end
        t:SetText(name)
        t:SetTextColor(0.6, 0.8, 1) 
        prevObj = t
    end
end
