 (defn- is? [type] (fn [item] (= (:type item) type)))
 (defn- child-text [parent selector] (.-textContent (.querySelector parent selector)))
 
-(defn- set-text! [selector text]
+(defn- set-text!
+  "Set the element matching the selector's `textContent` property"
+   [selector text]
   (set! (.-textContent (js/document.querySelector selector)) text))
 
-(defn- commit-sha [element]
+(defn- commit-sha
+  "Given an element with a link to a commit, with the class `commit-id`, get the commit SHA"
+  [element]
   (last (string/split (.getAttribute (.querySelector element ".commit-id") "href") "/")))
 
-(defn- commit-shas [item]
+(defn- commit-shas
+  "Seq of the commit SHAs contained within the item's element"
+  [item]
   (if-let [element (:element item)]
     (map commit-sha (.querySelectorAll (:element item) ".commit"))
     []))
 
-(defn- item-type [creator item]
+(defn- item-type
+  "Categorise an item based on its class and the creator of the PR"
+  [creator item]
   (let [classes (.-classList item)]
     (cond (.contains classes "discussion-commits") "commit-block"
           (.contains classes "discussion-item-assigned") "assigned"

    {:last-reviewed-commit (-> reviewed-commits last commit-shas last)
     :new-commits (mapcat commit-shas new-commits)}))

(defn- diffstat-count [gitique-enabled direction]
  (let [selector (str "#toc ol>li" (when gitique-enabled ":not(.gitique-hidden)") " .diffstat>.text-diff-" direction)
        elements (js/document.querySelectorAll selector)
        contents (map #(string/replace (.-textContent %) "−" "-") elements)
        numbers (map #(js/parseInt % 10) contents)]
    (reduce + numbers)))

(defn- update-overall! []
  (let [gitique-enabled (.contains (.-classList pjax-wrapper) "gitique-enabled")
        selector (str "#files .file" (when gitique-enabled ":not(.gitique-hidden)"))
        file-count (count (js/document.querySelectorAll selector))
        added (diffstat-count gitique-enabled "added")
        deleted (- (diffstat-count gitique-enabled "deleted"))]
    (set-text! "#files_tab_counter" file-count)
    (set-text! "#diffstat>.text-diff-added" (str "+" added))
    (set-text! "#diffstat>.text-diff-deleted" (str "−" deleted))

        current-pr (when (= (get components 3) "pull") {:repo repo :pr pr})]
    (swap! state assoc :current-pr current-pr)))

(defn ^:export watch
  "Run `main` once, then watch for DOM mutations in the PJAX container and run `main` when
  it changes"
  []
  (let [is-valid-mutation? #(and (= (.-type %) "childList") (not-empty (.-addedNodes %)))
        observer (js/MutationObserver. #(when (some is-valid-mutation? %) (main)))]
    (.observe observer pjax-wrapper #js{:childList true :attributes false :characterData false})
