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

-- Keep this private. The same name is a Blizzard-owned global mixin on modern
-- clients, so a bare global assignment here would clobber FrameXML's copy.
local UIButtonFitToTextBehaviorMixin = {};

function UIButtonFitToTextBehaviorMixin:SetTextToFit(text)
	self:SetText(text);
	self:FitToText();
end

function UIButtonFitToTextBehaviorMixin:FitToText()
	local minWidth = self.fitTextCanWidthDecrease and 0 or self:GetWidth();
	self:SetWidth(math.max(minWidth, self:GetTextWidth() + self.fitTextWidthPadding));
end

lib.UIButtonFitToTextBehaviorMixin = UIButtonFitToTextBehaviorMixin

function lib:Mixin(target, padding, canDecrease)
    if not target then return target end
    target.SetTextToFit = UIButtonFitToTextBehaviorMixin.SetTextToFit
    target.FitToText    = UIButtonFitToTextBehaviorMixin.FitToText
    target.fitTextWidthPadding   = padding or 0
    target.fitTextCanWidthDecrease = canDecrease and true or false
    return target
end

local FontStringScaleToFit = {}

function FontStringScaleToFit:SetTextToFit(text, maxWidth)
    self:SetText(text)
    self:ScaleToFit(maxWidth or self.fitMaxWidth)
end

function FontStringScaleToFit:ScaleToFit(maxWidth)
    maxWidth = maxWidth or self.fitMaxWidth
    if not maxWidth or maxWidth <= 0 then return end
    if self.SetTextScale then self:SetTextScale(1) end
    local current = self.GetStringWidth and self:GetStringWidth() or 0
    if current > 0 and current > maxWidth and self.SetTextScale then
        self:SetTextScale(maxWidth / current)
    end
end

lib.FontStringScaleToFit = FontStringScaleToFit

function lib:MixinFontString(fs, maxWidth)
    if not fs then return fs end
    fs.SetTextToFit = FontStringScaleToFit.SetTextToFit
    fs.ScaleToFit   = FontStringScaleToFit.ScaleToFit
    fs.fitMaxWidth  = maxWidth
    return fs
end
