;; =============================================================================
;; Conimo Open Sunsama — Reactive WASM Frontend
;; Replicates https://opensunsama.com/ (Board, Tasks, Calendar, Focus, Ideas,
;; Routines, AI/MCP Connector Hub, Task Detail Modal, and ⌘K Command Palette)
;; =============================================================================

(require "libs/dom/src/dom.coni" :as dom)
(require "libs/str/src/str.coni" :as str)
(require "libs/conimo/src/client.coni" :as client)

;; ── Dynamic Calendar & Date Computation ────────────────────────────────────

(defn leap-year? [y]
  (and (= (mod y 4) 0)
       (or (not= (mod y 100) 0)
           (= (mod y 400) 0))))

(defn days-in-month [y m]
  (cond
    (= m 2) (if (leap-year? y) 29 28)
    (or (= m 4) (= m 6) (= m 9) (= m 11)) 30
    :else 31))

(defn step-day [y m d delta]
  (if (= delta 0)
    {:year y :month m :day d}
    (if (> delta 0)
      (let [dim (days-in-month y m)
            nd (+ d 1)]
        (if (> nd dim)
          (if (= m 12)
            (step-day (+ y 1) 1 1 (- delta 1))
            (step-day y (+ m 1) 1 (- delta 1)))
          (step-day y m nd (- delta 1))))
      (let [nd (- d 1)]
        (if (< nd 1)
          (if (= m 1)
            (step-day (- y 1) 12 31 (+ delta 1))
            (let [pm (- m 1)]
              (step-day y pm (days-in-month y pm) (+ delta 1))))
          (step-day y m nd (+ delta 1)))))))

(def weekday-names ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"])
(def weekday-shorts ["Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"])
(def month-shorts ["" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"])

(defn pad2 [n]
  (if (< n 10) (str "0" n) (str n)))

(defn compute-days []
  (let [tp (try (sys-time-parts) (catch _ {:year 2026 :month 11 :day 9 :weekday 1}))
        by (or (:year tp) 2026)
        bm (or (:month tp) 11)
        bd (or (:day tp) 9)
        bw (or (:weekday tp) 1)
        offsets [-1 0 1 2 3 4]]
    (into []
      (map (fn [off]
             (let [dt (step-day by bm bd off)
                   y (:year dt)
                   m (:month dt)
                   d (:day dt)
                   w (mod (+ bw off 70) 7)
                   dname (nth weekday-names w)
                   dshort (nth weekday-shorts w)
                   mshort (nth month-shorts m)
                   month-day (str mshort " " d)
                   short-str (str dshort ", " month-day)
                   iso-date (str y "-" (pad2 m) "-" (pad2 d))
                   label (cond
                           (= off -1) "Yesterday"
                           (= off 0)  "Today"
                           (= off 1)  "Tomorrow"
                           :else short-str)]
               {:offset off
                :date iso-date
                :day-name dname
                :day-short dshort
                :month-day month-day
                :short short-str
                :label label}))
           offsets))))

(defn get-day-info [days offset]
  (let [ds (if (and days (> (count days) 0)) days (compute-days))]
    (or (first (filter #(= (:offset %) offset) ds))
        (first (filter #(= (:offset %) offset) (compute-days))))))

;; ── Reactive Application State ─────────────────────────────────────────────

(def *state*
  (atom {:theme "light"
         :color-theme "default"
         :profile {:name "Alex Rivera"
                   :email "alex@opensunsama.com"
                   :role "Head of Product"
                   :timezone "Asia/Tokyo"
                   :work-start-hour 8
                   :work-end-hour 18
                   :api-key "os_live_9f8a7b6c5d4e3f2a1b0c"
                   :mcp-url "https://sunsama.coni-lang.org/api/mcp"}
         :days (compute-days)
         :tasks []
         :time-blocks []
         :idea-boards []
         :routines []
         :calendars []
         :mcp-clients []
         :mcp-logs []
         :mcp-tools []
         :metrics {:today-planned-mins 0
                   :today-actual-mins 0
                   :today-done-count 0
                   :today-total-count 0}}))

;; Active Tab: "board" | "tasks" | "calendar" | "focus" | "ideas" | "routines" | "mcp"
(def *active-tab* (atom "board"))

;; UI & Modal State
(def *show-backlog* (atom true))
(def *selected-schedule-day* (atom 0))
(def *selected-task-id* (atom nil))
(def *cmd-k-open* (atom false))
(def *cmd-k-query* (atom ""))
(def *shortcuts-open* (atom false))
(def *toast-msg* (atom nil))

;; Quick-add & Filter Inputs
(def *quick-add-day* (atom {}))
(def *new-task-title* (atom ""))
(def *new-task-channel* (atom ""))
(def *new-task-prio* (atom "P1"))
(def *new-task-mins* (atom "45"))
(def *new-task-day* (atom "0"))
(def *new-subtask-title* (atom ""))
(def *edit-notes-text* (atom ""))
(def *edit-channel-text* (atom ""))
(def *edit-modal-title* (atom ""))
(def *edit-modal-mins* (atom ""))
(def *editing-task-id* (atom nil))
(def *editing-task-title* (atom ""))
(def *editing-prio-task-id* (atom nil))
(def *editing-time-task-id* (atom nil))
(def *editing-time-mins* (atom ""))
(def *editing-block-task-id* (atom nil))
(def *editing-block-start* (atom "10:00"))
(def *editing-block-end* (atom "11:00"))

;; Tasks Tab Filters
(def *tasks-status-filter* (atom "all")) ;; "all" | "active" | "completed"
(def *tasks-prio-filter* (atom "all"))   ;; "all" | "P0" | "P1" | "P2" | "P3"

;; Calendar Quick Block Inputs
(def *block-title* (atom ""))
(def *block-day* (atom 0))
(def *block-start* (atom "10:00"))
(def *block-end* (atom "11:00"))
(def *block-color* (atom "#EF4444"))

;; Focus Mode Timer State
(def *focus-task-id* (atom nil))
(def *focus-running* (atom false))
(def *focus-elapsed-secs* (atom 0))

;; Ideas Board State
(def *active-board-id* (atom "ib-product"))
(def *new-idea-title* (atom ""))
(def *new-idea-col* (atom "col-someday"))
(def *new-idea-prio* (atom "P1"))

;; Routines Input State
(def *new-routine-title* (atom ""))
(def *new-routine-sched* (atom "Weekdays • 09:00"))

;; AI / MCP Playground Input State
(def *ai-custom-prompt* (atom ""))
(def *mcp-selected-tool* (atom "get_schedule_for_day"))
(def *mcp-last-output* (atom nil))

(declare render-ui)

;; ── Helpers & API Communication ────────────────────────────────────────────

(defn fmt-duration [mins]
  (let [m (or mins 0)]
    (cond
      (<= m 0) "0m"
      (< m 60) (str m "m")
      (= (mod m 60) 0) (str (int (/ m 60)) "h")
      :else (str (int (/ m 60)) "h " (mod m 60) "m"))))

(defn fmt-clock [secs]
  (let [s (max 0 (or secs 0))
        m (int (/ s 60))
        rem-s (mod s 60)
        m-str (if (< m 10) (str "0" m) (str m))
        s-str (if (< rem-s 10) (str "0" rem-s) (str rem-s))]
    (str m-str ":" s-str)))

(defn day-label [days offset]
  (if (nil? offset)
    "Backlog"
    (let [found (first (filter #(= (:offset %) offset) days))]
      (if found
        (str (:label found) " (" (:short found) ")")
        (cond
          (= offset -1) "Yesterday"
          (= offset 0)  "Today"
          (= offset 1)  "Tomorrow"
          :else (str "Day +" offset))))))

(defn show-toast! [msg]
  (reset! *toast-msg* msg)
  (render-ui)
  (let [win (try (js/global "window") (catch _ nil))]
    (when win
      (js/call win "setTimeout"
        (fn []
          (reset! *toast-msg* nil)
          (render-ui))
        2500))))

(defn apply-state! [res & [toast-text]]
  (when (and res (:state res))
    (reset! *state* (:state res))
    (when (or toast-text (:message res))
      (reset! *toast-msg* (or toast-text (:message res)))
      (let [win (try (js/global "window") (catch _ nil))]
        (when win
          (js/call win "setTimeout"
            (fn []
              (reset! *toast-msg* nil)
              (render-ui))
            2400))))
    (render-ui)))

(defn load-state! []
  (client/fetch-edn "/api/state"
    (fn [res]
      (apply-state! res))))

(defn post-action! [url payload & [toast-text]]
  (client/post-edn url payload
    (fn [res]
      (apply-state! res toast-text))))

(defn open-task-modal! [task]
  (reset! *selected-task-id* (:id task))
  (reset! *edit-modal-title* (or (:title task) ""))
  (reset! *edit-modal-mins* (str (or (:estimated-mins task) 30)))
  (reset! *edit-notes-text* (or (:notes task) ""))
  (reset! *edit-channel-text* (or (:channel task) ""))
  (reset! *new-subtask-title* "")
  (render-ui))

(defn start-inline-edit! [task]
  (reset! *editing-task-id* (:id task))
  (reset! *editing-task-title* (or (:title task) ""))
  (reset! *editing-prio-task-id* nil)
  (reset! *editing-time-task-id* nil)
  (reset! *editing-block-task-id* nil)
  (render-ui))

(defn save-inline-title! [tid]
  (let [new-title (str/trim (str (deref *editing-task-title*)))]
    (reset! *editing-task-id* nil)
    (if (> (count new-title) 0)
      (post-action! "/api/task/update" {:id tid :title new-title} "Updated task title ✓")
      (render-ui))))

(defn save-inline-time! [tid mins-val]
  (let [m (or (sys-try-parse-number (str/trim (str mins-val))) 0)]
    (reset! *editing-time-task-id* nil)
    (if (> m 0)
      (post-action! "/api/task/update" {:id tid :estimated-mins m}
        (str "Updated time to " (fmt-duration m) " ✓"))
      (render-ui))))

(defn save-inline-block! [bid start-str end-str]
  (let [s (str/trim (str start-str))
        e (str/trim (str end-str))]
    (reset! *editing-block-task-id* nil)
    (if (and (> (count s) 0) (> (count e) 0))
      (post-action! "/api/block/update" {:id bid :start s :end e}
        (str "Updated block time to " s "–" e " ✓"))
      (render-ui))))

(defn enter-focus-mode! [task-id]
  (let [tasks (or (:tasks (deref *state*)) [])
        t (first (filter #(= (:id %) task-id) tasks))
        tracked-mins (if t (or (:actual-mins t) 0) 0)]
    (reset! *focus-task-id* task-id)
    (reset! *focus-elapsed-secs* (* (max tracked-mins 0) 60))
    (reset! *focus-running* false)
    (reset! *selected-task-id* nil)
    (reset! *active-tab* "focus")
    (render-ui)))

;; ── Top Chrome Header ──────────────────────────────────────────────────────

(defn render-header [st]
  (let [tab (deref *active-tab*)
        theme (or (:theme st) "light")
        tasks (or (:tasks st) [])
        active-today (count (filter #(and (= (:day %) 0) (not (:done %))) tasks))
        mcp-count (count (or (:mcp-tools st) []))]
    [:header {:class "sunsama-header"}
      [:div {:class "header-left"}
        [:div {:class "brand-logo"
               :on-click (fn [_]
                           (reset! *active-tab* "board")
                           (render-ui))}
          [:span {:class "brand-orb"} "☀️"]
          [:span {} "Open Sunsama"]]

        [:nav {:class "nav-pills"}
          [:button {:class (str "nav-pill" (if (= tab "board") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "board") (render-ui))}
            [:span {} "▦"]
            [:span {} "Board"]
            [:span {:class "nav-badge"} (str active-today)]]

          [:button {:class (str "nav-pill" (if (= tab "tasks") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "tasks") (render-ui))}
            [:span {} "☰"]
            [:span {} "Tasks"]]

          [:button {:class (str "nav-pill" (if (= tab "calendar") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "calendar") (render-ui))}
            [:span {} "🗓️"]
            [:span {} "Calendar"]]

          [:button {:class (str "nav-pill" (if (= tab "focus") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "focus") (render-ui))}
            [:span {} "🎯"]
            [:span {} "Focus"]]

          [:button {:class (str "nav-pill" (if (= tab "ideas") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "ideas") (render-ui))}
            [:span {} "💡"]
            [:span {} "Ideas"]]

          [:button {:class (str "nav-pill" (if (= tab "routines") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "routines") (render-ui))}
            [:span {} "🔁"]
            [:span {} "Routines"]]

          [:button {:class (str "nav-pill" (if (= tab "mcp") " active" ""))
                    :on-click (fn [_] (reset! *active-tab* "mcp") (render-ui))}
            [:span {} "🔌"]
            [:span {} "AI & MCP"]
            [:span {:class "nav-badge"} (str (if (> mcp-count 0) mcp-count 24))]]]]

      [:div {:class "header-right"}
        [:button {:class "cmd-k-trigger"
                  :on-click (fn [_]
                              (reset! *cmd-k-open* true)
                              (reset! *cmd-k-query* "")
                              (render-ui))}
          [:span {} "🔍 Search tasks, ideas, tools..."]
          [:span {:class "kbd-chip"} "⌘K"]]

        [:button {:class (str "chrome-icon-btn" (if (deref *show-backlog*) " active" ""))
                  :title "Toggle Backlog Rail"
                  :on-click (fn [_]
                              (swap! *show-backlog* not)
                              (render-ui))}
          "📥 Backlog"]

        [:button {:class "chrome-icon-btn"
                  :title "Keyboard Shortcuts (?)"
                  :on-click (fn [_]
                              (swap! *shortcuts-open* not)
                              (render-ui))}
          "⌨️ ?"]

        [:button {:class "chrome-icon-btn"
                  :title "Toggle Light / Dark Theme"
                  :on-click (fn [_]
                              (post-action! "/api/theme" {}
                                (if (= theme "dark") "Switched to Light Mode ☀️" "Switched to Dark Mode 🌙")))}
          (if (= theme "dark") "☀️ Light" "🌙 Dark")]

        [:button {:class "avatar-chip"
                  :title "Alex Rivera • Head of Product (Settings & MCP)"
                  :on-click (fn [_]
                              (reset! *active-tab* "mcp")
                              (render-ui))}
          "AR"]]]))

;; ── Reusable Task Card Component ───────────────────────────────────────────

(defn render-task-card [t blocks]
  (let [tid (:id t)
        done? (:done t)
        prio (or (:priority t) "P2")
        subs (or (:subtasks t) [])
        sub-total (count subs)
        sub-done (count (filter :done subs))
        est (or (:estimated-mins t) 0)
        act (or (:actual-mins t) 0)
        linked-block (first (filter #(= (:task-id %) tid) blocks))]
    [:div {:class (str "task-card" (if done? " done" ""))}
      [:div {:class "task-card-top"}
        [:button {:class (str "task-check-btn" (if done? " checked" ""))
                  :title (if done? "Mark incomplete" "Complete task")
                  :on-click (fn [_]
                              (post-action! "/api/task/toggle" {:id tid}
                                (if done? "Task reopened" "Completed task ✓")))}
          (if done? "✓" "")]
        (if (= (deref *editing-task-id*) tid)
          [:div {:style "display:flex;align-items:center;gap:4px;flex:1;"}
            [:input {:class "quick-add-input"
                     :style "flex:1;height:26px;padding:2px 6px;font-size:13px;font-weight:600;"
                     :value (deref *editing-task-title*)
                     :on-input (fn [e]
                                 (reset! *editing-task-title* (js/get (js/get e "target") "value")))
                     :on-keydown (fn [e]
                                   (let [k (js/get e "key")]
                                     (cond
                                       (= k "Enter")  (save-inline-title! tid)
                                       (= k "Escape") (do (reset! *editing-task-id* nil) (render-ui))
                                       :else nil)))}]
            [:button {:class "mini-action-btn"
                      :style "color:var(--primary);font-weight:700;"
                      :title "Save title (Enter)"
                      :on-click (fn [_] (save-inline-title! tid))}
              "✓"]
            [:button {:class "mini-action-btn"
                      :title "Cancel (Esc)"
                      :on-click (fn [_]
                                  (reset! *editing-task-id* nil)
                                  (render-ui))}
              "✕"]]
          [:div {:style "display:flex;align-items:flex-start;justify-content:space-between;gap:4px;flex:1;min-width:0;"}
            [:div {:class "task-title-text"
                   :title "Click to open task details"
                   :on-click (fn [_] (open-task-modal! t))}
              (:title t)]
            [:button {:class "inline-edit-icon-btn"
                      :title "Edit title inline"
                      :on-click (fn [_] (start-inline-edit! t))}
              "✎"]])]

      [:div {:class "task-meta-row"}
        [:div {:class "task-badges"}
          (if (= (deref *editing-prio-task-id*) tid)
            [:div {:class "inline-picker-group"}
              (into [:div {:style "display:contents;"}]
                (map (fn [p]
                       [:button {:class (str "prio-badge prio-" p " prio-clickable" (if (= prio p) " active-choice" ""))
                                 :title (str "Set priority to " p)
                                 :on-click (fn [_]
                                             (reset! *editing-prio-task-id* nil)
                                             (if (= p prio)
                                               (render-ui)
                                               (post-action! "/api/task/update" {:id tid :priority p}
                                                 (str "Updated priority to " p " ✓"))))}
                         p])
                     ["P0" "P1" "P2" "P3"]))]
            [:button {:class (str "prio-badge prio-" prio " prio-clickable")
                      :title "Click to change priority (P0–P3)"
                      :on-click (fn [_]
                                  (reset! *editing-prio-task-id* tid)
                                  (reset! *editing-time-task-id* nil)
                                  (reset! *editing-block-task-id* nil)
                                  (render-ui))}
              prio])
          (when (and (:channel t) (not= (str/trim (str (:channel t))) ""))
            [:span {:class "channel-tag"
                    :style "cursor:pointer;"
                    :title "Click to edit tag"
                    :on-click (fn [_] (open-task-modal! t))}
              (:channel t)])
          (when (> sub-total 0)
            [:span {:class "subtask-pill"
                    :style "cursor:pointer;"
                    :title "Click to view subtasks"
                    :on-click (fn [_] (open-task-modal! t))}
              (str "☑ " sub-done "/" sub-total)])
          (when linked-block
            [:button {:class "subtask-pill prio-clickable"
                      :style "color:var(--primary);border:none;"
                      :title "Click to change scheduled block time"
                      :on-click (fn [_]
                                  (if (= (deref *editing-block-task-id*) tid)
                                    (reset! *editing-block-task-id* nil)
                                    (do
                                      (reset! *editing-block-task-id* tid)
                                      (reset! *editing-block-start* (or (:start linked-block) "10:00"))
                                      (reset! *editing-block-end* (or (:end linked-block) "11:00"))
                                      (reset! *editing-prio-task-id* nil)
                                      (reset! *editing-time-task-id* nil)))
                                  (render-ui))}
              (str "🗓️ " (:start linked-block))])]

        [:button {:class (str "estimate-pill estimate-clickable" (if (> act 0) " tracked" ""))
                  :title "Click to change estimated time"
                  :on-click (fn [_]
                              (if (= (deref *editing-time-task-id*) tid)
                                (reset! *editing-time-task-id* nil)
                                (do
                                  (reset! *editing-time-task-id* tid)
                                  (reset! *editing-time-mins* (str (if (> est 0) est 30)))
                                  (reset! *editing-prio-task-id* nil)
                                  (reset! *editing-block-task-id* nil)))
                              (render-ui))}
          (if (> act 0)
            (str (fmt-duration act) " / " (fmt-duration est))
            (str "⏱ " (fmt-duration est)))]]

      (when (= (deref *editing-time-task-id*) tid)
        [:div {:class "inline-card-popover"}
          [:div {:style "display:flex;align-items:center;gap:3px;flex-wrap:wrap;"}
            (into [:div {:style "display:contents;"}]
              (map (fn [m]
                     [:button {:class (str "mini-action-btn" (if (= est m) " active-mini" ""))
                               :on-click (fn [_] (save-inline-time! tid m))}
                       (fmt-duration m)])
                   [15 30 45 60 90 120]))]
          [:div {:style "display:flex;align-items:center;gap:4px;margin-top:4px;"}
            [:input {:class "quick-add-input"
                     :style "width:54px;height:22px;padding:0 5px;font-size:11px;"
                     :placeholder "Mins"
                     :value (deref *editing-time-mins*)
                     :on-input (fn [e] (reset! *editing-time-mins* (js/get (js/get e "target") "value")))
                     :on-keydown (fn [e]
                                   (let [k (js/get e "key")]
                                     (cond
                                       (= k "Enter")  (save-inline-time! tid (deref *editing-time-mins*))
                                       (= k "Escape") (do (reset! *editing-time-task-id* nil) (render-ui))
                                       :else nil)))}]
            [:span {:style "font-size:10.5px;color:var(--muted-foreground);"} "min"]
            [:button {:class "mini-action-btn"
                      :style "color:var(--primary);font-weight:700;"
                      :on-click (fn [_] (save-inline-time! tid (deref *editing-time-mins*)))}
              "✓"]
            [:button {:class "mini-action-btn"
                      :on-click (fn [_] (reset! *editing-time-task-id* nil) (render-ui))}
              "✕"]]])

      (when (and linked-block (= (deref *editing-block-task-id*) tid))
        [:div {:class "inline-card-popover"}
          [:div {:style "display:flex;align-items:center;gap:4px;"}
            [:span {:style "font-size:10.5px;color:var(--muted-foreground);"} "Block:"]
            [:input {:class "quick-add-input"
                     :style "width:54px;height:22px;padding:0 5px;font-size:11px;"
                     :value (deref *editing-block-start*)
                     :on-input (fn [e] (reset! *editing-block-start* (js/get (js/get e "target") "value")))}]
            [:span {:style "font-size:10.5px;color:var(--muted-foreground);"} "–"]
            [:input {:class "quick-add-input"
                     :style "width:54px;height:22px;padding:0 5px;font-size:11px;"
                     :value (deref *editing-block-end*)
                     :on-input (fn [e] (reset! *editing-block-end* (js/get (js/get e "target") "value")))}]
            [:button {:class "mini-action-btn"
                      :style "color:var(--primary);font-weight:700;"
                      :on-click (fn [_]
                                  (save-inline-block! (:id linked-block)
                                    (deref *editing-block-start*)
                                    (deref *editing-block-end*)))}
              "✓"]
            [:button {:class "mini-action-btn"
                      :on-click (fn [_] (reset! *editing-block-task-id* nil) (render-ui))}
              "✕"]]])

      [:div {:class "task-quick-actions"}
        [:div {:style "display:flex;gap:4px;"}
          [:button {:class "mini-action-btn"
                    :title "Focus on this task"
                    :on-click (fn [_] (enter-focus-mode! tid))}
            "▶ Focus"]
          (when (not linked-block)
            [:button {:class "mini-action-btn"
                      :title "Time-block onto calendar"
                      :on-click (fn [_]
                                  (post-action! "/api/block/add"
                                    {:task-id tid
                                     :day (or (:day t) 0)
                                     :start "10:00"
                                     :end "11:00"}
                                    (str "Time-blocked '" (:title t) "' at 10:00")))}
              "+ Block"])]

        [:div {:style "display:flex;gap:4px;"}
          (when (not= (:day t) 0)
            [:button {:class "mini-action-btn"
                      :on-click (fn [_]
                                  (post-action! "/api/task/schedule" {:id tid :day 0} "Moved to Today"))}
              "→ Today"])
          (when (= (:day t) 0)
            [:button {:class "mini-action-btn"
                      :on-click (fn [_]
                                  (post-action! "/api/task/schedule" {:id tid :day 1} "Moved to Tomorrow"))}
              "→ Tmrw"])
          [:button {:class "mini-action-btn"
                    :on-click (fn [_] (open-task-modal! t))}
            "⋯"]]]]))

;; ── 1. BOARD VIEW (Kanban of Days + Time-Blocked Schedule + Backlog Rail) ──

(defn render-board-view [st]
  (let [days (or (:days st) (compute-days))
        today-d (get-day-info days 0)
        today-heading (if today-d
                        (str "🗓️ " (:day-name today-d) ", " (or (:month-day today-d) (:short today-d)))
                        "🗓️ Today")
        prof-name (or (:name (:profile st)) "Alex Rivera")
        board-days (filter #(and (>= (:offset %) 0) (<= (:offset %) 3)) days)
        tasks (or (:tasks st) [])
        blocks (or (:time-blocks st) [])
        metrics (or (:metrics st) {})
        planned-mins (or (:today-planned-mins metrics) 0)
        actual-mins (or (:today-actual-mins metrics) 0)
        done-cnt (or (:today-done-count metrics) 0)
        total-cnt (or (:today-total-count metrics) 0)
        pct (if (<= planned-mins 0) 0 (min 100 (int (* 100 (/ planned-mins 360)))))
        sched-day (deref *selected-schedule-day*)
        sched-blocks (filter #(= (:day %) sched-day) blocks)
        backlog-tasks (filter #(nil? (:day %)) tasks)
        show-backlog? (deref *show-backlog*)]
    [:div {:style "display:flex;flex-direction:column;flex:1;min-height:0;"}
      ;; Top Planner Subbar
      [:div {:class "planner-subbar"}
        [:div {:class "subbar-left"}
          [:div {:class "subbar-title"}
            [:span {} today-heading]
            [:span {:style "font-size:12px;color:var(--muted-foreground);font-weight:400;"}
              (str "• " prof-name "'s Daily Planning Board")]]

          [:div {:class "workload-pill"}
            [:span {} (str "Today's Workload: " (fmt-duration planned-mins) " planned • " (fmt-duration actual-mins) " focused")]
            [:div {:class "workload-bar-track"}
              [:div {:class "workload-bar-fill" :style (str "width:" pct "%;")}]]
            [:span {:style "font-weight:600;color:var(--foreground);"}
              (str done-cnt "/" total-cnt " done")]]]

        [:div {:class "subbar-actions"}
          [:button {:class "btn btn-ai"
                    :on-click (fn [_]
                                (post-action! "/api/ai/prompt" {:preset "triage-today"}))}
            "🤖 AI Triage: Keep P0/P1 Today"]
          [:button {:class "btn btn-ai"
                    :on-click (fn [_]
                                (post-action! "/api/ai/prompt" {:preset "block-deep-work"}))}
            "⚡ AI Block 9–11am Deep Work"]
          [:button {:class "btn"
                    :on-click (fn [_]
                                (post-action! "/api/task/rollover" {} "Rolled over unfinished tasks ✓"))}
            "↪ Rollover Unfinished"]
          (when (> (count tasks) 0)
            [:button {:class "btn"
                      :on-click (fn [_]
                                  (post-action! "/api/task/clear" {} "Cleared all tasks ✓"))}
              "🗑️ Clear All"])]]

      ;; Main 2- or 3-Column Workspace
      [:div {:class (str "board-workspace" (if show-backlog? " with-backlog" ""))}
        ;; Left/Center: 4 Day Columns (Today, Tomorrow, Mon, Tue)
        [:div {:class "day-columns-strip"}
          (into [:div {:style "display:contents;"}]
            (map (fn [d]
                   (let [off (:offset d)
                         today? (= off 0)
                         day-tasks (filter #(= (:day %) off) tasks)
                         col-mins (reduce (fn [acc t] (+ acc (or (:estimated-mins t) 0))) 0 day-tasks)
                         draft-val (get (deref *quick-add-day*) off "")]
                     [:div {:class (str "day-column" (if today? " today-col" ""))}
                       [:div {:class "day-col-header"}
                         [:div {}
                           [:div {:class "day-col-title"}
                             (when today? [:span {:class "today-dot"}])
                             [:span {} (:label d)]]
                           [:div {:class "day-col-sub"} (:short d)]]
                         [:span {:class "day-col-estimate"} (fmt-duration col-mins)]]

                       ;; Quick Add Input for this Day Column
                       [:div {:class "quick-add-box"}
                         [:input {:class "quick-add-input"
                                  :placeholder (str "+ Add to " (:label d) " (use #tag)...")
                                  :value draft-val
                                  :on-input (fn [e]
                                              (let [v (js/get (js/get e "target") "value")]
                                                (swap! *quick-add-day* assoc off v)))}]
                         [:button {:class "btn btn-sm btn-primary"
                                   :on-click (fn [_]
                                               (let [txt (str/trim (str (get (deref *quick-add-day*) off "")))]
                                                 (when (> (count txt) 0)
                                                   (swap! *quick-add-day* assoc off "")
                                                   (post-action! "/api/task/add"
                                                     {:title txt :day off :priority (if today? "P1" "P2") :estimated-mins 30}
                                                     (str "Added task to " (:label d))))))}
                           "+"]]

                       ;; Task Cards Stack
                       (into [:div {:style "display:flex;flex-direction:column;gap:8px;"}]
                         (map (fn [t] (render-task-card t blocks)) day-tasks))]))
                 board-days))]

        ;; Right Rail 1: Time-Blocked Schedule for Selected Day
        [:aside {:class "schedule-rail"}
          [:div {:class "rail-header"}
            [:div {:class "rail-title"}
              [:span {} "🕒 Time-Blocked Schedule"]]
            [:div {:style "display:flex;gap:4px;"}
              [:button {:class (str "btn btn-sm" (if (= sched-day 0) " btn-primary" ""))
                        :on-click (fn [_] (reset! *selected-schedule-day* 0) (render-ui))}
                "Today"]
              [:button {:class (str "btn btn-sm" (if (= sched-day 1) " btn-primary" ""))
                        :on-click (fn [_] (reset! *selected-schedule-day* 1) (render-ui))}
                "Tmrw"]]]

          [:div {:class "rail-body"}
            [:div {:style "font-size:11px;color:var(--muted-foreground);margin-bottom:4px;display:flex;justify-content:space-between;"}
              [:span {} "08:00 – 18:00 Workday"]
              [:span {:style "color:var(--primary);font-weight:600;cursor:pointer;"
                      :on-click (fn [_] (reset! *active-tab* "calendar") (render-ui))}
                "Full Week →"]]

            (into [:div {:style "display:flex;flex-direction:column;gap:7px;"}]
              (map (fn [b]
                     [:div {:class "time-block-item"
                            :style (str "border-left-color:" (or (:color b) "#F97316") ";")}
                       [:div {:style "flex:1;"}
                         [:div {:class "tb-time"} (str (:start b) " – " (:end b))]
                         [:div {:class "tb-title"} (:title b)]
                         (when (:task-id b)
                           [:div {:style "font-size:10.5px;color:var(--primary);margin-top:2px;cursor:pointer;"
                                  :on-click (fn [_]
                                              (let [lt (first (filter #(= (:id %) (:task-id b)) tasks))]
                                                (when lt (open-task-modal! lt))))}
                             "🔗 Linked to task"])]
                       [:div {:style "display:flex;flex-direction:column;align-items:flex-end;gap:4px;"}
                         [:span {:class "tb-source-badge"}
                           (if (= (:source b) "gcal") "📅 GCal" "⚡ Block")]
                         [:button {:class "mini-action-btn"
                                   :on-click (fn [_]
                                               (post-action! "/api/block/delete" {:id (:id b)} "Removed time block"))}
                           "×"]]])
                   sched-blocks))]]

        ;; Right Rail 2 (Optional): Backlog Rail ("The backlog waits one click away in the right rail")
        (when show-backlog?
          [:aside {:class "schedule-rail"}
            [:div {:class "rail-header"}
              [:div {:class "rail-title"}
                [:span {} "📥 Backlog & Later"]
                [:span {:class "nav-badge"} (str (count backlog-tasks))]]
              [:button {:class "btn btn-sm"
                        :on-click (fn [_]
                                    (swap! *show-backlog* not)
                                    (render-ui))}
                "Hide"]]

            [:div {:class "rail-body"}
              [:div {:class "quick-add-box"}
                [:input {:class "quick-add-input"
                         :placeholder "+ Add to backlog..."
                         :value (get (deref *quick-add-day*) "backlog" "")
                         :on-input (fn [e]
                                     (let [v (js/get (js/get e "target") "value")]
                                       (swap! *quick-add-day* assoc "backlog" v)))}]
                [:button {:class "btn btn-sm btn-primary"
                          :on-click (fn [_]
                                      (let [txt (str/trim (str (get (deref *quick-add-day*) "backlog" "")))]
                                        (when (> (count txt) 0)
                                          (swap! *quick-add-day* assoc "backlog" "")
                                          (post-action! "/api/task/add"
                                            {:title txt :day nil :priority "P2" :estimated-mins 45}
                                            "Added to Backlog"))))}
                  "+"]]

              (into [:div {:style "display:flex;flex-direction:column;gap:8px;"}]
                (map (fn [t] (render-task-card t blocks)) backlog-tasks))]])]]))

;; ── 2. TASKS VIEW ("Every task, one list") ─────────────────────────────────

(defn render-tasks-view [st]
  (let [tasks (or (:tasks st) [])
        days (or (:days st) (compute-days))
        blocks (or (:time-blocks st) [])
        s-filt (deref *tasks-status-filter*)
        p-filt (deref *tasks-prio-filter*)
        filtered (filter (fn [t]
                           (and (cond
                                  (= s-filt "active") (not (:done t))
                                  (= s-filt "completed") (:done t)
                                  :else true)
                                (if (= p-filt "all")
                                  true
                                  (= (:priority t) p-filt))))
                         tasks)
        d0 (get-day-info days 0)
        d1 (get-day-info days 1)
        d2 (get-day-info days 2)
        d3 (get-day-info days 3)
        d4 (get-day-info days 4)
        dm1 (get-day-info days -1)
        fmt-full (fn [d] (if d (str (:day-name d) ", " (or (:month-day d) (:short d))) ""))
        groups [{:day 0   :title (str "☀️ Today — " (fmt-full d0))}
                {:day 1   :title (str "🌅 Tomorrow — " (fmt-full d1))}
                {:day 2   :title (str "🗓️ " (fmt-full d2))}
                {:day 3   :title (str "🗓️ " (fmt-full d3))}
                {:day 4   :title (str "🗓️ " (fmt-full d4))}
                {:day -1  :title (str "⏮️ Yesterday — " (fmt-full dm1))}
                {:day nil :title "📥 Backlog (Unscheduled)"}]]
    [:div {:style "display:flex;flex-direction:column;flex:1;"}
      [:div {:class "planner-subbar"}
        [:div {:class "subbar-left"}
          [:div {:class "subbar-title"} "☰ Every Task, One List"]
          [:div {:style "display:flex;gap:4px;"}
            [:button {:class (str "btn btn-sm" (if (= s-filt "all") " btn-primary" ""))
                      :on-click (fn [_] (reset! *tasks-status-filter* "all") (render-ui))}
              (str "All (" (count tasks) ")")]
            [:button {:class (str "btn btn-sm" (if (= s-filt "active") " btn-primary" ""))
                      :on-click (fn [_] (reset! *tasks-status-filter* "active") (render-ui))}
              "Active"]
            [:button {:class (str "btn btn-sm" (if (= s-filt "completed") " btn-primary" ""))
                      :on-click (fn [_] (reset! *tasks-status-filter* "completed") (render-ui))}
              "Completed"]]

          [:div {:style "display:flex;gap:4px;"}
            (into [:div {:style "display:contents;"}]
              (map (fn [p]
                     [:button {:class (str "btn btn-sm" (if (= p-filt p) " btn-primary" ""))
                               :on-click (fn [_] (reset! *tasks-prio-filter* p) (render-ui))}
                       (if (= p "all") "All Priorities" p)])
                   ["all" "P0" "P1" "P2" "P3"]))]]

        ;; Quick Add Task Form
        [:div {:class "subbar-actions"}
          [:input {:class "input-field"
                   :placeholder "Task title (or #tag)..."
                   :value (deref *new-task-title*)
                   :on-input (fn [e] (reset! *new-task-title* (js/get (js/get e "target") "value")))}]
          [:input {:class "input-field"
                   :style "width:96px;"
                   :placeholder "#tag (opt)"
                   :value (deref *new-task-channel*)
                   :on-input (fn [e] (reset! *new-task-channel* (js/get (js/get e "target") "value")))}]
          [:select {:class "select-field"
                    :value (deref *new-task-prio*)
                    :on-change (fn [e] (reset! *new-task-prio* (js/get (js/get e "target") "value")))}
            [:option {:value "P0"} "P0 Urgent"]
            [:option {:value "P1"} "P1 High"]
            [:option {:value "P2"} "P2 Medium"]
            [:option {:value "P3"} "P3 Low"]]
          [:input {:class "input-field"
                   :style "width:70px;"
                   :placeholder "Mins"
                   :value (deref *new-task-mins*)
                   :on-input (fn [e] (reset! *new-task-mins* (js/get (js/get e "target") "value")))}]
          [:button {:class "btn btn-primary"
                    :on-click (fn [_]
                                (let [title (str/trim (deref *new-task-title*))
                                      chan (str/trim (deref *new-task-channel*))]
                                  (when (> (count title) 0)
                                    (reset! *new-task-title* "")
                                    (reset! *new-task-channel* "")
                                    (post-action! "/api/task/add"
                                      {:title title
                                       :channel (if (> (count chan) 0) chan nil)
                                       :priority (deref *new-task-prio*)
                                       :estimated-mins (or (sys-try-parse-number (deref *new-task-mins*)) 30)
                                       :day 0}
                                      "Created task on Today's board"))))}
            "+ Add Task"]]]

      [:div {:style "padding:18px;max-width:980px;width:100%;margin:0 auto;display:flex;flex-direction:column;gap:20px;"}
        (into [:div {:style "display:contents;"}]
          (map (fn [g]
                 (let [g-tasks (filter #(= (:day %) (:day g)) filtered)
                       g-mins (reduce (fn [acc t] (+ acc (or (:estimated-mins t) 0))) 0 g-tasks)]
                   (when (> (count g-tasks) 0)
                     [:div {:style "background:var(--surface);border-radius:12px;padding:14px 16px;box-shadow:var(--shadow-card);"}
                       [:div {:style "display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid var(--border);"}
                         [:div {:style "font-size:13.5px;font-weight:700;"} (:title g)]
                         [:span {:class "day-col-estimate"} (str (count g-tasks) " tasks • " (fmt-duration g-mins))]]
                       (into [:div {:style "display:grid;grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:10px;"}]
                         (map (fn [t] (render-task-card t blocks)) g-tasks))])))
               groups))]]))

;; ── 3. CALENDAR VIEW ("Time-block your week") ──────────────────────────────

(defn render-calendar-view [st]
  (let [days (or (:days st) [])
        blocks (or (:time-blocks st) [])
        tasks (or (:tasks st) [])
        cals (or (:calendars st) [])]
    [:div {:style "display:flex;flex-direction:column;flex:1;"}
      [:div {:class "planner-subbar"}
        [:div {:class "subbar-left"}
          [:div {:class "subbar-title"} "🗓️ Week Time-Blocking Calendar"]
          (into [:div {:style "display:flex;gap:8px;align-items:center;"}]
            (map (fn [c]
                   [:span {:class "workload-pill"}
                     [:span {:style (str "width:8px;height:8px;border-radius:99px;background:" (:color c) ";display:inline-block;")}]
                     [:span {} (str (:provider c) " (" (:account c) ")")]])
                 (filter :synced cals)))]

        ;; Quick Add Time Block Bar
        [:div {:class "subbar-actions"}
          [:input {:class "input-field"
                   :placeholder "Block title (e.g. Deep work)..."
                   :value (deref *block-title*)
                   :on-input (fn [e] (reset! *block-title* (js/get (js/get e "target") "value")))}]
          [:select {:class "select-field"
                    :on-change (fn [e]
                                 (let [v (js/get (js/get e "target") "value")]
                                   (reset! *block-day* (or (sys-try-parse-number v) 0))))}
            (into [:optgroup {:label "Schedule Day"}]
              (map (fn [d]
                     (let [off (:offset d)
                           lbl (cond
                                 (= off 0) (str "Today (" (or (:day-short d) (:day-name d)) ")")
                                 (= off 1) (str "Tomorrow (" (or (:day-short d) (:day-name d)) ")")
                                 :else (:short d))]
                       [:option {:value (str off)} lbl]))
                   (filter #(>= (:offset %) 0) days)))]
          [:input {:class "input-field"
                   :style "width:68px;"
                   :value (deref *block-start*)
                   :on-input (fn [e] (reset! *block-start* (js/get (js/get e "target") "value")))}]
          [:input {:class "input-field"
                   :style "width:68px;"
                   :value (deref *block-end*)
                   :on-input (fn [e] (reset! *block-end* (js/get (js/get e "target") "value")))}]
          [:button {:class "btn btn-primary"
                    :on-click (fn [_]
                                (let [title (str/trim (deref *block-title*))]
                                  (when (> (count title) 0)
                                    (reset! *block-title* "")
                                    (post-action! "/api/block/add"
                                      {:title title
                                       :day (deref *block-day*)
                                       :start (deref *block-start*)
                                       :end (deref *block-end*)
                                       :color (deref *block-color*)}
                                      "Added time block to calendar"))))}
            "+ Add Time Block"]]]

      [:div {:class "week-calendar-grid"}
        (into [:div {:style "display:contents;"}]
          (map (fn [d]
                 (let [off (:offset d)
                       today? (= off 0)
                       day-blocks (filter #(= (:day %) off) blocks)
                       day-tasks (filter #(and (= (:day %) off) (not (:done %))) tasks)]
                   [:div {:class (str "cal-day-col" (if today? " today" ""))}
                     [:div {:class "cal-day-head"}
                       [:div {}
                         [:div {:style "font-size:12.5px;font-weight:700;"} (:label d)]
                         [:div {:style "font-size:11px;color:var(--muted-foreground);"} (:short d)]]
                       [:span {:class "day-col-estimate"} (str (count day-blocks) " blocks")]]

                     [:div {:class "cal-day-body"}
                       (into [:div {:style "display:flex;flex-direction:column;gap:7px;"}]
                         (map (fn [b]
                                [:div {:class "time-block-item"
                                       :style (str "border-left-color:" (or (:color b) "#F97316") ";")}
                                  [:div {:style "flex:1;"}
                                    [:div {:class "tb-time"} (str (:start b) " – " (:end b))]
                                    [:div {:class "tb-title"} (:title b)]
                                    (when (:task-id b)
                                      [:div {:style "font-size:10px;color:var(--primary);margin-top:2px;"}
                                        "🔗 Linked Task"])]
                                  [:button {:class "mini-action-btn"
                                            :on-click (fn [_]
                                                        (post-action! "/api/block/delete" {:id (:id b)} "Deleted block"))}
                                    "×"]])
                              day-blocks))

                       (when (> (count day-tasks) 0)
                         [:div {:style "margin-top:auto;padding-top:10px;border-top:1px dashed var(--border);"}
                           [:div {:style "font-size:10.5px;font-weight:600;color:var(--muted-foreground);margin-bottom:6px;"}
                             "Unblocked Tasks (1-click block):"]
                           (into [:div {:style "display:flex;flex-direction:column;gap:4px;"}]
                             (map (fn [t]
                                    [:button {:class "mini-action-btn"
                                              :style "text-align:left;width:100%;display:flex;justify-content:space-between;"
                                              :on-click (fn [_]
                                                          (post-action! "/api/block/add"
                                                            {:task-id (:id t)
                                                             :day off
                                                             :start "11:00"
                                                             :end "12:00"}
                                                            (str "Blocked '" (:title t) "'")))}
                                      [:span {:style "overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:140px;"}
                                        (str "+ " (:title t))]
                                      [:span {} (fmt-duration (:estimated-mins t))]])
                                  (take 3 day-tasks)))])]]))
               days))]]))

;; ── 4. FOCUS MODE VIEW ("One task, one timer") ─────────────────────────────

(defn render-focus-view [st]
  (let [tasks (or (:tasks st) [])
        fid (deref *focus-task-id*)
        task (or (first (filter #(= (:id %) fid) tasks))
                 (first (filter #(and (= (:day %) 0) (not (:done %))) tasks))
                 (first tasks))
        running? (deref *focus-running*)
        secs (deref *focus-elapsed-secs*)
        est-mins (if task (or (:estimated-mins task) 60) 60)
        tracked-mins (int (/ secs 60))
        pct (min 100 (int (* 100 (/ (max tracked-mins 1) (max est-mins 1)))))
        subs (if task (or (:subtasks task) []) [])]
    [:div {:class "focus-zen-wrap"}
      [:div {:class "focus-zen-card"}
        [:div {:style "display:flex;justify-content:space-between;align-items:center;"}
          [:div {:style "display:flex;align-items:center;gap:8px;"}
            [:span {:class "nav-badge"} "🎯 ZEN FOCUS MODE"]
            (when task
              [:span {:class (str "prio-badge prio-" (or (:priority task) "P1"))} (:priority task)])
            (when (and task (:channel task))
              [:span {:class "channel-tag"} (:channel task)])]
          [:button {:class "btn btn-sm"
                    :on-click (fn [_] (reset! *active-tab* "board") (render-ui))}
            "← Back to Board (Esc)"]]

        (if task
          [:div {:style "display:flex;flex-direction:column;gap:18px;"}
            [:div {}
              [:h2 {:style "margin:0 0 6px 0;font-size:22px;font-weight:700;letter-spacing:-0.02em;"}
                (:title task)]
              (when (and (:notes task) (> (count (:notes task)) 0))
                [:p {:style "margin:0;font-size:13px;color:var(--muted-foreground);line-height:1.5;"}
                  (:notes task)])]

            ;; Timer Ring Box
            [:div {:class "focus-timer-ring"}
              [:div {}
                [:div {:style "font-size:11px;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:0.06em;"}
                  (if running? "⏱️ FOCUS TIMER RUNNING" "⏱️ ACTUAL VS ESTIMATE")]
                [:div {:class "focus-big-clock"} (fmt-clock secs)]
                [:div {:style "font-size:12px;color:var(--muted-foreground);margin-top:2px;"}
                  (str tracked-mins " minutes tracked against " est-mins "-minute estimate (" pct "%)")]]

              [:div {:style "display:flex;flex-direction:column;gap:8px;"}
                [:button {:class (str "btn " (if running? "" "btn-primary"))
                          :style "height:38px;padding:0 18px;font-size:13px;"
                          :on-click (fn [_]
                                      (swap! *focus-running* not)
                                      (render-ui))}
                  (if running? "⏸ Pause Timer" "▶ Start Focus Timer")]
                [:div {:style "display:flex;gap:6px;"}
                  [:button {:class "btn btn-sm"
                            :on-click (fn [_]
                                        (swap! *focus-elapsed-secs* + 900)
                                        (post-action! "/api/task/focus" {:id (:id task) :mins 15} "Logged +15m focus time"))}
                    "+15m"]
                  [:button {:class "btn btn-sm btn-primary"
                            :on-click (fn [_]
                                        (post-action! "/api/task/focus"
                                          {:id (:id task) :mins 15 :done true}
                                          "Completed focus session & task! 🎉")
                                        (reset! *active-tab* "board"))}
                    "✓ Complete Task"]]]]

            ;; Progress Bar
            [:div {:class "workload-bar-track" :style "width:100%;height:8px;"}
              [:div {:class "workload-bar-fill" :style (str "width:" pct "%;")}]]

            ;; Interactive Subtasks Checklist inside Focus Mode
            [:div {:style "border-top:1px solid var(--border);padding-top:14px;"}
              [:div {:style "font-size:12px;font-weight:700;margin-bottom:8px;"}
                (str "Subtasks (" (count (filter :done subs)) "/" (count subs) ")")]
              (into [:div {:style "display:flex;flex-direction:column;gap:6px;"}]
                (map (fn [s]
                       [:div {:style "display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:7px;background:var(--surface-subtle);"}
                         [:button {:class (str "task-check-btn" (if (:done s) " checked" ""))
                                   :on-click (fn [_]
                                               (post-action! "/api/subtask/toggle"
                                                 {:task-id (:id task) :subtask-id (:id s)}))}
                           (if (:done s) "✓" "")]
                         [:span {:style (str "font-size:12.5px;" (if (:done s) "text-decoration:line-through;color:var(--muted-foreground);" ""))}
                           (:title s)]])
                     subs))]

            ;; Switch Focus Task Selector
            [:div {:style "border-top:1px solid var(--border);padding-top:12px;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;"}
              [:span {:style "font-size:11.5px;color:var(--muted-foreground);"} "Switch active focus task:"]
              [:select {:class "select-field"
                        :value (:id task)
                        :on-change (fn [e]
                                     (let [nid (js/get (js/get e "target") "value")]
                                       (enter-focus-mode! nid)))}
                (into [:optgroup {:label "Today's Tasks"}]
                  (map (fn [t]
                         [:option {:value (:id t)} (str (:priority t) " — " (:title t))])
                       (filter #(= (:day %) 0) tasks)))]]]
          [:div {} "No active tasks found."])]]))

;; ── 5. IDEAS VIEW ("Ideas: your someday boards") ───────────────────────────

(defn render-ideas-view [st]
  (let [boards (or (:idea-boards st) [])
        active-id (deref *active-board-id*)
        board (or (first (filter #(= (:id %) active-id) boards)) (first boards))
        cols (if board (or (:columns board) []) [])]
    [:div {:style "display:flex;flex-direction:column;flex:1;"}
      [:div {:class "planner-subbar"}
        [:div {:class "subbar-left"}
          [:div {:class "subbar-title"} "💡 Ideas: Your Someday Boards"]
          (into [:div {:style "display:flex;gap:6px;"}]
            (map (fn [b]
                   [:button {:class (str "btn btn-sm" (if (= (:id b) (:id board)) " btn-primary" ""))
                             :on-click (fn [_]
                                         (reset! *active-board-id* (:id b))
                                         (when (first (:columns b))
                                           (reset! *new-idea-col* (:id (first (:columns b)))))
                                         (render-ui))}
                     (str (:icon b) " " (:name b))])
                 boards))]

        [:div {:class "subbar-actions"}
          [:input {:class "input-field"
                   :placeholder "Capture a new idea or bet..."
                   :value (deref *new-idea-title*)
                   :on-input (fn [e] (reset! *new-idea-title* (js/get (js/get e "target") "value")))}]
          [:select {:class "select-field"
                    :value (deref *new-idea-col*)
                    :on-change (fn [e] (reset! *new-idea-col* (js/get (js/get e "target") "value")))}
            (into [:optgroup {:label "Column"}]
              (map (fn [c] [:option {:value (:id c)} (:name c)]) cols))]
          [:button {:class "btn btn-primary"
                    :on-click (fn [_]
                                (let [title (str/trim (deref *new-idea-title*))]
                                  (when (and board (> (count title) 0))
                                    (reset! *new-idea-title* "")
                                    (post-action! "/api/idea/add"
                                      {:board-id (:id board)
                                       :column-id (or (deref *new-idea-col*) (:id (first cols)))
                                       :title title
                                       :priority "P1"
                                       :estimated-mins 60}
                                      "Added idea card 💡"))))}
            "+ Add Idea"]]]

      [:div {:class "ideas-board-grid"}
        (into [:div {:style "display:contents;"}]
          (map (fn [col]
                 (let [ideas (or (:ideas col) [])]
                   [:div {:class "idea-col"}
                     [:div {:style "display:flex;justify-content:space-between;align-items:center;padding:2px 4px;"}
                       [:div {:style "font-size:13px;font-weight:700;"} (:name col)]
                       [:span {:class "nav-badge"} (str (count ideas))]]

                     (into [:div {:style "display:flex;flex-direction:column;gap:8px;"}]
                       (map (fn [idea]
                              [:div {:class "task-card"}
                                [:div {:style "font-size:13px;font-weight:600;"} (:title idea)]
                                [:div {:class "task-meta-row"}
                                  [:span {:class (str "prio-badge prio-" (or (:priority idea) "P2"))}
                                    (or (:priority idea) "P2")]
                                  [:span {:class "estimate-pill"}
                                    (fmt-duration (or (:estimated-mins idea) 45))]]
                                [:div {:class "task-quick-actions"}
                                  [:button {:class "mini-action-btn"
                                            :style "color:var(--primary);font-weight:600;"
                                            :on-click (fn [_]
                                                        (post-action! "/api/idea/promote"
                                                          {:id (:id idea) :day 0}
                                                          (str "Promoted '" (:title idea) "' to Today's Board! 🚀")))}
                                    "🚀 Promote to Today"]
                                  [:button {:class "mini-action-btn"
                                            :on-click (fn [_]
                                                        (post-action! "/api/idea/delete" {:id (:id idea)} "Removed idea"))}
                                    "×"]]])
                            ideas))]))
               cols))]]))

;; ── 6. ROUTINES VIEW (Recurring Rituals & Rollover) ────────────────────────

(defn render-routines-view [st]
  (let [routines (or (:routines st) [])]
    [:div {:style "display:flex;flex-direction:column;flex:1;"}
      [:div {:class "planner-subbar"}
        [:div {:class "subbar-left"}
          [:div {:class "subbar-title"} "🔁 Recurring Routines & Daily Planning Rituals"]]
        [:div {:class "subbar-actions"}
          [:input {:class "input-field"
                   :placeholder "New recurring routine..."
                   :value (deref *new-routine-title*)
                   :on-input (fn [e] (reset! *new-routine-title* (js/get (js/get e "target") "value")))}]
          [:input {:class "input-field"
                   :value (deref *new-routine-sched*)
                   :on-input (fn [e] (reset! *new-routine-sched* (js/get (js/get e "target") "value")))}]
          [:button {:class "btn btn-primary"
                    :on-click (fn [_]
                                (let [title (str/trim (deref *new-routine-title*))]
                                  (when (> (count title) 0)
                                    (reset! *new-routine-title* "")
                                    (post-action! "/api/routine/add"
                                      {:title title :schedule (deref *new-routine-sched*)}
                                      "Added recurring routine 🔁"))))}
            "+ Add Routine"]]]

      [:div {:style "padding:20px;max-width:960px;width:100%;margin:0 auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(420px,1fr));gap:14px;"}
        (into [:div {:style "display:contents;"}]
          (map (fn [rt]
                 [:div {:class "task-card" :style "padding:16px;"}
                   [:div {:style "display:flex;justify-content:space-between;align-items:center;"}
                     [:div {:style "display:flex;gap:6px;align-items:center;"}
                       [:span {:class (str "prio-badge prio-" (or (:priority rt) "P2"))} (or (:priority rt) "P2")]
                       [:span {:class "channel-tag"} (:schedule rt)]
                       [:span {:class "channel-tag"} (:channel rt)]]
                     [:span {:class "nav-badge"} (str "🔥 " (or (:streak rt) 1) " day streak")]]
                   [:div {:style "font-size:15px;font-weight:700;margin-top:4px;"} (:title rt)]
                   [:p {:style "margin:0;font-size:12.5px;color:var(--muted-foreground);line-height:1.45;"}
                     (:description rt)]
                   [:div {:style "display:flex;justify-content:space-between;align-items:center;padding-top:10px;border-top:1px solid var(--border);margin-top:4px;"}
                     [:span {:class "estimate-pill"} (str "⏱️ " (fmt-duration (:estimated-mins rt)))]
                     [:button {:class "btn btn-sm btn-primary"
                               :on-click (fn [_]
                                           (post-action! "/api/routine/run" {:id (:id rt)}
                                             (str "Added '" (:title rt) "' to Today's Board! ☀️")))}
                       "☀️ Spawn into Today's Plan"]]])
               routines))]]))

;; ── 7. AI & MCP CONNECTOR HUB (24 Tools, OAuth 2.1, Live Playground) ───────

(defn render-mcp-view [st]
  (let [prof (or (:profile st) {})
        clients (or (:mcp-clients st) [])
        tools (or (:mcp-tools st) [])
        logs (or (:mcp-logs st) [])
        sel-tool (deref *mcp-selected-tool*)
        last-out (deref *mcp-last-output*)]
    [:div {:style "display:flex;flex-direction:column;flex:1;"}
      [:div {:class "planner-subbar"}
        [:div {:class "subbar-left"}
          [:div {:class "subbar-title"} "🔌 Connect Claude, ChatGPT, Cursor & Claude Code (MCP)"]
          [:span {:class "workload-pill"}
            "Streamable HTTP + OAuth 2.1 PKCE • 24 Annotated Tools"]]
        [:div {:class "subbar-actions"}
          [:button {:class "btn"
                    :on-click (fn [_]
                                (post-action! "/api/reset" {} "Workspace reset to demo seed ✓"))}
            "↺ Reset Demo Seed"]]]

      [:div {:style "padding:20px;max-width:1180px;width:100%;margin:0 auto;display:flex;flex-direction:column;gap:18px;"}
        ;; Top Row: One-URL MCP Connector Card + Live AI Co-Planner Prompt Bar
        [:div {:style "display:grid;grid-template-columns:repeat(auto-fit,minmax(460px,1fr));gap:16px;"}
          ;; Card 1: One-Click Connector URL & Setup
          [:div {:class "task-card" :style "padding:18px;gap:12px;"}
            [:div {:style "display:flex;justify-content:space-between;align-items:center;"}
              [:div {:style "font-size:15px;font-weight:700;"} "🔗 One-URL MCP Connector (No API Key Required)"]
              [:span {:class "nav-badge"} "OAuth 2.1 Verified"]]
            [:p {:style "margin:0;font-size:12.5px;color:var(--muted-foreground);line-height:1.5;"}
              "Paste this URL into Claude (Settings → Connectors → Add), ChatGPT Developer Mode, Cursor, or Claude Code:"]
            [:div {:style "padding:10px 12px;border-radius:8px;background:var(--surface-subtle);border:1px solid var(--border);font-family:'JetBrains Mono',monospace;font-size:12px;display:flex;justify-content:space-between;align-items:center;"}
              [:span {:style "color:var(--primary);font-weight:600;"} (or (:mcp-url prof) "https://sunsama.coni-lang.org/api/mcp")]
              [:span {:class "kbd-chip"} "Streamable HTTP"]]
            [:div {:style "padding:10px 12px;border-radius:8px;background:var(--surface-subtle);border:1px solid var(--border);font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--muted-foreground);"}
              (str "claude mcp add --transport http open-sunsama " (or (:mcp-url prof) "https://sunsama.coni-lang.org/api/mcp"))]

            [:div {:style "font-size:12px;font-weight:700;margin-top:4px;"} "Connected AI Assistants:"]
            (into [:div {:style "display:flex;flex-direction:column;gap:6px;"}]
              (map (fn [c]
                     [:div {:style "display:flex;justify-content:space-between;align-items:center;padding:7px 10px;border-radius:8px;background:var(--surface-subtle);"}
                       [:div {:style "display:flex;align-items:center;gap:8px;"}
                         [:span {:style "color:var(--done-color);font-weight:700;"} "●"]
                         [:span {:style "font-size:12.5px;font-weight:600;"} (:name c)]
                         [:span {:class "channel-tag"} (:protocol c)]]
                       [:span {:style "font-size:11px;color:var(--muted-foreground);"} (:last-used c)]])
                   clients))]

          ;; Card 2: Interactive AI Co-Planner & MCP Tool Playground
          [:div {:class "task-card" :style "padding:18px;gap:12px;"}
            [:div {:style "font-size:15px;font-weight:700;"} "🤖 Ask Your AI Assistant to Plan With You"]
            [:p {:style "margin:0;font-size:12.5px;color:var(--muted-foreground);"}
              "Run any of Open Sunsama's signature AI prompts or test the 24 MCP tools directly against your live board:"]

            [:div {:style "display:flex;flex-direction:column;gap:7px;"}
              [:button {:class "btn btn-ai"
                        :style "justify-content:flex-start;height:34px;"
                        :on-click (fn [_] (post-action! "/api/ai/prompt" {:preset "triage-today"}))}
                "💬 \"What's on my plate today? Move anything that isn't a P0 or P1 to tomorrow.\""]
              [:button {:class "btn btn-ai"
                        :style "justify-content:flex-start;height:34px;"
                        :on-click (fn [_] (post-action! "/api/ai/prompt" {:preset "block-deep-work"}))}
                "💬 \"Block 9–11am tomorrow for deep work on the launch plan and link it.\""]
              [:button {:class "btn btn-ai"
                        :style "justify-content:flex-start;height:34px;"
                        :on-click (fn [_] (post-action! "/api/ai/prompt" {:preset "board-subtasks"}))}
                "💬 \"Add subtasks to 'Board deck': metrics slide, roadmap slide, asks.\""]]

            [:div {:style "display:flex;gap:6px;margin-top:4px;"}
              [:input {:class "input-field"
                       :style "flex:1;"
                       :placeholder "Or ask AI to schedule a custom task & time block..."
                       :value (deref *ai-custom-prompt*)
                       :on-input (fn [e] (reset! *ai-custom-prompt* (js/get (js/get e "target") "value")))}]
              [:button {:class "btn btn-primary"
                        :on-click (fn [_]
                                    (let [p (str/trim (deref *ai-custom-prompt*))]
                                      (when (> (count p) 0)
                                        (reset! *ai-custom-prompt* "")
                                        (post-action! "/api/ai/prompt" {:preset "custom" :prompt p}))))}
                "Run AI"]]

            ;; Direct MCP Tool Tester
            [:div {:style "border-top:1px solid var(--border);padding-top:10px;margin-top:4px;"}
              [:div {:style "font-size:12px;font-weight:700;margin-bottom:6px;"} "🛠️ Test MCP Tool Call (`POST /api/mcp`):"]
              [:div {:style "display:flex;gap:6px;"}
                [:select {:class "select-field"
                          :style "flex:1;"
                          :value sel-tool
                          :on-change (fn [e] (reset! *mcp-selected-tool* (js/get (js/get e "target") "value")))}
                  (into [:optgroup {:label "24 MCP Tools"}]
                    (map (fn [tl]
                           [:option {:value (:name tl)}
                             (str (:name tl) " (" (:category tl) ")")])
                         tools))]
                [:button {:class "btn btn-primary"
                          :on-click (fn [_]
                                      (client/post-edn "/api/mcp/call"
                                        {:tool (deref *mcp-selected-tool*)
                                         :args {:day 0}
                                         :agent "MCP Inspector"}
                                        (fn [res]
                                          (when res
                                            (reset! *mcp-last-output* (pr-str (:result res)))
                                            (apply-state! res (str "Executed MCP tool: " (deref *mcp-selected-tool*)))))))}
                  "Invoke Tool"]]
              (when last-out
                [:pre {:style "margin:8px 0 0 0;padding:8px 10px;border-radius:7px;background:var(--surface-subtle);font-family:'JetBrains Mono',monospace;font-size:10.5px;max-height:110px;overflow:auto;white-space:pre-wrap;"}
                  last-out])]]]

        ;; Recent AI / MCP Audit Log
        [:div {:class "task-card" :style "padding:16px;"}
          [:div {:style "font-size:13.5px;font-weight:700;margin-bottom:6px;"} "📜 Live MCP Agent Activity Stream"]
          (into [:div {:style "display:flex;flex-direction:column;gap:6px;"}]
            (map (fn [lg]
                   [:div {:style "display:flex;align-items:center;justify-content:space-between;padding:6px 10px;border-radius:7px;background:var(--surface-subtle);font-size:12px;"}
                     [:div {:style "display:flex;align-items:center;gap:8px;"}
                       [:span {:class "prio-badge prio-P1"} (:agent lg)]
                       [:span {:style "font-family:'JetBrains Mono',monospace;font-weight:600;color:var(--primary);"} (:tool lg)]
                       [:span {} (:summary lg)]]
                     [:span {:style "font-size:11px;color:var(--muted-foreground);"} (:ts lg)]])
                 logs))]

        ;; Full 24 Annotated Tools Reference Table
        [:div {:class "task-card" :style "padding:16px;"}
          [:div {:style "font-size:13.5px;font-weight:700;margin-bottom:10px;"}
            "🧰 All 24 Annotated MCP Tools (Read-Only vs Destructive Annotations)"]
          [:div {:style "display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:8px;"}
            (into [:div {:style "display:contents;"}]
              (map (fn [tl]
                     [:div {:style "padding:9px 11px;border-radius:8px;background:var(--surface-subtle);border:1px solid var(--border);display:flex;flex-direction:column;gap:4px;"}
                       [:div {:style "display:flex;justify-content:space-between;align-items:center;"}
                         [:span {:style "font-family:'JetBrains Mono',monospace;font-size:11.5px;font-weight:700;color:var(--foreground);"}
                           (:name tl)]
                         [:span {:class (str "prio-badge " (if (:destructive tl) "prio-P0" (if (:readOnly tl) "prio-P2" "prio-P1")))}
                           (if (:destructive tl) "destructive" (if (:readOnly tl) "readOnly" "write"))]]
                       [:div {:style "font-size:11px;color:var(--muted-foreground);line-height:1.35;"}
                         (:description tl)]])
                   tools))]]]]))

;; ── Task Detail Modal ("Dig into any task") ────────────────────────────────

(defn render-task-modal [st]
  (let [tid (deref *selected-task-id*)]
    (when tid
      (let [tasks (or (:tasks st) [])
            t (first (filter #(= (:id %) tid) tasks))]
        (when t
          (let [subs (or (:subtasks t) [])
                existing-tags (into []
                                (distinct
                                  (filter #(and % (not= (str/trim (str %)) ""))
                                          (map :channel tasks))))]
            [:div {:class "modal-backdrop"}
              [:div {:class "modal-panel"}
                [:div {:style "padding:16px 20px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;"}
                  [:div {:style "display:flex;align-items:center;gap:8px;"}
                    [:span {:class (str "prio-badge prio-" (or (:priority t) "P2"))} (or (:priority t) "P2")]
                    (when (and (:channel t) (not= (str/trim (str (:channel t))) ""))
                      [:span {:class "channel-tag"} (:channel t)])
                    [:span {:class "estimate-pill"}
                      (str (fmt-duration (:actual-mins t)) " / " (fmt-duration (:estimated-mins t)))]]
                  [:div {:style "display:flex;gap:6px;"}
                    [:button {:class "btn btn-sm btn-primary"
                              :on-click (fn [_] (enter-focus-mode! (:id t)))}
                      "▶ Focus on Task"]
                    [:button {:class "btn btn-sm"
                              :on-click (fn [_] (reset! *selected-task-id* nil) (render-ui))}
                      "✕ Close"]]]

                [:div {:style "padding:20px;display:flex;flex-direction:column;gap:16px;"}
                  [:div {:style "display:flex;align-items:center;gap:8px;"}
                    [:button {:class (str "task-check-btn" (if (:done t) " checked" ""))
                              :on-click (fn [_] (post-action! "/api/task/toggle" {:id (:id t)}))}
                      (if (:done t) "✓" "")]
                    [:input {:class "input-field"
                             :style "flex:1;font-size:16px;font-weight:700;height:36px;"
                             :value (deref *edit-modal-title*)
                             :on-input (fn [e] (reset! *edit-modal-title* (js/get (js/get e "target") "value")))
                             :on-keydown (fn [e]
                                           (when (= (js/get e "key") "Enter")
                                             (let [nt (str/trim (deref *edit-modal-title*))]
                                               (when (> (count nt) 0)
                                                 (post-action! "/api/task/update"
                                                   {:id (:id t) :title nt}
                                                   "Updated task title ✓")))))}]
                    [:button {:class "btn btn-sm btn-primary"
                              :on-click (fn [_]
                                          (let [nt (str/trim (deref *edit-modal-title*))]
                                            (when (> (count nt) 0)
                                              (post-action! "/api/task/update"
                                                {:id (:id t) :title nt}
                                                "Updated task title ✓"))))}
                      "Rename"]]

                  ;; Priority & Schedule Controls
                  [:div {:style "display:flex;gap:8px;flex-wrap:wrap;align-items:center;"}
                    [:span {:style "font-size:12px;color:var(--muted-foreground);"} "Priority:"]
                    (into [:div {:style "display:flex;gap:4px;"}]
                      (map (fn [p]
                             [:button {:class (str "btn btn-sm" (if (= (:priority t) p) " btn-primary" ""))
                                       :on-click (fn [_]
                                                   (post-action! "/api/task/update" {:id (:id t) :priority p}
                                                     (str "Updated priority to " p)))}
                               p])
                           ["P0" "P1" "P2" "P3"]))

                    [:span {:style "font-size:12px;color:var(--muted-foreground);margin-left:8px;"} "Schedule:"]
                    [:button {:class (str "btn btn-sm" (if (= (:day t) 0) " btn-primary" ""))
                              :on-click (fn [_] (post-action! "/api/task/schedule" {:id (:id t) :day 0} "Scheduled for Today"))}
                      "Today"]
                    [:button {:class (str "btn btn-sm" (if (= (:day t) 1) " btn-primary" ""))
                              :on-click (fn [_] (post-action! "/api/task/schedule" {:id (:id t) :day 1} "Scheduled for Tomorrow"))}
                      "Tomorrow"]
                    [:button {:class (str "btn btn-sm" (if (nil? (:day t)) " btn-primary" ""))
                              :on-click (fn [_] (post-action! "/api/task/schedule" {:id (:id t) :day nil} "Moved to Backlog"))}
                      "Backlog"]]

                  ;; Estimated Time Controls
                  [:div {:style "display:flex;gap:6px;flex-wrap:wrap;align-items:center;"}
                    [:span {:style "font-size:12px;color:var(--muted-foreground);"} "⏱️ Time:"]
                    (into [:div {:style "display:flex;gap:4px;flex-wrap:wrap;"}]
                      (map (fn [m]
                             [:button {:class (str "btn btn-sm" (if (= (or (:estimated-mins t) 0) m) " btn-primary" ""))
                                       :on-click (fn [_]
                                                   (reset! *edit-modal-mins* (str m))
                                                   (post-action! "/api/task/update" {:id (:id t) :estimated-mins m}
                                                     (str "Updated time to " (fmt-duration m) " ✓")))}
                               (fmt-duration m)])
                           [15 30 45 60 90 120]))
                    [:input {:class "input-field"
                             :style "width:68px;height:24px;font-size:11.5px;padding:0 6px;"
                             :placeholder "Mins"
                             :value (deref *edit-modal-mins*)
                             :on-input (fn [e] (reset! *edit-modal-mins* (js/get (js/get e "target") "value")))
                             :on-keydown (fn [e]
                                           (when (= (js/get e "key") "Enter")
                                             (let [m (or (sys-try-parse-number (str/trim (deref *edit-modal-mins*))) 0)]
                                               (when (> m 0)
                                                 (post-action! "/api/task/update" {:id (:id t) :estimated-mins m}
                                                   (str "Updated time to " (fmt-duration m) " ✓"))))))}]
                    [:button {:class "btn btn-sm"
                              :on-click (fn [_]
                                          (let [m (or (sys-try-parse-number (str/trim (deref *edit-modal-mins*))) 0)]
                                            (when (> m 0)
                                              (post-action! "/api/task/update" {:id (:id t) :estimated-mins m}
                                                (str "Updated time to " (fmt-duration m) " ✓")))))}
                      "Set Mins"]]

                  ;; Tag / Channel Editor
                  [:div {:style "display:flex;flex-direction:column;gap:6px;"}
                    [:div {:style "display:flex;gap:6px;align-items:center;flex-wrap:wrap;"}
                      [:span {:style "font-size:12px;color:var(--muted-foreground);"} "🏷️ Tag:"]
                      [:input {:class "input-field"
                               :style "width:150px;"
                               :placeholder "e.g. #work, #personal"
                               :value (deref *edit-channel-text*)
                               :on-input (fn [e] (reset! *edit-channel-text* (js/get (js/get e "target") "value")))}]
                      [:button {:class "btn btn-sm btn-primary"
                                :on-click (fn [_]
                                            (let [raw (str/trim (deref *edit-channel-text*))
                                                  norm (if (= raw "") "" (if (str/starts-with? raw "#") raw (str "#" raw)))]
                                              (reset! *edit-channel-text* norm)
                                              (post-action! "/api/task/update"
                                                {:id (:id t) :channel norm}
                                                (if (= norm "") "Removed tag" (str "Updated tag to " norm)))))}
                        "Save Tag"]
                      (when (and (:channel t) (not= (str/trim (str (:channel t))) ""))
                        [:button {:class "btn btn-sm"
                                  :on-click (fn [_]
                                              (reset! *edit-channel-text* "")
                                              (post-action! "/api/task/update"
                                                {:id (:id t) :channel ""}
                                                "Cleared tag"))}
                          "Clear Tag"])]
                    (when (> (count existing-tags) 0)
                      [:div {:style "display:flex;gap:4px;align-items:center;flex-wrap:wrap;"}
                        [:span {:style "font-size:11px;color:var(--muted-foreground);"} "Your tags:"]
                        (into [:div {:style "display:flex;gap:4px;flex-wrap:wrap;"}]
                          (map (fn [tg]
                                 [:button {:class "mini-action-btn"
                                           :on-click (fn [_]
                                                       (reset! *edit-channel-text* tg)
                                                       (post-action! "/api/task/update"
                                                         {:id (:id t) :channel tg}
                                                         (str "Set tag to " tg)))}
                                   tg])
                               existing-tags))])]

                  ;; Rich Notes Editor
                  [:div {}
                    [:div {:style "font-size:12px;font-weight:700;margin-bottom:6px;display:flex;justify-content:space-between;"}
                      [:span {} "📝 Task Notes & Context"]
                      [:button {:class "mini-action-btn"
                                :on-click (fn [_]
                                            (post-action! "/api/task/update"
                                              {:id (:id t) :notes (deref *edit-notes-text*)}
                                              "Saved task notes ✓"))}
                        "Save Notes"]]
                    [:textarea {:class "textarea-field"
                                :rows "3"
                                :placeholder "Add rich notes, links, or acceptance criteria..."
                                :value (deref *edit-notes-text*)
                                :on-input (fn [e] (reset! *edit-notes-text* (js/get (js/get e "target") "value")))}]]

                  ;; Subtasks Section
                  [:div {}
                    [:div {:style "font-size:12px;font-weight:700;margin-bottom:8px;"}
                      (str "☑ Subtasks (" (count (filter :done subs)) "/" (count subs) ")")]
                    [:div {:style "display:flex;gap:6px;margin-bottom:8px;"}
                      [:input {:class "input-field"
                               :style "flex:1;"
                               :placeholder "Add a subtask..."
                               :value (deref *new-subtask-title*)
                               :on-input (fn [e] (reset! *new-subtask-title* (js/get (js/get e "target") "value")))}]
                      [:button {:class "btn btn-sm btn-primary"
                                :on-click (fn [_]
                                            (let [stitle (str/trim (deref *new-subtask-title*))]
                                              (when (> (count stitle) 0)
                                                (reset! *new-subtask-title* "")
                                                (post-action! "/api/subtask/add"
                                                  {:task-id (:id t) :title stitle}
                                                  "Added subtask"))))}
                        "+ Add"]]

                    (into [:div {:style "display:flex;flex-direction:column;gap:5px;"}]
                      (map (fn [s]
                             [:div {:style "display:flex;align-items:center;justify-content:space-between;padding:6px 9px;border-radius:7px;background:var(--surface-subtle);"}
                               [:div {:style "display:flex;align-items:center;gap:8px;"}
                                 [:button {:class (str "task-check-btn" (if (:done s) " checked" ""))
                                           :on-click (fn [_]
                                                       (post-action! "/api/subtask/toggle"
                                                         {:task-id (:id t) :subtask-id (:id s)}))}
                                   (if (:done s) "✓" "")]
                                 [:span {:style (str "font-size:12.5px;" (if (:done s) "text-decoration:line-through;color:var(--muted-foreground);" ""))}
                                   (:title s)]]
                               [:button {:class "mini-action-btn"
                                         :on-click (fn [_]
                                                     (post-action! "/api/subtask/delete"
                                                       {:task-id (:id t) :subtask-id (:id s)}))}
                                 "×"]])
                           subs))]

                  ;; Footer Actions
                  [:div {:style "display:flex;justify-content:space-between;align-items:center;padding-top:12px;border-top:1px solid var(--border);"}
                    [:button {:class "btn btn-sm"
                              :style "color:var(--p0-color);"
                              :on-click (fn [_]
                                          (reset! *selected-task-id* nil)
                                          (post-action! "/api/task/delete" {:id (:id t)} "Deleted task"))}
                      "🗑️ Delete Task"]
                    [:button {:class "btn btn-sm btn-primary"
                              :on-click (fn [_] (reset! *selected-task-id* nil) (render-ui))}
                      "Done"]]]]]))))))

;; ── ⌘K Command Palette ("⌘K for everything") ───────────────────────────────

(defn render-cmd-k-modal [st]
  (when (deref *cmd-k-open*)
    (let [q (str/lower-case (str/trim (deref *cmd-k-query*)))
          tasks (or (:tasks st) [])
          matching-tasks (filter (fn [t]
                                   (or (= q "")
                                       (str/includes? (str/lower-case (:title t)) q)
                                       (str/includes? (str/lower-case (or (:channel t) "")) q)))
                                 tasks)]
      [:div {:class "modal-backdrop"}
        [:div {:class "cmd-k-panel"}
          [:input {:class "cmd-k-input"
                   :placeholder "Type a command or search tasks, ideas, MCP tools..."
                   :value (deref *cmd-k-query*)
                   :on-input (fn [e]
                               (reset! *cmd-k-query* (js/get (js/get e "target") "value"))
                               (render-ui))}]

          [:div {:class "cmd-k-list"}
            [:div {:style "font-size:10.5px;font-weight:700;color:var(--muted-foreground);padding:4px 8px;text-transform:uppercase;"}
              "Quick Navigation & AI Actions"]
            [:button {:class "cmd-k-item"
                      :on-click (fn [_] (reset! *cmd-k-open* false) (reset! *active-tab* "board") (render-ui))}
              [:span {} "▦ Go to Daily Planning Board"]
              [:span {:class "kbd-chip"} "G B"]]
            [:button {:class "cmd-k-item"
                      :on-click (fn [_] (reset! *cmd-k-open* false) (reset! *active-tab* "calendar") (render-ui))}
              [:span {} "🗓️ Go to Week Time-Blocking Calendar"]
              [:span {:class "kbd-chip"} "G C"]]
            [:button {:class "cmd-k-item"
                      :on-click (fn [_] (reset! *cmd-k-open* false) (reset! *active-tab* "focus") (render-ui))}
              [:span {} "🎯 Enter Zen Focus Mode"]
              [:span {:class "kbd-chip"} "F"]]
            [:button {:class "cmd-k-item"
                      :on-click (fn [_]
                                  (reset! *cmd-k-open* false)
                                  (post-action! "/api/ai/prompt" {:preset "triage-today"}))}
              [:span {} "🤖 AI: Move non-P0/P1 tasks from Today to Tomorrow"]
              [:span {:class "kbd-chip"} "MCP"]]
            [:button {:class "cmd-k-item"
                      :on-click (fn [_]
                                  (reset! *cmd-k-open* false)
                                  (post-action! "/api/theme" {}))}
              [:span {} "🌓 Toggle Light / Dark Theme"]
              [:span {:class "kbd-chip"} "⌘J"]]

            [:div {:style "font-size:10.5px;font-weight:700;color:var(--muted-foreground);padding:8px 8px 4px 8px;text-transform:uppercase;"}
              (str "Tasks (" (count matching-tasks) ")")]
            (into [:div {:style "display:contents;"}]
              (map (fn [t]
                     [:button {:class "cmd-k-item"
                               :on-click (fn [_]
                                           (reset! *cmd-k-open* false)
                                           (open-task-modal! t))}
                       [:div {:style "display:flex;align-items:center;gap:8px;"}
                         [:span {:class (str "prio-badge prio-" (or (:priority t) "P2"))} (:priority t)]
                         [:span {} (:title t)]]
                       [:span {:class "estimate-pill"} (fmt-duration (:estimated-mins t))]])
                   (take 8 matching-tasks)))]

          [:div {:style "padding:8px 14px;border-top:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;background:var(--surface-subtle);"}
            [:span {:style "font-size:11px;color:var(--muted-foreground);"} "Open Sunsama Command Palette"]
            [:button {:class "btn btn-sm"
                      :on-click (fn [_] (reset! *cmd-k-open* false) (render-ui))}
              "Close (Esc)"]]]])))

;; ── Keyboard Shortcuts Modal (`?`) ─────────────────────────────────────────

(defn render-shortcuts-modal []
  (when (deref *shortcuts-open*)
    [:div {:class "modal-backdrop"}
      [:div {:class "cmd-k-panel" :style "padding:20px;"}
        [:div {:style "display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;"}
          [:div {:style "font-size:15px;font-weight:700;"} "⌨️ Keyboard-First Shortcuts"]
          [:button {:class "btn btn-sm"
                    :on-click (fn [_] (reset! *shortcuts-open* false) (render-ui))}
            "✕"]]
        [:div {:style "display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:12.5px;"}
          [:div {:style "display:flex;justify-content:space-between;padding:6px 8px;background:var(--surface-subtle);border-radius:6px;"}
            [:span {} "Command Palette"] [:span {:class "kbd-chip"} "⌘K"]]
          [:div {:style "display:flex;justify-content:space-between;padding:6px 8px;background:var(--surface-subtle);border-radius:6px;"}
            [:span {} "Start Focus Timer"] [:span {:class "kbd-chip"} "F"]]
          [:div {:style "display:flex;justify-content:space-between;padding:6px 8px;background:var(--surface-subtle);border-radius:6px;"}
            [:span {} "Toggle Backlog Rail"] [:span {:class "kbd-chip"} "B"]]
          [:div {:style "display:flex;justify-content:space-between;padding:6px 8px;background:var(--surface-subtle);border-radius:6px;"}
            [:span {} "Rollover Unfinished"] [:span {:class "kbd-chip"} "R"]]
          [:div {:style "display:flex;justify-content:space-between;padding:6px 8px;background:var(--surface-subtle);border-radius:6px;"}
            [:span {} "Set Priority P0..P3"] [:span {:class "kbd-chip"} "1 – 4"]]
          [:div {:style "display:flex;justify-content:space-between;padding:6px 8px;background:var(--surface-subtle);border-radius:6px;"}
            [:span {} "Toggle Dark Theme"] [:span {:class "kbd-chip"} "⌘J"]]]]]))

;; ── Root UI & Render Loop ──────────────────────────────────────────────────

(defn render-active-tab [st]
  (let [tab (deref *active-tab*)]
    (cond
      (= tab "tasks")    (render-tasks-view st)
      (= tab "calendar") (render-calendar-view st)
      (= tab "focus")    (render-focus-view st)
      (= tab "ideas")    (render-ideas-view st)
      (= tab "routines") (render-routines-view st)
      (= tab "mcp")      (render-mcp-view st)
      :else              (render-board-view st))))

(defn ui []
  (let [st (deref *state*)
        theme (or (:theme st) "light")
        accent (or (:color-theme st) "default")
        toast (deref *toast-msg*)]
    [:div {:class "sunsama-shell" :data-theme theme :data-accent accent}
      (render-header st)
      [:div {:class "sunsama-canvas-wrap"}
        [:main {:class "sunsama-canvas"}
          (render-active-tab st)]]
      (render-task-modal st)
      (render-cmd-k-modal st)
      (render-shortcuts-modal)
      (when toast
        [:div {:class "sunsama-toast"} toast])]))

(defn render-ui []
  (dom/render "app" (ui)))

;; ── Focus Timer Tick Loop (1s interval when Focus Timer is running) ────────

(let [win (try (js/global "window") (catch _ nil))]
  (when win
    (js/call win "setInterval"
      (fn []
        (when (deref *focus-running*)
          (swap! *focus-elapsed-secs* inc)
          (render-ui)))
      1000)))

;; ── Boot Frontend ──────────────────────────────────────────────────────────

(render-ui)
(load-state!)

;; Keep WASM interpreter channel alive
(<! (chan 1))
