export function numericPrefix(name) {
  const match = name?.match(/(\d+)/)
  return match ? parseInt(match[1], 10) : Infinity
}

export function stages(source) {
  const frames = []
  const idsByFrame = new Map()
  for (const el of source.elements) {
    if (el.type === 'frame') { frames.push(el); continue }
    if (!el.frameId) continue
    if (!idsByFrame.has(el.frameId)) idsByFrame.set(el.frameId, [])
    idsByFrame.get(el.frameId).push(el.id)
  }
  frames.sort((a, b) => numericPrefix(a.name) - numericPrefix(b.name))

  const visibleIds = new Set()
  return frames.map(frame => {
    for (const id of (idsByFrame.get(frame.id) ?? [])) visibleIds.add(id)
    return { frame, elementIds: new Set(visibleIds) }
  })
}
