EbonholdHub.AffixDoll = {}

local AD = EbonholdHub.AffixData

local function LayoutDoll(holder)
    if not holder or not holder.dollFrame then return end
    AD.RefreshDollLayout(holder.dollFrame, holder.slots, holder.slotSize)
    if holder.model then
        AD.UpdateDollModel(holder.model, holder.dollFrame, holder.slotSize)
    end
end

function EbonholdHub.AffixDoll.Create(parent, opts)
    opts = opts or {}
    local slotSize = opts.slotSize or AD.DOLL.REF_SIZE
    local showModel = opts.showModel ~= false

    local holder = CreateFrame("Frame", nil, parent)
    holder.slotSize = slotSize
    holder.slots = {}

    local dollFrame = CreateFrame("Frame", nil, holder)
    dollFrame:SetAllPoints(holder)
    holder.dollFrame = dollFrame

    if showModel then
        local model = CreateFrame("PlayerModel", nil, dollFrame)
        model:EnableMouse(false)
        model:SetFrameLevel(dollFrame:GetFrameLevel() - 1)
        holder.model = model
    end

    holder.Layout = function()
        LayoutDoll(holder)
    end

    dollFrame:SetScript("OnSizeChanged", holder.Layout)
    holder:SetScript("OnShow", holder.Layout)

    return holder
end

function EbonholdHub.AffixDoll.RegisterSlot(holder, key, btn)
    if not holder then return end
    holder.slots = holder.slots or {}
    holder.slots[key] = btn
    if btn and btn.SetFrameLevel and holder.dollFrame then
        btn:SetFrameLevel(holder.dollFrame:GetFrameLevel() + 2)
    end
end

function EbonholdHub.AffixDoll.Refresh(holder)
    LayoutDoll(holder)
end
