;; =============================================================================
;; Paw & Crown — Cute 2D Chess: Multi-Room, Official Timers & Parallel Tournaments
;; Features:
;;   • Official FIDE & Online Fischer Chess Clocks:
;;     Base Minutes (30, 15, 10, 5, 3, 1 min + Unlimited) & Increment (+0..+30s/move)
;;     Official Presets: Classical (30+20, 30+0), Rapid (15+10, 15+0, 10+5, 10+0),
;;     Blitz (5+3, 5+0, 3+2, 3+0), Bullet (2+1, 1+1, 1+0) & Custom Builder
;;   • Multiple Rooms (1 Room = 1 Game) with Live Mini-Board Previews & Live Clocks
;;   • Come Back to Game (localStorage persistence, URL deep-link, My Active Games
;;     resume bar, and 1-click Reclaim Seat across tabs/devices)
;;   • Parallel Tournaments (Knockout Bracket & Round-Robin) with Side-by-Side
;;     Live Ongoing Games Multi-Board View
;;   • Cute 2D Kawaii SVG Chess Pieces, Move Highlighting, Impossible Move
;;     Explanations, Checkmate & Flag-Fall Timeout Detection
;; =============================================================================

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

;; ── 1. Persistent Client Identity & URL Deep-Link Helpers ───────────────────

(defn get-storage []
  "Prefers localStorage so players can close tabs and come back to their games!"
  (let [w (try (js/global "window") (catch e nil))]
    (when w
      (or (try (js/get w "localStorage") (catch e nil))
          (try (js/get w "sessionStorage") (catch e nil))))))

(defn init-client-id []
  (let [st (get-storage)
        saved (when st (try (js/call st "getItem" "conimo_chess_pid") (catch e nil)))]
    (if (and saved (not= (str saved) "") (not= (str saved) "null"))
      (str saved)
      (let [w (try (js/global "window") (catch e nil))
            math (when w (try (js/get w "Math") (catch e nil)))
            rand-num (if math
                       (int (* (js/call math "random") 899999))
                       (rem (sys-time-now) 899999))
            new-id (str "player-" (+ 100000 rand-num))]
        (when st
          (try (js/call st "setItem" "conimo_chess_pid" new-id) (catch e nil)))
        new-id))))

(defn load-saved-name []
  (let [st (get-storage)
        saved (when st (try (js/call st "getItem" "conimo_chess_name") (catch e nil)))]
    (if (and saved (not= (str saved) "") (not= (str saved) "null"))
      (str saved)
      "")))

(defn save-player-name! [nm]
  (let [st (get-storage)]
    (when st
      (try (js/call st "setItem" "conimo_chess_name" nm) (catch e nil)))))

(defn get-url-param [param-key]
  (let [w (try (js/global "window") (catch e nil))
        loc (when w (try (js/get w "location") (catch e nil)))
        search (when loc (try (js/get loc "search") (catch e "")))]
    (if (and search (str/includes? (str search) (str param-key "=")))
      (let [after (second (str/split (str search) (str param-key "=")))
            val (first (str/split (or after "") "&"))]
        (str/trim (or val "")))
      "")))

(defn update-url-params! [room-id tourney-id]
  (let [w (try (js/global "window") (catch e nil))
        hist (when w (try (js/get w "history") (catch e nil)))]
    (when hist
      (let [q (cond
                (and room-id (not= room-id "")) (str "?room=" room-id)
                (and tourney-id (not= tourney-id "")) (str "?tournament=" tourney-id)
                :else "/")]
        (try (js/call hist "replaceState" nil "" q) (catch e nil))))))

;; ── 2. Official FIDE / Fischer Time Controls & Clock Formatting ─────────────

(def official-tc-presets
  [{:id "30+20"     :short "30+20" :cat "Classical" :desc "FIDE Classical (30m + 20s)"}
   {:id "30+0"      :short "30+0"  :cat "Classical" :desc "Classical 30 min"}
   {:id "15+10"     :short "15+10" :cat "Rapid"     :desc "FIDE Official Rapid (15m + 10s)"}
   {:id "15+0"      :short "15+0"  :cat "Rapid"     :desc "Rapid 15 min"}
   {:id "10+5"      :short "10+5"  :cat "Rapid"     :desc "Rapid 10m + 5s"}
   {:id "10+0"      :short "10+0"  :cat "Rapid"     :desc "Rapid 10 min"}
   {:id "5+3"       :short "5+3"   :cat "Blitz"     :desc "Club Blitz (5m + 3s)"}
   {:id "5+0"       :short "5+0"   :cat "Blitz"     :desc "Blitz 5 min"}
   {:id "3+2"       :short "3+2"   :cat "Blitz"     :desc "FIDE Official Blitz (3m + 2s)"}
   {:id "3+0"       :short "3+0"   :cat "Blitz"     :desc "Blitz 3 min"}
   {:id "2+1"       :short "2+1"   :cat "Bullet"    :desc "Bullet 2m + 1s"}
   {:id "1+1"       :short "1+1"   :cat "Bullet"    :desc "Bullet 1m + 1s"}
   {:id "1+0"       :short "1+0"   :cat "Bullet"    :desc "Bullet 1 min"}
   {:id "unlimited" :short "∞"     :cat "Casual"    :desc "No Timer (Unlimited)"}])

(def base-min-choices [30 15 10 5 3 1])
(def inc-sec-choices  [0 1 2 3 5 10 15 20 30])

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

(defn format-clock-ms [ms]
  (if (nil? ms)
    "∞"
    (let [clamped (max 0 (int ms))
          total-sec (int (/ clamped 1000))
          tenths (int (/ (rem clamped 1000) 100))
          hrs (int (/ total-sec 3600))
          mins (int (/ (rem total-sec 3600) 60))
          secs (rem total-sec 60)]
      (cond
        (> hrs 0)
        (str hrs ":" (pad2 mins) ":" (pad2 secs))

        (and (< clamped 20000) (> clamped 0))
        (str "0:" (pad2 secs) "." tenths)

        :else
        (str (pad2 mins) ":" (pad2 secs))))))

;; ── 3. Reactive State Atoms ─────────────────────────────────────────────────

(def *client-id* (atom (init-client-id)))
(def *name-input* (atom (load-saved-name)))
(def *local-p2-name* (atom ""))
(def *pass-and-play* (atom false))
(def *local-p2-id* (atom (str (deref *client-id*) "-local-p2")))

;; Main navigation view: "board" | "rooms" | "tournaments"
(def *nav-view* (atom "board"))
(def *active-room-id* (atom (let [r (get-url-param "room")] (if (= r "") "room-paw-1" r))))
(def *active-tourney-id* (atom (let [t (get-url-param "tournament")] (if (= t "") nil t))))

;; Forms for creating rooms, tournaments, and configuring timers
(def *new-room-name* (atom ""))
(def *new-room-tc* (atom "10+5"))
(def *new-tourney-name* (atom ""))
(def *new-tourney-format* (atom "knockout-4"))
(def *new-tourney-tc* (atom "5+3"))
(def *new-tourney-players-str* (atom "Mochi, Boba, Kiki, Yuzu"))
(def *tourney-join-name* (atom (load-saved-name)))

;; Custom timer builder state on the Active Board
(def *show-custom-tc* (atom false))
(def *custom-base-min* (atom 10))
(def *custom-inc-sec* (atom 5))

;; Hub state from server
(def *game*
  (atom {:active-room-id "room-paw-1"
         :rooms {}
         :room-order []
         :tournaments {}
         :tournament-order []
         :status "waiting"
         :players {:w nil :b nil}
         :spectators []
         :time-control {:id "10+5" :label "Rapid 10+5" :category "Rapid" :base-min 10 :inc-sec 5 :enabled true}
         :clocks {:w-ms 600000 :b-ms 600000 :last-tick-ms nil :running false}
         :board ["bR" "bN" "bB" "bQ" "bK" "bB" "bN" "bR"
                 "bP" "bP" "bP" "bP" "bP" "bP" "bP" "bP"
                 "" "" "" "" "" "" "" ""
                 "" "" "" "" "" "" "" ""
                 "" "" "" "" "" "" "" ""
                 "" "" "" "" "" "" "" ""
                 "wP" "wP" "wP" "wP" "wP" "wP" "wP" "wP"
                 "wR" "wN" "wB" "wQ" "wK" "wB" "wN" "wR"]
         :turn "w"
         :in-check false
         :winner nil
         :winner-name nil
         :reason ""
         :last-move nil
         :history []
         :captured-by-w []
         :captured-by-b []
         :legal-moves {}}))

(def *selected-sq* (atom nil))
(def *invalid-sq* (atom nil))
(def *feedback-msg* (atom nil))
(def *promo-piece* (atom "Q"))
(def *flip-board* (atom nil))
(def *ws* (atom nil))

(declare render-ui)

;; ── 4. Board, Room & Role Helpers ───────────────────────────────────────────

(def file-labels ["a" "b" "c" "d" "e" "f" "g" "h"])

(defn sq-idx [r c]
  (+ (* r 8) c))

(defn board-get [board r c]
  (if (and (>= r 0) (< r 8) (>= c 0) (< c 8))
    (or (nth board (sq-idx r c)) "")
    ""))

(defn piece-color [p]
  (if (and p (>= (count (str p)) 2))
    (str/substring (str p) 0 1)
    ""))

(defn piece-type [p]
  (if (and p (>= (count (str p)) 2))
    (str/substring (str p) 1 2)
    ""))

(defn piece-name [ptype]
  (cond
    (= ptype "K") "King"
    (= ptype "Q") "Queen"
    (= ptype "R") "Rook"
    (= ptype "B") "Bishop"
    (= ptype "N") "Knight"
    (= ptype "P") "Pawn"
    :else "Piece"))

(defn coord->alg [r c]
  (str (nth file-labels c) (- 8 r)))

(defn sq-key [r c]
  (str r "," c))

(defn get-room-map [hub]
  (or (:rooms hub) {}))

(defn get-current-room [hub]
  (let [rooms (get-room-map hub)
        rid (deref *active-room-id*)
        found (or (get rooms rid) (get rooms (keyword rid)))]
    (if found
      found
      (let [fallback-id (or (:active-room-id hub)
                            (first (:room-order hub))
                            "room-paw-1")
            fb-room (or (get rooms fallback-id) (first (vals rooms)))]
        (if fb-room
          (do
            (reset! *active-room-id* (:id fb-room))
            fb-room)
          hub)))))

(defn player-matches-me? [p-entry]
  (when p-entry
    (let [cid (deref *client-id*)
          p2-id (deref *local-p2-id*)
          my-nm (str/trim (str/lower-case (deref *name-input*)))
          p-nm (str/trim (str/lower-case (str (:name p-entry))))]
      (or (= (:id p-entry) cid)
          (= (:id p-entry) p2-id)
          (and (not= my-nm "") (= my-nm p-nm))))))

(defn my-role [room]
  (let [cid (deref *client-id*)
        p2-id (deref *local-p2-id*)
        wp (get-in room [:players :w])
        bp (get-in room [:players :b])
        is-w? (and wp (= (:id wp) cid))
        is-b? (and bp (= (:id bp) cid))
        is-p2-b? (and bp (= (:id bp) p2-id))
        is-p2-w? (and wp (= (:id wp) p2-id))
        in-specs? (some (fn [sp] (= (:id sp) cid)) (or (:spectators room) []))]
    (cond
      (and (or is-w? is-p2-w?) (or is-b? is-p2-b?)) "both"
      is-w? "w"
      is-b? "b"
      in-specs? "spectator"
      (= (:status room) "playing") "spectator"
      :else "unjoined")))

(defn active-client-id-for-turn [room]
  (let [role (my-role room)
        turn (:turn room)
        wp (get-in room [:players :w])
        bp (get-in room [:players :b])]
    (if (= role "both")
      (if (= turn "w") (:id wp) (:id bp))
      (deref *client-id*))))

(defn legal-moves-for-sq [room r c]
  (let [lm (or (:legal-moves room) {})
        k (sq-key r c)]
    (or (get lm k) (get lm (keyword k)) [])))

(defn find-legal-move [room r1 c1 r2 c2]
  (let [ms (legal-moves-for-sq room r1 c1)]
    (first (filter (fn [m]
                     (let [[tr tc] (:to m)]
                       (and (= tr r2) (= tc c2))))
                   ms))))

(defn find-my-active-rooms [hub]
  "Finds all rooms (casual or tournament) where this player is seated by ID or by saved Name!"
  (let [rooms (get-room-map hub)
        r-order (or (:room-order hub) (keys rooms))]
    (into []
      (filter (fn [rm]
                (and rm
                     (or (= (:status rm) "playing") (= (:status rm) "waiting"))
                     (or (player-matches-me? (get-in rm [:players :w]))
                         (player-matches-me? (get-in rm [:players :b])))))
              (map (fn [rid] (or (get rooms rid) (get rooms (keyword rid)))) r-order)))))

;; ── 5. Cute 2D Kawaii SVG Chess Pieces & Live Mini-Board ────────────────────

(defn render-cute-face [is-white? y-eyes state-mode]
  (let [eye-col (if is-white? "#3b1d0a" "#fef3c7")
        sparkle-col "#ffffff"
        cheek-col (if is-white? "#fda4af" "#f472b6")
        mouth-col (if is-white? "#78350f" "#fde68a")
        y-cheek (+ y-eyes 3.5)]
    (cond
      (= state-mode "checkmate")
      [:g {}
        [:circle {:cx 23 :cy y-cheek :r 3.2 :fill cheek-col :opacity "0.75"}]
        [:circle {:cx 41 :cy y-cheek :r 3.2 :fill cheek-col :opacity "0.75"}]
        [:line {:x1 24 :y1 (- y-eyes 2) :x2 28 :y2 (+ y-eyes 2) :stroke eye-col :stroke-width 2 :stroke-linecap "round"}]
        [:line {:x1 28 :y1 (- y-eyes 2) :x2 24 :y2 (+ y-eyes 2) :stroke eye-col :stroke-width 2 :stroke-linecap "round"}]
        [:line {:x1 36 :y1 (- y-eyes 2) :x2 40 :y2 (+ y-eyes 2) :stroke eye-col :stroke-width 2 :stroke-linecap "round"}]
        [:line {:x1 40 :y1 (- y-eyes 2) :x2 36 :y2 (+ y-eyes 2) :stroke eye-col :stroke-width 2 :stroke-linecap "round"}]
        [:circle {:cx 32 :cy (+ y-eyes 4) :r 2.2 :fill "none" :stroke mouth-col :stroke-width 1.6}]]

      (= state-mode "check")
      [:g {}
        [:circle {:cx 23 :cy y-cheek :r 3.2 :fill cheek-col :opacity "0.8"}]
        [:circle {:cx 41 :cy y-cheek :r 3.2 :fill cheek-col :opacity "0.8"}]
        [:circle {:cx 26.5 :cy y-eyes :r 2.7 :fill "#ffffff" :stroke eye-col :stroke-width 1.6}]
        [:circle {:cx 26.5 :cy y-eyes :r 1.1 :fill eye-col}]
        [:circle {:cx 37.5 :cy y-eyes :r 2.7 :fill "#ffffff" :stroke eye-col :stroke-width 1.6}]
        [:circle {:cx 37.5 :cy y-eyes :r 1.1 :fill eye-col}]
        [:path {:d (str "M 29.5 " (+ y-eyes 4.5) " Q 32 " (+ y-eyes 2) " 34.5 " (+ y-eyes 4.5))
                :fill "none" :stroke mouth-col :stroke-width 1.7 :stroke-linecap "round"}]
        [:path {:d "M 45 20 C 43 24 43 27 45 27 C 47 27 47 24 45 20 Z" :fill "#38bdf8" :stroke "#0284c7" :stroke-width 1}]]

      :else
      [:g {}
        [:circle {:cx 23.5 :cy y-cheek :r 3.1 :fill cheek-col :opacity "0.8"}]
        [:circle {:cx 40.5 :cy y-cheek :r 3.1 :fill cheek-col :opacity "0.8"}]
        [:circle {:cx 26.8 :cy y-eyes :r 2.3 :fill eye-col}]
        [:circle {:cx 26.0 :cy (- y-eyes 0.8) :r 0.85 :fill sparkle-col}]
        [:circle {:cx 37.2 :cy y-eyes :r 2.3 :fill eye-col}]
        [:circle {:cx 36.4 :cy (- y-eyes 0.8) :r 0.85 :fill sparkle-col}]
        [:path {:d (str "M 29.5 " (+ y-eyes 2.5) " Q 32 " (+ y-eyes 5.2) " 34.5 " (+ y-eyes 2.5))
                :fill "none" :stroke mouth-col :stroke-width 1.6 :stroke-linecap "round"}]])))

(defn render-piece-svg [piece-str & [king-alert-mode size-cls]]
  (let [color (piece-color piece-str)
        ptype (piece-type piece-str)
        is-w? (= color "w")
        fill-main (if is-w? "#fffbeb" "#3b3054")
        fill-shade (if is-w? "#fde68a" "#2a223d")
        stroke-col (if is-w? "#6b3410" "#191326")
        crown-fill (if is-w? "#fbbf24" "#f59e0b")
        crown-gem (if is-w? "#f43f5e" "#38bdf8")
        face-mode (if (= ptype "K") (or king-alert-mode "normal") "normal")]
    [:svg {:viewBox "0 0 64 64" :class (or size-cls "piece-svg")}
      [:circle {:cx 32 :cy 55 :r 17 :fill "rgba(0,0,0,0.14)"}]
      (cond
        (= ptype "P")
        [:g {}
          [:rect {:x 16 :y 49 :width 32 :height 7 :rx 3.5 :fill fill-shade :stroke stroke-col :stroke-width 2.4}]
          [:path {:d "M 19 49 C 17 34 21 23 32 23 C 43 23 47 34 45 49 Z"
                  :fill fill-main :stroke stroke-col :stroke-width 2.4 :stroke-linejoin "round"}]
          [:circle {:cx 32 :cy 18 :r 6.5 :fill crown-fill :stroke stroke-col :stroke-width 2.3}]
          [:circle {:cx 30 :cy 16 :r 2 :fill "#ffffff" :opacity "0.7"}]
          (render-cute-face is-w? 36 "normal")]

        (= ptype "R")
        [:g {}
          [:rect {:x 14 :y 49 :width 36 :height 7 :rx 3.5 :fill fill-shade :stroke stroke-col :stroke-width 2.4}]
          [:path {:d "M 18 49 L 20 22 L 44 22 L 46 49 Z"
                  :fill fill-main :stroke stroke-col :stroke-width 2.4 :stroke-linejoin "round"}]
          [:path {:d "M 16 22 L 16 13 L 23 13 L 23 17 L 28 17 L 28 13 L 36 13 L 36 17 L 41 17 L 41 13 L 48 13 L 48 22 Z"
                  :fill crown-fill :stroke stroke-col :stroke-width 2.3 :stroke-linejoin "round"}]
          [:line {:x1 23 :y1 44 :x2 41 :y2 44 :stroke stroke-col :stroke-width 1.6 :stroke-linecap "round" :opacity "0.45"}]
          (render-cute-face is-w? 34 "normal")]

        (= ptype "N")
        [:g {}
          [:rect {:x 14 :y 49 :width 36 :height 7 :rx 3.5 :fill fill-shade :stroke stroke-col :stroke-width 2.4}]
          [:path {:d "M 36 15 C 46 17 49 26 45 34 C 49 38 48 45 43 49 L 35 49 Z"
                  :fill crown-fill :stroke stroke-col :stroke-width 2.2 :stroke-linejoin "round"}]
          [:path {:d "M 19 49 C 19 37 22 32 25 29 C 17 29 14 25 16 20 C 18 16 24 16 28 14 L 31 8 L 36 14 C 42 16 44 26 42 49 Z"
                  :fill fill-main :stroke stroke-col :stroke-width 2.4 :stroke-linejoin "round"}]
          [:polygon {:points "31,10 34,14 29,14" :fill "#fda4af"}]
          [:circle {:cx 27 :cy 21.5 :r 2.5 :fill (if is-w? "#3b1d0a" "#fef3c7")}]
          [:circle {:cx 26.2 :cy 20.6 :r 0.9 :fill "#ffffff"}]
          [:circle {:cx 24 :cy 25 :r 3.2 :fill (if is-w? "#fda4af" "#f472b6") :opacity "0.85"}]
          [:circle {:cx 19 :cy 22 :r 1.1 :fill stroke-col}]
          [:path {:d "M 19 25.5 Q 22 27.5 24.5 25.5" :fill "none" :stroke stroke-col :stroke-width 1.6 :stroke-linecap "round"}]]

        (= ptype "B")
        [:g {}
          [:rect {:x 15 :y 49 :width 34 :height 7 :rx 3.5 :fill fill-shade :stroke stroke-col :stroke-width 2.4}]
          [:path {:d "M 18 49 C 16 32 21 15 32 12 C 43 15 48 32 46 49 Z"
                  :fill fill-main :stroke stroke-col :stroke-width 2.4 :stroke-linejoin "round"}]
          [:circle {:cx 32 :cy 9.5 :r 4.2 :fill crown-fill :stroke stroke-col :stroke-width 2.2}]
          [:line {:x1 32 :y1 17 :x2 32 :y2 25 :stroke crown-fill :stroke-width 2.8 :stroke-linecap "round"}]
          [:line {:x1 28 :y1 21 :x2 36 :y2 21 :stroke crown-fill :stroke-width 2.8 :stroke-linecap "round"}]
          (render-cute-face is-w? 35 "normal")]

        (= ptype "Q")
        [:g {}
          [:rect {:x 13 :y 49 :width 38 :height 7 :rx 3.5 :fill fill-shade :stroke stroke-col :stroke-width 2.4}]
          [:path {:d "M 16 49 C 14 33 19 21 32 21 C 45 21 50 33 48 49 Z"
                  :fill fill-main :stroke stroke-col :stroke-width 2.4 :stroke-linejoin "round"}]
          [:polygon {:points "18,24 15,12 25,19 32,9 39,19 49,12 46,24"
                     :fill crown-fill :stroke stroke-col :stroke-width 2.2 :stroke-linejoin "round"}]
          [:circle {:cx 15 :cy 11 :r 2.6 :fill crown-gem :stroke stroke-col :stroke-width 1.6}]
          [:circle {:cx 32 :cy 8 :r 3.0 :fill crown-gem :stroke stroke-col :stroke-width 1.6}]
          [:circle {:cx 49 :cy 11 :r 2.6 :fill crown-gem :stroke stroke-col :stroke-width 1.6}]
          (render-cute-face is-w? 35 "normal")]

        :else
        [:g {}
          [:rect {:x 13 :y 49 :width 38 :height 7 :rx 3.5 :fill fill-shade :stroke stroke-col :stroke-width 2.4}]
          [:path {:d "M 16 49 C 14 33 18 22 32 22 C 46 22 50 33 48 49 Z"
                  :fill fill-main :stroke stroke-col :stroke-width 2.4 :stroke-linejoin "round"}]
          [:path {:d "M 18 24 L 17 15 L 25 19 L 32 14 L 39 19 L 47 15 L 46 24 Z"
                  :fill crown-fill :stroke stroke-col :stroke-width 2.2 :stroke-linejoin "round"}]
          [:line {:x1 32 :y1 4.5 :x2 32 :y2 13.5 :stroke crown-fill :stroke-width 3.4 :stroke-linecap "round"}]
          [:line {:x1 27.5 :y1 8.5 :x2 36.5 :y2 8.5 :stroke crown-fill :stroke-width 3.4 :stroke-linecap "round"}]
          [:circle {:cx 32 :cy 19.5 :r 2.2 :fill crown-gem}]
          (render-cute-face is-w? 35 face-mode)])]))

(defn render-mini-chessboard [room & [on-click-fn]]
  "Renders a live 8x8 mini 2D chessboard for parallel tournament games & room previews!"
  (let [board (or (:board room) [])
        last-m (:last-move room)
        in-chk-col (:in-check room)]
    [:div {:class "mini-board-frame"
           :on-click (fn [_] (when on-click-fn (on-click-fn)))}
      (into [:div {:class "mini-board-grid"}]
        (loop [i 0 acc []]
          (if (>= i 64)
            acc
            (let [r (int (/ i 8))
                  c (rem i 8)
                  light? (= (rem (+ r c) 2) 0)
                  p (board-get board r c)
                  pcol (piece-color p)
                  ptype (piece-type p)
                  is-last? (and last-m
                                (or (and (= (nth (:from last-m) 0) r) (= (nth (:from last-m) 1) c))
                                    (and (= (nth (:to last-m) 0) r) (= (nth (:to last-m) 1) c))))
                  is-chk? (and (= ptype "K") (= in-chk-col pcol))
                  sq-cls (str "mini-sq "
                              (if light? "sq-light" "sq-dark")
                              (if is-last? " sq-last-move" "")
                              (if is-chk? " sq-king-check" ""))]
              (recur (+ i 1)
                     (conj acc
                           [:div {:class sq-cls}
                             (if (not= p "")
                               (render-piece-svg p (if is-chk? "check" "normal") "mini-board-piece-svg")
                               [:span {} ""])]))))))]))

;; ── 6. Server API Actions & Navigation Helpers ──────────────────────────────

(defn set-feedback! [kind text]
  (reset! *feedback-msg* (when text {:kind kind :text text}))
  (render-ui))

(defn open-room! [room-id & [auto-reclaim-by-name?]]
  (reset! *active-room-id* room-id)
  (reset! *nav-view* "board")
  (reset! *selected-sq* nil)
  (reset! *invalid-sq* nil)
  (reset! *feedback-msg* nil)
  (update-url-params! room-id nil)
  (let [hub (deref *game*)
        rm (get-in hub [:rooms room-id])
        my-nm (str/trim (deref *name-input*))]
    (if (and auto-reclaim-by-name? rm (not= my-nm ""))
      (client/post-edn "/api/join"
        {:room-id room-id
         :client-id (deref *client-id*)
         :name my-nm
         :seat "auto"}
        (fn [res]
          (when (and res (:rooms res))
            (reset! *game* res))
          (render-ui)))
      (render-ui))))

(defn open-tournament! [tourney-id]
  (reset! *active-tourney-id* tourney-id)
  (reset! *nav-view* "tournaments")
  (update-url-params! nil tourney-id)
  (render-ui))

(defn set-room-time-control! [tc-id & [custom-base custom-inc]]
  (let [rid (deref *active-room-id*)
        payload (if (and custom-base (some? custom-inc))
                  {:room-id rid :base-min custom-base :inc-sec custom-inc}
                  {:room-id rid :time-control tc-id})]
    (client/post-edn "/api/room/time-control" payload
      (fn [res]
        (when (and res (:board res))
          (reset! *game* res)
          (reset! *show-custom-tc* false)
          (let [rm (get-current-room res)
                tc (:time-control rm)]
            (set-feedback! "info" (str "⏱️ Time control updated to " (:label tc) " (" (:category tc) ")! Clocks reset.")))
          (render-ui))))))

(defn check-room-clock! [room-id]
  (client/post-edn "/api/room/clock-check" {:room-id room-id}
    (fn [res]
      (when (and res (:board res))
        (reset! *game* res)
        (render-ui)))))

(defn join-game! [seat-pref & [target-room-id]]
  (let [rid (or target-room-id (deref *active-room-id*))
        nm (str/trim (deref *name-input*))
        clean-nm (if (= nm "") "Player" nm)]
    (save-player-name! clean-nm)
    (reset! *active-room-id* rid)
    (reset! *nav-view* "board")
    (update-url-params! rid nil)
    (client/post-edn "/api/join"
      {:room-id rid
       :client-id (deref *client-id*)
       :name clean-nm
       :seat (or seat-pref "auto")}
      (fn [res]
        (when (and res (:board res))
          (reset! *game* res)
          (reset! *selected-sq* nil)
          (reset! *invalid-sq* nil)
          (reset! *feedback-msg* nil)
          (render-ui))))))

(defn reclaim-seat! [room-id color]
  "Reclaims White or Black seat when returning to an ongoing game!"
  (let [hub (deref *game*)
        rm (or (get-in hub [:rooms room-id]) (get-current-room hub))
        p-info (get-in rm [:players (if (= color "b") :b :w)])
        seat-name (or (:name p-info) (deref *name-input*))]
    (when (and seat-name (not= seat-name ""))
      (reset! *name-input* seat-name)
      (save-player-name! seat-name))
    (client/post-edn "/api/room/reclaim"
      {:room-id room-id
       :color color
       :client-id (deref *client-id*)
       :name seat-name}
      (fn [res]
        (when (and res (:board res))
          (reset! *game* res)
          (reset! *active-room-id* room-id)
          (reset! *nav-view* "board")
          (set-feedback! "info" (str "🔑 Welcome back, " seat-name "! You have reclaimed the " (if (= color "w") "White" "Black") " seat."))
          (render-ui))))))

(defn join-local-second-player! []
  (let [rid (deref *active-room-id*)
        nm (str/trim (deref *local-p2-name*))
        clean-nm (if (= nm "") "Player 2" nm)]
    (reset! *pass-and-play* true)
    (client/post-edn "/api/join"
      {:room-id rid
       :client-id (deref *local-p2-id*)
       :name clean-nm
       :seat "auto"}
      (fn [res]
        (when (and res (:board res))
          (reset! *game* res)
          (reset! *selected-sq* nil)
          (reset! *feedback-msg* {:kind "info" :text (str "🎉 " clean-nm " joined! Game started — White moves first!")})
          (render-ui))))))

(defn create-new-room! [auto-join?]
  (let [rname (str/trim (deref *new-room-name*))
        pname (str/trim (deref *name-input*))
        tc-id (deref *new-room-tc*)]
    (when (not= pname "")
      (save-player-name! pname))
    (client/post-edn "/api/room/create"
      {:name rname
       :time-control tc-id
       :client-id (deref *client-id*)
       :player-name (if (= pname "") "Player 1" pname)
       :auto-join auto-join?}
      (fn [res]
        (when (and res (:rooms res))
          (reset! *new-room-name* "")
          (reset! *game* res)
          (when (:created-room-id res)
            (open-room! (:created-room-id res)))
          (render-ui))))))

(defn delete-room! [room-id]
  (client/post-edn "/api/room/delete" {:room-id room-id}
    (fn [res]
      (when (and res (:rooms res))
        (reset! *game* res)
        (render-ui)))))

(defn create-tournament! [auto-start?]
  (let [tname (str/trim (deref *new-tourney-name*))
        fmt (deref *new-tourney-format*)
        tc-id (deref *new-tourney-tc*)
        raw-ps (str/split (deref *new-tourney-players-str*) ",")
        players (into []
                  (filter (fn [s] (not= s ""))
                          (map (fn [s] (str/trim s)) raw-ps)))]
    (client/post-edn "/api/tournament/create"
      {:name tname
       :format fmt
       :time-control tc-id
       :players (if auto-start? players [])
       :auto-start auto-start?}
      (fn [res]
        (when (and res (:tournaments res))
          (reset! *new-tourney-name* "")
          (reset! *game* res)
          (when (:tournament-id res)
            (reset! *active-tourney-id* (:tournament-id res)))
          (reset! *nav-view* "tournaments")
          (render-ui))))))

(defn join-tournament-player! [tourney-id & [custom-name]]
  (let [nm (str/trim (or custom-name (deref *tourney-join-name*) (deref *name-input*)))]
    (when (not= nm "")
      (client/post-edn "/api/tournament/join"
        {:tournament-id tourney-id
         :client-id (if custom-name (str "tp-" (sys-time-now)) (deref *client-id*))
         :name nm}
        (fn [res]
          (when (and res (:tournaments res))
            (reset! *game* res)
            (render-ui)))))))

(defn start-tournament! [tourney-id]
  (client/post-edn "/api/tournament/start" {:tournament-id tourney-id}
    (fn [res]
      (if (and res (:ok res))
        (do
          (reset! *game* res)
          (set-feedback! "info" "🏆 Tournament started! All Round 1 games are now live in parallel!")
          (render-ui))
        (set-feedback! "error" (or (:error res) "Could not start tournament."))))))

(defn delete-tournament! [tourney-id]
  (client/post-edn "/api/tournament/delete" {:tournament-id tourney-id}
    (fn [res]
      (when (and res (:rooms res))
        (reset! *game* res)
        (reset! *active-tourney-id* (first (:tournament-order res)))
        (render-ui)))))

(defn submit-move! [r1 c1 r2 c2]
  (let [hub (deref *game*)
        room (get-current-room hub)
        rid (:id room)
        actor-cid (active-client-id-for-turn room)]
    (client/post-edn "/api/move"
      {:room-id rid
       :client-id actor-cid
       :from [r1 c1]
       :to [r2 c2]
       :promote (deref *promo-piece*)}
      (fn [res]
        (if (and res (:ok res))
          (do
            (reset! *game* res)
            (reset! *selected-sq* nil)
            (reset! *invalid-sq* nil)
            (reset! *feedback-msg* nil)
            (render-ui))
          (let [err-msg (or (:error res) "⚠️ Impossible move!")]
            (reset! *invalid-sq* [r2 c2])
            (set-feedback! "error" err-msg)))))))

(defn handle-square-click [r c]
  (let [hub (deref *game*)
        st (get-current-room hub)
        status (:status st)
        role (my-role st)
        turn (:turn st)
        board (:board st)
        clicked-p (board-get board r c)
        clicked-col (piece-color clicked-p)
        sel (deref *selected-sq*)]
    (cond
      (= status "waiting")
      (set-feedback! "warn" "⏳ Waiting for 2 players to join this room before the game starts!")

      (not= status "playing")
      (set-feedback! "info" "🏁 Game over! Click 'Rematch' or switch to another room.")

      (or (= role "spectator") (= role "unjoined"))
      (set-feedback! "info" "👀 You are watching as a spectator. (If you are one of the seated players returning to the game, click '🔑 Reclaim Seat' next to your name!)")

      (and (not= role "both") (not= role turn))
      (let [opp-p (get-in st [:players (if (= turn "w") :w :b)])
            opp-name (or (:name opp-p) (if (= turn "w") "White" "Black"))]
        (set-feedback! "warn" (str "⏳ Wait for your turn! It is currently " opp-name "'s (" (if (= turn "w") "White" "Black") ") turn.")))

      (some? sel)
      (let [[sr sc] sel]
        (cond
          (and (= sr r) (= sc c))
          (do
            (reset! *selected-sq* nil)
            (reset! *invalid-sq* nil)
            (reset! *feedback-msg* nil)
            (render-ui))

          (= clicked-col turn)
          (let [ms (legal-moves-for-sq st r c)]
            (reset! *selected-sq* [r c])
            (reset! *invalid-sq* nil)
            (if (= (count ms) 0)
              (if (= (:in-check st) turn)
                (set-feedback! "warn" (str "👑 Your King is in check! This " (piece-name (piece-type clicked-p)) " on " (coord->alg r c) " has no legal moves to save your King."))
                (set-feedback! "info" (str "🔒 This " (piece-name (piece-type clicked-p)) " on " (coord->alg r c) " is blocked or pinned and has no legal moves.")))
              (do
                (reset! *feedback-msg* nil)
                (render-ui))))

          :else
          (submit-move! sr sc r c)))

      :else
      (cond
        (= clicked-p "")
        (do
          (reset! *invalid-sq* nil)
          (set-feedback! "info" (str "👆 Select one of your " (if (= turn "w") "White" "Black") " pieces to see its possible moves!")))

        (not= clicked-col turn)
        (do
          (reset! *invalid-sq* [r c])
          (set-feedback! "error" (str "⚠️ Impossible selection: The " (piece-name (piece-type clicked-p)) " on " (coord->alg r c) " belongs to your opponent!")))

        :else
        (let [ms (legal-moves-for-sq st r c)]
          (reset! *selected-sq* [r c])
          (reset! *invalid-sq* nil)
          (if (= (count ms) 0)
            (if (= (:in-check st) turn)
              (set-feedback! "warn" (str "👑 Your King is in check! This " (piece-name (piece-type clicked-p)) " on " (coord->alg r c) " has no legal moves to resolve check."))
              (set-feedback! "info" (str "🔒 This " (piece-name (piece-type clicked-p)) " on " (coord->alg r c) " is blocked or pinned and has no legal moves.")))
            (do
              (reset! *feedback-msg* nil)
              (render-ui))))))))

(defn resign-game! []
  (let [hub (deref *game*)
        room (get-current-room hub)
        actor-cid (active-client-id-for-turn room)]
    (client/post-edn "/api/resign" {:room-id (:id room) :client-id actor-cid}
      (fn [res]
        (when (and res (:board res))
          (reset! *game* res)
          (reset! *selected-sq* nil)
          (render-ui))))))

(defn start-new-game! [keep-players?]
  (when (not keep-players?)
    (reset! *pass-and-play* false))
  (let [rid (deref *active-room-id*)]
    (client/post-edn "/api/new-game" {:room-id rid :keep-players keep-players?}
      (fn [res]
        (when (and res (:board res))
          (reset! *game* res)
          (reset! *selected-sq* nil)
          (reset! *invalid-sq* nil)
          (reset! *feedback-msg* nil)
          (render-ui))))))

;; ── 7. Component Renderers: Active Game Resume Bar, Rooms & Tournaments ─────

(defn render-active-games-resume-bar [hub]
  "Pinned bar at the top showing any ongoing games the user is seated in so they can
   always come back to their game with 1 click!"
  (let [my-rooms (find-my-active-rooms hub)
        cur-rid (deref *active-room-id*)
        cur-view (deref *nav-view*)]
    (if (empty? my-rooms)
      [:span {} ""]
      [:div {:class "resume-games-bar"}
        [:div {:class "resume-bar-label"}
          [:span {:class "pulse-dot"}]
          [:strong {} (str "⚡ Your Active Game" (if (> (count my-rooms) 1) "s" "") " (" (count my-rooms) "):")]]
        (into [:div {:class "resume-pills-list"}]
          (map (fn [rm]
                 (let [rid (:id rm)
                       wp (get-in rm [:players :w])
                       bp (get-in rm [:players :b])
                       am-w? (player-matches-me? wp)
                       my-col (if am-w? "w" "b")
                       my-turn? (and (= (:status rm) "playing") (= (:turn rm) my-col))
                       is-viewing? (and (= cur-view "board") (= cur-rid rid))]
                   [:button {:class (str "resume-game-pill"
                                         (if my-turn? " my-turn-glow" "")
                                         (if is-viewing? " active-viewing" ""))
                             :on-click (fn [_] (open-room! rid true))}
                     [:span {} (if (= (:kind rm) "tournament") "🏆 " "🎲 ")]
                     [:strong {} (:name rm)]
                     [:span {:class "resume-vs"}
                       (str " (" (or (:name wp) "Open") " vs " (or (:name bp) "Open") ")")]
                     (cond
                       my-turn?
                       [:span {:class "resume-turn-tag turn-urgent"} "✨ YOUR TURN!"]

                       (= (:status rm) "waiting")
                       [:span {:class "resume-turn-tag"} "⏳ Waiting for Opponent"]

                       :else
                       [:span {:class "resume-turn-tag"} "👀 Opponent's Turn"])
                     [:span {:class "resume-cta"} (if is-viewing? "📍 Viewing" "▶️ Come Back")]]))
               my-rooms))])))

(defn render-room-card [rm]
  (let [rid (:id rm)
        status (:status rm)
        wp (get-in rm [:players :w])
        bp (get-in rm [:players :b])
        specs (or (:spectators rm) [])
        moves-cnt (count (or (:history rm) []))
        is-tourney? (= (:kind rm) "tournament")
        my-seat? (or (player-matches-me? wp) (player-matches-me? bp))
        tc (or (:time-control rm) {:label "10+5" :enabled true})
        clks (:clocks rm)]
    [:div {:class (str "room-card"
                       (if is-tourney? " room-card-tourney" "")
                       (if my-seat? " room-card-mine" ""))}
      [:div {:class "room-card-header"}
        [:div {:class "room-card-title-row"}
          [:strong {:class "room-card-name"} (:name rm)]
          [:span {:class "tc-mini-badge"} (str "⏱️ " (or (:label tc) "10+5"))]
          (if is-tourney?
            [:span {:class "tourney-tag"} (or (:round-label rm) "Tournament")]
            [:span {:class "casual-tag"} "1 Room = 1 Game"])]
        [:span {:class (str "status-badge status-" status)}
          (cond
            (= status "waiting") "⏳ Waiting for Players"
            (= status "playing") (str "🟢 Live • " (if (= (:turn rm) "w") "White's Turn" "Black's Turn"))
            (= status "checkmate") (str "👑 Checkmate • " (:winner-name rm))
            (= status "timeout") (str "⏰ Time Out • " (:winner-name rm))
            (= status "stalemate") "🤝 Stalemate"
            :else "🏁 Finished")]]

      ;; Mini 2D Board + Matchup Info Side-by-Side
      [:div {:class "room-card-body"}
        (render-mini-chessboard rm (fn [] (open-room! rid true)))

        [:div {:class "room-card-matchup"}
          [:div {:class "matchup-player"}
            [:span {:class "color-pill pill-w"} "♔ White"]
            [:strong {} (if wp (:name wp) "Open Seat")]
            (if (:enabled tc)
              [:span {:class "mini-clock-pill"} (format-clock-ms (:w-ms clks))]
              [:span {} ""])
            (if (and (= status "playing") (= (:turn rm) "w"))
              [:span {:class "mini-turn-dot"} "●"]
              [:span {} ""])]

          [:div {:class "matchup-vs"} "— VS —"]

          [:div {:class "matchup-player"}
            [:span {:class "color-pill pill-b"} "♚ Black"]
            [:strong {} (if bp (:name bp) "Open Seat")]
            (if (:enabled tc)
              [:span {:class "mini-clock-pill"} (format-clock-ms (:b-ms clks))]
              [:span {} ""])
            (if (and (= status "playing") (= (:turn rm) "b"))
              [:span {:class "mini-turn-dot"} "●"]
              [:span {} ""])]

          [:div {:class "room-card-meta"}
            [:span {} (str "📜 " moves-cnt " moves")]
            [:span {} (str "👀 " (count specs) " watching")]
            (if (:in-check rm)
              [:span {:class "check-mini-alert"} "🚨 CHECK!"]
              [:span {} ""])]]]

      ;; Action Buttons
      [:div {:class "room-card-footer"}
        (cond
          my-seat?
          [:button {:class "btn btn-join"
                    :on-click (fn [_] (open-room! rid true))}
            "▶️ Come Back to Your Game!"]

          (= status "waiting")
          [:button {:class "btn btn-join"
                    :on-click (fn [_] (join-game! "auto" rid))}
            (if (nil? wp) "♔ Join Room as Player 1" "♚ Join as Player 2 & Start!")]

          :else
          [:button {:class "btn btn-secondary"
                    :on-click (fn [_] (open-room! rid false))}
            "👀 Watch Ongoing Game"])

        (if (and (not is-tourney?) (not= rid "room-paw-1"))
          [:button {:class "btn btn-danger-soft"
                    :on-click (fn [_] (delete-room! rid))}
            "🗑️"]
          [:span {} ""])]]))

(defn render-rooms-lobby-view [hub]
  (let [rooms (get-room-map hub)
        r-order (or (:room-order hub) (keys rooms))
        all-rooms (into [] (filter (fn [x] (some? x)) (map (fn [id] (get rooms id)) r-order)))
        casual-rooms (into [] (filter (fn [r] (not= (:kind r) "tournament")) all-rooms))
        tourney-rooms (into [] (filter (fn [r] (= (:kind r) "tournament")) all-rooms))]
    [:div {:class "lobby-hub-container"}
      ;; Create New Room Bar
      [:div {:class "lobby-card create-room-bar"}
        [:div {}
          [:h2 {:class "lobby-title"} "🚪 Game Rooms (One Room = One Game)"]
          [:p {:class "lobby-desc"}
            "Pick an open room below to play, watch any ongoing game live, or create a brand new room with your chosen official time control!"]]
        [:div {:class "join-form-row"}
          [:input {:type "text"
                   :class "cute-input"
                   :placeholder "Your Player Name..."
                   :value (deref *name-input*)
                   :on-input (fn [e]
                               (let [v (js/get (js/get e "target") "value")]
                                 (reset! *name-input* v)
                                 (save-player-name! v)))}]
          [:input {:type "text"
                   :class "cute-input"
                   :placeholder "New Room Name (e.g. Matcha Table)..."
                   :value (deref *new-room-name*)
                   :on-input (fn [e] (reset! *new-room-name* (js/get (js/get e "target") "value")))
                   :on-keydown (fn [e]
                                 (when (= (js/get e "key") "Enter")
                                   (reset! *new-room-name* (js/get (js/get e "target") "value"))
                                   (create-new-room! true)))}]
          [:select {:class "cute-input"
                    :value (deref *new-room-tc*)
                    :on-change (fn [e] (reset! *new-room-tc* (js/get (js/get e "target") "value")))}
            (into [:optgroup {:label "⏱️ Official FIDE & Online Timers"}]
              (map (fn [p]
                     [:option {:value (:id p)} (str "⏱️ " (:short p) " — " (:desc p))])
                   official-tc-presets))]
          [:button {:class "btn btn-join"
                    :on-click (fn [_] (create-new-room! true))}
            "➕ Create Room & Sit"]]]

      ;; Casual Rooms Grid
      [:div {:class "rooms-grid"}
        (into [:div {:class "rooms-grid-inner"}]
          (map render-room-card casual-rooms))]

      ;; If there are active tournament rooms, also show a quick section linking to Tournament Arena!
      (if (not (empty? tourney-rooms))
        [:div {:class "tourney-rooms-section"}
          [:div {:class "section-hdr-row"}
            [:h3 {:class "lobby-title"} (str "🏆 Ongoing Tournament Match Rooms (" (count tourney-rooms) " Parallel Games)")]
            [:button {:class "btn btn-outline"
                      :on-click (fn [_] (reset! *nav-view* "tournaments") (render-ui))}
              "🏆 Open Full Tournament Bracket & Parallel View →"]]
          (into [:div {:class "rooms-grid-inner"}]
            (map render-room-card tourney-rooms))]
        [:span {} ""])]))

;; ── 8. Parallel Tournament Studio View ──────────────────────────────────────

(defn render-tournament-detail [hub tourney]
  (let [tid (:id tourney)
        status (:status tourney)
        fmt (:format tourney)
        tc (or (:time-control tourney) {:label "Blitz 5+3" :enabled true})
        players (or (:players tourney) [])
        matches (or (:matches tourney) [])
        rooms (get-room-map hub)
        ongoing-matches (into [] (filter (fn [m] (= (:status m) "playing")) matches))
        completed-matches (into [] (filter (fn [m] (= (:status m) "completed")) matches))]
    [:div {:class "tourney-detail-box"}
      ;; Tournament Header Banner
      [:div {:class "lobby-card tourney-hero-card"}
        [:div {:class "tourney-hero-top"}
          [:div {}
            [:div {:style "display:flex;gap:8px;flex-wrap:wrap;align-items:center;"}
              [:span {:class "lobby-badge"}
                (cond
                  (= fmt "knockout-4") "⚔️ 4-Player Knockout Bracket (Parallel Rounds)"
                  (= fmt "knockout-8") "⚔️ 8-Player Knockout Bracket (Parallel Rounds)"
                  :else "🔁 Round-Robin League (All Games in Parallel)")]
              [:span {:class "tc-mini-badge"} (str "⏱️ Official Timer: " (or (:label tc) "5+3"))]]
            [:h2 {:class "lobby-title"} (:name tourney)]
            [:p {:class "lobby-desc"}
              (cond
                (= status "registration")
                (str "Registration Open (" (count players) "/" (:target-size tourney) " players). Add players below and click Start to launch all Round 1 games in parallel!")

                (= status "playing")
                (str "🟢 Tournament in Progress — " (count ongoing-matches) " game(s) currently playing in parallel, " (count completed-matches) " completed!")

                :else
                (str "👑 Tournament Completed! Champion: " (or (:champion tourney) "Decided") "!"))]]

          [:div {:class "tourney-hero-actions"}
            (if (= status "completed")
              [:div {:class "champion-trophy-pill"}
                (str "🏆 Champion: " (:champion tourney))]
              [:span {} ""])
            [:button {:class "btn btn-danger-soft"
                      :on-click (fn [_] (delete-tournament! tid))}
              "🗑️ Delete Tournament"]]]

        ;; Registration Controls (when status == "registration")
        (if (= status "registration")
          [:div {:class "tourney-reg-box"}
            [:div {:class "reg-players-list"}
              [:strong {} "Registered Players: "]
              (if (empty? players)
                [:span {:class "empty-specs"} "No players registered yet."]
                (into [:div {:class "spec-pills"}]
                  (map (fn [p] [:span {:class "spec-pill"} (str "♟️ " (:name p))]) players)))]
            [:div {:class "join-form-row"}
              [:input {:type "text"
                       :class "cute-input"
                       :placeholder "Player name to add..."
                       :value (deref *tourney-join-name*)
                       :on-input (fn [e] (reset! *tourney-join-name* (js/get (js/get e "target") "value")))
                       :on-keydown (fn [e]
                                     (when (= (js/get e "key") "Enter")
                                       (let [v (js/get (js/get e "target") "value")]
                                         (reset! *tourney-join-name* "")
                                         (join-tournament-player! tid v))))}]
              [:button {:class "btn btn-secondary"
                        :on-click (fn [_]
                                    (let [v (deref *tourney-join-name*)]
                                      (reset! *tourney-join-name* "")
                                      (join-tournament-player! tid v)))}
                "➕ Add Player to Roster"]
              [:button {:class "btn btn-join"
                        :on-click (fn [_] (start-tournament! tid))}
                "🚀 Start Tournament (Launch Parallel Games!)"]]]
          [:span {} ""])]

      ;; ── SECTION A: LIVE PARALLEL GAMES MULTI-BOARD MONITOR ───────────────
      (if (not= status "registration")
        [:div {:class "parallel-boards-section"}
          [:div {:class "section-hdr-row"}
            [:h3 {:class "lobby-title"}
              (str "📺 Live Tournament Games (Played in Parallel — " (count ongoing-matches) " Active / " (count matches) " Total)")]
            [:span {:class "lobby-badge"} "Live Real-Time WebSocket Multiplex View"]]

          (into [:div {:class "parallel-boards-grid"}]
            (map (fn [m]
                   (let [rid (:room-id m)
                         rm (when rid (or (get rooms rid) (get rooms (keyword rid))))
                         m-status (if rm (:status rm) (:status m))
                         p1 (:p1 m)
                         p2 (:p2 m)
                         my-match? (or (player-matches-me? p1) (player-matches-me? p2))
                         moves-cnt (if rm (count (or (:history rm) [])) 0)
                         clks (when rm (:clocks rm))
                         rm-tc (when rm (:time-control rm))]
                     [:div {:class (str "parallel-match-card"
                                        (if (= m-status "playing") " match-live" "")
                                        (if (= m-status "completed") " match-done" "")
                                        (if my-match? " match-mine" ""))}
                       [:div {:class "pm-header"}
                         [:span {:class "pm-round-tag"} (:label m)]
                         [:span {:class (str "status-badge status-" m-status)}
                           (cond
                             (= m-status "playing")
                             (str "🟢 Live • " (if (= (:turn rm) "w") "White's Turn" "Black's Turn"))

                             (or (= m-status "completed") (= m-status "checkmate") (= m-status "resigned") (= m-status "timeout"))
                             (str "✅ Winner: " (or (:winner m) (:winner-name rm)))

                             :else "⏳ Waiting for Previous Round")]]

                       ;; Players Bar with Live Mini Clocks
                       [:div {:class "pm-players-row"}
                         [:div {:class (str "pm-player" (if (and rm (= (:turn rm) "w") (= m-status "playing")) " pm-turn" ""))}
                           [:span {:class "color-pill pill-w"} "♔"]
                           [:strong {} (if p1 (:name p1) "TBD")]
                           (if (and rm-tc (:enabled rm-tc))
                             [:span {:class "mini-clock-pill"} (format-clock-ms (:w-ms clks))]
                             [:span {} ""])]
                         [:span {:class "pm-vs"} "vs"]
                         [:div {:class (str "pm-player" (if (and rm (= (:turn rm) "b") (= m-status "playing")) " pm-turn" ""))}
                           [:span {:class "color-pill pill-b"} "♚"]
                           [:strong {} (if p2 (:name p2) "TBD")]
                           (if (and rm-tc (:enabled rm-tc))
                             [:span {:class "mini-clock-pill"} (format-clock-ms (:b-ms clks))]
                             [:span {} ""])]]

                       ;; Live 2D Mini-Board!
                       (if rm
                         [:div {:class "pm-board-wrap"}
                           (render-mini-chessboard rm (fn [] (open-room! rid true)))
                           [:div {:class "pm-board-meta"}
                             [:span {} (str "Move #" moves-cnt)]
                             (if (:last-move rm)
                               [:span {:class "pm-last-move"} (str "Last: " (:notation (:last-move rm)))]
                               [:span {} "Opening"])
                             (if (:in-check rm)
                               [:span {:class "check-mini-alert"} "🚨 CHECK!"]
                               [:span {} ""])]]
                         [:div {:class "pm-pending-box"}
                           "⏳ Match room will spawn automatically as soon as both players advance!"])

                       ;; Action Button to Open Full Board
                       (if rm
                         [:div {:class "pm-footer"}
                           [:button {:class (str "btn " (if my-match? "btn-join" "btn-secondary") " btn-full")
                                     :on-click (fn [_] (open-room! rid true))}
                             (cond
                               (and my-match? (= m-status "playing")) "▶️ Enter & Play Your Tournament Match!"
                               (= m-status "playing") "🔍 Watch Full Board Live"
                               :else "📜 Inspect Final Board & Moves")]]
                         [:span {} ""])]))
                 matches))]
        [:span {} ""])

      ;; ── SECTION B: ROUND-ROBIN STANDINGS TABLE ───────────────────────────
      (if (and (not= status "registration") (= fmt "round-robin"))
        [:div {:class "lobby-card standings-card"}
          [:h3 {:class "lobby-title"} "📊 Round-Robin Live Standings"]
          [:div {:class "standings-table"}
            [:div {:class "st-row st-head"}
              [:span {} "#"]
              [:span {} "Player"]
              [:span {} "Played"]
              [:span {} "W / D / L"]
              [:span {} "Points"]]
            (into [:div {:class "st-body"}]
              (loop [rows (or (:standings tourney) []) idx 0 acc []]
                (if (empty? rows)
                  acc
                  (let [row (first rows)]
                    (recur (rest rows)
                           (+ idx 1)
                           (conj acc
                                 [:div {:class "st-row"}
                                   [:strong {} (str (+ idx 1))]
                                   [:strong {} (:name row)]
                                   [:span {} (str (:played row))]
                                   [:span {} (str (:wins row) " / " (:draws row) " / " (:losses row))]
                                   [:span {:class "st-pts"} (str (:points row) " pt")]]))))))]]
        [:span {} ""])]))

(defn render-tournaments-view [hub]
  (let [tournaments (or (:tournaments hub) {})
        t-order (or (:tournament-order hub) (keys tournaments))
        all-tourneys (into [] (filter (fn [x] (some? x)) (map (fn [id] (get tournaments id)) t-order)))
        sel-tid (or (deref *active-tourney-id*) (:id (first all-tourneys)))
        active-t (when sel-tid (or (get tournaments sel-tid) (first all-tourneys)))]
    [:div {:class "tourney-studio-container"}
      ;; Create New Tournament Card
      [:div {:class "lobby-card create-tourney-card"}
        [:div {}
          [:h2 {:class "lobby-title"} "🏆 Parallel Chess Tournaments"]
          [:p {:class "lobby-desc"}
            "Launch a Knockout Bracket or Round-Robin tournament with Official FIDE/Fischer clocks! All matches in a round run in parallel rooms."]]
        [:div {:class "tourney-create-grid"}
          [:input {:type "text"
                   :class "cute-input"
                   :placeholder "Tournament Name (e.g. Cozy Sunday Cup)..."
                   :value (deref *new-tourney-name*)
                   :on-input (fn [e] (reset! *new-tourney-name* (js/get (js/get e "target") "value")))}]
          [:select {:class "cute-input"
                    :value (deref *new-tourney-format*)
                    :on-change (fn [e]
                                 (let [v (js/get (js/get e "target") "value")]
                                   (reset! *new-tourney-format* v)
                                   (when (= v "knockout-8")
                                     (reset! *new-tourney-players-str* "Mochi, Boba, Kiki, Yuzu, Sora, Toto, Nori, Pocky"))
                                   (when (= v "knockout-4")
                                     (reset! *new-tourney-players-str* "Mochi, Boba, Kiki, Yuzu"))
                                   (render-ui)))}
            [:option {:value "knockout-4"} "⚔️ 4-Player Knockout (2 Semifinals in Parallel -> Final)"]
            [:option {:value "knockout-8"} "⚔️ 8-Player Knockout (4 Quarterfinals in Parallel -> SF -> Final)"]
            [:option {:value "round-robin"} "🔁 Round-Robin League (All Pairings in Parallel)"]]
          [:select {:class "cute-input"
                    :value (deref *new-tourney-tc*)
                    :on-change (fn [e] (reset! *new-tourney-tc* (js/get (js/get e "target") "value")))}
            (into [:optgroup {:label "⏱️ Tournament Time Control"}]
              (map (fn [p]
                     [:option {:value (:id p)} (str "⏱️ " (:short p) " — " (:desc p))])
                   official-tc-presets))]
          [:input {:type "text"
                   :class "cute-input"
                   :placeholder "Players (comma-separated, e.g. Mochi, Boba, Kiki, Yuzu)..."
                   :value (deref *new-tourney-players-str*)
                   :on-input (fn [e] (reset! *new-tourney-players-str* (js/get (js/get e "target") "value")))}]
          [:div {:class "join-form-row"}
            [:button {:class "btn btn-join"
                      :on-click (fn [_] (create-tournament! true))}
              "🚀 Create & Start Parallel Games Now!"]
            [:button {:class "btn btn-outline"
                      :on-click (fn [_] (create-tournament! false))}
              "📋 Create Open Registration Lobby"]]]]

      ;; Tournament Selector Tabs (if multiple tournaments exist)
      (if (> (count all-tourneys) 1)
        (into [:div {:class "tourney-tabs-bar"}]
          (map (fn [t]
                 [:button {:class (str "btn " (if (= (:id t) (:id active-t)) "btn-join" "btn-outline"))
                           :on-click (fn [_] (open-tournament! (:id t)))}
                   (str "🏆 " (:name t) " (" (:status t) ")")])
               all-tourneys))
        [:span {} ""])

      ;; Active Tournament Detail + Parallel Boards Grid
      (if active-t
        (render-tournament-detail hub active-t)
        [:div {:class "lobby-card empty-tourney-msg"}
          "No active tournament yet! Click '🚀 Create & Start Parallel Games Now!' above to launch a tournament with parallel live boards."])]))

;; ── 9. Active Board View Renderers (with Official Clocks & Timer Picker) ───

(defn render-time-control-bar [st]
  "Official FIDE & Online Chess Timer Selector Bar (30, 15, 10, 5, 3, 1 min + increment seconds)"
  (let [tc (or (:time-control st) {:id "10+5" :label "Rapid 10+5" :category "Rapid" :base-min 10 :inc-sec 5 :enabled true})
        cur-id (:id tc)
        custom-open? (deref *show-custom-tc*)]
    [:div {:class "tc-bar-card"}
      [:div {:class "tc-bar-top"}
        [:div {:class "tc-current-info"}
          [:span {:class "tc-icon"} "⏱️"]
          [:div {}
            [:div {:class "tc-title-line"}
              [:strong {} (str "Timer: " (:label tc))]
              [:span {:class (str "tc-cat-pill tc-cat-" (str/lower-case (or (:category tc) "rapid")))}
                (or (:category tc) "Rapid")]
              (if (and (:enabled tc) (> (or (:inc-sec tc) 0) 0))
                [:span {:class "tc-inc-note"} (str "(+" (:inc-sec tc) "s added after every move)")]
                [:span {} ""])]]]

        ;; 1-Click Official Presets (30, 15, 10, 5, 3, 1 min + Fischer increments)
        [:div {:class "tc-preset-pills"}
          (into [:div {:class "tc-pills-wrap"}]
            (map (fn [p]
                   (let [active? (= cur-id (:id p))]
                     [:button {:class (str "tc-pill-btn" (if active? " active" ""))
                               :title (:desc p)
                               :on-click (fn [_] (set-room-time-control! (:id p)))}
                       (:short p)]))
                 official-tc-presets))
          [:button {:class (str "tc-pill-btn tc-custom-toggle" (if custom-open? " active" ""))
                    :on-click (fn [_]
                                (swap! *show-custom-tc* not)
                                (render-ui))}
            "⚙️ Custom (Min + Sec)"]]]

      ;; Expandable Custom Timer Builder: Base (30, 15, 10, 5, 3, 1 min) + Increment (+0..+30s)
      (if custom-open?
        [:div {:class "tc-custom-drawer"}
          [:div {:class "tc-custom-group"}
            [:span {:class "tc-custom-label"} "Minutes per Player:"]
            (into [:div {:class "tc-choice-row"}]
              (map (fn [m]
                     [:button {:class (str "tc-choice-btn" (if (= (deref *custom-base-min*) m) " active" ""))
                               :on-click (fn [_] (reset! *custom-base-min* m) (render-ui))}
                       (str m " min")])
                   base-min-choices))]
          [:div {:class "tc-custom-group"}
            [:span {:class "tc-custom-label"} "Increment (+ sec / move):"]
            (into [:div {:class "tc-choice-row"}]
              (map (fn [s]
                     [:button {:class (str "tc-choice-btn" (if (= (deref *custom-inc-sec*) s) " active" ""))
                               :on-click (fn [_] (reset! *custom-inc-sec* s) (render-ui))}
                       (str "+" s "s")])
                   inc-sec-choices))]
          [:button {:class "btn btn-join btn-sm"
                    :on-click (fn [_]
                                (set-room-time-control!
                                  "custom"
                                  (deref *custom-base-min*)
                                  (deref *custom-inc-sec*)))}
            (str "✅ Apply " (deref *custom-base-min*) "+" (deref *custom-inc-sec*) " Timer")]]
        [:span {} ""])]))

(defn render-captured-row [pieces]
  (if (empty? pieces)
    [:span {:class "no-captures"} "No captures yet"]
    (into [:div {:class "captured-pieces"}]
      (map (fn [p]
             [:div {:class "mini-captured-piece" :title (piece-name (piece-type p))}
               (render-piece-svg p "normal" "mini-piece-svg")])
           pieces))))

(defn render-player-bar [st color]
  (let [rid (:id st)
        p-info (get-in st [:players (if (= color "w") :w :b)])
        p-name (if p-info (:name p-info) (str "Waiting for " (if (= color "w") "White" "Black") "..."))
        is-turn? (and (= (:status st) "playing") (= (:turn st) color))
        in-chk? (= (:in-check st) color)
        is-winner? (= (:winner st) color)
        cid (deref *client-id*)
        is-me? (and p-info (or (= (:id p-info) cid) (= (:id p-info) (deref *local-p2-id*))))
        captures (if (= color "w") (or (:captured-by-w st) []) (or (:captured-by-b st) []))
        avatar-piece (str color "K")
        tc (or (:time-control st) {:enabled false :inc-sec 0})
        clks (:clocks st)
        rem-ms (if (= color "w") (:w-ms clks) (:b-ms clks))
        low-time? (and (:enabled tc) rem-ms (< rem-ms 30000) (> rem-ms 0))
        flagged? (and (:enabled tc) rem-ms (<= rem-ms 0))
        king-face (cond
                    (and (or (= (:status st) "checkmate") (= (:status st) "timeout"))
                         (not= (:winner st) color)) "checkmate"
                    in-chk? "check"
                    :else "normal")]
    [:div {:class (str "player-bar"
                       (if is-turn? " active-turn" "")
                       (if in-chk? " in-check-bar" "")
                       (if is-winner? " winner-bar" ""))}
      [:div {:class "player-identity"}
        [:div {:class (str "player-avatar " (if (= color "w") "avatar-w" "avatar-b"))}
          (render-piece-svg avatar-piece king-face "avatar-svg")]
        [:div {:class "player-details"}
          [:div {:class "player-name-row"}
            [:span {:class "player-name"} p-name]
            [:span {:class (str "color-pill " (if (= color "w") "pill-w" "pill-b"))}
              (if (= color "w") "♔ White" "♚ Black")]
            (if is-me?
              [:span {:class "you-badge"} "You"]
              (if p-info
                [:button {:class "reclaim-btn"
                          :title "Reconnecting from a new tab or device? Click to reclaim this player's seat!"
                          :on-click (fn [_] (reclaim-seat! rid color))}
                  "🔑 Reclaim Seat"]
                [:span {} ""]))]
          (render-captured-row captures)]]

      [:div {:class "player-status-area"}
        ;; Official Digital Fischer Chess Clock
        (if (:enabled tc)
          [:div {:class (str "chess-clock-box"
                             (if is-turn? " clock-running" "")
                             (if low-time? " clock-low-time" "")
                             (if flagged? " clock-flagged" ""))}
            [:span {:class "clock-icon"} (if flagged? "⏰" (if is-turn? "⏱️" "🕒"))]
            [:span {:class "clock-digits"} (format-clock-ms rem-ms)]
            (if (> (or (:inc-sec tc) 0) 0)
              [:span {:class "clock-inc-tag"} (str "+" (:inc-sec tc) "s")]
              [:span {} ""])]
          [:div {:class "chess-clock-box clock-unlimited"}
            [:span {:class "clock-digits"} "∞ No Timer"]])

        (cond
          is-winner?
          [:span {:class "turn-pill winner-pill"} "🏆 Winner!"]

          flagged?
          [:span {:class "turn-pill check-pill"} "⏰ Flagged!"]

          in-chk?
          [:span {:class "turn-pill check-pill"} "🚨 IN CHECK!"]

          is-turn?
          [:span {:class "turn-pill thinking-pill"} "✨ Turn to Move"]

          (= (:status st) "waiting")
          [:span {:class "turn-pill waiting-pill"} (if p-info "✅ Ready" "⏳ Open Seat")]

          :else
          [:span {:class "turn-pill idle-pill"} "Waiting"])]]))

(defn render-chessboard [st]
  (let [board (:board st)
        role (my-role st)
        manual-flip (deref *flip-board*)
        flipped? (if (nil? manual-flip)
                   (= role "b")
                   manual-flip)
        rows (if flipped? [7 6 5 4 3 2 1 0] [0 1 2 3 4 5 6 7])
        cols (if flipped? [7 6 5 4 3 2 1 0] [0 1 2 3 4 5 6 7])
        sel (deref *selected-sq*)
        inv-sq (deref *invalid-sq*)
        sel-moves (if sel
                    (legal-moves-for-sq st (nth sel 0) (nth sel 1))
                    [])
        last-m (:last-move st)
        in-chk-col (:in-check st)
        status (:status st)]
    [:div {:class "board-frame"}
      (into [:div {:class "board-grid"}]
        (loop [rs rows acc []]
          (if (empty? rs)
            acc
            (let [r (first rs)
                  row-squares
                  (loop [cs cols r-acc []]
                    (if (empty? cs)
                      r-acc
                      (let [c (first cs)
                            light? (= (rem (+ r c) 2) 0)
                            p (board-get board r c)
                            pcol (piece-color p)
                            ptype (piece-type p)
                            selected? (and sel (= (nth sel 0) r) (= (nth sel 1) c))
                            invalid? (and inv-sq (= (nth inv-sq 0) r) (= (nth inv-sq 1) c))
                            legal-m (first (filter (fn [m]
                                                     (let [[tr tc] (:to m)]
                                                       (and (= tr r) (= tc c))))
                                                   sel-moves))
                            is-legal-dest? (some? legal-m)
                            is-capture-dest? (and legal-m
                                                  (or (= (:kind legal-m) "capture")
                                                      (= (:kind legal-m) "en-passant")
                                                      (not= p "")))
                            is-castle-dest? (and legal-m
                                                 (or (= (:kind legal-m) "castle-k")
                                                     (= (:kind legal-m) "castle-q")))
                            is-last-from? (and last-m
                                               (= (nth (:from last-m) 0) r)
                                               (= (nth (:from last-m) 1) c))
                            is-last-to? (and last-m
                                             (= (nth (:to last-m) 0) r)
                                             (= (nth (:to last-m) 1) c))
                            is-checked-king? (and (= ptype "K")
                                                  (or (= in-chk-col pcol)
                                                      (and (or (= status "checkmate") (= status "timeout"))
                                                           (not= (:winner st) pcol))))
                            king-face-mode (cond
                                             (and (or (= status "checkmate") (= status "timeout"))
                                                  (= ptype "K")
                                                  (not= (:winner st) pcol)) "checkmate"
                                             is-checked-king? "check"
                                             :else "normal")
                            show-rank? (= c (first cols))
                            show-file? (= r (last rows))
                            sq-classes (str "chess-sq "
                                            (if light? "sq-light" "sq-dark")
                                            (if selected? " sq-selected" "")
                                            (if is-legal-dest? " sq-legal" "")
                                            (if is-capture-dest? " sq-capture" "")
                                            (if invalid? " sq-invalid" "")
                                            (if (or is-last-from? is-last-to?) " sq-last-move" "")
                                            (if is-checked-king? " sq-king-check" ""))]
                        (recur (rest cs)
                               (conj r-acc
                                     [:div {:class sq-classes
                                            :data-sq (coord->alg r c)
                                            :on-click (fn [_] (handle-square-click r c))}
                                       (if show-rank?
                                         [:span {:class "coord-rank"} (str (- 8 r))]
                                         [:span {} ""])
                                       (if show-file?
                                         [:span {:class "coord-file"} (nth file-labels c)]
                                         [:span {} ""])

                                       (if (not= p "")
                                         [:div {:class "piece-holder"}
                                           (render-piece-svg p king-face-mode "piece-svg")]
                                         [:span {} ""])

                                       (cond
                                         is-capture-dest?
                                         [:div {:class "legal-capture-ring"}
                                           [:span {:class "capture-badge"} "⚔️"]]

                                         is-castle-dest?
                                         [:div {:class "legal-move-dot castle-dot"}
                                           [:span {:class "castle-tag"} "🏰"]]

                                         is-legal-dest?
                                         [:div {:class "legal-move-dot"}]

                                         :else
                                         [:span {} ""])])))))]
              (recur (rest rs) (into acc row-squares))))))]))

(defn render-lobby-or-status-card [st]
  (let [rid (:id st)
        status (:status st)
        role (my-role st)
        wp (get-in st [:players :w])
        bp (get-in st [:players :b])
        is-tourney? (= (:kind st) "tournament")]
    (cond
      (and (= status "waiting") (= role "unjoined"))
      [:div {:class "lobby-card join-card"}
        [:div {:class "lobby-badge"}
          (if (and (nil? wp) (nil? bp))
            (str "🌱 " (:name st) " — Waiting for 2 Players (0/2 Joined)")
            (str "👋 1/2 Joined in " (:name st) " — " (:name (or wp bp)) " is waiting for an opponent!"))]
        [:h3 {:class "lobby-title"} (str "Enter Your Name to Join " (:name st))]
        [:p {:class "lobby-desc"}
          (if (nil? wp)
            "No game in progress in this room yet! Enter your name below to take Seat #1 (White)."
            (str (:name wp) " is seated as White. Enter your name below to join as Black and start the game immediately!"))]
        [:div {:class "join-form-row"}
          [:input {:type "text"
                   :class "cute-input"
                   :placeholder "Your name (e.g. Mochi)..."
                   :value (deref *name-input*)
                   :on-input (fn [e] (reset! *name-input* (js/get (js/get e "target") "value")))
                   :on-keydown (fn [e]
                                 (when (= (js/get e "key") "Enter")
                                   (reset! *name-input* (js/get (js/get e "target") "value"))
                                   (join-game! "auto" rid)))}]
          [:button {:class "btn btn-join"
                    :on-click (fn [_] (join-game! "auto" rid))}
            (if (nil? wp) "♔ Join as Player 1" "♚ Join & Start Game!")]]]

      (and (= status "waiting") (or (= role "w") (= role "b")))
      [:div {:class "lobby-card waiting-card"}
        [:div {:class "waiting-Header"}
          [:span {:class "pulse-dot"}]
          [:strong {} (str "Hello " (:name (if (= role "w") wp bp)) "! Waiting for 2nd player in " (:name st) "...")]]
        [:p {:class "lobby-desc"}
          "Share this room or have the 2nd player open this room on their browser — or add Player 2 on this screen below:"]
        [:div {:class "local-p2-box"}
          [:input {:type "text"
                   :class "cute-input input-sm"
                   :placeholder "2nd player's name (same screen)..."
                   :value (deref *local-p2-name*)
                   :on-input (fn [e] (reset! *local-p2-name* (js/get (js/get e "target") "value")))
                   :on-keydown (fn [e]
                                 (when (= (js/get e "key") "Enter")
                                   (reset! *local-p2-name* (js/get (js/get e "target") "value"))
                                   (join-local-second-player!)))}]
          [:button {:class "btn btn-secondary"
                    :on-click (fn [_] (join-local-second-player!))}
            "🎮 Add 2nd Player Here"]]]

      (and (= status "playing") (= role "spectator"))
      [:div {:class "lobby-card spectator-card"}
        [:div {:class "spectator-banner"}
          [:span {:class "spec-icon"} "👀"]
          [:div {}
            [:strong {} (str "Watching " (:name st) ": " (:name wp) " (White) vs " (:name bp) " (Black)")]
            [:p {:class "lobby-desc"}
              "Are you one of the seated players returning to this game? Click '🔑 Reclaim Seat' next to your name on the board, or watch live as a Spectator!"]]]
        [:div {:class "join-form-row"}
          [:button {:class "btn btn-outline"
                    :on-click (fn [_] (reclaim-seat! rid "w"))}
            (str "🔑 I am " (:name wp) " (White)")]
          [:button {:class "btn btn-outline"
                    :on-click (fn [_] (reclaim-seat! rid "b"))}
            (str "🔑 I am " (:name bp) " (Black)")]]]

      (or (= status "checkmate") (= status "stalemate") (= status "resigned") (= status "timeout"))
      [:div {:class "lobby-card gameover-card"}
        [:div {:class "trophy-icon"}
          (cond
            (= status "checkmate") "👑🏆✨"
            (= status "timeout") "⏰🏆✨"
            :else "🤝✨")]
        [:h2 {:class "gameover-title"}
          (cond
            (= status "checkmate") (str "CHECKMATE! " (:winner-name st) " Wins!")
            (= status "timeout") (str "TIME OUT! " (:winner-name st) " Wins on Time!")
            (= status "stalemate") "STALEMATE! It's a Draw!"
            :else (str "Game Over — " (:winner-name st) " Wins!"))]
        [:p {:class "gameover-reason"} (:reason st)]
        [:div {:class "gameover-actions"}
          (if (and is-tourney? (not= status "stalemate"))
            [:button {:class "btn btn-join"
                      :on-click (fn [_] (open-tournament! (:tournament-id st)))}
              "🏆 View Tournament Bracket & Parallel Games →"]
            [:button {:class "btn btn-join"
                      :on-click (fn [_] (start-new-game! true))}
              (if is-tourney? "⚡ Start Tiebreaker Rematch (Swap Colors)" "🔄 Rematch (Swap Colors)")])
          (if (not is-tourney?)
            [:button {:class "btn btn-secondary"
                      :on-click (fn [_] (start-new-game! false))}
              "🆕 Open Room for New Players"]
            [:span {} ""])]]

      :else
      [:span {} ""])))

(defn render-sidebar [hub st]
  (let [history (or (:history st) [])
        specs (or (:spectators st) [])
        role (my-role st)
        sel (deref *selected-sq*)
        sel-moves (if sel (legal-moves-for-sq st (nth sel 0) (nth sel 1)) [])
        rooms (get-room-map hub)
        r-order (or (:room-order hub) (keys rooms))
        pairs (loop [hs history p-acc []]
                (if (empty? hs)
                  p-acc
                  (let [w-move (first hs)
                        b-move (second hs)]
                    (recur (drop 2 hs) (conj p-acc [w-move b-move])))))]
    [:aside {:class "chess-sidebar"}
      ;; Quick Room Switcher Card
      [:div {:class "side-card room-switcher-card"}
        [:div {:class "side-card-title"}
          [:span {} "🚪 Switch Room / Table"]
          [:button {:class "btn-link"
                    :on-click (fn [_] (reset! *nav-view* "rooms") (render-ui))}
            "All Rooms →"]]
        [:select {:class "cute-input input-sm"
                  :style "width:100%;max-width:100%;"
                  :value (:id st)
                  :on-change (fn [e]
                               (open-room! (js/get (js/get e "target") "value") true))}
          (into [:optgroup {:label "Active Rooms"}]
            (map (fn [rid]
                   (let [rm (get rooms rid)]
                     (when rm
                       [:option {:value rid}
                         (str (:name rm) " • " (get-in rm [:time-control :label] "10+5") " (" (:status rm) ")")])))
                 r-order))]]

      ;; Selected Piece Inspector & Promotion Picker
      [:div {:class "side-card inspector-card"}
        [:div {:class "side-card-title"} "🎯 Move Helper & Promotion"]
        (if sel
          (let [[sr sc] sel
                p (board-get (:board st) sr sc)]
            [:div {:class "selected-piece-info"}
              [:div {:class "sel-preview"}
                (render-piece-svg p "normal" "sel-piece-svg")]
              [:div {:class "sel-text"}
                [:strong {} (str (if (= (piece-color p) "w") "White " "Black ")
                                 (piece-name (piece-type p))
                                 " on " (coord->alg sr sc))]
                [:span {:class "sel-moves-count"}
                  (str (count sel-moves) " possible legal move" (if (= (count sel-moves) 1) "" "s") " highlighted")]]])
          [:div {:class "sel-empty-hint"}
            "Click any of your pieces on the board to highlight its possible moves!"])

        [:div {:class "promo-picker"}
          [:span {:class "promo-label"} "Pawn Promotion:"]
          [:div {:class "promo-btns"}
            (into [:div {:class "promo-btn-group"}]
              (map (fn [[code label]]
                     [:button {:class (str "promo-btn" (if (= (deref *promo-piece*) code) " active" ""))
                               :on-click (fn [_] (reset! *promo-piece* code) (render-ui))}
                       label])
                   [["Q" "♕ Queen"]
                    ["R" "♖ Rook"]
                    ["B" "♗ Bishop"]
                    ["N" "♘ Knight"]]))]]]

      ;; Move History Card
      [:div {:class "side-card history-card"}
        [:div {:class "side-card-title"}
          [:span {} "📜 Move History"]
          [:span {:class "move-count-badge"} (str (count history) " ply")]]
        (if (empty? pairs)
          [:div {:class "empty-history"} "No moves played yet. White moves first!"]
          (into [:div {:class "history-list"}]
            (map (fn [[wm bm]]
                   [:div {:class "history-row"}
                     [:span {:class "turn-num"} (str (int (/ (+ (:num wm) 1) 2)) ".")]
                     [:span {:class (str "ply-move" (if (:checkmate? wm) " ply-mate" (if (:check? wm) " ply-check" "")))}
                       (:notation wm)]
                     [:span {:class (str "ply-move" (if (and bm (:checkmate? bm)) " ply-mate" (if (and bm (:check? bm)) " ply-check" "")))}
                       (if bm (:notation bm) "")]])
                 pairs)))]

      ;; Spectators & Controls Card
      [:div {:class "side-card controls-card"}
        [:div {:class "side-card-title"}
          [:span {} (str "👀 Spectators (" (count specs) ")")]]
        (if (empty? specs)
          [:div {:class "empty-specs"} "Anyone else opening this room during a game watches live!"]
          (into [:div {:class "spec-pills"}]
            (map (fn [sp]
                   [:span {:class "spec-pill"} (str "👁️ " (:name sp))])
                 specs)))

        [:div {:class "control-buttons"}
          [:button {:class "btn btn-outline"
                    :on-click (fn [_]
                                (let [cur (deref *flip-board*)
                                      eff (if (nil? cur) (= role "b") cur)]
                                  (reset! *flip-board* (not eff))
                                  (render-ui)))}
            "🔄 Flip Board"]
          (if (and (= (:status st) "playing") (or (= role "w") (= role "b") (= role "both")))
            [:button {:class "btn btn-danger-soft"
                      :on-click (fn [_] (resign-game!))}
              "🏳️ Resign"]
            [:span {} ""])
          (if (not= (:kind st) "tournament")
            [:button {:class "btn btn-outline"
                      :on-click (fn [_] (start-new-game! false))}
              "♻️ Reset Room"]
            [:span {} ""])]]]))

;; ── 10. Top-Level UI Render ─────────────────────────────────────────────────

(defn render-ui []
  (let [hub (deref *game*)
        st (get-current-room hub)
        role (my-role st)
        manual-flip (deref *flip-board*)
        flipped? (if (nil? manual-flip) (= role "b") manual-flip)
        top-color (if flipped? "w" "b")
        bottom-color (if flipped? "b" "w")
        fb (deref *feedback-msg*)
        in-chk-col (:in-check st)
        status (:status st)
        nav (deref *nav-view*)
        rooms-cnt (count (or (:room-order hub) (keys (get-room-map hub))))
        tourneys-cnt (count (or (:tournament-order hub) (keys (or (:tournaments hub) {}))))]
    (dom/render "app"
      [:div {:class "chess-app-shell"}
        ;; Top Navigation & Mode Tabs Header
        [:header {:class "chess-header"}
          [:div {:class "brand-box"
                 :style "cursor:pointer;"
                 :on-click (fn [_] (reset! *nav-view* "board") (render-ui))}
            [:span {:class "brand-logo"} "🐾👑"]
            [:div {}
              [:h1 {:class "brand-title"} "Paw & Crown — Cute 2D Chess"]
              [:p {:class "brand-sub"} "Official Fischer Clocks • Multi-Room Clubhouse • Parallel Tournaments"]]]

          ;; Main View Navigation Tabs
          [:nav {:class "nav-tabs"}
            [:button {:class (str "nav-tab-btn" (if (= nav "board") " active" ""))
                      :on-click (fn [_] (reset! *nav-view* "board") (render-ui))}
              (str "♟️ Active Board (" (:name st) ")")]
            [:button {:class (str "nav-tab-btn" (if (= nav "rooms") " active" ""))
                      :on-click (fn [_] (reset! *nav-view* "rooms") (render-ui))}
              (str "🚪 Rooms (" rooms-cnt ")")]
            [:button {:class (str "nav-tab-btn" (if (= nav "tournaments") " active" ""))
                      :on-click (fn [_] (reset! *nav-view* "tournaments") (render-ui))}
              (str "🏆 Tournaments (" tourneys-cnt ")")]]]

        ;; Pinned "Come Back to Your Game" Resume Bar
        (render-active-games-resume-bar hub)

        ;; Feedback / Impossible Move / Check Toast Banner
        (if fb
          [:div {:class (str "feedback-banner fb-" (:kind fb))}
            [:span {:class "fb-text"} (:text fb)]
            [:button {:class "fb-close"
                      :on-click (fn [_] (reset! *feedback-msg* nil) (reset! *invalid-sq* nil) (render-ui))}
              "✕"]]
          (if (and (= nav "board") (= status "playing") in-chk-col)
            [:div {:class "feedback-banner fb-check"}
              [:span {:class "fb-text"}
                (str "🚨 CHECK! "
                     (or (:name (get-in st [:players (if (= in-chk-col "w") :w :b)]))
                         (if (= in-chk-col "w") "White" "Black"))
                     "'s King is under attack — you must protect your King!")]]
            [:span {} ""]))

        ;; Main Content Area by Active Navigation Tab
        (cond
          (= nav "rooms")
          (render-rooms-lobby-view hub)

          (= nav "tournaments")
          (render-tournaments-view hub)

          :else
          [:div {:class "board-view-wrapper"}
            ;; Room Context Breadcrumb Bar
            [:div {:class "room-context-bar"}
              [:div {:class "room-context-left"}
                [:span {:class "room-pill-badge"}
                  (if (= (:kind st) "tournament") "🏆 Tournament Match Room" "🎲 Casual Game Room")]
                [:strong {:class "room-context-title"} (:name st)]]
              [:div {:class "room-context-actions"}
                (if (= (:kind st) "tournament")
                  [:button {:class "btn btn-outline"
                            :on-click (fn [_] (open-tournament! (:tournament-id st)))}
                    "📺 Watch All Parallel Games in Tournament →"]
                  [:span {} ""])
                [:button {:class "btn btn-outline"
                          :on-click (fn [_] (reset! *nav-view* "rooms") (render-ui))}
                  "🚪 Browse All Rooms"]]]

            ;; Official FIDE & Online Chess Timer Selector Bar
            (render-time-control-bar st)

            ;; Join / Waiting / Spectator / Checkmate / Timeout Card for this Room
            (render-lobby-or-status-card st)

            ;; 2-Column Chessboard + Sidebar
            [:main {:class "chess-workspace"}
              [:section {:class "board-column"}
                (render-player-bar st top-color)
                (render-chessboard st)
                (render-player-bar st bottom-color)]

              (render-sidebar hub st)]])])))

;; ── 11. Smooth Local Clock Ticker & Boot WebSocket ──────────────────────────

(defn tick-local-clocks! []
  "Smoothly decrements active running clocks every 250ms and triggers server
   flag-fall check if any active clock reaches 0."
  (let [hub (deref *game*)
        rooms (or (:rooms hub) {})
        any-running? (some (fn [[_ rm]]
                             (and (= (:status rm) "playing")
                                  (get-in rm [:time-control :enabled])
                                  (get-in rm [:clocks :running])))
                           rooms)]
    (when any-running?
      (let [flagged-rids (atom [])
            updated-rooms
            (into {}
              (map (fn [[rid rm]]
                     (if (and (= (:status rm) "playing")
                              (get-in rm [:time-control :enabled])
                              (get-in rm [:clocks :running]))
                       (let [turn (:turn rm)
                             k (if (= turn "w") :w-ms :b-ms)
                             old-ms (or (get-in rm [:clocks k]) 0)
                             new-ms (max 0 (- old-ms 250))]
                         (when (and (> old-ms 0) (<= new-ms 0))
                           (swap! flagged-rids conj rid))
                         [rid (assoc-in rm [:clocks k] new-ms)])
                       [rid rm]))
                   rooms))]
        (swap! *game* assoc :rooms updated-rooms)
        (doseq [frid (deref flagged-rids)]
          (check-room-clock! frid))
        (render-ui)))))

(defn start-clock-ticker! []
  (let [w (try (js/global "window") (catch e nil))]
    (when w
      (try (js/call w "setInterval" (fn [] (tick-local-clocks!)) 250) (catch e nil)))))

(defn connect-ws! []
  (let [w (try (js/global "window") (catch e nil))
        loc (when w (js/get w "location"))
        port-str (when loc (js/get loc "port"))
        ws-port (when (and port-str (not= port-str ""))
                  (+ (try (int port-str) (catch e 3080)) 1))]
    (ws-client/connect!
      {:path "/ws/"
       :port ws-port
       :on-message (fn [data _]
                     (when (and (map? data) (= (:type data) :game-state))
                       (reset! *game* data)
                       (reset! *selected-sq* nil)
                       (reset! *invalid-sq* nil)
                       (render-ui)))})))

(client/fetch-edn "/api/state"
  (fn [data]
    (when (and data (:board data))
      (reset! *game* data)
      (let [url-tourney (get-url-param "tournament")
            url-room (get-url-param "room")]
        (cond
          (not= url-tourney "")
          (do
            (reset! *active-tourney-id* url-tourney)
            (reset! *nav-view* "tournaments"))

          (not= url-room "")
          (do
            (reset! *active-room-id* url-room)
            (reset! *nav-view* "board"))))
      (render-ui))
    (start-clock-ticker!)
    (reset! *ws* (connect-ws!))))

(<! (chan 1))
