local PT = AhUI
local UI = {}
local L = PT.L
PT.Settings = UI

function UI:Create()
    if self.panel then
        return self.panel
    end
	self.checkboxes = {}

    local f = CreateFrame("Frame", "AhUISettingsMain", UIParent)
    f:SetSize(500, 440)

    local title = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
    title:SetPoint("TOPLEFT", 16, -16)
    title:SetText(L["Settings_Title"])

    local saveLabel = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    saveLabel:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 480, 0)
    saveLabel:SetText(L["Settings_SaveMode"] or "Save settings")

    local cbChar = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cbChar:SetPoint("TOPLEFT", saveLabel, "BOTTOMLEFT", 6, -6)
    cbChar.text:SetText(L["Settings_SaveCharacter"] or "Save per character")

    local cbAcc = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cbAcc:SetPoint("TOPLEFT", cbChar, "BOTTOMLEFT", 0, -4)
    cbAcc.text:SetText(L["Settings_SaveAccount"] or "Save for account")

    local function UpdateSaveModeUI()
        cbChar:SetChecked(AhUI_DB.saveMode == "character")
        cbAcc:SetChecked(AhUI_DB.saveMode == "account")
    end

    local function SetSaveMode(mode)
        if AhUI_DB.saveMode == mode then return end
        AhUI_DB.saveMode = mode
        PT.config = PT:GetConfigDB()
        UpdateSaveModeUI()
        PT:RefreshData()
        PT:RefreshUI()
    end

cbChar:SetScript("OnClick", function(self)
    if AhUI_DB.saveMode ~= "character" then
        SetSaveMode("character")
    else
        UpdateSaveModeUI()
    end
end)

cbAcc:SetScript("OnClick", function(self)
    if AhUI_DB.saveMode ~= "account" then
        SetSaveMode("account")
    else
        UpdateSaveModeUI()
    end
end)
    UpdateSaveModeUI()

    local cb = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cb:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -12)
    cb.text:SetText(L["Settings_Concentration"])
    cb.GetValue = function()
		return PT.config.showConcentration ~= false
	end
	cb:SetChecked(cb.GetValue())
	self.checkboxes.showConcentration = cb

    cb:SetScript("OnClick", function(self)
        PT.config.showConcentration = self:GetChecked()
        if PT.ConcentrationUI then
            if PT.config.showConcentration then
                PT.ConcentrationUI:Show()
            else
                PT.ConcentrationUI:Hide()
            end
        end
    end)

    local concAlphaSlider = CreateFrame("Slider", "AhUI_ConcAlphaSlider", f, "OptionsSliderTemplate")
    concAlphaSlider:SetPoint("LEFT", cb.text, "RIGHT", 40, 0)
    concAlphaSlider:SetSize(150, 17)
    concAlphaSlider:SetMinMaxValues(20, 100)
    concAlphaSlider:SetValueStep(5)
    concAlphaSlider:SetObeyStepOnDrag(true)

    AhUI_CharConfig.concentrationAlpha = AhUI_CharConfig.concentrationAlpha or 100

    _G[concAlphaSlider:GetName().."Low"]:SetText("20%")
    _G[concAlphaSlider:GetName().."High"]:SetText("100%")
    _G[concAlphaSlider:GetName().."Text"]:SetText(L["Settings_Transparency"])

    concAlphaSlider:SetValue(AhUI_CharConfig.concentrationAlpha)
    concAlphaSlider.valueText = concAlphaSlider:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    concAlphaSlider.valueText:SetPoint("TOP", concAlphaSlider, "BOTTOM", 0, -2)
    concAlphaSlider.valueText:SetText(AhUI_CharConfig.concentrationAlpha .. "%")

    concAlphaSlider:SetScript("OnValueChanged", function(self, value)
        value = math.floor(value)
        AhUI_CharConfig.concentrationAlpha = value
        self.valueText:SetText(value .. "%")
        if PT.ConcentrationUI and PT.ConcentrationUI.frame then
            PT.ConcentrationUI.frame:SetAlpha(value / 100)
        end
    end)

    local cb2 = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cb2:SetPoint("TOPLEFT", cb, "BOTTOMLEFT", 0, -10)
    cb2.text:SetText(L["Settings_ProfWindow"])
cb2.GetValue = function()
    return PT.config.showProfessionsWindow ~= false
end
cb2:SetChecked(cb2.GetValue())
self.checkboxes.showProfessionsWindow = cb2

cb2:SetScript("OnClick", function(self)
    local enabled = self:GetChecked()
    PT.config.showProfessionsWindow = enabled

    if enabled then
        if PT.UI then
            PT.UI:CreateMainFrame()
        end
        if PT.RefreshData then
            PT:RefreshData()
        end

        if PT.RefreshUI then
            PT:RefreshUI()
        end
    end

    if PT.UI and PT.UI.frame then
        if enabled then
            PT.UI.frame:Show()
        else
            PT.UI.frame:Hide()
        end
    end
end)

    local profAlphaSlider = CreateFrame("Slider", "AhUI_ProfAlphaSlider", f, "OptionsSliderTemplate")
    profAlphaSlider:SetPoint("TOPLEFT", concAlphaSlider, "BOTTOMLEFT", 0, -28)
    profAlphaSlider:SetSize(150, 17)
    profAlphaSlider:SetMinMaxValues(20, 100)
    profAlphaSlider:SetValueStep(5)
    profAlphaSlider:SetObeyStepOnDrag(true)

    AhUI_CharConfig.professionsAlpha = AhUI_CharConfig.professionsAlpha or 100

    _G[profAlphaSlider:GetName().."Low"]:SetText("20%")
    _G[profAlphaSlider:GetName().."High"]:SetText("100%")
    _G[profAlphaSlider:GetName().."Text"]:SetText(L["Settings_Transparency"])

    profAlphaSlider:SetValue(AhUI_CharConfig.professionsAlpha)
    profAlphaSlider.valueText = profAlphaSlider:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    profAlphaSlider.valueText:SetPoint("TOP", profAlphaSlider, "BOTTOM", 0, -2)
    profAlphaSlider.valueText:SetText(AhUI_CharConfig.professionsAlpha .. "%")

    profAlphaSlider:SetScript("OnValueChanged", function(self, value)
        value = math.floor(value)
        AhUI_CharConfig.professionsAlpha = value
        self.valueText:SetText(value .. "%")
        if PT.UI and PT.UI.frame then
            PT.UI.frame:SetAlpha(value / 100)
        end
    end)

    local cb3 = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cb3:SetPoint("TOPLEFT", cb2, "BOTTOMLEFT", 0, -10)
    cb3.text:SetText(L["Settings_LockWindows"])
    cb3:SetChecked(PT.config.lockWindows)

    cb3:SetScript("OnClick", function(self)
        PT.config.lockWindows = self:GetChecked()
        local windows = {
            PT.UI and PT.UI.frame,
            PT.ConcentrationUI and PT.ConcentrationUI.frame,
        }
        for _, w in ipairs(windows) do
            if w then
                w:SetMovable(not PT.config.lockWindows)
                w:EnableMouse(not PT.config.lockWindows)
            end
        end
    end)

    PT.config.confirmOK = PT.config.confirmOK ~= false
    PT.config.confirmReload = PT.config.confirmReload ~= false
    PT.config.confirmButtonStyle = PT.config.confirmButtonStyle or "default"

    local cbOK = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cbOK:SetPoint("TOPLEFT", cb3, "BOTTOMLEFT", 0, -10)
    cbOK.text:SetText(L["Settings_ConfirmOK"])
cbOK.GetValue = function()
    return PT.config.confirmOK ~= false
end
cbOK:SetChecked(cbOK.GetValue())
self.checkboxes.confirmOK = cbOK

    cbOK:SetScript("OnClick", function(self)
        PT.config.confirmOK = self:GetChecked()
        if PT.ConfirmButtons then
            PT.ConfirmButtons:SetOKEnabled(PT.config.confirmOK)
        end
    end)

    local cbR = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    cbR:SetPoint("TOPLEFT", cbOK, "BOTTOMLEFT", 0, -10)
    cbR.text:SetText(L["Settings_ConfirmReload"])
cbR.GetValue = function()
    return PT.config.confirmReload ~= false
end
cbR:SetChecked(cbR.GetValue())
self.checkboxes.confirmReload = cbR

    cbR:SetScript("OnClick", function(self)
        PT.config.confirmReload = self:GetChecked()
        if PT.ConfirmButtons then
            PT.ConfirmButtons:SetReloadEnabled(PT.config.confirmReload)
        end
    end)

    if PT.ConfirmButtons then
        PT.ConfirmButtons:SetOKEnabled(PT.config.confirmOK)
        PT.ConfirmButtons:SetReloadEnabled(PT.config.confirmReload)
    end

    local styleLabel = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    styleLabel:SetPoint("TOPLEFT", cbR, "BOTTOMLEFT", 0, -8)
    styleLabel:SetText(L["Settings_ConfirmStyle"])

    local styles = {}
    if PT.ConfirmButtons and PT.ConfirmButtons.STYLES then
        for key, info in pairs(PT.ConfirmButtons.STYLES) do
            table.insert(styles, { key = key, name = info.name or key })
        end
    end
    table.sort(styles, function(a, b) return a.name < b.name end)

    local dd = CreateFrame("Frame", "AhUIConfirmStyleDropdown", f, "UIDropDownMenuTemplate")
    dd:SetPoint("TOPLEFT", styleLabel, "BOTTOMLEFT", -16, -4)
    UIDropDownMenu_SetWidth(dd, 200)

    UIDropDownMenu_Initialize(dd, function(_, level)
        for _, s in ipairs(styles) do
            local info = UIDropDownMenu_CreateInfo()
            info.text = s.name
            info.checked = (PT.config.confirmButtonStyle == s.key)
            info.func = function()
                PT.config.confirmButtonStyle = s.key
                UIDropDownMenu_SetText(dd, s.name)
                if PT.ConfirmButtons and PT.ConfirmButtons.ApplyStyle then
                    PT.ConfirmButtons:ApplyStyle()
                end
            end
            UIDropDownMenu_AddButton(info, level)
        end
    end)

    do
        local cur = PT.config.confirmButtonStyle
        local style = PT.ConfirmButtons and PT.ConfirmButtons.STYLES and PT.ConfirmButtons.STYLES[cur]
        UIDropDownMenu_SetText(dd, style and style.name or L["Default"])
    end

    local reset = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    reset:SetSize(260, 22)
    reset:SetPoint("TOPLEFT", styleLabel, "BOTTOMLEFT", 0, -42)
    reset:SetText(L["Settings_ResetOK"])
    reset:SetScript("OnClick", function()
        if PT.ConfirmButtons and PT.ConfirmButtons.ResetOKExclusions then
            PT.ConfirmButtons:ResetOKExclusions()
        end
    end)

    PT.config.skinningCheckEnabled = PT.config.skinningCheckEnabled == true
    PT.config.skinningIconSize = PT.config.skinningIconSize or 50

    local scb = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    scb:SetPoint("TOPLEFT", reset, "BOTTOMLEFT", 0, -20)
scb.GetValue = function()
    return PT.config.skinningCheckEnabled ~= false
end
scb:SetChecked(scb.GetValue())
self.checkboxes.skinningCheckEnabled = scb

    scb.text = scb:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    scb.text:SetPoint("LEFT", scb, "RIGHT", 4, 0)
    scb.text:SetText(L["Settings_SkinningCheck"])

    scb:SetScript("OnClick", function(self)
        PT.config.skinningCheckEnabled = self:GetChecked()
        if PT.UI_SkinningCheck then
            PT.UI_SkinningCheck:Update()
        end
    end)

    local btn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btn:SetSize(140, 22)
    btn:SetPoint("LEFT", scb, "RIGHT", 120, 0)
    btn:SetText(L["Settings_SkinningTargets"])
    btn:SetScript("OnClick", function()
        if PT.UI_SkinningTargets and PT.UI_SkinningTargets.Toggle then
            PT.UI_SkinningTargets:Toggle()
        end
    end)

    local sizeLabel = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    sizeLabel:SetPoint("TOPLEFT", scb, "BOTTOMLEFT", 4, -18)
    sizeLabel:SetText(L["Settings_SkinningIconSize"])

    local sizeInput = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
    sizeInput:SetSize(30, 20)
    sizeInput:SetPoint("LEFT", sizeLabel, "RIGHT", 8, 0)
    sizeInput:SetAutoFocus(false)
    sizeInput:SetNumeric(true)
    sizeInput:SetMaxLetters(3)
    sizeInput:SetText(PT.config.skinningIconSize)
    sizeInput:SetCursorPosition(0)

    sizeInput:SetScript("OnEnterPressed", function(self)
        local v = tonumber(self:GetText())
        if not v then
            self:SetText(PT.config.skinningIconSize)
            self:ClearFocus()
            return
        end
        v = math.max(20, math.min(300, math.floor(v)))
        PT.config.skinningIconSize = v
        self:SetText(v)
        self:SetCursorPosition(0)
        if PT.UI_SkinningCheck then
            PT.UI_SkinningCheck:Update()
        end
        self:ClearFocus()
    end)

    self.panel = f
    return f
end

function UI:Refresh()
    if not self.checkboxes then return end

    for _, cb in pairs(self.checkboxes) do
        if cb.GetValue then
            cb:SetChecked(cb.GetValue())
        end
    end

    if PT.WelcomeUI and PT.WelcomeUI.Refresh then
        PT.WelcomeUI:Refresh()
    end
end

function UI:Register()
    if self.category then return end

    local ev = CreateFrame("Frame")
    ev:RegisterEvent("PLAYER_LOGIN")
    ev:SetScript("OnEvent", function()
        if self.category then return end

        local panel = UI:Create()
        local category = Settings.RegisterCanvasLayoutCategory(panel, "AhUI")
        Settings.RegisterAddOnCategory(category)

        UI.category = category
        if UI.RegisterInfoPanelSubcategory then
            UI:RegisterInfoPanelSubcategory()
        end
    end)
end

SLASH_AHUI1 = "/ahui"
SlashCmdList["AHUI"] = function()
    if PT.Settings and PT.Settings.category then
        Settings.OpenToCategory(PT.Settings.category:GetID())
    end
end
