-- ============================================================
-- Asylum Compagnon — Bars.lua
-- Widget de barre réutilisable (esprit Portal Authority) : icône
-- carrée à gauche + StatusBar qui se vide en temps réel, textes
-- gauche/droite superposés. Utilisé par les overlays kicks & CD.
-- NS.CreateBar(parent, w, h) → frame avec :Set(icon, col, l, r, pct, rcol)
-- ============================================================

local ADDON_NAME, NS = ...

local WHITE   = "Interface\\Buttons\\WHITE8x8"
local FONT    = "Fonts\\FRIZQT__.TTF"
local BAR_TEX = "Interface\\TargetingFrame\\UI-StatusBar"

function NS.ClassRGB(token)
    local c = token and RAID_CLASS_COLORS and RAID_CLASS_COLORS[token]
    if c then return { c.r, c.g, c.b } end
    return { 0.6, 0.6, 0.62 }
end

-- Icône d'un sort (sécurisé Midnight)
function NS.SpellIcon(spellID)
    local fn = (C_Spell and C_Spell.GetSpellTexture) or GetSpellTexture
    if not fn or not spellID then return nil end
    local ok, tex = pcall(fn, spellID)
    if ok then return tex end
end

-- Icône de cooldown façon OmniCD : icône du sort + balayage (Cooldown frame)
-- + décompte au centre. :SetState(tex, start, duration, remaining) ; quand
-- remaining>0 → désaturée + assombrie + swipe + décompte (s, ou "Nm" ≥ 60 s) ;
-- sinon → nette et pleine (prête). Survol → tooltip (SetInfo), bord teintable.
function NS.CreateCDIcon(parent, size)
    size = size or 22
    local f = CreateFrame("Frame", nil, parent)
    f:SetSize(size, size)

    local border = f:CreateTexture(nil, "BACKGROUND")
    border:SetPoint("TOPLEFT", -1, 1)
    border:SetPoint("BOTTOMRIGHT", 1, -1)
    border:SetColorTexture(0, 0, 0, 0.9)
    f.border = border

    local tex = f:CreateTexture(nil, "ARTWORK")
    tex:SetAllPoints()
    tex:SetTexCoord(0.08, 0.92, 0.08, 0.92)
    f.tex = tex

    local cdf = CreateFrame("Cooldown", nil, f, "CooldownFrameTemplate")
    cdf:SetAllPoints()
    if cdf.SetDrawEdge then cdf:SetDrawEdge(true) end
    if cdf.SetSwipeColor then cdf:SetSwipeColor(0, 0, 0, 0.78) end
    if cdf.SetHideCountdownNumbers then cdf:SetHideCountdownNumbers(true) end
    f.cdf = cdf

    local count = f:CreateFontString(nil, "OVERLAY")
    count:SetFont(FONT, math.max(10, size - 9), "OUTLINE")
    count:SetPoint("CENTER", 0, 0)
    f.count = count

    -- compteur de charges (coin bas-droit)
    local chargeText = f:CreateFontString(nil, "OVERLAY")
    chargeText:SetFont(FONT, math.max(9, size - 11), "OUTLINE")
    chargeText:SetPoint("BOTTOMRIGHT", 1, -1)
    f.chargeText = chargeText

    -- tooltip au survol (sans bloquer le déplacement du cadre : seul l'icône
    -- capte la souris, le reste du cadre reste déplaçable)
    f:EnableMouse(true)
    f:SetScript("OnEnter", function(self)
        if not (self.spellID or self.title) then return end
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        local shown = false
        if self.spellID and GameTooltip.SetSpellByID then
            shown = pcall(GameTooltip.SetSpellByID, GameTooltip, self.spellID)
        end
        if not shown then GameTooltip:SetText(self.title or "") end
        if self.subText and self.subText ~= "" then
            GameTooltip:AddLine(self.subText, 0.72, 0.78, 0.92)
        end
        if self.catText and self.catText ~= "" then
            GameTooltip:AddLine(self.catText, 0.55, 0.75, 1)
        end
        GameTooltip:Show()
    end)
    f:SetScript("OnLeave", function() GameTooltip:Hide() end)

    function f:SetInfo(spellID, title, subText, catText)
        self.spellID, self.title, self.subText, self.catText = spellID, title, subText, catText
    end
    function f:SetBorderColor(r, g, b, a)
        self.border:SetColorTexture(r, g, b, a or 0.9)
    end
    function f:SetState(iconTex, start, duration, remaining)
        if iconTex then self.tex:SetTexture(iconTex) end
        self.chargeText:SetText("")
        if remaining and remaining > 0 then
            if start and duration and duration > 0 then
                pcall(self.cdf.SetCooldown, self.cdf, start, duration)
            end
            self.tex:SetDesaturated(true)
            self.tex:SetVertexColor(0.72, 0.72, 0.72)
            self.border:SetColorTexture(0.88, 0.34, 0.30, 0.95) -- rouge = en recharge
            local txt = (remaining >= 60) and (("%dm"):format(math.ceil(remaining / 60)))
                or (("%d"):format(math.ceil(remaining)))
            self.count:SetText(txt)
            self.count:SetTextColor(0.97, 0.86, 0.4)
        else
            self.cdf:Clear()
            self.tex:SetDesaturated(false)
            self.tex:SetVertexColor(1, 1, 1)
            self.border:SetColorTexture(0.24, 0.64, 0.38, 0.9) -- vert = prêt
            self.count:SetText("")
        end
    end
    function f:SetCount(t, r, g, b)
        self.count:SetText(t or "")
        if r then self.count:SetTextColor(r, g, b) end
    end
    -- état complet avec charges : o = { onCD, start, dur, remaining, cur, max }
    -- charge dispo (cur>0) = prêt (pas de swipe) ; 0 charge = CD de la prochaine
    function f:SetCD(iconTex, o)
        if iconTex then self.tex:SetTexture(iconTex) end
        o = o or {}
        if o.max and o.max > 1 then
            self.chargeText:SetText(tostring(o.cur or 0))
            if (o.cur or 0) > 0 then self.chargeText:SetTextColor(0.95, 0.95, 0.98)
            else self.chargeText:SetTextColor(0.95, 0.45, 0.4) end
        else
            self.chargeText:SetText("")
        end
        if o.onCD then
            if o.start and o.dur and o.dur > 0 then
                pcall(self.cdf.SetCooldown, self.cdf, o.start, o.dur)
            end
            self.tex:SetDesaturated(true)
            self.tex:SetVertexColor(0.72, 0.72, 0.72)
            self.border:SetColorTexture(0.88, 0.34, 0.30, 0.95)
            local rem = o.remaining or 0
            local txt = (rem >= 60) and (("%dm"):format(math.ceil(rem / 60)))
                or (("%d"):format(math.ceil(rem)))
            self.count:SetText(txt)
            self.count:SetTextColor(0.97, 0.86, 0.4)
        else
            self.cdf:Clear()
            self.tex:SetDesaturated(false)
            self.tex:SetVertexColor(1, 1, 1)
            self.border:SetColorTexture(0.24, 0.64, 0.38, 0.9)
            self.count:SetText("")
        end
    end
    return f
end

-- Barre pleine largeur : la StatusBar va jusqu'au bout à gauche ; l'icône du
-- sort et la coche ✓/✗ sont À L'INTÉRIEUR de la barre, entre le nom (gauche)
-- et l'état/décompte (droite).
function NS.CreateBar(parent, width, height)
    local bar = CreateFrame("Frame", nil, parent)
    bar:SetSize(width, height)

    local sb = CreateFrame("StatusBar", nil, bar)
    sb:SetAllPoints()
    sb:SetStatusBarTexture(BAR_TEX)
    sb:SetMinMaxValues(0, 1)
    sb:SetValue(1)
    bar.sb = sb

    local sbBg = sb:CreateTexture(nil, "BACKGROUND")
    sbBg:SetAllPoints()
    sbBg:SetTexture(WHITE)
    sbBg:SetVertexColor(0, 0, 0, 0.55)
    bar.bg = sbBg

    local fsz = math.max(9, height - 8)

    -- état / décompte (droite)
    local right = sb:CreateFontString(nil, "OVERLAY")
    right:SetFont(FONT, fsz, "OUTLINE")
    right:SetPoint("RIGHT", -4, 0)
    right:SetJustifyH("RIGHT")
    bar.right = right

    -- coche ✓/✗, juste à gauche du décompte
    local mark = sb:CreateFontString(nil, "OVERLAY")
    mark:SetFont(FONT, fsz, "OUTLINE")
    mark:SetPoint("RIGHT", right, "LEFT", -3, 0)
    bar.mark = mark

    -- icône du sort, juste à gauche de la coche → ordre : icône PUIS coche
    local icon = sb:CreateTexture(nil, "ARTWORK")
    icon:SetSize(height - 2, height - 2)
    icon:SetPoint("RIGHT", mark, "LEFT", -3, 0)
    icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
    bar.icon = icon

    -- nom (gauche), tronqué avant le cluster icône/coche/décompte
    local left = sb:CreateFontString(nil, "OVERLAY")
    left:SetFont(FONT, fsz, "OUTLINE")
    left:SetPoint("LEFT", 5, 0)
    left:SetPoint("RIGHT", icon, "LEFT", -3, 0)
    left:SetJustifyH("LEFT")
    left:SetWordWrap(false)
    bar.left = left

    -- iconTex, col{r,g,b} (barre), leftText, rightText, pct(0..1), rcol{r,g,b}, markText
    function bar:Set(iconTex, col, leftText, rightText, pct, rcol, markText)
        if iconTex then
            self.icon:SetTexture(iconTex); self.icon:Show()
        else
            self.icon:Hide()
        end
        self.mark:SetText(markText or "")
        col = col or { 0.5, 0.5, 0.5 }
        self.sb:SetStatusBarColor(col[1], col[2], col[3], 0.9)
        self.sb:SetValue(pct == nil and 1 or math.max(0, math.min(1, pct)))
        self.left:SetText(leftText or "")
        self.right:SetText(rightText or "")
        if rcol then
            self.right:SetTextColor(rcol[1], rcol[2], rcol[3])
        else
            self.right:SetTextColor(1, 1, 1)
        end
    end

    return bar
end
