local _, addon = ...
local HLY = addon.HLY

local _G = _G
local GetTime = GetTime

local function TryAutoAccept()
    if _G.CompleteLFGRoleCheck then
        _G.CompleteLFGRoleCheck(true)
        return
    end

    local popup = _G.LFDRoleCheckPopup or _G.LFGRoleCheckPopup
    local button = popup and (popup.AcceptButton or popup.acceptButton)
    if button and button:IsEnabled() then
        button:Click()
    end
end

function HLY:HandleRoleCheck()
    if not self.db or not self.db.autoAccept or not self.db.autoAccept.enabled then
        return
    end

    local now = GetTime()
    if self.lastAutoAccept and (now - self.lastAutoAccept) < 0.5 then
        return
    end

    self.lastAutoAccept = now
    TryAutoAccept()
end

function HLY:SetupAutoAccept()
    if self.autoAcceptSetup then
        return
    end

    self:RegisterEvent("LFG_ROLE_CHECK_SHOW", "HandleRoleCheck")
    self:RegisterEvent("LFG_ROLE_CHECK_UPDATE", "HandleRoleCheck")

    self.autoAcceptSetup = true
end

-- LibHLYUI options pane (v2) ------------------------------------------------
function HLY:BuildAutoAcceptOptions(tab)
    tab:Note("Akzeptiert Rollenabfragen automatisch für deine aktuell ausgewählte Rolle.")
    tab:Checkbox({
        label = "Enable",
        get = function() return self.db.autoAccept.enabled end,
        set = function(v) self.db.autoAccept.enabled = v end,
    })
end

addon.options = addon.options or {}
addon.options[#addon.options + 1] = {
    group = "Group Finder", groupOrder = 250, name = "Auto Role", order = 3,
    build = "BuildAutoAcceptOptions",
}
