 (ns todomvc-reagent.core
-    (:require [reagent.core :as r]))
+  (:require [reagent.core :as r]
+            [clojure.string :as s]))
 
 ;; -------------------------
 ;; Db

           active-cnt (- (count items) completed-cnt)]
      [:div
       [:section.todoapp
        [todo-header "reagent" "What needs to be done?"]

        (when (pos? (count items))
          [:div
           [:section.main
            [:input.toggle-all {:type "checkbox" :checked (zero? active-cnt) :on-click #(complete-all (pos? active-cnt))}]
            [:label {:for "toggle-all"} "Mark all as complte"]

            [todo-list showing items]]

;; -------------------------
;; Views

(defn todo-input [{:keys [title on-save on-stop]}]
  (let [val (r/atom title)
        stop #(do (reset! val "")
                  (if on-stop (on-stop)))
        save #(let [v (-> @val str s/trim)]
                (if-not (empty? v) (on-save v))
                (stop))]
    (fn [{:keys [id class placeholder]}]
      [:input
       {:id id :class class
        :value @val
        :autoFocus true
        :placeholder placeholder
        :on-blur save
        :on-change #(reset! val (-> % .-target .-value))
        :on-key-down #(case (.-which %)
                        13 (save)
                        27 (stop)
                        nil)}])))

(defn todo-item []
  (let [editing (r/atom false)]
    (fn [{:keys [id title done]}]
      [:li {:class (str (when done "completed ") (when @editing "editing"))}
       [:div.view
        [:input.toggle {:type "checkbox" :checked done :on-change #(toggle id)}]
        [:label
         {:on-double-click #(reset! editing true)}
         title]
        [:button.destroy {:on-click #(delete id)}]]
       (when @editing
         [todo-input {:class "edit" :title title
                      :on-save #(save id %)
                      :on-stop #(reset! editing false)}])])))

(defn todo-list [showing todos]
  [:ul.todo-list
