local AddonName, Kz = ...

Kz.Equip = {}

-- --- 1. FONCTIONS LOCALES (STATS) ---
local function FillStatGroup(group, statsTable)
    for _, line in pairs(group.lines) do line:Hide() end
    local y = -25; local count = 0
    for _, data in ipairs(statsTable) do
        count = count + 1; local line = group.lines[count]
        if not line then 
            line = CreateFrame("Frame", nil, group); line:SetSize(210, 18)
            line.l = line:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall"); line.l:SetPoint("LEFT", 5, 0)
            line.v = line:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); line.v:SetPoint("RIGHT", -5, 0)
            group.lines[count] = line 
        end
        line:SetPoint("TOPLEFT", 5, y); line.l:SetText(data[1]); line.v:SetText(data[2]); line.label = data[1]
        line.id = data[4]; line.stat = data[4]; line.type = data[3] 
        line:EnableMouse(true)
        if data[3] == "SIMPLE" then 
            line.desc = data[5]; line:SetScript("OnEnter", Kz.ShowSimpleTooltip) 
        else 
            line:SetScript("OnEnter", Kz.ShowStatTooltip) 
        end
        line:SetScript("OnLeave", Kz.HideTooltip); line:Show(); y = y - 18
    end
    group:SetHeight(math.abs(y) + 5); return group:GetHeight()
end

-- --- 2. CRÉATION DES SLOTS ---
local function CreateSlot(id, anchor, x, y, align, parent)
    local container = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    container:SetSize(320, 60); container:SetPoint(anchor, parent, anchor, x, y)
    
    local btn = CreateFrame("Button", nil, container, "BackdropTemplate")
    btn:SetSize(37, 37); btn:SetID(id)
    
    if align == "RIGHT" then btn:SetPoint("RIGHT", 0, 0) else btn:SetPoint("LEFT", 0, 0) end

    btn:SetBackdrop({bgFile="Interface\\Buttons\\WHITE8x8", edgeFile="Interface\\Buttons\\WHITE8x8", edgeSize=1})
    btn:SetBackdropColor(0,0,0,0); btn:SetBackdropBorderColor(0,0,0,1)
    
    btn.icon = btn:CreateTexture(nil, "BACKGROUND"); btn.icon:SetPoint("TOPLEFT",1,-1); btn.icon:SetPoint("BOTTOMRIGHT",-1,1)
    Kz.SkinIcon(btn.icon)
    
    btn:RegisterForClicks("LeftButtonUp", "RightButtonUp")
    btn:RegisterForDrag("LeftButton")
    
    btn:SetScript("OnClick", function(self) 
        if not InCombatLockdown() then 
            if IsShiftKeyDown() then SocketInventoryItem(self:GetID()) else PickupInventoryItem(self:GetID()) end 
        end 
    end)
    
    btn:SetScript("OnDragStart", function(self)
        if not InCombatLockdown() then PickupInventoryItem(self:GetID()) end
    end)
    
    btn:SetScript("OnReceiveDrag", function(self)
        if not InCombatLockdown() then PickupInventoryItem(self:GetID()) end
    end)

    btn:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT"); GameTooltip:SetInventoryItem("player", self:GetID()); GameTooltip:Show() end)
    btn:SetScript("OnLeave", function() GameTooltip:Hide() end)
    
    container.txt = container:CreateFontString(nil, "OVERLAY", "GameFontNormal"); container.txt:SetWordWrap(false)
    container.lvl = container:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    container.encht = container:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall"); container.encht:SetTextColor(0, 1, 0); container.encht:SetWidth(215); container.encht:SetWordWrap(false)
    container.dur = container:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    
    if align == "RIGHT" then
        container.txt:SetPoint("TOPRIGHT", -80, -5); container.txt:SetJustifyH("RIGHT"); container.txt:SetWidth(180)
        container.lvl:SetPoint("TOPRIGHT", container.txt, "BOTTOMRIGHT", 0, -2)
        container.encht:SetPoint("TOPRIGHT", container.lvl, "BOTTOMRIGHT", 0, -2); container.encht:SetJustifyH("RIGHT")
        container.dur:SetPoint("BOTTOM", container, "RIGHT", -20, 0)
    else
        container.txt:SetPoint("TOPLEFT", 80, -5); container.txt:SetJustifyH("LEFT"); container.txt:SetWidth(180)
        container.lvl:SetPoint("TOPLEFT", container.txt, "BOTTOMLEFT", 0, -2)
        container.encht:SetPoint("TOPLEFT", container.lvl, "BOTTOMLEFT", 0, -2); container.encht:SetJustifyH("LEFT")
        container.dur:SetPoint("BOTTOM", container, "LEFT", 20, 0)
    end

    container.Gems = {}
    for i = 1, 3 do
        local bg = CreateFrame("Button", nil, container, "BackdropTemplate"); bg:SetSize(16, 16); bg:EnableMouse(false)
        Kz.SkinFrame(bg); bg:SetBackdropColor(0,0,0,0.9); bg:Hide()
        local g = bg:CreateTexture(nil, "OVERLAY"); g:SetPoint("TOPLEFT",1,-1); g:SetPoint("BOTTOMRIGHT",-1,1); Kz.SkinIcon(g)
        
        if align == "RIGHT" then
            if i == 1 then bg:SetPoint("RIGHT", btn, "LEFT", -5, 0) else bg:SetPoint("RIGHT", container.Gems[i-1].Frame, "LEFT", -2, 0) end
        else
            if i == 1 then bg:SetPoint("LEFT", btn, "RIGHT", 5, 0) else bg:SetPoint("LEFT", container.Gems[i-1].Frame, "RIGHT", 2, 0) end
        end
        container.Gems[i] = { Icon = g, Frame = bg }
        if Kz.Msq and Kz.Msq.Gems then Kz.Msq.Gems:AddButton(bg, {Icon = g}) end
    end

    container.KzBtn = btn
    if Kz.Msq and Kz.Msq.Slots then Kz.Msq.Slots:AddButton(btn) end
    
    return container
end

-- --- 3. MODULE SPÉCIALISATIONS ---
local function CheckAndCreateSpecButtons()
    if not Kz.UI.SpecButtonsContainer then
        local c = CreateFrame("Frame", nil, Kz.UI.Views.Equip)
        c:SetSize(200, 40)
        
        -- [[ MODIFIER ICI : POSITION DES BOUTONS DE SPÉ ]]
        -- "20" = Position X (Horizontal)
        -- "100" = Position Y (Vertical)
        if Kz.UI.Frames and Kz.UI.Frames[1] then 
            c:SetPoint("BOTTOMLEFT", Kz.UI.Frames[1], "TOPLEFT", -80, 80) 
        else 
            c:SetPoint("TOPLEFT", 80, 0) 
        end
        
        c:SetFrameStrata("HIGH")
        Kz.UI.SpecButtonsContainer = c
        Kz.UI.SpecButtons = {}
    end

    local numSpecs = GetNumSpecializations()
    if numSpecs > 0 and #Kz.UI.SpecButtons == 0 then
        for i = 1, numSpecs do
            local id, name, description, icon = GetSpecializationInfo(i)
            local btn = CreateFrame("Button", nil, Kz.UI.SpecButtonsContainer, "BackdropTemplate")
            btn:SetSize(30, 30)
            if i == 1 then btn:SetPoint("LEFT", 0, 0) else btn:SetPoint("LEFT", Kz.UI.SpecButtons[i-1], "RIGHT", 10, 0) end
            btn.icon = btn:CreateTexture(nil, "ARTWORK"); btn.icon:SetAllPoints(); btn.icon:SetTexture(icon); Kz.SkinIcon(btn.icon)
            btn.border = CreateFrame("Frame", nil, btn, "BackdropTemplate"); btn.border:SetPoint("TOPLEFT", -2, 2); btn.border:SetPoint("BOTTOMRIGHT", 2, -2)
            btn.border:SetBackdrop({edgeFile = "Interface\\Buttons\\WHITE8x8", edgeSize = 2}); btn.border:SetBackdropBorderColor(1, 0.8, 0, 1); btn.border:Hide()
            btn:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT"); GameTooltip:SetText(name, 1, 1, 1); GameTooltip:AddLine("Clic Gauche pour activer", 0.7, 0.7, 0.7); GameTooltip:Show() end)
            btn:SetScript("OnLeave", function() GameTooltip:Hide() end)
            btn:SetScript("OnClick", function() if InCombatLockdown() then print("|cffff0000Kazolitus:|r Combat en cours."); return end; if GetSpecialization() ~= i and C_SpecializationInfo.SetSpecialization then C_SpecializationInfo.SetSpecialization(i) end end)
            table.insert(Kz.UI.SpecButtons, btn)
        end
    end
end

local function UpdateSpecButtons()
    CheckAndCreateSpecButtons()
    if not Kz.UI.SpecButtons then return end
    local currentSpec = GetSpecialization()
    for i, btn in ipairs(Kz.UI.SpecButtons) do
        if i == currentSpec then btn.icon:SetDesaturated(false); btn.icon:SetAlpha(1); btn.border:Show() 
        else btn.icon:SetDesaturated(true); btn.icon:SetAlpha(0.5); btn.border:Hide() end
    end
end

-- --- 4. INITIALISATION ---
function Kz.Equip.Init(parent)
    local view = CreateFrame("Frame", nil, parent); view:SetAllPoints()
    Kz.UI.Views.Equip = view
    Kz.UI.Frames = {}

    local PM = CreateFrame("Frame", nil, view); PM:SetSize(450, 550); PM:SetPoint("CENTER", -100, -20)
    
    -- IMAGE STATIQUE
    Kz.UI.PlayerImage = PM:CreateTexture(nil, "ARTWORK")
    Kz.UI.PlayerImage:SetAllPoints()
    
    -- MODELE 3D
    Kz.UI.PlayerModel = CreateFrame("PlayerModel", nil, PM)
    Kz.UI.PlayerModel:SetAllPoints()
    Kz.UI.PlayerModel:SetUnit("player")
    Kz.UI.PlayerModel:Hide()

    for i, id in ipairs(Kz.SlotIDs.Left) do Kz.UI.Frames[id] = CreateSlot(id, "TOPLEFT", 80, -30-(i*65), "RIGHT", view) end
    for i, id in ipairs(Kz.SlotIDs.Right) do Kz.UI.Frames[id] = CreateSlot(id, "TOPRIGHT", -295, -30-(i*65), "LEFT", view) end
    
    Kz.UI.PlayerInfo = {}
    Kz.UI.PlayerInfo.iLvl = view:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge"); Kz.UI.PlayerInfo.iLvl:SetPoint("TOP", parent, "TOP", 10, 0)
    Kz.UI.PlayerInfo.MScore = view:CreateFontString(nil, "OVERLAY", "GameFontNormal"); Kz.UI.PlayerInfo.MScore:SetPoint("TOP", Kz.UI.PlayerInfo.iLvl, "BOTTOM", 0, -5)

    local SS = CreateFrame("ScrollFrame", nil, view, "UIPanelScrollFrameTemplate"); SS:SetSize(250, 600); SS:SetPoint("RIGHT", parent, "RIGHT", -30, -10)
    local SC = CreateFrame("Frame", nil, SS); SC:SetSize(230, 800); SS:SetScrollChild(SC)
    
    Kz.UI.Groups = {}
    Kz.UI.Groups.Attrib = Kz.CreateStatGroup(SC, "ATTRIBUTS")
    Kz.UI.Groups.Sec = Kz.CreateStatGroup(SC, "SECONDAIRES")
    Kz.UI.Groups.Tert = Kz.CreateStatGroup(SC, "TERTIAIRES")
    Kz.UI.Groups.Def = Kz.CreateStatGroup(SC, "DÉFENSE")
    Kz.UI.Groups.Div = Kz.CreateStatGroup(SC, "DIVERS")
    
    view:Hide()
end

-- --- 5. UPDATE LOGIC ---
function Kz.Equip.Update()
    if not Kz.UI.Views.Equip:IsShown() then return end
    
    UpdateSpecButtons()
    
    -- Refresh Modèle 3D si actif
    if Kz.UI.PlayerModel and Kz.UI.PlayerModel:IsShown() then
        Kz.UI.PlayerModel:SetUnit("player")
    end
    
    local _, avg = GetAverageItemLevel()
    if avg then Kz.UI.PlayerInfo.iLvl:SetText(string.format("iLvl: |c%s%.1f|r", Kz.ClassColor:GenerateHexColor(), avg)) end
    local score = C_ChallengeMode.GetOverallDungeonScore()
    if score and score > 0 then Kz.UI.PlayerInfo.MScore:SetText((C_ChallengeMode.GetDungeonScoreRarityColor(score) or CreateColor(1,1,1)):WrapTextInColorCode("Score M+: " .. score)) else Kz.UI.PlayerInfo.MScore:SetText("") end

    local ScanTT = _G["KzScan"] or CreateFrame("GameTooltip", "KzScan", nil, "GameTooltipTemplate"); ScanTT:SetOwner(WorldFrame,"ANCHOR_NONE")

    for id, f in pairs(Kz.UI.Frames) do
        local texture = GetInventoryItemTexture("player", id)
        local lnk = GetInventoryItemLink("player", id)
        
        if texture then
            f.KzBtn.icon:SetTexture(texture)
        else
            f.KzBtn.icon:SetTexture(nil)
        end

        f.encht:SetText(""); f.dur:SetText(""); f.lvl:SetText(""); f.txt:SetText("")
        for _, g in pairs(f.Gems) do g.Frame:Hide() end
        if f.KzBtn.SetBackdropBorderColor then f.KzBtn:SetBackdropBorderColor(0, 0, 0, 1) end

        if lnk then
            local itemName,_,q,_,_,_,_,_,equipLoc = GetItemInfo(lnk)
            local il = GetDetailedItemLevelInfo(lnk)
            if itemName then f.txt:SetText(itemName); local r,g,b = GetItemQualityColor(q or 1); f.txt:SetTextColor(r,g,b); f.KzBtn:SetBackdropBorderColor(r,g,b,1) end
            if il and avg then local diff = il - avg; f.lvl:SetText((diff>=0 and "|cff00ff00" or "|cffff0000")..il.."|r") else f.lvl:SetText(il or "") end
            
            local cur, max = GetInventoryItemDurability(id)
            if cur and max and max>0 then 
                local p=(cur/max)*100
                if p<100 then local r,g,b = Kz.GetGradientColor(p); f.dur:SetText(string.format("%.0f%%", p)); f.dur:SetTextColor(r,g,b) end 
            end

            ScanTT:ClearLines(); ScanTT:SetHyperlink(lnk)
            local finalEnchantText = ""
            for i=2, ScanTT:NumLines() do 
                local l = _G["KzScanTextLeft"..i]
                if l and l:IsShown() then
                    local tx = l:GetText(); local r,g,b = l:GetTextColor()
                    if tx and (tx:match("^Enchanté :") or tx:match("^Enchant :")) then finalEnchantText = tx:gsub("Enchanté : ", ""):gsub("Enchant : ", ""); break end
                    if r < 0.2 and g > 0.9 and b < 0.2 and tx and not tx:match("^%+") and not tx:match("^Utiliser") and not tx:match("^Équipé") and not tx:match("^Chance") and not tx:match("^Complet") then if finalEnchantText == "" then finalEnchantText = tx end end
                end
            end
            if finalEnchantText == "" then
                local shouldBeEnchanted = false; local enchantSlots = {[5]=true, [7]=true, [8]=true, [9]=true, [11]=true, [12]=true, [15]=true, [16]=true}
                if enchantSlots[id] then shouldBeEnchanted = true elseif id == 17 and (equipLoc == "INVTYPE_WEAPON" or equipLoc == "INVTYPE_2HWEAPON" or equipLoc == "INVTYPE_WEAPONMAINHAND") then shouldBeEnchanted = true end
                if shouldBeEnchanted then finalEnchantText = "|cffff0000Enchantement manquant|r" end
            end
            f.encht:SetText(finalEnchantText)

            local itemString = string.match(lnk, "item[%-?%d:]+")
            if itemString then
                local _, _, _, gem1, gem2, gem3 = strsplit(":", itemString)
                local gems = {gem1, gem2, gem3}
                for i, gemID in ipairs(gems) do
                    if gemID and tonumber(gemID) and tonumber(gemID) > 0 and f.Gems[i] then
                        local texture = select(10, GetItemInfo(tonumber(gemID)))
                        if texture then f.Gems[i].Icon:SetTexture(texture); f.Gems[i].Frame:Show() end
                    end
                end
            end
        end
    end

    local spec = GetSpecialization(); local primStatID = 0; if spec then _,_,_,_,_,primStatID = GetSpecializationInfo(spec) end; if not primStatID or primStatID == 0 then primStatID = -1 end
    local tAttrib, tSec, tTert, tDef, tDiv = {}, {}, {}, {}, {}
    if primStatID == 1 or primStatID == -1 then table.insert(tAttrib, {"Force", Kz.FormatNumber(select(2, UnitStat("player", 1)) or 0), "ATTRIB", 1}) end
    if primStatID == 2 or primStatID == -1 then table.insert(tAttrib, {"Agilité", Kz.FormatNumber(select(2, UnitStat("player", 2)) or 0), "ATTRIB", 2}) end
    if primStatID == 4 or primStatID == -1 then table.insert(tAttrib, {"Intelligence", Kz.FormatNumber(select(2, UnitStat("player", 4)) or 0), "ATTRIB", 4}) end
    table.insert(tAttrib, {"Endurance", Kz.FormatNumber(select(2, UnitStat("player", 3)) or 0), "ATTRIB", 3})
    
    local spellPower = 0; for i=2,7 do spellPower = math.max(spellPower, GetSpellBonusDamage(i)) end
    if spellPower > 0 then table.insert(tAttrib, {"Puissance des sorts", Kz.FormatNumber(spellPower), "SIMPLE", 0, "Augmente les dégâts et les soins."}) end

    table.insert(tSec, {"Critique", string.format("%.2f%%", GetCritChance()), "SEC", "CRIT"})
    table.insert(tSec, {"Hâte", string.format("%.2f%%", GetHaste()), "SEC", "HASTE"})
    table.insert(tSec, {"Maîtrise", string.format("%.2f%%", GetMasteryEffect()), "SEC", "MASTERY"})
    table.insert(tSec, {"Polyvalence", string.format("%.2f%%", GetCombatRatingBonus(29) + GetVersatilityBonus(29)), "SEC", "VERSATILITY"})
    table.insert(tTert, {"Ponction", string.format("%.2f%%", GetCombatRatingBonus(17)), "SEC", "LIFESTEAL"})
    table.insert(tTert, {"Évitement", string.format("%.2f%%", GetCombatRatingBonus(21)), "SEC", "AVOIDANCE"})
    table.insert(tTert, {"Vitesse", string.format("%.2f%%", GetCombatRatingBonus(14)), "SEC", "SPEED"})
    local _, effArmor = UnitArmor("player"); table.insert(tDef, {"Armure", Kz.FormatNumber(effArmor), "SEC", "ARMOR"})
    table.insert(tDef, {"Esquive", string.format("%.2f%%", GetDodgeChance()), "SEC", "DODGE"})
    table.insert(tDef, {"Parade", string.format("%.2f%%", GetParryChance()), "SEC", "PARRY"})
    table.insert(tDef, {"Blocage", string.format("%.2f%%", GetBlockChance()), "SEC", "BLOCK"})
    local _, runSpeed = GetUnitSpeed("player"); table.insert(tDiv, {"Vitesse Dépla.", string.format("%d%%", (runSpeed/7)*100), "SIMPLE", 0, "Vitesse de déplacement actuelle."})
    table.insert(tDiv, {"Santé Max", Kz.FormatNumber(UnitHealthMax("player")), "SIMPLE", 0, "Points de vie totaux."})

    local yPos = -30; local G = Kz.UI.Groups
    G.Attrib:SetPoint("TOP", 0, yPos); yPos = yPos - FillStatGroup(G.Attrib, tAttrib) - 10
    G.Sec:SetPoint("TOP", 0, yPos); yPos = yPos - FillStatGroup(G.Sec, tSec) - 10
    G.Tert:SetPoint("TOP", 0, yPos); yPos = yPos - FillStatGroup(G.Tert, tTert) - 10
    G.Def:SetPoint("TOP", 0, yPos); yPos = yPos - FillStatGroup(G.Def, tDef) - 10
    G.Div:SetPoint("TOP", 0, yPos); FillStatGroup(G.Div, tDiv)
end