--[[--------------------------------------------------------------------
  PaladinHolyPower – ui/settings_panel/textboxes.lua
  Minimal router: delegates to the textbox component builder.

  Handles ONLY the "Custom Icon" textbox for the HP Bar tab.
  Visibility is handled by the Icons subpanel in hp_bar_subtab.lua.

  Notes:
  • Per-style storage: reads/writes to ActiveHP(S), not the root S.
  • On style change, if style == "custom" (Icons), refresh the shown value.
----------------------------------------------------------------------]]

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

local Textboxes = Textboxes or {}

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

-- Public API used by hp_bar_subtab.lua
-- Signature mirrors the tab’s call:
--   Textboxes.AddIconTextbox(parent, PHP, S, x, y, key, label, tip)
function Textboxes.AddIconTextbox(parent, PHPobj, S, x, y, key, label, tip)
  -- Expect the real builder to live here:
  local builder = PHP.Textbox and PHP.Textbox.AddIconTextbox
  if type(builder) ~= "function" then
    -- No component available; do not build anything here.
    return nil
  end

  local settingKey = key or "customIcon"
  local labelText  = label or "Icon"

  -- Initial value from the ACTIVE style at build time
  local active     = ActiveHP(S)
  local valueId    = active[settingKey]
  local valueText  = active.customIconLabel

  -- Create the actual textbox widget via the component builder
  local box = builder(parent, PHPobj or PHP, S, x, y, {
    label     = labelText,
    tooltip   = tip,
    value     = valueId,
    valueText = valueText,
    onChange  = function(newId, newLabel)
      -- Resolve target at change time for correct per-style write
      local t = ActiveHP(S)
      t[settingKey]     = newId
      t.customIconLabel = newLabel
      if PHP and PHP.UpdateHPTracker then PHP.UpdateHPTracker() end
    end,
  })

  if not box then
    return nil
  end

  -- Optional: refresh the shown value when switching to Icons style
  local function RefreshFromActive()
    local t  = ActiveHP(S)
    local id = t[settingKey]
    local vt = t.customIconLabel
    if box.SetValue then
      pcall(box.SetValue, box, id, vt)         -- preferred if supported by component
    elseif box.EditBox and box.EditBox.SetText then
      pcall(box.EditBox.SetText, box.EditBox, vt or "")
    end
  end

  if _G.HPBarDD and _G.HPBarDD._RegisterStyleListener then
    _G.HPBarDD._RegisterStyleListener(function(style)
      style = tostring(style or S.style or "default"):lower()
      if style == "custom" then
        RefreshFromActive()
      end
      -- No visibility toggle here; Icons panel handles that.
    end)
  end

  return box
end

-- Keep existing code that expects a global table working:
_G.HPBarTB = Textboxes

return Textboxes