local addonName, ns = ...

local cache = {}
local W = ns.Widgets
local C = ns.COLORS

function ns:InitPersonalReminders()
    local p    = ns.MainFrame.Content
    local db   = BrightQoL.personalReminders
    local DEFS = ns.PersonalReminderDefs or {}

    W:CachedPanel(cache, "prFrame", p, function(f)
        local sf, sc = W:CreateScrollFrame(f, 1800)

        W:CreatePageHeader(sc,
            {{"PERSONAL ", C.BLUE}, {"REMINDERS", C.ORANGE}},
            W.Colorize("Show text alerts when buffs or class abilities are missing", C.GRAY))

        -- --------------------------------------------------------
        -- MASTER TOGGLE
        -- --------------------------------------------------------
        local toggleArea = CreateFrame("Frame", nil, sc, "BackdropTemplate")
        toggleArea:SetSize(460, 38)
        toggleArea:SetPoint("TOPLEFT", 10, -75)
        toggleArea:SetBackdrop({ bgFile = [[Interface\Buttons\WHITE8x8]] })
        toggleArea:SetBackdropColor(0.01, 0.56, 0.91, 0.08)

        W:CreateCheckbox(toggleArea, {
            label    = "Enable Personal Reminders",
            db       = db, key = "enabled",
            x        = 15, y = -8,
            isMaster = true,
            onChange = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        -- --------------------------------------------------------
        -- SECTION CONTAINER
        -- --------------------------------------------------------
        local sectionContainer = CreateFrame("Frame", nil, sc)
        sectionContainer:SetPoint("TOPLEFT", toggleArea, "BOTTOMLEFT", 0, -10)
        sectionContainer:SetPoint("RIGHT", sc, "RIGHT", -10, 0)
        sectionContainer:SetHeight(2000)

        local allSectionWrappers = {}
        local function RelayoutSections()
            local yOff = 0
            for _, wrap in ipairs(allSectionWrappers) do
                wrap:ClearAllPoints()
                wrap:SetPoint("TOPLEFT", sectionContainer, "TOPLEFT", 0, -yOff)
                wrap:SetPoint("RIGHT",   sectionContainer, "RIGHT",   0,  0)
                yOff = yOff + wrap:GetHeight() + 8
            end
            sectionContainer:SetHeight(yOff + 10)
            sc:SetHeight(yOff + 200)
        end

        -- --------------------------------------------------------
        -- DISPLAY SETTINGS
        -- --------------------------------------------------------
        local dispWrap, dispContent = W:CreateCollapsibleSection(sectionContainer, {
            text      = "DISPLAY",
            startOpen = true,
            onCollapse = RelayoutSections,
        })
        table.insert(allSectionWrappers, dispWrap)

        -- Font Size
        W:CreateSlider(dispContent, {
            label   = "Font Size",
            min     = 8, max = 28, step = 1,
            db      = db, key = "fontSize",
            x       = 0, y   = -10,
            width   = 150,
            tooltip = "Size of the reminder text",
            onChange = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        -- Font picker
        local fpLabel = dispContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontHighSmall")
        fpLabel:SetPoint("TOPLEFT", 0, -70)
        fpLabel:SetText(W.Colorize("FONT", C.BLUE))

        W:CreateFontPicker(dispContent, 0, -84, db.fontPath or "Fonts\\FRIZQT__.TTF", function(path, name)
            db.fontPath = path
            if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
        end)

        -- Outline dropdown
        W:CreateDropdown(dispContent, {
            label   = "Outline",
            x       = 0, y = -122,
            width   = 150,
            db      = db, key = "fontOutline",
            options = {
                { text = "Outline",       value = "OUTLINE" },
                { text = "Thick Outline", value = "THICKOUTLINE" },
                { text = "None",          value = "NONE" },
            },
            current  = function() return db.fontOutline or "OUTLINE" end,
            onSelect = function(val)
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        -- Pulse enabled
        W:CreateCheckbox(dispContent, {
            label    = "Enable Pulse Effect",
            db       = db, key = "pulseEnabled",
            x        = 0, y = -162,
            onChange = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        -- Pulse colors
        W:CreateColorPicker(dispContent, {
            label        = "Pulse Color A",
            x            = 0, y = -188,
            db           = db,
            rKey         = "pulseColorAR", gKey = "pulseColorAG", bKey = "pulseColorAB",
            noClassColor = true,
            onChange     = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        W:CreateColorPicker(dispContent, {
            label        = "Pulse Color B",
            x            = 200, y = -188,
            db           = db,
            rKey         = "pulseColorBR", gKey = "pulseColorBG", bKey = "pulseColorBB",
            noClassColor = true,
            onChange     = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        -- Pulse speed
        W:CreateSlider(dispContent, {
            label   = "Pulse Speed",
            min     = 0.2, max = 4.0, step = 0.1,
            db      = db, key = "pulseSpeed",
            x       = 0, y   = -238,
            width   = 150,
            tooltip = "Speed of the colour pulse (higher = faster)",
            onChange = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })

        -- Lock/Unlock + Force Update buttons
        local lockBtn
        lockBtn = W:CreateButton(dispContent, {
            text    = db.unlock and "Lock Position" or "Unlock Position",
            onClick = function()
                db.unlock = not db.unlock
                lockBtn:SetText(db.unlock and "Lock Position" or "Unlock Position")
                if ns.PersonalReminders then
                    ns.PersonalReminders:SetUnlocked(db.unlock)
                end
            end,
        })
        lockBtn:SetPoint("TOPLEFT", 0, -298)

        local forceBtn = W:CreateButton(dispContent, {
            text    = "Force Update",
            onClick = function()
                if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
            end,
        })
        forceBtn:SetPoint("TOPLEFT", 140, -298)

        dispContent:SetHeight(340)
        dispWrap:RecalcHeight()

        -- --------------------------------------------------------
        -- REMINDER TOGGLES per class
        -- --------------------------------------------------------
        local playerClass = select(2, UnitClass("player"))
        local classDefs = {}
        for _, def in ipairs(DEFS) do
            if def.class == nil or def.class == playerClass then
                table.insert(classDefs, def)
            end
        end

        if #classDefs > 0 then
            local remWrap, remContent = W:CreateCollapsibleSection(sectionContainer, {
                text      = "REMINDERS",
                startOpen = true,
                onCollapse = RelayoutSections,
            })
            table.insert(allSectionWrappers, remWrap)

            -- Column headers
            local hEnable = remContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontSmall")
            hEnable:SetPoint("TOPLEFT", 4, -8)
            hEnable:SetText(W.Colorize("Reminder", C.BLUE))

            local hDungeon = remContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontSmall")
            hDungeon:SetPoint("TOPLEFT", 255, -8)
            hDungeon:SetText(W.Colorize("Dung", C.GRAY))

            local hRaid = remContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontSmall")
            hRaid:SetPoint("TOPLEFT", 300, -8)
            hRaid:SetText(W.Colorize("Raid", C.GRAY))

            local hGroup = remContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontSmall")
            hGroup:SetPoint("TOPLEFT", 345, -8)
            hGroup:SetText(W.Colorize("Group", C.GRAY))

            local hOutside = remContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontSmall")
            hOutside:SetPoint("TOPLEFT", 395, -8)
            hOutside:SetText(W.Colorize("Out", C.GRAY))

            local sep = remContent:CreateTexture(nil, "BACKGROUND")
            sep:SetHeight(1)
            sep:SetPoint("TOPLEFT",  0, -22)
            sep:SetPoint("TOPRIGHT", 0, -22)
            sep:SetColorTexture(0.2, 0.2, 0.2, 0.8)

            local yBase = -28
            local rowH  = 24

            -- Ensure reminder cfg entries exist
            db.reminders = db.reminders or {}
            for _, def in ipairs(classDefs) do
                if not db.reminders[def.id] then
                    db.reminders[def.id] = { enabled = true, onlyInDungeon = false, onlyInRaid = false, onlyInGroup = false, onlyOutside = false }
                end
            end

            for ri, def in ipairs(classDefs) do
                local cfg  = db.reminders[def.id]
                local yRow = yBase - (ri - 1) * rowH

                W:CreateCheckbox(remContent, {
                    label    = def.label,
                    db       = cfg, key = "enabled",
                    x        = 4, y = yRow,
                    onChange = function()
                        if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
                    end,
                })

                local condDefs = {
                    { key = "onlyInDungeon", x = 258 },
                    { key = "onlyInRaid",    x = 302 },
                    { key = "onlyInGroup",   x = 347 },
                    { key = "onlyOutside",   x = 398 },
                }
                for _, cd in ipairs(condDefs) do
                    W:CreateCheckbox(remContent, {
                        db    = cfg, key  = cd.key,
                        x     = cd.x, y   = yRow + 2,
                        size  = 14,
                        onChange = function()
                            if ns.PersonalReminders then ns.PersonalReminders:ForceUpdate() end
                        end,
                    })
                end

                if ri % 2 == 0 then
                    local rowBg = remContent:CreateTexture(nil, "BACKGROUND")
                    rowBg:SetHeight(rowH)
                    rowBg:SetPoint("TOPLEFT",  0, yRow + 4)
                    rowBg:SetPoint("TOPRIGHT", 0, yRow + 4)
                    rowBg:SetColorTexture(1, 1, 1, 0.03)
                end
            end

            local totalH = 28 + #classDefs * rowH + 10
            remContent:SetHeight(totalH)
            remWrap:RecalcHeight()
        end

        C_Timer.After(0.05, RelayoutSections)
    end)
end
