local MAJOR, MINOR = "LibMatic-AlertShadow-1.0", 1
assert(LibStub, MAJOR .. " requires LibStub")
local lib = LibStub:NewLibrary(MAJOR, MINOR)
if not lib then return end

local function clamp01(v)
    if type(v) ~= "number" then return 0 end
    if v < 0 then return 0 end
    if v > 1 then return 1 end
    return v
end
lib._clamp01 = clamp01

function lib._strengthToAlpha(strength, maxAlpha)
    if type(maxAlpha) ~= "number" then maxAlpha = 1 end
    return clamp01(strength) * maxAlpha
end

function lib:ApplyTextShadow(fs, strength, opts)
    if not fs or not fs.SetShadowColor then return end
    opts = opts or {}
    local s = clamp01(strength)
    local color = opts.color or { 0, 0, 0 }
    local r, g, b = color[1] or 0, color[2] or 0, color[3] or 0
    if s <= 0 then
        if fs.SetShadowOffset then fs:SetShadowOffset(0, 0) end
        fs:SetShadowColor(r, g, b, 0)
        return
    end
    local offset = opts.offset or { 2, -2 }
    if fs.SetShadowOffset then fs:SetShadowOffset(offset[1] or 2, offset[2] or -2) end
    fs:SetShadowColor(r, g, b, lib._strengthToAlpha(s, opts.maxAlpha))
end

function lib:ApplyIconShadow(icon, strength, opts)
    if not icon or not icon.GetParent then return nil end
    opts = opts or {}
    local s = clamp01(strength)
    local shadow = icon.__lmShadow
    if not shadow then
        local parent = icon:GetParent()
        if not parent or not parent.CreateTexture then return nil end
        shadow = parent:CreateTexture(nil, "BACKGROUND")
        icon.__lmShadow = shadow
    end
    if s <= 0 then
        if shadow.Hide then shadow:Hide() end
        return shadow
    end
    local offset = opts.offset or { 2, -2 }
    local color = opts.color or { 0, 0, 0 }
    if icon.GetTexture and shadow.SetTexture then
        shadow:SetTexture(icon:GetTexture())
    end
    if shadow.SetVertexColor then
        shadow:SetVertexColor(color[1] or 0, color[2] or 0, color[3] or 0, lib._strengthToAlpha(s, opts.maxAlpha))
    end
    if shadow.ClearAllPoints and shadow.SetPoint then
        shadow:ClearAllPoints()
        shadow:SetPoint("CENTER", icon, "CENTER", offset[1] or 2, offset[2] or -2)
    end
    if icon.GetSize and shadow.SetSize then
        local w, h = icon:GetSize()
        if w and h and w > 0 then
            local scale = opts.scale or 1
            shadow:SetSize(w * scale, h * scale)
        end
    end
    if shadow.Show then shadow:Show() end
    return shadow
end
