;; Extension — document normalization (drop empty text blocks + empty sections).

(st-bootstrap-classes!)
(content/bootstrap!)
(content-bootstrap-section!)

;; ── drop empty text blocks ──
(define
  d
  (doc-append
    (doc-append
      (doc-append (doc-empty "d") (mk-heading "h" 1 "Hi"))
      (mk-text "empty" ""))
    (mk-text "p" "Body")))
(content-test
  "drops empty text"
  (doc-ids (content/normalize d))
  (list "h" "p"))
(content-test "normalize immutable" (doc-ids d) (list "h" "empty" "p"))
(content-test
  "keeps non-empty text"
  (str (blk-send (doc-find (content/normalize d) "p") "text"))
  "Body")

;; ── drop empty sections ──
(define
  d2
  (doc-append
    (doc-append (doc-empty "d") (mk-text "p" "x"))
    (mk-section "empty-sec" (list))))
(content-test
  "drops empty section"
  (doc-ids (content/normalize d2))
  (list "p"))

;; ── section that becomes empty (all children dropped) is itself dropped ──
(define
  d3
  (doc-append
    (doc-empty "d")
    (mk-section "s" (list (mk-text "e1" "") (mk-text "e2" "")))))
(content-test
  "section emptied then dropped"
  (doc-ids (content/normalize d3))
  (list))

;; ── section with some content keeps surviving children ──
(define
  d4
  (doc-append
    (doc-empty "d")
    (mk-section
      "s"
      (list (mk-text "e" "") (mk-heading "k" 2 "Keep")))))
(define n4 (content/normalize d4))
(content-test "section kept" (doc-ids n4) (list "s"))
(content-test
  "empty child dropped, real kept"
  (doc-tree-ids n4)
  (list "s" "k"))

;; ── nested: empty deep section removed, content bubbles correctly ──
(define
  d5
  (doc-append
    (doc-empty "d")
    (mk-section
      "outer"
      (list (mk-text "a" "A") (mk-section "inner" (list (mk-text "x" "")))))))
(content-test
  "nested empty inner dropped"
  (doc-tree-ids (content/normalize d5))
  (list "outer" "a"))

;; ── already-clean doc unchanged ──
(define
  clean
  (doc-append
    (doc-append (doc-empty "d") (mk-heading "h" 1 "T"))
    (mk-text "p" "B")))
(content-test
  "clean doc unchanged ids"
  (doc-ids (content/normalize clean))
  (list "h" "p"))
(content-test
  "clean doc render"
  (asHTML (content/normalize clean))
  (asHTML clean))

;; ── non-text empties preserved (divider, image with empty alt) ──
(define
  d6
  (doc-append
    (doc-append (doc-empty "d") (mk-divider "dv"))
    (mk-image "i" "/a.png" "")))
(content-test
  "divider + image kept"
  (doc-ids (content/normalize d6))
  (list "dv" "i"))
