local RUI = LibStub("RUI-1.0")
if not RUI then return end

-- RUI.Widget.ColorButton(parent, label, x, y, width, get_rgba, set_rgba[, hasAlpha]) → Button, Refresh()
-- Full-width button with embedded label (left) and 40×16 color swatch (right). No separate label above.
-- get_rgba() must return r, g, b [, a] (0-1 each).
-- set_rgba(r, g, b[, a]) called on live change and on confirm; nil alpha when hasAlpha is false.
-- Total height consumed: COLOR_H(24) + CONTROL_GAP(4) = 28px.
function RUI.Widget.ColorButton(parent, label, x, y, width, get_rgba, set_rgba, hasAlpha)
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(width, RUI.COLOR_H)
    btn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    btn:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1,
    })
    btn:SetBackdropColor(RUI.C.ELEMENT.r, RUI.C.ELEMENT.g, RUI.C.ELEMENT.b, 1)
    btn:SetBackdropBorderColor(RUI.C.BORDER.r, RUI.C.BORDER.g, RUI.C.BORDER.b, 1)

    local lbl = btn:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    lbl:SetPoint("LEFT",  btn, "LEFT",  8,   0)
    lbl:SetPoint("RIGHT", btn, "RIGHT", -54, 0)
    lbl:SetJustifyH("LEFT")
    lbl:SetText(label)
    lbl:SetTextColor(RUI.C.TEXT.r, RUI.C.TEXT.g, RUI.C.TEXT.b)

    local swatch = btn:CreateTexture(nil, "ARTWORK")
    swatch:SetSize(40, 16)
    swatch:SetPoint("RIGHT", btn, "RIGHT", -6, 0)
    btn._swatch = swatch

    btn:SetScript("OnEnter", function(self)
        self:SetBackdropColor(RUI.C.HOVER.r, RUI.C.HOVER.g, RUI.C.HOVER.b, 1)
        self:SetBackdropBorderColor(RUI.C.ACCENT.r, RUI.C.ACCENT.g, RUI.C.ACCENT.b, 1)
    end)
    btn:SetScript("OnLeave", function(self)
        self:SetBackdropColor(RUI.C.ELEMENT.r, RUI.C.ELEMENT.g, RUI.C.ELEMENT.b, 1)
        self:SetBackdropBorderColor(RUI.C.BORDER.r, RUI.C.BORDER.g, RUI.C.BORDER.b, 1)
    end)

    btn:SetScript("OnClick", function()
        local r, g, b, a = get_rgba()
        a = a or 1
        local origR, origG, origB, origA = r, g, b, a
        RUI.OpenColorPicker(
            {r=r, g=g, b=b, a=a},
            hasAlpha,
            function(c)  -- onAccept
                set_rgba(c.r, c.g, c.b, hasAlpha and c.a or nil)
                swatch:SetColorTexture(c.r, c.g, c.b, c.a)
            end,
            function()   -- onCancel
                set_rgba(origR, origG, origB, hasAlpha and origA or nil)
                swatch:SetColorTexture(origR, origG, origB, origA)
            end,
            function(c)  -- onChange (live preview)
                set_rgba(c.r, c.g, c.b, hasAlpha and c.a or nil)
                swatch:SetColorTexture(c.r, c.g, c.b, c.a)
            end
        )
    end)

    local function Refresh()
        local r, g, b, a = get_rgba()
        swatch:SetColorTexture(r, g, b, a or 1)
    end
    Refresh()
    return btn, Refresh
end
