-- ============================================================================
-- pom/pvp/pvp_ui.lua
-- PvP Settings Window (no Ace)
-- Slash:
--   /pompvp
--   /pvppom   (alias)
-- ============================================================================

local ADDON_NAME, ns = ...

ns = _G[ADDON_NAME] or ns
_G[ADDON_NAME] = ns

ns.pvp_ui = ns.pvp_ui or {}
local UI = ns.pvp_ui

-- minimal DB wrapper fallback
ns.pvp_db = ns.pvp_db or {}
local DB = ns.pvp_db

-- ------------------------------------------------------------
-- Defaults (merged into PlateOMaticDB.pvp)
-- ------------------------------------------------------------
local function CopyTableShallow(t)
local o = {}
if type(t) == "table" then
    for k,v in pairs(t) do
        if type(v) == "table" then
            local c = {}
            for kk,vv in pairs(v) do c[kk]=vv end
                o[k]=c
                else
                    o[k]=v
                    end
                    end
                    end
                    return o
                    end

                    local function DeepMergeMissing(dst, src)
                    if type(dst) ~= "table" or type(src) ~= "table" then return end
                        for k,v in pairs(src) do
                            if dst[k] == nil then
                                dst[k] = (type(v) == "table") and CopyTableShallow(v) or v
                                elseif type(dst[k]) == "table" and type(v) == "table" then
                                    DeepMergeMissing(dst[k], v)
                                    end
                                    end
                                    end

                                    DB.DEFAULTS = DB.DEFAULTS or {
                                        enabled = false,
                                        useArena = true,
                                        useBG    = true,
                                        useWorld = false,

                                        -- visuals
                                        classColorBars    = true,
                                        greyHPBackground  = true,

                                        showTargetBorder = true,
                                        showFocusBorder  = true,
                                        targetBorderColor = { r=1.0, g=0.82, b=0.0, a=1.0 },
                                        focusBorderColor  = { r=0.0, g=0.8,  b=1.0, a=1.0 },

                                        -- arena numbers
                                        arenaNumbersEnabled = true,
                                        arenaNumbersOnly123 = true,

                                        -- NEW: arena number layout
                                        arenaNumbersSize = 18,
                                        arenaNumbersX    = 0,
                                        arenaNumbersY    = 8,

                                        -- healer marker
                                        healerMarkEnabled = true,
                                        healerMarkSize    = 12,
                                        healerMarkX       = 0,
                                        healerMarkY       = 16, -- above numbers

                                        -- target cc
                                        showTargetCC = true,
                                    }

                                    function DB:Ensure()
                                    PlateOMaticDB = PlateOMaticDB or {}
                                    PlateOMaticDB.pvp = PlateOMaticDB.pvp or {}
                                    DeepMergeMissing(PlateOMaticDB.pvp, self.DEFAULTS)
                                    end

                                    function DB:Get()
                                    self:Ensure()
                                    return PlateOMaticDB.pvp
                                    end

                                    function DB:SetBool(key, val)
                                    local db = self:Get()
                                    db[key] = val and true or false
                                    end

                                    function DB:SetNumber(key, val)
                                    local db = self:Get()
                                    db[key] = tonumber(val) or 0
                                    end

                                    -- ------------------------------------------------------------
                                    -- UI helpers
                                    -- ------------------------------------------------------------
                                    local function MakeHeader(parent, text, x, y)
                                    local fs = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
                                    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                                    fs:SetText(text)
                                    return fs
                                    end

                                    local function MakeSubHeader(parent, text, x, y)
                                    local fs = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                                    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                                    fs:SetText(text)
                                    fs:SetTextColor(1, 0.82, 0)
                                    return fs
                                    end

                                    local function MakeCheck(parent, label, x, y, onClick)
                                    local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
                                    cb:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                                    cb.Text:SetText(label)
                                    cb:SetScript("OnClick", function(selfBtn)
                                    if onClick then onClick(selfBtn:GetChecked() and true or false) end
                                        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON)
                                        end)
                                    return cb
                                    end

                                    local _sliderN = 0
                                    local function MakeSlider(parent, label, x, y, minv, maxv, step, getFn, setFn, onApply)
                                    _sliderN = _sliderN + 1
                                    local name = "POM_PvP_Slider_" .. _sliderN

                                    local fs = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                                    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                                    fs:SetText(label)

                                    local s = CreateFrame("Slider", name, parent, "OptionsSliderTemplate")
                                    s:SetPoint("TOPLEFT", parent, "TOPLEFT", x + 240, y - 4)
                                    s:SetWidth(220)
                                    s:SetMinMaxValues(minv, maxv)
                                    s:SetValueStep(step or 1)
                                    s:SetObeyStepOnDrag(true)

                                    -- Safe label refs (template differs; avoid forbidden _G indexing unless it exists)
                                    local low  = s.Low  or (name and _G[name.."Low"])
                                    local high = s.High or (name and _G[name.."High"])
                                    local text = s.Text or (name and _G[name.."Text"])
                                    if low  and low.SetText  then low:SetText(tostring(minv)) end
                                        if high and high.SetText then high:SetText(tostring(maxv)) end
                                            if text and text.SetText then text:SetText("") end

                                                local valText = parent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
                                                valText:SetPoint("LEFT", s, "RIGHT", 10, 0)
                                                valText:SetText("")

                                                local function Refresh()
                                                local v = tonumber(getFn() or minv) or minv
                                                s:SetValue(v)
                                                valText:SetText(tostring(v))
                                                end

                                                s:SetScript("OnValueChanged", function(selfSlider, value)
                                                local v = tonumber(value) or 0
                                                if step and step > 0 then
                                                    v = math.floor(v / step + 0.5) * step
                                                    end
                                                    valText:SetText(tostring(v))
                                                    if setFn then setFn(v) end
                                                        if onApply then onApply() end
                                                            end)

                                                s._Refresh = Refresh
                                                Refresh()
                                                return s
                                                end

                                                -- ------------------------------------------------------------
                                                -- Refresh MUST be defined outside Build (fixes nil Refresh on old tables)
                                                -- ------------------------------------------------------------
                                                function UI:Refresh()
                                                local w = self._widgets
                                                if not w then return end

                                                    local db = DB:Get()

                                                    if w.cbEnabled then w.cbEnabled:SetChecked(db.enabled and true or false) end
                                                        if w.cbArena   then w.cbArena:SetChecked(db.useArena and true or false) end
                                                            if w.cbBG      then w.cbBG:SetChecked(db.useBG and true or false) end
                                                                if w.cbWorld   then w.cbWorld:SetChecked(db.useWorld and true or false) end

                                                                    if w.cbClassColors then w.cbClassColors:SetChecked(db.classColorBars and true or false) end
                                                                        if w.cbGreyBG      then w.cbGreyBG:SetChecked(db.greyHPBackground and true or false) end

                                                                            if w.cbTargetBorder then w.cbTargetBorder:SetChecked(db.showTargetBorder and true or false) end
                                                                                if w.cbFocusBorder  then w.cbFocusBorder:SetChecked(db.showFocusBorder and true or false) end

                                                                                    if w.cbArenaNums then w.cbArenaNums:SetChecked(db.arenaNumbersEnabled and true or false) end
                                                                                        if w.cbArena123  then w.cbArena123:SetChecked(db.arenaNumbersOnly123 and true or false) end

                                                                                            if w.cbHealerMark then w.cbHealerMark:SetChecked(db.healerMarkEnabled and true or false) end

                                                                                                if w.cbTargetCC then w.cbTargetCC:SetChecked(db.showTargetCC and true or false) end

                                                                                                    if w.sNumSize and w.sNumSize._Refresh then w.sNumSize._Refresh() end
                                                                                                        if w.sNumX    and w.sNumX._Refresh    then w.sNumX._Refresh() end
                                                                                                            if w.sNumY    and w.sNumY._Refresh    then w.sNumY._Refresh() end

                                                                                                                if w.sHealSize and w.sHealSize._Refresh then w.sHealSize._Refresh() end
                                                                                                                    if w.sHealX    and w.sHealX._Refresh    then w.sHealX._Refresh() end
                                                                                                                        if w.sHealY    and w.sHealY._Refresh    then w.sHealY._Refresh() end
                                                                                                                            end

                                                                                                                            -- ------------------------------------------------------------
                                                                                                                            -- Window
                                                                                                                            -- ------------------------------------------------------------
                                                                                                                            function UI:Toggle(applyAll)
                                                                                                                            if self._window and self._window:IsShown() then
                                                                                                                                self._window:Hide()
                                                                                                                                return
                                                                                                                                end

                                                                                                                                if not self._window then
                                                                                                                                    local f = CreateFrame("Frame", "POM_PvPSettingsFrame", UIParent, "BasicFrameTemplateWithInset")
                                                                                                                                    f:SetFrameStrata("DIALOG") 
                                                                                                                                    f:SetSize(640, 560)
                                                                                                                                    f:SetPoint("CENTER")
                                                                                                                                    f:SetMovable(true)
                                                                                                                                    f:EnableMouse(true)
                                                                                                                                    f:RegisterForDrag("LeftButton")
                                                                                                                                    f:SetScript("OnDragStart", f.StartMoving)
                                                                                                                                    f:SetScript("OnDragStop", f.StopMovingOrSizing)
                                                                                                                                    f.TitleText:SetText("Plate-o-Matic - PvP")
                                                                                                                                    self._window = f
                                                                                                                                    end

                                                                                                                                    if not self._built then
                                                                                                                                        self:Build(self._window, applyAll)
                                                                                                                                        else
                                                                                                                                            -- ensure latest values
                                                                                                                                            self:Refresh()
                                                                                                                                            end

                                                                                                                                            self._window:Show()
                                                                                                                                            self._window:Raise()
                                                                                                                                            end

                                                                                                                                            function UI:Build(parent, applyAll)
                                                                                                                                            if self._built then
                                                                                                                                                self:Refresh()
                                                                                                                                                return
                                                                                                                                                end
                                                                                                                                                self._built = true

                                                                                                                                                DB:Ensure()

                                                                                                                                                local function ApplyNow()
                                                                                                                                                if applyAll then applyAll() end
                                                                                                                                                    end

                                                                                                                                                    local box = CreateFrame("Frame", nil, parent)
                                                                                                                                                    box:SetPoint("TOPLEFT", parent, "TOPLEFT", 14, -32)
                                                                                                                                                    box:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", -14, 14)

                                                                                                                                                    MakeHeader(box, "PvP Settings", 0, 0)

                                                                                                                                                    local x = 0
                                                                                                                                                    local y = -36

                                                                                                                                                    MakeSubHeader(box, "General", x, y); y = y - 26

                                                                                                                                                    local cbEnabled = MakeCheck(box, "Enable PvP module", x, y, function(v)
                                                                                                                                                    DB:SetBool("enabled", v); ApplyNow(); UI:Refresh()
                                                                                                                                                    end); y = y - 24

                                                                                                                                                    local cbArena = MakeCheck(box, "Arena", x, y, function(v)
                                                                                                                                                    DB:SetBool("useArena", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    local cbBG = MakeCheck(box, "Battlegrounds", x + 120, y, function(v)
                                                                                                                                                    DB:SetBool("useBG", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    local cbWorld = MakeCheck(box, "World PvP", x + 280, y, function(v)
                                                                                                                                                    DB:SetBool("useWorld", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    y = y - 34
                                                                                                                                                    MakeSubHeader(box, "Visuals", x, y); y = y - 26

                                                                                                                                                    local cbClassColors = MakeCheck(box, "Class colors on enemy players", x, y, function(v)
                                                                                                                                                    DB:SetBool("classColorBars", v); ApplyNow()
                                                                                                                                                    end); y = y - 24

                                                                                                                                                    local cbGreyBG = MakeCheck(box, "Grey HP-bar background (inside bar)", x, y, function(v)
                                                                                                                                                    DB:SetBool("greyHPBackground", v); ApplyNow()
                                                                                                                                                    end); y = y - 24

                                                                                                                                                    local cbTargetBorder = MakeCheck(box, "Target Border", x, y, function(v)
                                                                                                                                                    DB:SetBool("showTargetBorder", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    local cbFocusBorder = MakeCheck(box, "Focus Border", x + 160, y, function(v)
                                                                                                                                                    DB:SetBool("showFocusBorder", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    y = y - 34
                                                                                                                                                    MakeSubHeader(box, "Arena Numbers", x, y); y = y - 26

                                                                                                                                                    local cbArenaNums = MakeCheck(box, "Enable Arena Numbers", x, y, function(v)
                                                                                                                                                    DB:SetBool("arenaNumbersEnabled", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    local cbArena123 = MakeCheck(box, "Only 1-3", x + 200, y, function(v)
                                                                                                                                                    DB:SetBool("arenaNumbersOnly123", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    y = y - 30
                                                                                                                                                    local sNumSize = MakeSlider(box, "Number Size", x, y, 10, 40, 1,
                                                                                                                                                                                function() return DB:Get().arenaNumbersSize end,
                                                                                                                                                                                function(v) DB:SetNumber("arenaNumbersSize", v) end,
                                                                                                                                                                                ApplyNow
                                                                                                                                                    ); y = y - 30

                                                                                                                                                    local sNumX = MakeSlider(box, "Number X Offset", x, y, -60, 60, 1,
                                                                                                                                                                             function() return DB:Get().arenaNumbersX end,
                                                                                                                                                                             function(v) DB:SetNumber("arenaNumbersX", v) end,
                                                                                                                                                                             ApplyNow
                                                                                                                                                    ); y = y - 30

                                                                                                                                                    local sNumY = MakeSlider(box, "Number Y Offset", x, y, 0, 60, 1,
                                                                                                                                                                             function() return DB:Get().arenaNumbersY end,
                                                                                                                                                                             function(v) DB:SetNumber("arenaNumbersY", v) end,
                                                                                                                                                                             ApplyNow
                                                                                                                                                    ); y = y - 34

                                                                                                                                                    MakeSubHeader(box, "Healer Marker", x, y); y = y - 26

                                                                                                                                                    local cbHealerMark = MakeCheck(box, "Show healer marker (arena spec)", x, y, function(v)
                                                                                                                                                    DB:SetBool("healerMarkEnabled", v); ApplyNow()
                                                                                                                                                    end); y = y - 30

                                                                                                                                                    local sHealSize = MakeSlider(box, "Healer Mark Size", x, y, 6, 30, 1,
                                                                                                                                                                                 function() return DB:Get().healerMarkSize end,
                                                                                                                                                                                 function(v) DB:SetNumber("healerMarkSize", v) end,
                                                                                                                                                                                 ApplyNow
                                                                                                                                                    ); y = y - 30

                                                                                                                                                    local sHealX = MakeSlider(box, "Healer Mark X Offset", x, y, -60, 60, 1,
                                                                                                                                                                              function() return DB:Get().healerMarkX end,
                                                                                                                                                                              function(v) DB:SetNumber("healerMarkX", v) end,
                                                                                                                                                                              ApplyNow
                                                                                                                                                    ); y = y - 30

                                                                                                                                                    local sHealY = MakeSlider(box, "Healer Mark Y Offset (above numbers)", x, y, 0, 80, 1,
                                                                                                                                                                              function() return DB:Get().healerMarkY end,
                                                                                                                                                                              function(v) DB:SetNumber("healerMarkY", v) end,
                                                                                                                                                                              ApplyNow
                                                                                                                                                    ); y = y - 34

                                                                                                                                                    MakeSubHeader(box, "Extras", x, y); y = y - 26

                                                                                                                                                    local cbTargetCC = MakeCheck(box, "Show Target CC icon (best-effort)", x, y, function(v)
                                                                                                                                                    DB:SetBool("showTargetCC", v); ApplyNow()
                                                                                                                                                    end)

                                                                                                                                                    self._widgets = {
                                                                                                                                                        cbEnabled=cbEnabled, cbArena=cbArena, cbBG=cbBG, cbWorld=cbWorld,
                                                                                                                                                        cbClassColors=cbClassColors, cbGreyBG=cbGreyBG,
                                                                                                                                                        cbTargetBorder=cbTargetBorder, cbFocusBorder=cbFocusBorder,
                                                                                                                                                        cbArenaNums=cbArenaNums, cbArena123=cbArena123,
                                                                                                                                                        cbHealerMark=cbHealerMark,
                                                                                                                                                        cbTargetCC=cbTargetCC,

                                                                                                                                                        sNumSize=sNumSize, sNumX=sNumX, sNumY=sNumY,
                                                                                                                                                        sHealSize=sHealSize, sHealX=sHealX, sHealY=sHealY,
                                                                                                                                                    }

                                                                                                                                                    self:Refresh()
                                                                                                                                                    end

                                                                                                                                                    -- ------------------------------------------------------------
                                                                                                                                                    -- Slash Commands
                                                                                                                                                    -- ------------------------------------------------------------
                                                                                                                                                    SLASH_POMPVP1 = "/pompvp"
                                                                                                                                                    SLASH_POMPVP2 = "/pvppom"

                                                                                                                                                    SlashCmdList["POMPVP"] = function()
                                                                                                                                                    local applyAll = nil
                                                                                                                                                    if ns.util and ns.util.RefreshAllPlates and ns.pvp and ns.pvp.Apply then
                                                                                                                                                        applyAll = function()
                                                                                                                                                        ns.util.RefreshAllPlates(function(frame)
                                                                                                                                                        if ns.pvp and ns.pvp.Apply then
                                                                                                                                                            ns.pvp:Apply(frame)
                                                                                                                                                            end
                                                                                                                                                            end)
                                                                                                                                                        end
                                                                                                                                                        end
                                                                                                                                                        UI:Toggle(applyAll)
                                                                                                                                                        end
