--[[--------------------------------------------------------------------
  PaladinHolyPower – ui/settings_panel/colorpickers.lua
  Settings Panel: Color Picker Utility, generic for all tabs/keys.
----------------------------------------------------------------------]]

local PHP = _G.PaladinHolyPower
if not PHP then return end

Color = Color or {}

-- Helpers
local function ActiveHP(S)
  if not S then return {} end
  local style = S.style or "default"
  S.styles = S.styles or {}
  S.styles[style] = S.styles[style] or {}
  return S.styles[style]
end

-- Decide storage scope:
-- • HP bar colors (fillColor, emptyColor, barColor) → per-style (ActiveHP)
-- • HPL/HUD text colors (valueColor, fontColor)    → stored on S (global to that tab)
local function IsPerStyleKey(key)
  return key == "fillColor" or key == "emptyColor" or key == "barColor"
end

-- Usage: Color.AddColorPicker(parent, PHP, S, x, y, key, label, tooltip)
function Color.AddColorPicker(parent, PHP, S, x, y, key, label, tooltip)
  local LABELS = {
    fillColor  = "Fill Color",
    emptyColor = "Empty Color",
    fontColor  = "Font Color",
    valueColor = "Font Color",
    barColor   = "Bar Color",
  }

  local colorKey   = key or "valueColor"
  local colorLabel = label or LABELS[colorKey] or "Color"
  local tipText    = tooltip or "Pick the color."
  local perStyle   = IsPerStyleKey(colorKey)

  -- Initial color shown in the swatch (reads current style at build time)
  local initTbl  = perStyle and ActiveHP(S) or S
  local current  = initTbl[colorKey] or { 1, 1, 0 }

  local colorPicker = PHP.CreateColorPicker(
    parent,
    colorLabel,
    current,
    x, y,
    function(r, g, b)
      -- IMPORTANT: resolve the target table AT CLICK TIME,
      -- so switching between Default / Custom Icons / Custom Bar writes correctly.
      local targetTbl = perStyle and ActiveHP(S) or S
      targetTbl[colorKey] = { r, g, b }

      -- Trigger both updates; harmless if unused on the current tab
      if PHP.UpdateHPLTracker then PHP.UpdateHPLTracker() end
      if PHP.UpdateHPTracker  then PHP.UpdateHPTracker()  end
    end
  )

  -- Reposition label to the right of the swatch (1px spacing)
  if colorPicker and colorPicker.label and colorPicker.swatch then
    colorPicker.label:ClearAllPoints()
    colorPicker.label:SetPoint("LEFT", colorPicker.swatch, "RIGHT", 1, 0)
    colorPicker.label:SetJustifyH("LEFT")
  end

  -- Optional: if your picker control exposes a way to update its displayed color
  -- (e.g., colorPicker:SetColor(r,g,b)), you could subscribe to style changes:
  -- if perStyle and HPBarDD and HPBarDD._RegisterStyleListener and colorPicker.SetColor then
  --   HPBarDD._RegisterStyleListener(function()
  --     local t = ActiveHP(S)
  --     local c = t[colorKey] or current
  --     colorPicker:SetColor(c[1] or 1, c[2] or 1, c[3] or 0)
  --   end)
  -- end

  return colorPicker
end

return Color