local addonName, SinsToolkit = ...

local MODE_VALUES = {
    off = "Off",
    session = "Session",
    permanent = "Permanent",
}

local function EnsureDB()
    if SinsToolkit.EnsureDB then SinsToolkit.EnsureDB() end
end

local function GetValue(key)
    EnsureDB()
    return SinsToolkitDB and SinsToolkitDB[key]
end

local function SetValue(key, value)
    EnsureDB()
    SinsToolkitDB[key] = value
    if SinsToolkit.TriggerUpdate then SinsToolkit.TriggerUpdate(key) end
end

function SinsToolkit.GetFrameToolsElvUIOptions(GradientText, PageIntro)
    return {
        type = "group",
        name = GradientText and GradientText("Frame Tools") or "Frame Tools",
        order = 5.2,
        args = {
            intro = PageIntro and PageIntro("Frame Tools", "Move and scale supported Blizzard and addon windows. Drag windows to reposition them, use Ctrl + mouse wheel to scale from 50%-200%, save per-frame placement, and right-click the Toolkit drag area to reset position or scale. If another addon also moves or scales frames, use one frame mover at a time for predictable behavior.") or nil,
            noAutoCloseHeader = { type = "header", name = "No Auto Close", order = 10 },
            keepPanelsOpen = {
                type = "toggle",
                name = "No Auto Close Panels",
                desc = "Keeps supported Blizzard panels open together. Reload after disabling because Blizzard panel layout hooks are persistent for the session.",
                order = 11,
                get = function() return GetValue("keepPanelsOpen") end,
                set = function(_, value) SetValue("keepPanelsOpen", value) end,
            },
            respectExcludedFrames = {
                type = "toggle",
                name = "Respect Excluded Frames",
                desc = "Leaves sensitive frames such as cinematics, barbershop, communities, player housing editor, and trading post under Blizzard control.",
                order = 12,
                get = function() EnsureDB(); return SinsToolkitDB.noAutoClose.respectExcludedFrames ~= false end,
                set = function(_, value) EnsureDB(); SinsToolkitDB.noAutoClose.respectExcludedFrames = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end,
            },
            defaultAnchor = {
                type = "select",
                name = "Default Position Anchor",
                desc = "Default anchor used when a Blizzard panel loses its layout point after No Auto Close removes it from Blizzard's UIPanel layout system.",
                values = { TOPLEFT = "Top Left", TOP = "Top", TOPRIGHT = "Top Right", CENTER = "Center" },
                order = 13,
                get = function() EnsureDB(); return SinsToolkitDB.noAutoClose.defaultPosition.anchor or "TOPLEFT" end,
                set = function(_, value) EnsureDB(); SinsToolkitDB.noAutoClose.defaultPosition.anchor = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end,
            },
            defaultX = {
                type = "range", name = "Default X", order = 14, min = -900, max = 900, step = 1,
                get = function() EnsureDB(); return SinsToolkitDB.noAutoClose.defaultPosition.x or 50 end,
                set = function(_, value) EnsureDB(); SinsToolkitDB.noAutoClose.defaultPosition.x = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end,
            },
            defaultY = {
                type = "range", name = "Default Y", order = 15, min = -900, max = 900, step = 1,
                get = function() EnsureDB(); return SinsToolkitDB.noAutoClose.defaultPosition.y or -50 end,
                set = function(_, value) EnsureDB(); SinsToolkitDB.noAutoClose.defaultPosition.y = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end,
            },
            moverHeader = { type = "header", name = "Frame Mover", order = 20 },
            frameMoverEnabled = {
                type = "toggle",
                name = "Enable Frame Mover",
                desc = "Lets Sin's Toolkit move supported Blizzard and addon frames with left-drag, scale supported windows from 50%-200% with Ctrl + mouse wheel, and reset position or scale from the right-click mover menu.",
                order = 21,
                get = function() return GetValue("frameMoverEnabled") end,
                set = function(_, value) SetValue("frameMoverEnabled", value) end,
            },
            requireModifier = {
                type = "toggle",
                name = "Require Shift to Move",
                desc = "Requires Shift while left-dragging to move frames. This prevents accidental movement.",
                order = 22,
                get = function() return GetValue("frameMoverRequireModifier") end,
                set = function(_, value) SetValue("frameMoverRequireModifier", value) end,
            },
            ctrlScrollScale = {
                type = "toggle",
                name = "Ctrl + Mouse Wheel Scaling",
                desc = "Allows Ctrl + mouse wheel over supported frames to scale them between 50% and 200%.",
                order = 23,
                get = function() return GetValue("frameMoverCtrlScrollScale") end,
                set = function(_, value) SetValue("frameMoverCtrlScrollScale", value) end,
            },
            positionMode = {
                type = "select",
                name = "Position Saving",
                desc = "Off does not save moved frames. Session keeps positions until reload. Permanent saves positions in SinsToolkitDB.",
                values = MODE_VALUES,
                order = 24,
                get = function() return GetValue("frameMoverPositionMode") or "session" end,
                set = function(_, value) SetValue("frameMoverPositionMode", value) end,
            },
            scaleMode = {
                type = "select",
                name = "Scale Saving",
                desc = "Off does not save scale changes. Session keeps scales until reload. Permanent saves scales in SinsToolkitDB.",
                values = MODE_VALUES,
                order = 25,
                get = function() return GetValue("frameMoverScaleMode") or "session" end,
                set = function(_, value) SetValue("frameMoverScaleMode", value) end,
            },
            resetMover = {
                type = "execute",
                name = "Reset Saved Positions and Scales",
                desc = "Clears all saved Frame Mover positions and scales. Reload UI afterward if a frame is already open.",
                order = 26,
                func = function() if SinsToolkit.FrameMover then SinsToolkit.FrameMover:ResetAll() end end,
            },
        },
    }
end

function SinsToolkit.BuildStandaloneFrameToolsPages(Window, contentPanel, CreateWrappedText, getGV, setGV)
    local frameTools = CreateFrame("Frame", nil, contentPanel)
    frameTools:SetAllPoints()
    frameTools:Hide()
    Window.pages["Frame Tools"] = frameTools

    local header = Window:CreateSectionHeader(frameTools, "Frame Tools")
    CreateWrappedText(frameTools, {"TOPLEFT", header, "BOTTOMLEFT", 0, -8}, 720, "No Auto Close keeps supported Blizzard panels open. Frame Mover lets supported frames be moved with left-drag, scaled from 50%-200% with Ctrl + mouse wheel, and reset from the right-click mover menu. If another addon also moves or scales frames, use one frame mover at a time for predictable behavior.", "GameFontHighlightSmall")

    local cbNoAutoClose = Window:CreateCheckbox(frameTools, "No Auto Close Panels", getGV("keepPanelsOpen"), setGV("keepPanelsOpen"), "Keeps supported Blizzard panels open together. Reload after disabling because Blizzard panel layout hooks are persistent for the current session.")
    cbNoAutoClose:SetPoint("TOPLEFT", header, "BOTTOMLEFT", 0, -54)

    local exclude = Window:CreateCheckbox(frameTools, "Respect Excluded Frames", function() EnsureDB(); return SinsToolkitDB.noAutoClose.respectExcludedFrames ~= false end, function(value) EnsureDB(); SinsToolkitDB.noAutoClose.respectExcludedFrames = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end, "Leaves sensitive frames such as cinematics, barbershop, communities, player housing editor, and trading post under Blizzard control.")
    exclude:SetPoint("TOPLEFT", cbNoAutoClose, "BOTTOMLEFT", 0, -8)

    local anchor = Window:CreateCycleButton(frameTools, "Default Position Anchor", { TOPLEFT = "Top Left", TOP = "Top", TOPRIGHT = "Top Right", CENTER = "Center" }, function() EnsureDB(); return SinsToolkitDB.noAutoClose.defaultPosition.anchor or "TOPLEFT" end, function(value) EnsureDB(); SinsToolkitDB.noAutoClose.defaultPosition.anchor = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end, "Default anchor used when a panel loses its Blizzard layout point.")
    anchor:SetPoint("TOPLEFT", exclude, "BOTTOMLEFT", 4, -24)

    local x = Window:CreateSlider(frameTools, "Default X", function() EnsureDB(); return SinsToolkitDB.noAutoClose.defaultPosition.x or 50 end, function(value) EnsureDB(); SinsToolkitDB.noAutoClose.defaultPosition.x = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end, -900, 900, 1, "Default X offset for No Auto Close panel placement.")
    x:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", -4, -26)

    local y = Window:CreateSlider(frameTools, "Default Y", function() EnsureDB(); return SinsToolkitDB.noAutoClose.defaultPosition.y or -50 end, function(value) EnsureDB(); SinsToolkitDB.noAutoClose.defaultPosition.y = value; if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end end, -900, 900, 1, "Default Y offset for No Auto Close panel placement.")
    y:SetPoint("LEFT", x, "RIGHT", 56, 0)

    local moverHeader = frameTools:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    moverHeader:SetPoint("TOPLEFT", x, "BOTTOMLEFT", -4, -36)
    moverHeader:SetText("Frame Mover")

    local cbMover = Window:CreateCheckbox(frameTools, "Enable Frame Mover", getGV("frameMoverEnabled"), setGV("frameMoverEnabled"), "Move supported frames with left-drag. Use Ctrl + mouse wheel to scale supported frames from 50%-200%. Right-click the Toolkit drag strip, or Shift-right-click a supported frame, to reset position or scale.")
    cbMover:SetPoint("TOPLEFT", moverHeader, "BOTTOMLEFT", -4, -10)

    local requireShift = Window:CreateCheckbox(frameTools, "Require Shift to Move", getGV("frameMoverRequireModifier"), setGV("frameMoverRequireModifier"), "Requires Shift while left-dragging to move frames.")
    requireShift:SetPoint("LEFT", cbMover, "RIGHT", 180, 0)

    local ctrlScale = Window:CreateCheckbox(frameTools, "Ctrl + Mouse Wheel Scaling", getGV("frameMoverCtrlScrollScale"), setGV("frameMoverCtrlScrollScale"), "Allows Ctrl + mouse wheel over supported frames to adjust scale.")
    ctrlScale:SetPoint("TOPLEFT", requireShift, "BOTTOMLEFT", 0, -8)

    local posMode = Window:CreateCycleButton(frameTools, "Position Saving", MODE_VALUES, getGV("frameMoverPositionMode"), setGV("frameMoverPositionMode"), "Off does not save moved frames. Session keeps positions until reload. Permanent saves positions in SinsToolkitDB.")
    posMode:SetPoint("TOPLEFT", ctrlScale, "BOTTOMLEFT", 4, -24)

    local scaleMode = Window:CreateCycleButton(frameTools, "Scale Saving", MODE_VALUES, getGV("frameMoverScaleMode"), setGV("frameMoverScaleMode"), "Off does not save scale changes. Session keeps scales until reload. Permanent saves scales in SinsToolkitDB.")
    scaleMode:SetPoint("LEFT", posMode, "RIGHT", 24, 0)

    local reset = Window:CreateButton(frameTools, "Reset Positions and Scales", 190, 26, function() if SinsToolkit.FrameMover then SinsToolkit.FrameMover:ResetAll() end end, "Clears saved Frame Mover positions and scales.")
    reset:SetPoint("TOPLEFT", posMode, "BOTTOMLEFT", -4, -22)

    local status = frameTools:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    status:SetPoint("TOPLEFT", reset, "BOTTOMLEFT", 0, -18)
    status:SetWidth(720)
    status:SetJustifyH("LEFT")
    frameTools.OnShowCallback = function()
        status:SetText(SinsToolkit.FrameMover and SinsToolkit.FrameMover:GetStatusText() or "")
    end
end
