#import "/src/cetz.typ": draw, styles

#import "/src/consts.typ": *
#import "/src/core/utils.typ": get-ctx, normalize-units, set-y

#let separator-default-style = (
  inset: (
    x: 3pt, y: 5pt
  ),
  fill: auto,
  stroke: auto,
  gap: 3pt,
  outset: 20pt
)

#let render(sep) = get-ctx(ctx => {
  let style = styles.resolve(
    ctx.style,
    merge: sep.style,
    root: "separator",
    base: separator-default-style
  )
  let gap = normalize-units(style.gap)
  let outset = normalize-units(style.outset)

  ctx.y -= ctx.style.y-space

  let x0 = ctx.x-pos.first() - outset
  let x1 = ctx.x-pos.last() + outset
  let name = box(
    sep.name,
    inset: style.inset,
    stroke: style.stroke,
    fill: style.fill
  )
  let m = measure(name)
  let w = m.width / 1pt
  let h = m.height / 1pt
  let cx = (x0 + x1) / 2
  let xl = cx - w / 2
  let xr = cx + w / 2

  let y0 = ctx.y
  let y2 = y0 - h
  let y1 = (y0 + y2) / 2

  let gap-y0 = y1 + gap / 2
  let gap-y1 = gap-y0 - gap

  draw.rect(
    (x0, gap-y0),
    (x1, gap-y1),
    stroke: none,
    fill: style.fill
  )
  draw.line((x0, gap-y0), (x1, gap-y0))
  draw.line((x0, gap-y1), (x1, gap-y1))
  draw.content(
    (cx, y1),
    name,
    anchor: "mid"
  )

  set-y(y2)
})
