-- HousingDecorGuide/UI/Widgets/HDG_W_SegmentedChip.lua
-- Cross-tab 3+ state segmented chip control (e.g. All | Have | Need).
-- Mutually-exclusive selection across N chip buttons in a horizontal row.
-- Built on HDG_UIHelpers.CreateChipButton + UpdateChipButtonState so styling
-- inherits the shared chip look.
--
-- Usage:
--   local seg = HDG_W_SegmentedChip:Create(parent, {
--       segments = { {key="all", label="All"}, {key="have", label="Have"} },
--       onSelect = function(key) ... end,
--       height   = 20,    -- per-chip height (default 20)
--       gap      = 2,     -- pixels between chips (default 2)
--       padX     = 16,    -- text horizontal padding inside each chip (default 16)
--   })
--   seg.frame:SetPoint("LEFT", 0, 0)        -- frame is the parent container
--   seg:SetActive("all")
--   local active = seg:GetActive()           -- returns key string
--   seg:GetWidth()                           -- total composed width

local _, privateDB = ...

local M = {}
M.__index = M

local DEFAULTS = {
    height = 20,
    gap    = 2,
    padX   = 16,
}

function M:Create(parent, opts)
    opts = opts or {}
    local height = opts.height or DEFAULTS.height
    local gap    = opts.gap    or DEFAULTS.gap
    local padX   = opts.padX   or DEFAULTS.padX
    local segments = opts.segments or {}

    local instance = setmetatable({}, M)
    instance._segments = segments
    instance._onSelect = opts.onSelect
    instance._buttons  = {}
    instance._active   = nil

    local frame = CreateFrame("Frame", nil, parent)
    frame:SetHeight(height)
    instance.frame = frame

    local x = 0
    for _, sd in ipairs(segments) do
        local btn = HDG_UIHelpers.CreateChipButton(frame, "", 40, false, nil)
        btn.text:SetText(sd.label)
        btn:SetWidth(btn.text:GetStringWidth() + padX)
        btn:SetHeight(height)
        btn:SetPoint("LEFT", x, 0)
        btn._segKey = sd.key
        instance._buttons[sd.key] = btn
        local key = sd.key
        btn:SetScript("OnClick", function()
            instance:SetActive(key)
            if instance._onSelect then instance._onSelect(key) end
        end)
        x = x + btn:GetWidth() + gap
    end
    -- Strip trailing gap from total width.
    instance._totalWidth = math.max(0, x - gap)
    frame:SetWidth(instance._totalWidth)

    return instance
end

function M:SetActive(key)
    if key == self._active then
        -- Re-apply visual state in case ChipButton style was reset elsewhere.
        for k, b in pairs(self._buttons) do
            HDG_UIHelpers.UpdateChipButtonState(b, k == key)
        end
        return
    end
    self._active = key
    for k, b in pairs(self._buttons) do
        HDG_UIHelpers.UpdateChipButtonState(b, k == key)
    end
end

function M:GetActive() return self._active end

function M:GetWidth() return self._totalWidth end

function M:SetOnSelect(fn) self._onSelect = fn end

if privateDB then privateDB.HDG_W_SegmentedChip = M end
return M
