local AddonName, Kz = ...
Kz.Rep = {}

function Kz.Rep.Init(parent)
    local scroll = CreateFrame("ScrollFrame", nil, parent, "UIPanelScrollFrameTemplate")
    scroll:SetPoint("TOPLEFT", 50, -30); scroll:SetPoint("BOTTOMRIGHT", -50, 30)
    
    local content = CreateFrame("Frame", nil, scroll); content:SetSize(1,1)
    scroll:SetScrollChild(content)
    
    Kz.UI.Views.Rep = scroll
    Kz.UI.Views.RepContent = content
    scroll:Hide()
end

function Kz.Rep.Update()
    local view = Kz.UI.Views.Rep
    if not view:IsShown() then return end
    
    local V = Kz.UI.Views.RepContent
    V:SetWidth(view:GetWidth())
    
    if Kz.UI.RepGroups then for _, g in pairs(Kz.UI.RepGroups) do g:Hide() end end
    
    local i = 1
    while i <= C_Reputation.GetNumFactions() do
        local data = C_Reputation.GetFactionDataByIndex(i)
        if data and data.isHeader and data.isCollapsed then
            C_Reputation.ExpandFactionHeader(i)
        else
            i = i + 1
        end
    end
    
    local num = C_Reputation.GetNumFactions()
    local yMain = -10
    local currentGroup = nil
    local groupIndex = 0
    local lineIndex = 0
    
    for i = 1, num do
        local data = C_Reputation.GetFactionDataByIndex(i)
        if data then
            local isHeader = data.isHeader
            local isChild = data.isChild
            local hasRep = data.hasRep or data.isHeaderWithRep 
            
            if isHeader and not isChild then
                groupIndex = groupIndex + 1
                if not Kz.UI.RepGroups[groupIndex] then
                    local f = CreateFrame("Frame", nil, V, "BackdropTemplate")
                    f:SetSize(960, 50); Kz.SkinFrame(f)
                    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge"); f.title:SetPoint("TOP", 0, -5)
                    f.lines = {}; Kz.UI.RepGroups[groupIndex] = f
                end
                currentGroup = Kz.UI.RepGroups[groupIndex]
                currentGroup:SetPoint("TOP", 0, yMain)
                currentGroup.title:SetText(data.name)
                currentGroup:Show()
                for _, l in pairs(currentGroup.lines) do l:Hide() end
                lineIndex = 0
            end

            if not currentGroup and not isHeader then
                groupIndex = groupIndex + 1
                if not Kz.UI.RepGroups[groupIndex] then
                    local f = CreateFrame("Frame", nil, V, "BackdropTemplate")
                    f:SetSize(960, 50); Kz.SkinFrame(f)
                    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge"); f.title:SetPoint("TOP", 0, -5)
                    f.lines = {}; Kz.UI.RepGroups[groupIndex] = f
                end
                currentGroup = Kz.UI.RepGroups[groupIndex]
                currentGroup:SetPoint("TOP", 0, yMain)
                currentGroup.title:SetText("Autres")
                currentGroup:Show()
                for _, l in pairs(currentGroup.lines) do l:Hide() end
                lineIndex = 0
            end

            if (not isHeader or hasRep) and currentGroup then
                lineIndex = lineIndex + 1
                
                -- --- CRÉATION DE LA BARRE ---
                if not currentGroup.lines[lineIndex] then
                    local f = CreateFrame("StatusBar", nil, currentGroup)
                    f:SetSize(450, 16)
                    f:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
                    f:GetStatusBarTexture():SetHorizTile(false)
                    f:SetMinMaxValues(0, 100)
                    
                    f.bg = f:CreateTexture(nil, "BACKGROUND")
                    f.bg:SetTexture("Interface\\TargetingFrame\\UI-StatusBar")
                    f.bg:SetAllPoints(true); f.bg:SetVertexColor(0.2, 0.2, 0.2, 0.5)
                    
                    f.name = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
                    f.name:SetPoint("LEFT", 5, 0)
                    f.val = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
                    f.val:SetPoint("RIGHT", -5, 0)
                    
                    f:EnableMouse(true)
                    
                    -- === OUVERTURE VIA LE GUIDE DE L'AVENTURIER ===
                    f:SetScript("OnMouseUp", function(self)
                        if self.isRenown and self.factionID then
                            -- 1. On cache ton addon pour libérer l'écran
                            if Kz.UI.Main and Kz.UI.Main:IsShown() then 
                                Kz.UI.Main:Hide() 
                            end

                            -- 2. On charge l'addon officiel du Guide de l'Aventurier (Encounter Journal)
                            if not C_AddOns.IsAddOnLoaded("Blizzard_EncounterJournal") then
                                UIParentLoadAddOn("Blizzard_EncounterJournal")
                            end

                            -- 3. On ouvre le Guide de l'Aventurier
                            if ToggleEncounterJournal then
                                ToggleEncounterJournal()
                            elseif EncounterJournal then
                                ShowUIPanel(EncounterJournal)
                            end
                            
                            -- Note : Quand Blizzard documentera complètement l'API de Midnight, 
                            -- nous pourrons ajouter ici la ligne précise pour cibler la bonne faction 
                            -- directement dans l'onglet Excursions. En attendant, cela t'ouvrira la bonne fenêtre !
                        end
                    end)
                    -- ===============================================
                    
                    f:SetScript("OnEnter", function(self)
                        if self.isRenown then
                            self.bg:SetVertexColor(1, 0.82, 0, 0.6)
                            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                            GameTooltip:SetText("Clic gauche pour ouvrir les Excursions", 1, 0.82, 0)
                            GameTooltip:Show()
                        end
                    end)
                    
                    f:SetScript("OnLeave", function(self)
                        self.bg:SetVertexColor(0.2, 0.2, 0.2, 0.5) 
                        GameTooltip:Hide()
                    end)
                    
                    currentGroup.lines[lineIndex] = f
                end
                
                -- --- MISE À JOUR DE LA BARRE ---
                local bar = currentGroup.lines[lineIndex]
                local col = (lineIndex % 2 == 1) and 0 or 1
                local row = math.ceil(lineIndex / 2)
                bar:SetPoint("TOPLEFT", 20 + (col * 470), -30 - ((row - 1) * 20))
                
                local barMin = data.currentReactionThreshold or 0
                local barMax = data.nextReactionThreshold or 0
                local barVal = data.currentStanding or 0
                local percent = 0
                local repText = _G["FACTION_STANDING_LABEL"..(data.reaction or 4)] or "Neutre"
                local isSpecialSystem = false
                local isRenown = false
                
                if C_MajorFactions and data.factionID then
                    local majorData = C_MajorFactions.GetMajorFactionData(data.factionID)
                    if majorData then
                        isSpecialSystem = true
                        isRenown = true
                        if C_MajorFactions.HasMaximumRenown(data.factionID) then
                            percent = 100
                            repText = "Renom Max"
                        else
                            barMin = 0
                            barMax = majorData.renownLevelThreshold
                            barVal = majorData.renownReputationEarned
                            if barMax > 0 then percent = (barVal / barMax) * 100 end
                            repText = "Renom " .. majorData.renownLevel
                        end
                    end
                end

                if not isSpecialSystem and data.factionID and C_GossipInfo and C_GossipInfo.GetFriendshipReputation then
                    local repInfo = C_GossipInfo.GetFriendshipReputation(data.factionID)
                    if repInfo and repInfo.friendshipFactionID and repInfo.friendshipFactionID > 0 then
                        isSpecialSystem = true
                        barMin = repInfo.reactionThreshold or 0
                        barMax = repInfo.nextThreshold or 0
                        barVal = repInfo.standing or 0
                        if barMax and barMax > 0 then
                            percent = ((barVal - barMin) / (barMax - barMin)) * 100
                        else
                            percent = 100 
                        end
                        repText = repInfo.reaction or "Amical"
                    end
                end
                
                if not isSpecialSystem then
                    if barMax == 0 or barMax == barMin then
                        percent = 100
                    elseif barMax > barMin then
                        percent = ((barVal - barMin) / (barMax - barMin)) * 100
                    end
                end
                
                if percent > 100 then percent = 100 end
                
                bar.factionID = data.factionID
                bar.isRenown = isRenown
                
                bar:SetValue(percent)
                local r, g, b = Kz.GetGradientColor(percent)
                bar:SetStatusBarColor(r, g, b)
                bar.name:SetText(data.name)
                bar.val:SetText(string.format("%s (%.0f%%)", repText, percent))
                bar:Show()
                
                currentGroup:SetHeight((math.ceil(lineIndex / 2) * 20) + 40)
            end
        end
    end
    
    local runningY = -10
    for idx=1, groupIndex do 
        local g = Kz.UI.RepGroups[idx]
        if g:IsShown() then
            g:SetPoint("TOP", 0, runningY)
            runningY = runningY - g:GetHeight() - 10 
        end
    end
    V:SetHeight(math.abs(runningY))
end