--[[--------------------------------------------------------------------
  PaladinHolyPower – ui/settings_panel/dropdowns.lua
  Font dropdowns that gather names from (in order):
    1) PHP.SharedMedia (modules/shared_media_support.lua)
    2) LibSharedMedia-3.0 (raw)
    3) PHP.fonts (bundled fallback map)
    4) Blizzard built-ins

  Also provides HP Bar dropdowns.

  UI labels:
    • Default   (internal key: "default")
    • Icons     (internal key: "custom")
    • Bar       (internal key: "custom_bar")
----------------------------------------------------------------------]]

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

local LSM = LibStub and LibStub("LibSharedMedia-3.0", true)
local SM  = PHP.SharedMedia  -- optional helper

-- publish/ensure globals used elsewhere
Fonts   = Fonts   or {}
HPBarDD = HPBarDD 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

-- build font name list
local function BuildFontList(current)
  local items, seen = {}, {}
  local function add(name)
    if name and not seen[name] then
      seen[name] = true
      items[#items+1] = name
    end
  end

  -- 1) From our Shared Media helper
  if SM and SM.ListSorted then
    local list = SM:ListSorted("font")
    for i=1,#list do add(list[i]) end
  elseif LSM then -- 2) Raw LSM
    local list = (type(LSM.List)=="function" and LSM:List("font")) or
                 (type(LSM.List)=="table"   and LSM.List.font) or {}
    for i=1,#list do add(list[i]) end
  end

  -- 3) Bundled fallback map
  if PHP.fonts and type(PHP.fonts)=="table" then
    for name,_ in pairs(PHP.fonts) do add(name) end
  end

  -- 4) Blizzard built-ins
  add("Fonts\\FRIZQT__.TTF")
  add("Fonts\\ARIALN.TTF")
  add("Fonts\\MORPHEUS.TTF")
  add("Fonts\\SKURRI.TTF")

  if current and not seen[current] then table.insert(items, 1, current) end

  table.sort(items, function(a,b) return tostring(a):lower() < tostring(b):lower() end)
  return items
end

local function BuildStatusbarList(current)
  local items, seen = {}, {}
  local function add(name)
    if name and not seen[name] then
      seen[name] = true
      items[#items+1] = name
    end
  end

  add("Solid Color")

  if SM and SM.ListSorted then
    local list = SM:ListSorted("statusbar")
    for i=1,#list do add(list[i]) end
  elseif LSM then
    local list = (type(LSM.List)=="function" and LSM:List("statusbar")) or
                 (type(LSM.List)=="table"   and LSM.List.statusbar) or {}
    for i=1,#list do add(list[i]) end
  end

  if current and not seen[current] then table.insert(items, 2, current) end
  return items
end

-- ========= HPBarDD internal style change mini-bus =========
do
  local styleListeners = {}

  function HPBarDD._RegisterStyleListener(fn)
    if type(fn) == "function" then
      styleListeners[#styleListeners+1] = fn
    end
  end

  function HPBarDD._NotifyStyleChanged(newStyle)
    for i = 1, #styleListeners do
      local ok, err = pcall(styleListeners[i], newStyle)
      if not ok and PHP and PHP.Print then
        PHP.Print("|cffff5050HPBarDD style listener error:|r " .. tostring(err))
      end
    end
  end
end

-- ---------- API ----------

-- Font dropdown:
-- • If key == "HPLFont" → HPL (global): read/write S[key]
-- • else                → HP  (per-style): read/write ActiveHP(S)[key]
function Fonts.AddFontDropdown(parent, PHP, S, x, y, key, label, tip)
  local settingKey = key or "font"
  local isHPL      = (settingKey == "HPLFont")

  local cur = isHPL and S[settingKey]
              or (S.styles and S.styles[S.style] and S.styles[S.style][settingKey]) or nil

  local items    = BuildFontList(cur)
  local name     = label or "Font"
  local tooltip  = tip or "Pick a font from SharedMedia, bundled fonts, or Blizzard fonts."

  local dd = PHP.CreateDropdown(
    "PHP_Dropdown_"..settingKey,
    name, items, parent, x, y,
    tostring(cur or items[1] or "Fonts\\FRIZQT__.TTF"),
    function(choice)
      if isHPL then
        S[settingKey] = choice
        if PHP.UpdateHPLTracker then PHP.UpdateHPLTracker() end
      else
        local active = ActiveHP(S)
        active[settingKey] = choice
        if PHP.UpdateHPTracker then PHP.UpdateHPTracker() end
      end
    end
  )
  if PHP.Tooltip and PHP.Tooltip.Attach then
    PHP.Tooltip.Attach(dd.Button, name, tooltip)
  end
  return dd
end

-- HPL-only mode dropdown (Generated/Spent/Wasted) — writes S.mode
function Fonts.AddModeDropdown(parent, PHP, S, x, y, key, label, tip)
  local settingKey = key or "mode"
  if type(S[settingKey]) ~= "string" then S[settingKey] = "wasted" end

  local items   = { "Generated", "Spent", "Wasted" }
  local name    = label or "Tracker"
  local tooltip = tip   or "Pick which Holy Power total to show on the tracker."

  local function ToLabel(v)
    v = string.lower(v or "wasted")
    return (v=="generated" and "Generated") or (v=="spent" and "Spent") or "Wasted"
  end

  local dd = PHP.CreateDropdown(
    "PHP_Dropdown_"..settingKey,
    name, items, parent, x, y, ToLabel(S[settingKey]),
    function(choice)
      local v = string.lower(choice or "wasted")
      if v~="generated" and v~="spent" and v~="wasted" then v = "wasted" end
      S[settingKey] = v
      if PHP.UpdateHPLTracker then PHP.UpdateHPLTracker() end
    end
  )
  if PHP.Tooltip and PHP.Tooltip.Attach then
    PHP.Tooltip.Attach(dd.Button, name, tooltip)
  end
  return dd
end

-- ======================= HP BAR DROPDOWNS =======================

-- HP Bar Style dropdown: Default / Icons / Bar (UI labels only)
function HPBarDD.AddStyleDropdown(parent, PHP, S, x, y, key)
  local settingKey = key or "style"
  if type(S[settingKey]) ~= "string" then S[settingKey] = "default" end

  -- UI labels
  local items = { "Default", "Icons", "Bar" }

  local function ToLabel(v)
    v = string.lower(v or "default")
    return (v == "custom" and "Icons")
        or (v == "custom_bar" and "Bar")
        or "Default"
  end

  local dd = PHP.CreateDropdown(
    "PHP_Dropdown_" .. settingKey,
    "Style",
    items,
    parent,
    x, y,
    ToLabel(S[settingKey]),
    function(choice)
      local lower = string.lower(choice or "default")
      local v = (lower == "icons" and "custom")
             or (lower == "bar"   and "custom_bar")
             or "default"

      S[settingKey] = v

      -- live update the bar immediately
      if PHP.UpdateHPTracker then PHP.UpdateHPTracker() end

      -- notify listeners (sliders, textbox) to refresh
      if HPBarDD._NotifyStyleChanged then
        HPBarDD._NotifyStyleChanged(v)
      end

      if PHP.OnHPStyleChanged then
        pcall(PHP.OnHPStyleChanged, v)
      end
    end
  )

  return dd
end

-- Bar texture dropdown (per-style). Visibility now handled by Bar subpanel.
function HPBarDD.AddBarTextureDropdown(parent, PHP, S, x, y, key)
  local settingKey = key or "barTexture"
  local cur        = (S.styles and S.styles[S.style] and S.styles[S.style][settingKey]) or "Solid Color"
  local items      = BuildStatusbarList(cur)

  local dd = PHP.CreateDropdown(
    "PHP_Dropdown_" .. settingKey,
    "Texture",
    items,
    parent, x, y,
    tostring(cur or "Solid Color"),
    function(choice)
      local active = ActiveHP(S)  -- resolve per-style at click time
      active[settingKey] = choice
      if PHP.UpdateHPTracker then PHP.UpdateHPTracker() end
    end
  )

  if PHP.Tooltip and PHP.Tooltip.Attach then
    PHP.Tooltip.Attach(dd.Button, "Texture", "Choose a statusbar texture (SharedMedia) or Solid Color.")
  end

  -- No visibility toggling here; BarPanel shows/hides this control.

  return dd
end