local NS = rawget(_G, "MCDVoiceCooldownNS") or {}
_G.MCDVoiceCooldownNS = NS

NS.UI = NS.UI or {}
NS.UI.MainFrame = NS.UI.MainFrame or {}
NS.UI.MainFrameActions = NS.UI.MainFrameActions or {}

local MainFrame = NS.UI.MainFrame
local L = NS.L or function(key, ...) if select("#", ...) > 0 then return string.format(tostring(key), ...) end return tostring(key) end

function MainFrame:BindActions(controls)
    controls = controls or {}
    local addBtn = controls.addBtn
    local addGroupBtn = controls.addGroupBtn
    local editBtn = controls.editBtn
    local deleteBtn = controls.deleteBtn
    local refreshBtn = controls.refreshBtn
    local importBtn = controls.importBtn
    local exportAllBtn = controls.exportAllBtn
    local savedList = controls.savedList

addBtn:SetScript("OnClick", function()
    NS.UI.EditorFrame:OpenForNew()
end)
addGroupBtn:SetScript("OnClick", function()
    self:OpenCollectionNameDialog()
end)
editBtn:SetScript("OnClick", function()
    local selectedKey = tostring(NS.AceOptions:GetState().selectedKey or "")
    if NS.AceOptions and type(NS.AceOptions.IsGroupKey) == "function" and NS.AceOptions:IsGroupKey(selectedKey) then
        self:OpenRenameCollectionDialog(selectedKey)
    else
        NS.UI.EditorFrame:OpenForEdit()
    end
end)
deleteBtn:SetScript("OnClick", function()
    local selectedKey = tostring(NS.AceOptions:GetState().selectedKey or "")
    if NS.AceOptions and type(NS.AceOptions.IsGroupKey) == "function" and NS.AceOptions:IsGroupKey(selectedKey) then
        if NS.AceOptions:DeleteCollection(selectedKey, true) then
            self:RequestRefresh("list")
        end
    else
        NS.AceOptions:DeleteSelectedEntry(true)
        self:RequestRefresh("list")
    end
end)
refreshBtn:SetScript("OnClick", function()
    self:Refresh()
end)
importBtn:SetScript("OnClick", function()
    self:OpenImportDialog()
end)
exportAllBtn:SetScript("OnClick", function()
    if NS.AceOptions and type(NS.AceOptions.ExportFullString) == "function" then
        self:OpenExportDialog(L("EXPORT_FULL_TITLE"), NS.AceOptions:ExportFullString())
    end
end)

savedList:SetOnSelectionChanged(function(key, entryType, oldKey)
    local state = NS.AceOptions:GetState()
    key = tostring(key or "")
    local isGroup = NS.AceOptions and type(NS.AceOptions.IsGroupKey) == "function" and NS.AceOptions:IsGroupKey(key)
    state.selectedKey = key
    if isGroup then
        state.selectedCollectionKey = key
    else
        state.selectedCollectionKey = nil
        state.entryType = entryType or state.entryType or "cooldown"
        NS.AceOptions:LoadSelectedEntry()
    end
    if savedList and type(savedList.UpdateSelectionOnly) == "function" then
        savedList:UpdateSelectionOnly(oldKey, key)
    end
    if type(self.RefreshActionButtons) == "function" then
        self:RefreshActionButtons()
    end
end)

end
