local _, addon = ...

addon.Settings = addon.Settings or {}
local SettingsModule = addon.Settings

function SettingsModule:OpenCategory()
    if not self.category then
        return
    end
    if Settings and Settings.OpenToCategory then
        Settings.OpenToCategory(self.category:GetID())
    elseif InterfaceOptionsFrame_OpenToCategory then
        InterfaceOptionsFrame_OpenToCategory(self.frame)
    end
end

local function setBindingText(button)
    local key = addon.Bindings:GetCurrentBoundKey()
    if key then
        button:SetText("Keybind: " .. key)
    else
        button:SetText("Keybind: Unset")
    end
end

function SettingsModule:BuildPanelUI(frame)
    local title = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightLarge")
    title:SetPoint("TOPLEFT", 16, -18)
    title:SetText("Mount Binder")

    local subtitle = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    subtitle:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
    subtitle:SetText("Bindings mode (v2.x) - radial returns in v3.0")

    local tabGeneral = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    tabGeneral:SetSize(120, 24)
    tabGeneral:SetPoint("TOPLEFT", subtitle, "BOTTOMLEFT", 0, -12)
    tabGeneral:SetText("General")

    local tabAssign = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    tabAssign:SetSize(120, 24)
    tabAssign:SetPoint("LEFT", tabGeneral, "RIGHT", 8, 0)
    tabAssign:SetText("Assignments")

    local content = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    content:SetPoint("TOPLEFT", tabGeneral, "BOTTOMLEFT", 0, -8)
    content:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, 16)
    content:SetBackdrop({
        bgFile = "Interface/Buttons/WHITE8x8",
        edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
        edgeSize = 10,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    content:SetBackdropColor(0.02, 0.02, 0.02, 0.35)

    local generalFrame = CreateFrame("Frame", nil, content)
    generalFrame:SetPoint("TOPLEFT", 12, -12)
    generalFrame:SetPoint("BOTTOMRIGHT", -12, 12)

    local assignFrame = CreateFrame("Frame", nil, content)
    assignFrame:SetPoint("TOPLEFT", 12, -12)
    assignFrame:SetPoint("BOTTOMRIGHT", -12, 12)
    assignFrame:Hide()

    local function showPage(which)
        generalFrame:SetShown(which == "GENERAL")
        assignFrame:SetShown(which == "ASSIGN")
        tabGeneral:SetButtonState(which == "GENERAL" and "PUSHED" or "NORMAL")
        tabAssign:SetButtonState(which == "ASSIGN" and "PUSHED" or "NORMAL")
    end

    tabGeneral:SetScript("OnClick", function() showPage("GENERAL") end)
    tabAssign:SetScript("OnClick", function() showPage("ASSIGN") end)

    local keyLabel = generalFrame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    keyLabel:SetPoint("TOPLEFT", 0, -6)
    keyLabel:SetText("Primary Keybind")

    self.keybindButton = CreateFrame("Button", nil, generalFrame, "UIPanelButtonTemplate")
    self.keybindButton:SetSize(170, 24)
    self.keybindButton:SetPoint("TOPLEFT", keyLabel, "BOTTOMLEFT", 0, -6)
    setBindingText(self.keybindButton)
    self.keybindButton:SetScript("OnClick", function(button)
        button:SetText("Press a key (ESC to cancel)")
        addon.Bindings:StartCapture(function()
            setBindingText(button)
        end)
    end)

    local clearButton = CreateFrame("Button", nil, generalFrame, "UIPanelButtonTemplate")
    clearButton:SetSize(120, 24)
    clearButton:SetPoint("LEFT", self.keybindButton, "RIGHT", 10, 0)
    clearButton:SetText("Clear Keybind")
    clearButton:SetScript("OnClick", function()
        addon.Bindings:ClearBoundKey()
        setBindingText(self.keybindButton)
    end)

    local advMods = CreateFrame("CheckButton", "MountBinderAdvancedModifiersCheckbox", generalFrame, "UICheckButtonTemplate")
    advMods:SetPoint("TOPLEFT", self.keybindButton, "BOTTOMLEFT", 0, -16)
    _G[advMods:GetName() .. "Text"]:SetText("Advanced modifiers are always enabled (8 slots)")
    advMods:SetChecked(true)
    advMods:Disable()

    local help1 = generalFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    help1:SetPoint("TOPLEFT", advMods, "BOTTOMLEFT", 4, -14)
    help1:SetText("Use Assignments page to add mounts, spells, macros, and commands to slots.")

    local help2 = generalFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    help2:SetPoint("TOPLEFT", help1, "BOTTOMLEFT", 0, -6)
    help2:SetText("Press key with modifiers (Shift/Ctrl/Alt) to trigger assigned slot action.")

    local indicatorHeader = generalFrame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    indicatorHeader:SetPoint("TOPLEFT", help2, "BOTTOMLEFT", 0, -16)
    indicatorHeader:SetText("Floating Indicator")

    local indicatorEnabled = CreateFrame("CheckButton", "MountBinderIndicatorEnabled", generalFrame, "UICheckButtonTemplate")
    indicatorEnabled:SetPoint("TOPLEFT", indicatorHeader, "BOTTOMLEFT", 0, -6)
    _G[indicatorEnabled:GetName() .. "Text"]:SetText("Enable floating icon")
    indicatorEnabled:SetChecked(addon.globalDB.indicator and addon.globalDB.indicator.enabled)
    indicatorEnabled:SetScript("OnClick", function(cb)
        addon.Indicator:SetEnabled(cb:GetChecked() == true)
    end)

    local indicatorLocked = CreateFrame("CheckButton", "MountBinderIndicatorLocked", generalFrame, "UICheckButtonTemplate")
    indicatorLocked:SetPoint("TOPLEFT", indicatorEnabled, "BOTTOMLEFT", 0, -6)
    _G[indicatorLocked:GetName() .. "Text"]:SetText("Lock position")
    indicatorLocked:SetChecked(addon.globalDB.indicator and addon.globalDB.indicator.locked)
    indicatorLocked:SetScript("OnClick", function(cb)
        addon.Indicator:SetLocked(cb:GetChecked() == true)
    end)

    local scaleLabel = generalFrame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    scaleLabel:SetPoint("TOPLEFT", indicatorLocked, "BOTTOMLEFT", 4, -12)
    local currentScale = addon.globalDB.indicator and addon.globalDB.indicator.scale or 1.0
    scaleLabel:SetText(string.format("Indicator scale: %.2f", currentScale))

    local scaleSlider = CreateFrame("Slider", "MountBinderIndicatorScaleSlider", generalFrame, "OptionsSliderTemplate")
    scaleSlider:SetPoint("TOPLEFT", scaleLabel, "BOTTOMLEFT", 2, -8)
    scaleSlider:SetSize(220, 20)
    scaleSlider:SetMinMaxValues(0.5, 2.0)
    scaleSlider:SetValueStep(0.05)
    scaleSlider:SetObeyStepOnDrag(true)
    scaleSlider:SetValue(currentScale)
    _G[scaleSlider:GetName() .. "Low"]:SetText("0.5")
    _G[scaleSlider:GetName() .. "High"]:SetText("2.0")
    _G[scaleSlider:GetName() .. "Text"]:SetText("Scale")
    scaleSlider:SetScript("OnValueChanged", function(_, value)
        value = math.floor((value * 100) + 0.5) / 100
        addon.Indicator:SetScale(value)
        scaleLabel:SetText(string.format("Indicator scale: %.2f", value))
    end)

    local resetPos = CreateFrame("Button", nil, generalFrame, "UIPanelButtonTemplate")
    resetPos:SetSize(150, 24)
    resetPos:SetPoint("TOPLEFT", scaleSlider, "BOTTOMLEFT", -2, -10)
    resetPos:SetText("Reset Icon Position")
    resetPos:SetScript("OnClick", function()
        addon.Indicator:ResetPosition()
    end)

    addon.Browser:BuildUI(assignFrame)
    showPage("GENERAL")
end

function SettingsModule:Initialize()
    addon.Browser:Initialize()

    local panel = CreateFrame("Frame", "MountBinderSettingsPanel", UIParent)
    panel.name = "Mount Binder"
    self.frame = panel
    self:BuildPanelUI(panel)

    if Settings and Settings.RegisterCanvasLayoutCategory and Settings.RegisterAddOnCategory then
        local category = Settings.RegisterCanvasLayoutCategory(panel, "Mount Binder", "Mount Binder")
        Settings.RegisterAddOnCategory(category)
        self.category = category
    elseif InterfaceOptions_AddCategory then
        InterfaceOptions_AddCategory(panel)
    end
end
