local addonName, ns = ...
local L = ns.L

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

local function CreateNote(parent, text, x, y, width)
    local note = parent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    note:SetPoint("TOPLEFT", x, y)
    note:SetWidth(width or 520)
    note:SetJustifyH("LEFT")
    note:SetText(W.Colorize(text, C.GRAY))
    return note
end

function ns:InitModuleOptions()
    local p = ns.MainFrame.Content

    W:CachedPanel(cache, "moduleFrame", p, function(f)
        local db = NaowhQOL.misc
        local sf, sc = W:CreateScrollFrame(f, 900)

        W:CreatePageHeader(sc,
            {{L["MODULES_TITLE"]:match("^(%S+)") .. " ", C.BLUE}, {L["MODULES_TITLE"]:match("%s(%S+)$") or "", C.ORANGE}},
            W.Colorize(L["MODULES_SUBTITLE"], C.GRAY))

        local sections = CreateFrame("Frame", nil, sc)
        sections:SetPoint("TOPLEFT", 10, -75)
        sections:SetPoint("RIGHT", sc, "RIGHT", -10, 0)
        sections:SetHeight(600)

        local RelayoutSections

        local itemsWrap, itemsContent = W:CreateCollapsibleSection(sections, {
            text = L["MODULES_SECTION_LOOT"],
            startOpen = false,
            onCollapse = function() if RelayoutSections then RelayoutSections() end end,
        })

        W:CreateCheckbox(itemsContent, {
            label = L["MODULES_FASTER_LOOT"], db = db, key = "fasterLoot",
            x = 10, y = -5, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_FASTER_LOOT_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(itemsContent, {
            label = L["MODULES_SUPPRESS_WARNINGS"], db = db, key = "suppressLootWarnings",
            x = 10, y = -35, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_SUPPRESS_WARNINGS_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(itemsContent, {
            label = L["MODULES_EASY_DESTROY"], db = db, key = "autoFillDelete",
            x = 10, y = -65, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_EASY_DESTROY_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(itemsContent, {
            label = L["MODULES_AUTO_KEYSTONE"], db = db, key = "autoSlotKeystone",
            x = 10, y = -95, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_AUTO_KEYSTONE_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(itemsContent, {
            label = L["MODULES_AH_EXPANSION"], db = db, key = "ahCurrentExpansion",
            x = 10, y = -125, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_AH_EXPANSION_DESC"],
            descWidth = 350,
        })
        itemsContent:SetHeight(155)
        itemsWrap:RecalcHeight()

        local clutterWrap, clutterContent = W:CreateCollapsibleSection(sections, {
            text = L["MODULES_SECTION_UI"],
            startOpen = false,
            onCollapse = function() if RelayoutSections then RelayoutSections() end end,
        })

        W:CreateCheckbox(clutterContent, {
            label = L["MODULES_HIDE_ALERTS"], db = db, key = "hideAlerts",
            x = 10, y = -5, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_HIDE_ALERTS_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(clutterContent, {
            label = L["MODULES_HIDE_TALKING"], db = db, key = "hideTalkingHead",
            x = 10, y = -35, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_HIDE_TALKING_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(clutterContent, {
            label = L["MODULES_HIDE_TOASTS"], db = db, key = "hideEventToasts",
            x = 10, y = -65, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_HIDE_TOASTS_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(clutterContent, {
            label = L["MODULES_HIDE_ZONE"], db = db, key = "hideZoneText",
            x = 10, y = -95, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_HIDE_ZONE_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(clutterContent, {
            label = L["MODULES_SKIP_QUEUE"], db = db, key = "skipQueueConfirm",
            x = 10, y = -125, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_SKIP_QUEUE_DESC"],
            descWidth = 350,
        })
        W:CreateCheckbox(clutterContent, {
            label = L["MODULES_HIDE_MINIMAP"], db = db, key = "hideMinimapIcon",
            x = 10, y = -155, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_HIDE_MINIMAP_DESC"],
            descWidth = 350,
            onChange = function(enabled)
                local iconDb = NaowhQOL.minimapIcon
                if iconDb then
                    iconDb.hide = enabled
                end
                local dbIcon = LibStub("LibDBIcon-1.0", true)
                if dbIcon then
                    if enabled then
                        dbIcon:Hide("NaowhQOL")
                    else
                        dbIcon:Show("NaowhQOL")
                    end
                end
            end,
        })

        clutterContent:SetHeight(185)
        clutterWrap:RecalcHeight()

        local copyDB = NaowhQOL.globalCopy
        local copyWrap, copyContent = W:CreateCollapsibleSection(sections, {
            text = L["MODULES_SECTION_GLOBAL_COPY"],
            startOpen = false,
            onCollapse = function() if RelayoutSections then RelayoutSections() end end,
        })

        W:CreateCheckbox(copyContent, {
            label = L["MODULES_ENABLE_GLOBAL_COPY"],
            db = copyDB, key = "enabled",
            x = 10, y = -5,
            template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_GLOBAL_COPY_DESC"],
            descWidth = 350,
            onChange = function()
                if ns.GlobalCopy then ns.GlobalCopy.Refresh() end
            end,
        })

        W:CreateCheckbox(copyContent, {
            label = L["MODULES_COPY_TOOLTIP_IDS"],
            db = copyDB, key = "tooltipIds",
            x = 30, y = -35,
            template = "ChatConfigCheckButtonTemplate",
            onChange = function()
                if ns.GlobalCopy then ns.GlobalCopy.Refresh() end
            end,
        })

        W:CreateDropdown(copyContent, {
            label = L["MODULES_COPY_MODIFIER"],
            db = copyDB, key = "modifier",
            options = {
                { text = "Ctrl", value = "CTRL" },
                { text = "Shift", value = "SHIFT" },
                { text = "Alt", value = "ALT" },
                { text = "None", value = "NONE" },
            },
            x = 10, y = -72,
            width = 130,
            onChange = function()
                if ns.GlobalCopy then ns.GlobalCopy.Refresh() end
            end,
        })

        W:CreateTextInput(copyContent, {
            label = L["MODULES_COPY_KEY"],
            db = copyDB, key = "key",
            default = "C",
            x = 190, y = -72,
            width = 44,
            maxLetters = 1,
            onChange = function(value)
                copyDB.key = strupper(value or "C")
                if ns.GlobalCopy then ns.GlobalCopy.Refresh() end
            end,
        })

        local copySlashText = copyContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        CreateNote(copyContent, L["MODULES_GLOBAL_COPY_NOTE"], 10, -122, 560)
        copySlashText:SetPoint("TOPLEFT", 10, -160)
        copySlashText:SetText(W.Colorize(L["MODULES_COPY_SLASH"], C.GRAY))
        copyContent:SetHeight(185)
        copyWrap:RecalcHeight()

        local durWrap, durContent = W:CreateCollapsibleSection(sections, {
            text = L["MODULES_SECTION_DEATH"],
            startOpen = false,
            onCollapse = function() if RelayoutSections then RelayoutSections() end end,
        })

        W:CreateCheckbox(durContent, {
            label = L["MODULES_DONT_RELEASE"], db = db, key = "deathReleaseProtection",
            x = 10, y = -5, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_DONT_RELEASE_DESC"],
            descWidth = 350,
        })

        local guildCB

        W:CreateCheckbox(durContent, {
            label = L["MODULES_AUTO_REPAIR"], db = db, key = "autoRepair",
            x = 10, y = -35, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_AUTO_REPAIR_DESC"],
            descWidth = 350,
            onChange = function(enabled)
                if guildCB then guildCB:SetShown(enabled) end
            end,
        })

        guildCB = W:CreateCheckbox(durContent, {
            label = L["MODULES_GUILD_FUNDS"], db = db, key = "guildRepair",
            x = 30, y = -65, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_GUILD_FUNDS_DESC"],
            descWidth = 330,
        })
        guildCB:SetShown(db.autoRepair)

        W:CreateCheckbox(durContent, {
            label = L["MODULES_DURABILITY"], db = db, key = "durabilityWarning",
            x = 10, y = -95, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_DURABILITY_DESC"],
            descWidth = 350,
        })

        W:CreateSlider(durContent, {
            label = L["MODULES_DURABILITY_THRESHOLD"],
            min = 30, max = 80, step = 5,
            isPercent = true,
            x = 10, y = -130,
            db = db, key = "durabilityThreshold",
            onChange = function(val) db.durabilityThreshold = val end
        })

        W:CreateFontPicker(durContent, 10, -175, db.durabilityFont or ns.Media.DEFAULT_FONT, function(name)
            db.durabilityFont = name
        end)

        durContent:SetHeight(225)
        durWrap:RecalcHeight()

        local combatWrap, combatContent = W:CreateCollapsibleSection(sections, {
            text = L["MODULES_SECTION_COMBAT"],
            startOpen = false,
            onCollapse = function() if RelayoutSections then RelayoutSections() end end,
        })

        W:CreateCheckbox(combatContent, {
            label = L["MODULES_COMBAT_CURSOR_CLIP"],
            db = db, key = "combatCursorClip",
            x = 10, y = -5, template = "ChatConfigCheckButtonTemplate",
            description = L["MODULES_COMBAT_CURSOR_CLIP_DESC"],
            descWidth = 350,
            onChange = function(enabled)
                if not enabled and ns.BattleCursorClip then
                    ns.BattleCursorClip.Restore()
                end
            end,
        })

        combatContent:SetHeight(55)
        combatWrap:RecalcHeight()

        local questWrap, questContent = W:CreateCollapsibleSection(sections, {
            text = L["MODULES_SECTION_QUESTING"],
            startOpen = false,
            onCollapse = function() if RelayoutSections then RelayoutSections() end end,
        })

        W:CreateCheckbox(questContent, {
            label = L["MODULES_AUTO_ACCEPT"], db = db, key = "autoQuestAccept",
            x = 10, y = -5, template = "ChatConfigCheckButtonTemplate",
        })
        W:CreateCheckbox(questContent, {
            label = L["MODULES_AUTO_TURNIN"], db = db, key = "autoQuestTurnIn",
            x = 10, y = -35, template = "ChatConfigCheckButtonTemplate",
        })
        W:CreateCheckbox(questContent, {
            label = L["MODULES_AUTO_GOSSIP"], db = db, key = "autoGossipSelect",
            x = 10, y = -65, template = "ChatConfigCheckButtonTemplate",
        })

        questContent:SetHeight(95)
        questWrap:RecalcHeight()

        local sectionList = { itemsWrap, clutterWrap, copyWrap, durWrap, combatWrap, questWrap }

        RelayoutSections = function()
            for i, section in ipairs(sectionList) do
                section:ClearAllPoints()
                if i == 1 then
                    section:SetPoint("TOPLEFT", sections, "TOPLEFT", 0, 0)
                else
                    section:SetPoint("TOPLEFT", sectionList[i - 1], "BOTTOMLEFT", 0, -12)
                end
                section:SetPoint("RIGHT", sections, "RIGHT", 0, 0)
            end

            local totalH = 0
            for _, s in ipairs(sectionList) do
                totalH = totalH + s:GetHeight() + 12
            end
            sections:SetHeight(math.max(totalH, 1))
            sc:SetHeight(math.max(75 + totalH + 40, 600))
        end

        RelayoutSections()
    end)
end
