local _, namespace = ...

local WTUI = namespace.WildThingsUI

local BORDER_COLOR = WTUI.settings.BORDER_COLOR
local BACKGROUND_COLOR = WTUI.settings.WIDGET_BACKGROUND_COLOR
local BACKGROUND_COLOR_ACTIVE = WTUI.settings.WIDGET_ACTIVE_BACKGROUND_COLOR

local DEFAULT_HEIGHT = 26

function namespace:CreateButton(parent, title, OnClick)
    local button = CreateFrame("Button", nil, parent)
    local fixedWidth = false

    button.OnEnter = function() end
    button.OnLeave = function() end

    button:SetScript("OnEnter", function(_self) _self.OnEnter() end)
    button:SetScript("OnLeave", function(_self) _self.OnLeave() end)

    button.OnClick = OnClick

    -- If no title is present, or the title is an empty string, no font string is created
    button:SetText(" ") -- Force font string creation
    button:SetText(title) -- Set text equal to title (even if it's nil or an empty string)
    button:SetNormalFontObject(WildThingsFont13)
    button:SetHighlightFontObject(WildThingsFont13)
    button:SetDisabledFontObject(WildThingsFont13)
    button:SetScript("OnClick", button.OnClick)

    local function UpdateWidth()
        button:SetSize(button:GetFontString():GetUnboundedStringWidth() + 20, DEFAULT_HEIGHT)
    end

    function button:SetFixedWidth(isFixed)
        fixedWidth = isFixed
    end

    hooksecurefunc(
        button,
        "SetText",
        function()
            if not fixedWidth then
                UpdateWidth()
            end
        end
    )

    hooksecurefunc(
        button,
        "SetNormalFontObject",
        function()
            if not fixedWidth then
                UpdateWidth()
            end
        end
    )

    -- Background
    button.tex = button:CreateTexture(nil, "BACKGROUND")
    button.tex:SetAllPoints()
    button.tex:SetColorTexture(BACKGROUND_COLOR.r, BACKGROUND_COLOR.g, BACKGROUND_COLOR.b, BACKGROUND_COLOR.a)
    button.tex:SetSnapToPixelGrid(false)
    button.tex:SetTexelSnappingBias(0)

    -- Border
    WTUI:AddBorder(button)
    button:SetBorderColor(BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b)

    -- Highlight
    WTUI:AddHoverHighlight(button)

    UpdateWidth()

    local function makeButtonActive()
        button.tex:SetColorTexture(BACKGROUND_COLOR_ACTIVE.r, BACKGROUND_COLOR_ACTIVE.g, BACKGROUND_COLOR_ACTIVE.b, BACKGROUND_COLOR_ACTIVE.a)
    end

    local function makeButtonInactive()
        button.tex:SetColorTexture(BACKGROUND_COLOR.r, BACKGROUND_COLOR.g, BACKGROUND_COLOR.b, BACKGROUND_COLOR.a)
    end

    return button
end
