local _, ns = ...

------------------------------------------------------------
-- Blizzard Settings Panel integration
-- Registers a "YippYapp Helper" entry in the standard
-- Settings UI (Esc → Options → AddOns → YippYapp Helper).
-- Each toggle is bound to a SavedVariables flag via a
-- proxy setting, so on/off persists across reloads.
------------------------------------------------------------

local ADDON_NAME = "YippYapp Helper"

-- Each entry describes one toggle in the panel.
-- `get`/`set` work directly against the addon's SavedVariables, with
-- side-effect callbacks (e.g. enabling/disabling event listeners) wired
-- through the existing public API on each feature module.
local TOGGLES = {
    {
        var      = "YYH_RELEASE_BLOCKER",
        name     = "Release Spirit Blocker",
        tooltip  = "Hides the Release Spirit popup in guild raids so you don't run back unnecessarily. Hold CTRL for 1s to override.",
        default  = true,
        get      = function() return ns.IsReleaseBlockerEnabled and ns:IsReleaseBlockerEnabled() end,
        set      = function(v)
            YippYappHelperDB = YippYappHelperDB or {}
            YippYappHelperDB.releaseBlocker = v and true or false
            -- Keep the in-raid-frame ON/OFF button in sync
            if ns.RefreshReleaseBlockerButton then ns.RefreshReleaseBlockerButton() end
        end,
    },
    {
        var      = "YYH_READY_CHECK",
        name     = "Ready Check window",
        tooltip  = "Shows the YippYapp ready-check overview when the raid leader starts a ready check.",
        default  = true,
        get      = function()
            return ns.ReadyCheck and ns.ReadyCheck.IsEnabled and ns.ReadyCheck.IsEnabled()
        end,
        set      = function(v)
            if ns.ReadyCheck and ns.ReadyCheck.SetEnabled then
                ns.ReadyCheck.SetEnabled(v)
            end
        end,
    },
    {
        var      = "YYH_LURA_RUNES",
        name     = "L'ura Runes display",
        tooltip  = "Shows the rune pentagon display during the L'ura memory game when raid clickers send rune messages.",
        default  = true,
        get      = function()
            return ns.LuraRunes and ns.LuraRunes.IsEnabled and ns.LuraRunes.IsEnabled()
        end,
        set      = function(v)
            if ns.LuraRunes and ns.LuraRunes.SetEnabled then
                ns.LuraRunes.SetEnabled(v)
            end
        end,
    },
    {
        var      = "YYH_MINIMAP_BUTTON",
        name     = "Minimap button",
        tooltip  = "Show the YippYapp icon next to the minimap. Disable if you launch the addon via slash command or the LibDataBroker tray.",
        default  = true,
        get      = function()
            YippYappHelperDB = YippYappHelperDB or {}
            YippYappHelperDB.libDBIcon = YippYappHelperDB.libDBIcon or {}
            return not YippYappHelperDB.libDBIcon.hide
        end,
        set      = function(v)
            YippYappHelperDB = YippYappHelperDB or {}
            YippYappHelperDB.libDBIcon = YippYappHelperDB.libDBIcon or {}
            YippYappHelperDB.libDBIcon.hide = not v
            local LDBIcon = LibStub and LibStub("LibDBIcon-1.0", true)
            if LDBIcon then
                if v then LDBIcon:Show("YippYappHelper") else LDBIcon:Hide("YippYappHelper") end
            end
        end,
    },
}

-- Registered setting objects keyed by their variable name. Populated by
-- BuildPanel so other modules can push value changes back into the UI.
local settingsByVar = {}
local syncing = false

-- Called by feature modules when their flag changes from elsewhere (e.g.
-- the in-raid-frame toggle button). Pushes the current getter value into
-- the checkbox widget so it stays in sync with SavedVariables.
function ns.NotifySettingChanged(var)
    if syncing then return end
    local setting = settingsByVar[var]
    if not setting then return end
    -- Read the authoritative current value via the getter and re-apply
    -- through the setting so the widget redraws. The setter will run
    -- once more (idempotent), guarded against recursion by `syncing`.
    for _, def in ipairs(TOGGLES) do
        if def.var == var then
            syncing = true
            setting:SetValue(def.get() and true or false)
            syncing = false
            return
        end
    end
end

------------------------------------------------------------
-- Build the panel
------------------------------------------------------------
local function BuildPanel()
    if not Settings or not Settings.RegisterVerticalLayoutCategory then
        -- Pre-Dragonflight client: settings API isn't available. Skip silently
        -- rather than erroring; the addon's in-window controls still work.
        return
    end

    local category, layout = Settings.RegisterVerticalLayoutCategory(ADDON_NAME)

    for _, def in ipairs(TOGGLES) do
        local setting = Settings.RegisterProxySetting(
            category,
            def.var,
            Settings.VarType.Boolean,
            def.name,
            def.default,
            def.get,
            def.set
        )
        Settings.CreateCheckbox(category, setting, def.tooltip)
        settingsByVar[def.var] = setting
    end

    Settings.RegisterAddOnCategory(category)
    ns.SettingsCategoryID = category:GetID()
end

------------------------------------------------------------
-- /yyh settings → opens the panel directly
------------------------------------------------------------
local function OpenSettings()
    if Settings and Settings.OpenToCategory and ns.SettingsCategoryID then
        Settings.OpenToCategory(ns.SettingsCategoryID)
    end
end
ns.OpenSettings = OpenSettings

SLASH_YYHSETTINGS1 = "/yyhopts"
SLASH_YYHSETTINGS2 = "/yyhsettings"
SlashCmdList.YYHSETTINGS = OpenSettings

------------------------------------------------------------
-- Init: defer to PLAYER_LOGIN so other modules' public APIs
-- (ns.LuraRunes, ns.ReadyCheck, ns.IsReleaseBlockerEnabled)
-- have registered themselves before our getters are called.
------------------------------------------------------------
local init = CreateFrame("Frame")
init:RegisterEvent("PLAYER_LOGIN")
init:SetScript("OnEvent", function(self)
    self:UnregisterAllEvents()
    BuildPanel()
end)
