;; Extension — deep tree editing (update/delete/insert into nested sections).

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

;; doc:  top  /  sec[ a, inner[ b ] ]
(define
  d
  (doc-append
    (doc-append (doc-empty "d") (mk-text "top" "T"))
    (mk-section
      "sec"
      (list
        (mk-text "a" "A")
        (mk-section "inner" (list (mk-text "b" "B")))))))

;; ── deep-update a nested block ──
(define d1 (doc-deep-update d "b" "text" "Edited"))
(content-test
  "deep-update nested"
  (str (blk-send (doc-deep-find d1 "b") "text"))
  "Edited")
(content-test
  "deep-update immutable"
  (str (blk-send (doc-deep-find d "b") "text"))
  "B")
(content-test
  "deep-update top-level"
  (str
    (blk-send
      (doc-deep-find (doc-deep-update d "top" "text" "X") "top")
      "text"))
  "X")
(content-test
  "deep-update mid-section"
  (str
    (blk-send (doc-deep-find (doc-deep-update d "a" "text" "AA") "a") "text"))
  "AA")
(content-test
  "deep-update preserves tree"
  (doc-tree-ids d1)
  (doc-tree-ids d))

;; ── deep-replace ──
(define d2 (doc-deep-replace d "b" (mk-heading "b" 3 "H")))
(content-test
  "deep-replace type"
  (blk-type (doc-deep-find d2 "b"))
  "heading")
(content-test
  "deep-replace render"
  (asHTML d2)
  "<p>T</p><section><p>A</p><section><h3>H</h3></section></section>")

;; ── deep-delete ──
(define d3 (doc-deep-delete d "b"))
(content-test "deep-delete removes nested" (doc-deep-find d3 "b") nil)
(content-test
  "deep-delete tree-ids"
  (doc-tree-ids d3)
  (list "top" "sec" "a" "inner"))
(content-test "deep-delete immutable" (doc-tree-count d) 5)
(content-test
  "deep-delete mid-section"
  (doc-tree-ids (doc-deep-delete d "a"))
  (list "top" "sec" "inner" "b"))
(content-test
  "deep-delete top-level"
  (doc-tree-ids (doc-deep-delete d "top"))
  (list "sec" "a" "inner" "b"))

;; ── deep-insert-into a nested section ──
(define d4 (doc-deep-insert-into d "inner" (mk-text "c" "C")))
(content-test
  "insert-into nested"
  (doc-tree-ids d4)
  (list "top" "sec" "a" "inner" "b" "c"))
(content-test
  "insert-into found"
  (str (blk-send (doc-deep-find d4 "c") "text"))
  "C")
(content-test
  "insert-into outer section"
  (doc-tree-ids (doc-deep-insert-into d "sec" (mk-divider "dv")))
  (list "top" "sec" "a" "inner" "b" "dv"))
(content-test "insert-into immutable" (doc-tree-count d) 5)
(content-test
  "insert-into render"
  (asHTML d4)
  "<p>T</p><section><p>A</p><section><p>B</p><p>C</p></section></section>")
