local RUI = LibStub("RUI-1.0")
if not RUI then return end

-- Gutter reserved at the right edge for the scrollbar. The bar is 10px wide
-- (StyleMenuScrollBar slims it) and is inset 4px from the border, so 20px of
-- child clearance leaves a 6px breathing gap between content and bar.
local SB_GUTTER = 20
local SB_INSET  = 4

-- RUI.ScrollFrame(parent, width, height) → {scroll=ScrollFrame, child=Frame}
-- Panel-styled scrollable area. Lay widgets on the returned child frame.
-- child width = width - 20 (scrollbar clearance). Set child:SetHeight() after populating.
-- Caller must SetPoint on scroll.
function RUI.ScrollFrame(parent, width, height)
    -- ScrollFrameTemplate, not UIPanelScrollFrameTemplate: the latter is
    -- deprecated and anchors its 16px Slider TOPLEFT->TOPRIGHT at x=+6, i.e.
    -- fully outside the frame, so the bar hangs off the edge of any dialog
    -- whose scroll area is inset by less than 22px. ScrollFrameTemplate builds
    -- a MinimalScrollBar we can re-anchor and theme.
    local scroll = CreateFrame("ScrollFrame", nil, parent, "ScrollFrameTemplate")
    scroll:SetSize(width, height)

    RUI.Draw.Background(scroll, RUI.C.BG)
    RUI.Draw.Border(scroll, RUI.C.BORDER)

    -- Pull the bar inside the frame's own border. ScrollFrame_OnLoad has
    -- already anchored it outside by the time CreateFrame returns, so this
    -- has to be a re-anchor rather than a scrollBarX keyvalue.
    local sb = scroll.ScrollBar
    if sb then
        RUI.Draw.StyleMenuScrollBar(scroll)
        sb:ClearAllPoints()
        sb:SetPoint("TOPRIGHT",    scroll, "TOPRIGHT",    -SB_INSET, -SB_INSET)
        sb:SetPoint("BOTTOMRIGHT", scroll, "BOTTOMRIGHT", -SB_INSET,  SB_INSET)
    end

    local child = CreateFrame("Frame", nil, scroll)
    child:SetSize(width - SB_GUTTER, 1)  -- height grows as caller adds content
    scroll:SetScrollChild(child)

    return {scroll=scroll, child=child}
end
