-- UI/Controls/Checkbox.lua
--
-- A reusable checkbox control that matches the Toolkit's visual style.

local addonName, SinsToolkit = ...

-- Ensure the namespace exists.
SinsToolkit.UI = SinsToolkit.UI or {}
SinsToolkit.UI.Controls = SinsToolkit.UI.Controls or {}

local Checkbox = {}
SinsToolkit.UI.Controls.Checkbox = Checkbox

--[[
    Creates a new Checkbox control.
    @param parent The parent frame for this control.
    @param text The label text for the checkbox.
    @param tooltip (Optional) The tooltip text to display on hover.
    @return A table representing the new control, with its own API.
--]]
function Checkbox:Create(parent, text, tooltip)
    local control = {}
    local callback

    -- Create the underlying Blizzard widget.
    local check = CreateFrame("CheckButton", nil, parent, "InterfaceOptionsCheckButtonTemplate")
    local size = SinsToolkit.UI.Theme.GetSize("checkbox")
    check:SetSize(size.width, size.height)
    _G[check:GetName() .. "Text"]:SetText(text or "")

    -- Private handler for when the widget is clicked.
    check:SetScript("OnClick", function(self)
        PlaySound(SOUNDKIT.U_CHAT_SCROLL_BUTTON)
        if callback then
            callback(self:GetChecked())
        end
    end)

    -- Private handler for tooltips.
    check:SetScript("OnEnter", function(self)
        if tooltip and tooltip ~= "" then
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetText(tooltip, nil, nil, nil, nil, true)
            GameTooltip:Show()
        end
    end)
    check:SetScript("OnLeave", function()
        GameTooltip:Hide()
    end)
    
    --[[
        Public API for the new control instance.
    --]]

    --[[
        Sets the checked state of the checkbox.
        @param value (boolean) True to check the box, false to uncheck it.
    --]]
    function control:SetValue(value)
        check:SetChecked(not not value)
    end

    --[[
        Gets the current checked state of the checkbox.
        @return (boolean) True if checked, false otherwise.
    --]]
    function control:GetValue()
        return check:GetChecked()
    end

    --[[
        Sets the function to be called when the checkbox state changes.
        @param func A function that accepts one argument: the new checked state (boolean).
    --]]
    function control:SetCallback(func)
        if type(func) == "function" then
            callback = func
        end
    end

    --[[
        Returns the underlying Frame widget for positioning.
        @return The CheckButton Frame.
    --]]
    function control:GetFrame()
        return check
    end

    return control
end
