;; =============================================================================
;; Conimo Cute 2D Chess — Multi-Room, Official FIDE Clocks & Parallel Tournaments
;; Features:
;;   • Official FIDE / Fischer Chess Clocks (30, 15, 10, 5, 3, 1 min + increment seconds)
;;   • Automatic Flag-Fall (Time Out) Detection & Increment Addition per Move
;;   • Multiple Rooms (1 Room = 1 Game) with Disk Persistence (data/chess_store.edn)
;;   • Seamless Game Resume & Cross-Device Seat Reclaim
;;   • Parallel Tournaments (Knockout Bracket & Round-Robin) with Auto-Room Spawning
;;   • Authoritative Chess Rules (Legal Move Highlighting, Impossible Move Explanations,
;;     Castling, En-Passant, Promotion, Check, Checkmate & Stalemate)
;; =============================================================================

(require "libs/conimo/src/server.coni" :as conimo)
(require "libs/str/src/str.coni" :as str)
(require "libs/os/src/io.coni" :as io)

(io/mkdir-p "data")

;; ── 0. Time & Official FIDE / Fischer Clock Presets ─────────────────────────

(defn now-ms []
  "Returns current epoch time in milliseconds."
  (let [t (sys-time-now)]
    (if (> t 1000000000000000)
      (int (/ t 1000000))
      t)))

(def official-time-controls
  [{:id "1+0"       :label "1+0 • Bullet"           :category "Bullet"    :base-min 1  :base-sec 60   :inc-sec 0  :enabled true}
   {:id "1+1"       :label "1+1 • Fischer Bullet"   :category "Bullet"    :base-min 1  :base-sec 60   :inc-sec 1  :enabled true}
   {:id "2+1"       :label "2+1 • Bullet"           :category "Bullet"    :base-min 2  :base-sec 120  :inc-sec 1  :enabled true}
   {:id "3+0"       :label "3+0 • Blitz"            :category "Blitz"     :base-min 3  :base-sec 180  :inc-sec 0  :enabled true}
   {:id "3+2"       :label "3+2 • FIDE World Blitz" :category "Blitz"     :base-min 3  :base-sec 180  :inc-sec 2  :enabled true}
   {:id "5+0"       :label "5+0 • Blitz"            :category "Blitz"     :base-min 5  :base-sec 300  :inc-sec 0  :enabled true}
   {:id "5+3"       :label "5+3 • Club Blitz"       :category "Blitz"     :base-min 5  :base-sec 300  :inc-sec 3  :enabled true}
   {:id "10+0"      :label "10+0 • Rapid"           :category "Rapid"     :base-min 10 :base-sec 600  :inc-sec 0  :enabled true}
   {:id "10+5"      :label "10+5 • Rapid Increment" :category "Rapid"     :base-min 10 :base-sec 600  :inc-sec 5  :enabled true}
   {:id "15+0"      :label "15+0 • Rapid"           :category "Rapid"     :base-min 15 :base-sec 900  :inc-sec 0  :enabled true}
   {:id "15+10"     :label "15+10 • FIDE Rapid"     :category "Rapid"     :base-min 15 :base-sec 900  :inc-sec 10 :enabled true}
   {:id "30+0"      :label "30+0 • Classical"       :category "Classical" :base-min 30 :base-sec 1800 :inc-sec 0  :enabled true}
   {:id "30+20"     :label "30+20 • FIDE Classical" :category "Classical" :base-min 30 :base-sec 1800 :inc-sec 20 :enabled true}
   {:id "unlimited" :label "∞ Unlimited"            :category "Casual"    :base-min 0  :base-sec 0    :inc-sec 0  :enabled false}])

(defn classify-tc-category [base-min inc-sec]
  (let [est-sec (+ (* base-min 60) (* 40 inc-sec))]
    (cond
      (<= base-min 0) "Casual"
      (< est-sec 180) "Bullet"
      (< est-sec 600) "Blitz"
      (< est-sec 1800) "Rapid"
      :else "Classical")))

(defn resolve-time-control [tc-spec & [custom-base-min custom-inc-sec]]
  "Resolves an official preset ID (e.g. '15+10', '3+2', '10+0', 'unlimited') or custom base-min + inc-sec."
  (let [tc-id (if (map? tc-spec) (or (:id tc-spec) "") (str/trim (str (or tc-spec ""))))
        preset (first (filter (fn [p] (= (:id p) tc-id)) official-time-controls))]
    (cond
      preset preset

      (and (some? custom-base-min) (> (int custom-base-min) 0))
      (let [bmin (int custom-base-min)
            isec (max 0 (int (or custom-inc-sec 0)))
            cat (classify-tc-category bmin isec)
            id-str (str bmin "+" isec)]
        {:id id-str
         :label (str id-str " • " cat)
         :category cat
         :base-min bmin
         :base-sec (* bmin 60)
         :inc-sec isec
         :enabled true})

      (and (map? tc-spec) (:base-sec tc-spec))
      tc-spec

      :else
      ;; Default to 10+0 Rapid
      (nth official-time-controls 7))))

(defn fresh-clocks [tc running?]
  (let [base-ms (* (or (:base-sec tc) 600) 1000)
        enabled? (= (:enabled tc) true)]
    {:w-ms base-ms
     :b-ms base-ms
     :last-tick-ms (if (and enabled? running?) (now-ms) nil)
     :running (if (and enabled? running?) true false)}))

;; ── 1. Board & Coordinate Helpers ───────────────────────────────────────────

(def initial-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"])

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

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

(defn in-bounds? [r c]
  (and (>= r 0) (< r 8) (>= c 0) (< c 8)))

(defn board-get [board r c]
  (if (in-bounds? r c)
    (or (nth board (sq-idx r c)) "")
    ""))

(defn board-set [board r c val]
  (assoc board (sq-idx r c) (or val "")))

(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 opp-color [color]
  (if (= color "w") "b" "w"))

(defn piece-label [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]
  (if (in-bounds? r c)
    (str (nth file-names c) (- 8 r))
    "??"))

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

;; ── 2. Attack & Check Detection ─────────────────────────────────────────────

(def knight-deltas
  [[-2 -1] [-2 1] [-1 -2] [-1 2]
   [1 -2]  [1 2]  [2 -1]  [2 1]])

(def king-deltas
  [[-1 -1] [-1 0] [-1 1]
   [0 -1]         [0 1]
   [1 -1]  [1 0]  [1 1]])

(def ortho-dirs
  [[-1 0] [1 0] [0 -1] [0 1]])

(def diag-dirs
  [[-1 -1] [-1 1] [1 -1] [1 1]])

(defn ray-attacked? [board r c dirs attacker-color type1 type2]
  (let [target1 (str attacker-color type1)
        target2 (str attacker-color type2)]
    (loop [ds dirs]
      (if (empty? ds)
        false
        (let [[dr dc] (first ds)
              hit? (loop [nr (+ r dr) nc (+ c dc)]
                     (if (not (in-bounds? nr nc))
                       false
                       (let [p (board-get board nr nc)]
                         (if (= p "")
                           (recur (+ nr dr) (+ nc dc))
                           (or (= p target1) (= p target2))))))]
          (if hit?
            true
            (recur (rest ds))))))))

(defn square-attacked-by? [board r c attacker-color]
  (let [pawn-src-r (if (= attacker-color "w") (+ r 1) (- r 1))
        target-pawn (str attacker-color "P")
        pawn-hit? (or (= (board-get board pawn-src-r (- c 1)) target-pawn)
                      (= (board-get board pawn-src-r (+ c 1)) target-pawn))
        target-knight (str attacker-color "N")
        knight-hit? (when (not pawn-hit?)
                      (some (fn [[dr dc]]
                              (= (board-get board (+ r dr) (+ c dc)) target-knight))
                            knight-deltas))
        target-king (str attacker-color "K")
        king-hit? (when (and (not pawn-hit?) (not knight-hit?))
                    (some (fn [[dr dc]]
                            (= (board-get board (+ r dr) (+ c dc)) target-king))
                          king-deltas))
        ortho-hit? (when (and (not pawn-hit?) (not knight-hit?) (not king-hit?))
                     (ray-attacked? board r c ortho-dirs attacker-color "R" "Q"))
        diag-hit? (when (and (not pawn-hit?) (not knight-hit?) (not king-hit?) (not ortho-hit?))
                    (ray-attacked? board r c diag-dirs attacker-color "B" "Q"))]
    (if (or pawn-hit? knight-hit? king-hit? ortho-hit? diag-hit?) true false)))

(defn find-king [board color]
  (let [target (str color "K")]
    (loop [i 0]
      (if (>= i 64)
        nil
        (if (= (nth board i) target)
          [(int (/ i 8)) (rem i 8)]
          (recur (+ i 1)))))))

(defn in-check? [board color]
  (let [kpos (find-king board color)]
    (if kpos
      (square-attacked-by? board (nth kpos 0) (nth kpos 1) (opp-color color))
      false)))

;; ── 3. Move Generation (Pseudo-Legal & Legal Moves) ─────────────────────────

(defn slide-moves [board r c color dirs]
  (let [enemy (opp-color color)]
    (loop [ds dirs acc []]
      (if (empty? ds)
        acc
        (let [[dr dc] (first ds)
              ray-acc (loop [nr (+ r dr) nc (+ c dc) racc acc]
                        (if (not (in-bounds? nr nc))
                          racc
                          (let [p (board-get board nr nc)
                                pc (piece-color p)]
                            (cond
                              (= p "")
                              (recur (+ nr dr) (+ nc dc)
                                     (conj racc {:from [r c] :to [nr nc] :kind "move"}))

                              (= pc enemy)
                              (conj racc {:from [r c] :to [nr nc] :kind "capture"})

                              :else
                              racc))))]
          (recur (rest ds) ray-acc))))))

(defn step-moves [board r c color deltas]
  (let [enemy (opp-color color)]
    (loop [ds deltas acc []]
      (if (empty? ds)
        acc
        (let [[dr dc] (first ds)
              nr (+ r dr)
              nc (+ c dc)]
          (if (not (in-bounds? nr nc))
            (recur (rest ds) acc)
            (let [p (board-get board nr nc)
                  pc (piece-color p)]
              (cond
                (= p "")
                (recur (rest ds) (conj acc {:from [r c] :to [nr nc] :kind "move"}))

                (= pc enemy)
                (recur (rest ds) (conj acc {:from [r c] :to [nr nc] :kind "capture"}))

                :else
                (recur (rest ds) acc)))))))))

(defn pawn-moves [board r c color en-passant]
  (let [dir (if (= color "w") -1 1)
        start-r (if (= color "w") 6 1)
        enemy (opp-color color)
        r1 (+ r dir)
        r2 (+ r (* dir 2))
        m1 (if (and (in-bounds? r1 c) (= (board-get board r1 c) ""))
             [{:from [r c] :to [r1 c] :kind "move"}]
             [])
        m2 (if (and (= r start-r)
                    (= (count m1) 1)
                    (in-bounds? r2 c)
                    (= (board-get board r2 c) ""))
             (conj m1 {:from [r c] :to [r2 c] :kind "pawn-double"})
             m1)
        m3 (loop [dc-list [-1 1] acc m2]
             (if (empty? dc-list)
               acc
               (let [dc (first dc-list)
                     nc (+ c dc)]
                 (if (not (in-bounds? r1 nc))
                   (recur (rest dc-list) acc)
                   (let [target-p (board-get board r1 nc)
                         target-c (piece-color target-p)
                         is-ep? (and en-passant
                                     (= (nth en-passant 0) r1)
                                     (= (nth en-passant 1) nc))]
                     (cond
                       (= target-c enemy)
                       (recur (rest dc-list) (conj acc {:from [r c] :to [r1 nc] :kind "capture"}))

                       is-ep?
                       (recur (rest dc-list) (conj acc {:from [r c] :to [r1 nc] :kind "en-passant"}))

                       :else
                       (recur (rest dc-list) acc)))))))]
    m3))

(defn castle-moves [board r c color castling]
  (let [enemy (opp-color color)
        home-r (if (= color "w") 7 0)
        can-k? (if (= color "w") (:wK castling) (:bK castling))
        can-q? (if (= color "w") (:wQ castling) (:bQ castling))]
    (if (or (not= r home-r) (not= c 4) (in-check? board color))
      []
      (let [k-moves (if (and can-k?
                             (= (board-get board home-r 5) "")
                             (= (board-get board home-r 6) "")
                             (= (board-get board home-r 7) (str color "R"))
                             (not (square-attacked-by? board home-r 5 enemy))
                             (not (square-attacked-by? board home-r 6 enemy)))
                      [{:from [r c] :to [home-r 6] :kind "castle-k"}]
                      [])
            q-moves (if (and can-q?
                             (= (board-get board home-r 1) "")
                             (= (board-get board home-r 2) "")
                             (= (board-get board home-r 3) "")
                             (= (board-get board home-r 0) (str color "R"))
                             (not (square-attacked-by? board home-r 3 enemy))
                             (not (square-attacked-by? board home-r 2 enemy)))
                      (conj k-moves {:from [r c] :to [home-r 2] :kind "castle-q"})
                      k-moves)]
        q-moves))))

(defn pseudo-moves-at [board r c castling en-passant]
  (let [p (board-get board r c)
        color (piece-color p)
        ptype (piece-type p)]
    (cond
      (= p "")      []
      (= ptype "P") (pawn-moves board r c color en-passant)
      (= ptype "N") (step-moves board r c color knight-deltas)
      (= ptype "B") (slide-moves board r c color diag-dirs)
      (= ptype "R") (slide-moves board r c color ortho-dirs)
      (= ptype "Q") (slide-moves board r c color (concat ortho-dirs diag-dirs))
      (= ptype "K") (into (step-moves board r c color king-deltas)
                          (castle-moves board r c color castling))
      :else [])))

(defn apply-move-to-board [board move & [promote-piece]]
  (let [[r1 c1] (:from move)
        [r2 c2] (:to move)
        kind (:kind move)
        p (board-get board r1 c1)
        color (piece-color p)
        ptype (piece-type p)
        promo-rank (if (= color "w") 0 7)
        valid-promo (let [pr (str/upper-case (str (or promote-piece "Q")))]
                      (if (or (= pr "Q") (= pr "R") (= pr "B") (= pr "N")) pr "Q"))
        final-piece (if (and (= ptype "P") (= r2 promo-rank))
                      (str color valid-promo)
                      p)
        b1 (-> board
               (board-set r1 c1 "")
               (board-set r2 c2 final-piece))]
    (cond
      (= kind "en-passant")
      (board-set b1 r1 c2 "")

      (= kind "castle-k")
      (-> b1
          (board-set r1 7 "")
          (board-set r1 5 (str color "R")))

      (= kind "castle-q")
      (-> b1
          (board-set r1 0 "")
          (board-set r1 3 (str color "R")))

      :else b1)))

(defn legal-moves-at [board r c castling en-passant]
  (let [p (board-get board r c)
        color (piece-color p)]
    (if (= p "")
      []
      (let [candidates (pseudo-moves-at board r c castling en-passant)]
        (into []
          (filter (fn [m]
                    (let [next-b (apply-move-to-board board m "Q")]
                      (not (in-check? next-b color))))
                  candidates))))))

(defn compute-all-legal-moves [board turn-color castling en-passant]
  (loop [i 0 by-sq {} turn-total 0]
    (if (>= i 64)
      {:by-square by-sq :total-for-turn turn-total}
      (let [r (int (/ i 8))
            c (rem i 8)
            p (board-get board r c)
            pc (piece-color p)]
        (if (not= pc turn-color)
          (recur (+ i 1) by-sq turn-total)
          (let [ms (legal-moves-at board r c castling en-passant)
                k (sq-key r c)
                next-by-sq (if (> (count ms) 0) (assoc by-sq k ms) by-sq)
                next-total (+ turn-total (count ms))]
            (recur (+ i 1) next-by-sq next-total)))))))

(defn explain-impossible-move [board r1 c1 r2 c2 turn-color castling en-passant]
  (let [p (board-get board r1 c1)
        pc (piece-color p)
        ptype (piece-type p)
        plabel (piece-label ptype)
        from-alg (coord->alg r1 c1)
        to-alg (coord->alg r2 c2)
        dest-p (board-get board r2 c2)
        dest-c (piece-color dest-p)]
    (cond
      (= p "")
      "No piece on the selected square!"

      (not= pc turn-color)
      (str "Impossible move: That " plabel " belongs to your opponent!")

      (and (= r1 r2) (= c1 c2))
      "Select a different destination square!"

      (= dest-c pc)
      (str "Impossible move: Square " to-alg " is already occupied by your own " (piece-label (piece-type dest-p)) "!")

      :else
      (let [pseudos (pseudo-moves-at board r1 c1 castling en-passant)
            matching-pseudo (first (filter (fn [m]
                                             (let [[tr tc] (:to m)]
                                               (and (= tr r2) (= tc c2))))
                                           pseudos))]
        (if matching-pseudo
          (if (in-check? board pc)
            (str "⚠️ Impossible move: Your King is in check! Moving your " plabel " to " to-alg " does not get your King out of check.")
            (str "⚠️ Impossible move: Moving your " plabel " from " from-alg " to " to-alg " is illegal because it would expose your King to check!"))
          (if (in-check? board pc)
            (str "⚠️ Impossible move: Your King is in check, and the " plabel " on " from-alg " cannot move to " to-alg ".")
            (str "⚠️ Impossible move: The " plabel " on " from-alg " cannot move to " to-alg " (invalid pattern or path is blocked).")))))))

(defn update-castling-rights [castling r1 c1 r2 c2 p]
  (let [b-k (:bK castling)
        b-q (:bQ castling)
        w-k (:wK castling)
        w-q (:wQ castling)]
    {:wK (and w-k
              (not= p "wK")
              (not (and (= r1 7) (= c1 7)))
              (not (and (= r2 7) (= c2 7))))
     :wQ (and w-q
              (not= p "wK")
              (not (and (= r1 7) (= c1 0)))
              (not (and (= r2 7) (= c2 0))))
     :bK (and b-k
              (not= p "bK")
              (not (and (= r1 0) (= c1 7)))
              (not (and (= r2 0) (= c2 7))))
     :bQ (and b-q
              (not= p "bK")
              (not (and (= r1 0) (= c1 0)))
              (not (and (= r2 0) (= c2 0))))}))

(defn format-move-notation [p r1 c1 r2 c2 kind captured promoted? promo-type check? checkmate?]
  (let [ptype (piece-type p)
        to-alg (coord->alg r2 c2)
        from-file (nth file-names c1)
        cap? (or (not= captured "") (= kind "en-passant"))
        base (cond
               (= kind "castle-k") "O-O"
               (= kind "castle-q") "O-O-O"
               (= ptype "P")
               (str (if cap? (str from-file "x") "")
                    to-alg
                    (if promoted? (str "=" promo-type) ""))
               :else
               (str ptype (if cap? "x" "") to-alg))
        suffix (cond
                 checkmate? "#"
                 check? "+"
                 :else "")]
    (str base suffix)))

;; ── 4. Multi-Room & Parallel Tournament Hub State ───────────────────────────

(def store-path "data/chess_store.edn")
(def *seq-counter* (atom 100))

(defn next-uid [prefix]
  (let [n (swap! *seq-counter* inc)]
    (str prefix "-" (now-ms) "-" n)))

(defn make-room [room-id room-name & [opts]]
  (let [init-castling {:wK true :wQ true :bK true :bQ true}
        legals (compute-all-legal-moves initial-board "w" init-castling nil)
        players (or (:players opts) {:w nil :b nil})
        both-seated? (and (:w players) (:b players))
        tc (resolve-time-control (or (:time-control opts) "10+0")
                                 (:base-min opts)
                                 (:inc-sec opts))
        clocks (fresh-clocks tc both-seated?)]
    {:id room-id
     :game-id room-id
     :name (or room-name "Chess Room")
     :kind (or (:kind opts) "casual")
     :tournament-id (:tournament-id opts)
     :tournament-name (:tournament-name opts)
     :match-id (:match-id opts)
     :round-label (:round-label opts)
     :locked-seats? (if (:locked-seats? opts) true false)
     :time-control tc
     :clocks clocks
     :status (if both-seated? "playing" "waiting")
     :players players
     :spectators (or (:spectators opts) [])
     :board initial-board
     :turn "w"
     :castling init-castling
     :en-passant nil
     :in-check false
     :winner nil
     :winner-name nil
     :reason ""
     :last-move nil
     :history []
     :captured-by-w []
     :captured-by-b []
     :legal-moves (:by-square legals)
     :created-at (now-ms)
     :updated-at (now-ms)}))

(defn ensure-room-clocks [rm]
  (if (and rm (:time-control rm) (:clocks rm))
    rm
    (let [tc (resolve-time-control "10+0")]
      (assoc rm
             :time-control tc
             :clocks (fresh-clocks tc (= (:status rm) "playing"))))))

(defn default-hub-state []
  (let [r1 (make-room "room-paw-1" "🐾 Paw Lounge #1" {:time-control "10+0"})
        r2 (make-room "room-crown-2" "👑 Crown Blitz #2" {:time-control "5+3"})]
    {:rooms {"room-paw-1" r1
             "room-crown-2" r2}
     :room-order ["room-paw-1" "room-crown-2"]
     :tournaments {}
     :tournament-order []}))

(defn load-hub-state []
  (if (io/exists? store-path)
    (let [raw (try (io/read-file store-path) (catch e ""))
          parsed (if (and raw (not= (str/trim raw) ""))
                   (try (read-string raw) (catch e nil))
                   nil)]
      (if (and (map? parsed) (:rooms parsed))
        (let [fixed-rooms (into {}
                            (map (fn [[k v]] [k (ensure-room-clocks v)])
                                 (:rooms parsed)))]
          (assoc parsed :rooms fixed-rooms))
        (default-hub-state)))
    (default-hub-state)))

(def *hub* (atom (load-hub-state)))

(defn save-hub! []
  (try
    (io/write-file store-path (pr-str (deref *hub*)))
    (catch e nil)))

(defn snapshot-room-clock [rm cur-ms]
  "Returns room with live-deducted :w-ms or :b-ms as of cur-ms so clients always get exact remaining ms."
  (let [clocks (:clocks rm)
        tc (:time-control rm)]
    (if (and (= (:status rm) "playing")
             tc (:enabled tc)
             clocks (:running clocks)
             (:last-tick-ms clocks))
      (let [elapsed (max 0 (- cur-ms (:last-tick-ms clocks)))
            turn (:turn rm)
            k (if (= turn "w") :w-ms :b-ms)
            rem-ms (max 0 (- (or (get clocks k) 0) elapsed))]
        (assoc rm :clocks (assoc clocks k rem-ms :last-tick-ms cur-ms)))
      rm)))

(defn active-room-for-view [hub & [preferred-room-id]]
  (let [rooms (:rooms hub)
        rid (if (and preferred-room-id (get rooms preferred-room-id))
              preferred-room-id
              (or (first (:room-order hub))
                  (first (keys rooms))))]
    (or (get rooms rid) (make-room "room-paw-1" "🐾 Paw Lounge #1"))))

(defn build-client-payload [& [active-room-id extra]]
  (let [cur-ms (now-ms)
        hub (deref *hub*)
        live-rooms (into {}
                     (map (fn [[k rm]] [k (snapshot-room-clock rm cur-ms)])
                          (:rooms hub)))
        hub-live (assoc hub :rooms live-rooms)
        active-room (active-room-for-view hub-live active-room-id)]
    (merge
      active-room
      {:type :game-state
       :server-now-ms cur-ms
       :official-time-controls official-time-controls
       :active-room-id (:id active-room)
       :rooms live-rooms
       :room-order (:room-order hub)
       :tournaments (:tournaments hub)
       :tournament-order (:tournament-order hub)}
      (or extra {}))))

(defn broadcast-hub! [& [active-room-id]]
  (save-hub!)
  (conimo/broadcast! (pr-str (build-client-payload active-room-id))))

;; ── 5. Parallel Tournament Engine ───────────────────────────────────────────

(defn spawn-tournament-match-room! [hub-val tourney match]
  (let [tid (:id tourney)
        mid (:id match)
        room-id (str tid "-" mid)
        p1 (:p1 match)
        p2 (:p2 match)
        tc (or (:time-control tourney) (resolve-time-control "5+3"))
        rname (str "🏆 " (:name tourney) " — " (:label match))
        new-room (make-room room-id rname
                   {:kind "tournament"
                    :tournament-id tid
                    :tournament-name (:name tourney)
                    :match-id mid
                    :round-label (:label match)
                    :time-control tc
                    :locked-seats? true
                    :players {:w {:id (:id p1) :name (:name p1) :joined-at (now-ms)}
                              :b {:id (:id p2) :name (:name p2) :joined-at (now-ms)}}})
        updated-match (assoc match
                             :room-id room-id
                             :status "playing")]
    {:room new-room
     :match updated-match}))

(defn build-knockout-4-matches [players]
  (let [p1 (nth players 0)
        p2 (nth players 1)
        p3 (nth players 2)
        p4 (nth players 3)]
    [{:id "sf1" :round 1 :label "Semifinal #1" :p1 p1 :p2 p2 :status "ready" :room-id nil :winner nil :next-match-id "final" :next-slot :p1}
     {:id "sf2" :round 1 :label "Semifinal #2" :p1 p3 :p2 p4 :status "ready" :room-id nil :winner nil :next-match-id "final" :next-slot :p2}
     {:id "final" :round 2 :label "Grand Final 👑" :p1 nil :p2 nil :status "pending" :room-id nil :winner nil :next-match-id nil :next-slot nil}]))

(defn build-knockout-8-matches [players]
  (let [p1 (nth players 0) p2 (nth players 1)
        p3 (nth players 2) p4 (nth players 3)
        p5 (nth players 4) p6 (nth players 5)
        p7 (nth players 6) p8 (nth players 7)]
    [{:id "qf1" :round 1 :label "Quarterfinal #1" :p1 p1 :p2 p2 :status "ready" :room-id nil :winner nil :next-match-id "sf1" :next-slot :p1}
     {:id "qf2" :round 1 :label "Quarterfinal #2" :p1 p3 :p2 p4 :status "ready" :room-id nil :winner nil :next-match-id "sf1" :next-slot :p2}
     {:id "qf3" :round 1 :label "Quarterfinal #3" :p1 p5 :p2 p6 :status "ready" :room-id nil :winner nil :next-match-id "sf2" :next-slot :p1}
     {:id "qf4" :round 1 :label "Quarterfinal #4" :p1 p7 :p2 p8 :status "ready" :room-id nil :winner nil :next-match-id "sf2" :next-slot :p2}
     {:id "sf1" :round 2 :label "Semifinal #1" :p1 nil :p2 nil :status "pending" :room-id nil :winner nil :next-match-id "final" :next-slot :p1}
     {:id "sf2" :round 2 :label "Semifinal #2" :p1 nil :p2 nil :status "pending" :room-id nil :winner nil :next-match-id "final" :next-slot :p2}
     {:id "final" :round 3 :label "Grand Final 👑" :p1 nil :p2 nil :status "pending" :room-id nil :winner nil :next-match-id nil :next-slot nil}]))

(defn build-round-robin-matches [players]
  (let [n (count players)]
    (loop [i 0 m-idx 1 acc []]
      (if (>= i n)
        acc
        (let [p1 (nth players i)
              inner (loop [j (+ i 1) idx m-idx r-acc acc]
                      (if (>= j n)
                        [idx r-acc]
                        (let [p2 (nth players j)
                              even-idx? (= (rem idx 2) 0)
                              wp (if even-idx? p2 p1)
                              bp (if even-idx? p1 p2)
                              m {:id (str "rr" idx)
                                 :round 1
                                 :label (str "Match #" idx)
                                 :p1 wp
                                 :p2 bp
                                 :status "ready"
                                 :room-id nil
                                 :winner nil
                                 :next-match-id nil
                                 :next-slot nil}]
                          (recur (+ j 1) (+ idx 1) (conj r-acc m)))))]
          (recur (+ i 1) (nth inner 0) (nth inner 1)))))))

(defn spawn-ready-matches-in-parallel [hub-val tourney]
  (let [matches (:matches tourney)]
    (loop [ms matches
           new-matches []
           rooms-map (:rooms hub-val)
           r-order (:room-order hub-val)]
      (if (empty? ms)
        {:hub (assoc hub-val :rooms rooms-map :room-order r-order)
         :tourney (assoc tourney :matches new-matches)}
        (let [m (first ms)]
          (if (and (:p1 m) (:p2 m) (nil? (:room-id m)) (not= (:status m) "completed"))
            (let [spawned (spawn-tournament-match-room! hub-val tourney m)
                  rm (:room spawned)
                  um (:match spawned)
                  rid (:id rm)
                  next-order (if (some (fn [x] (= x rid)) r-order)
                               r-order
                               (conj r-order rid))]
              (recur (rest ms)
                     (conj new-matches um)
                     (assoc rooms-map rid rm)
                     next-order))
            (recur (rest ms)
                   (conj new-matches m)
                   rooms-map
                   r-order)))))))

(defn compute-rr-standings [players matches]
  (let [init-scores (into {}
                      (map (fn [p]
                             [(:id p) {:id (:id p) :name (:name p) :played 0 :wins 0 :draws 0 :losses 0 :points 0.0}])
                           players))
        tallied (loop [ms matches sc init-scores]
                  (if (empty? ms)
                    sc
                    (let [m (first ms)]
                      (if (not= (:status m) "completed")
                        (recur (rest ms) sc)
                        (let [p1-id (get-in m [:p1 :id])
                              p2-id (get-in m [:p2 :id])
                              w-col (:winner-color m)]
                          (cond
                            (= w-col "w")
                            (recur (rest ms)
                                   (-> sc
                                       (update-in [p1-id :played] inc)
                                       (update-in [p1-id :wins] inc)
                                       (update-in [p1-id :points] (fn [pts] (+ pts 1.0)))
                                       (update-in [p2-id :played] inc)
                                       (update-in [p2-id :losses] inc)))

                            (= w-col "b")
                            (recur (rest ms)
                                   (-> sc
                                       (update-in [p2-id :played] inc)
                                       (update-in [p2-id :wins] inc)
                                       (update-in [p2-id :points] (fn [pts] (+ pts 1.0)))
                                       (update-in [p1-id :played] inc)
                                       (update-in [p1-id :losses] inc)))

                            :else
                            (recur (rest ms)
                                   (-> sc
                                       (update-in [p1-id :played] inc)
                                       (update-in [p1-id :draws] inc)
                                       (update-in [p1-id :points] (fn [pts] (+ pts 0.5)))
                                       (update-in [p2-id :played] inc)
                                       (update-in [p2-id :draws] inc)
                                       (update-in [p2-id :points] (fn [pts] (+ pts 0.5)))))))))))]
    (into [] (reverse (sort-by :points (vals tallied))))))

(defn sync-tournament-on-room-finish! [room-id finished-room]
  (let [tid (:tournament-id finished-room)
        mid (:match-id finished-room)
        status (:status finished-room)
        winner-col (:winner finished-room)]
    (when (and tid mid (or (= status "checkmate") (= status "resigned") (= status "timeout") (= status "stalemate")))
      (swap! *hub*
        (fn [hub]
          (let [tourney (get-in hub [:tournaments tid])]
            (if (nil? tourney)
              hub
              (let [is-knockout? (str/starts-with? (str (:format tourney)) "knockout")
                    can-complete? (or (not is-knockout?) (not= status "stalemate"))
                    winning-player (cond
                                     (= winner-col "w") (get-in finished-room [:players :w])
                                     (= winner-col "b") (get-in finished-room [:players :b])
                                     :else nil)]
                (if (not can-complete?)
                  hub
                  (let [cur-matches (:matches tourney)
                        target-m (first (filter (fn [m] (= (:id m) mid)) cur-matches))
                        next-mid (:next-match-id target-m)
                        next-slot (:next-slot target-m)
                        updated-matches
                        (into []
                          (map (fn [m]
                                 (cond
                                   (= (:id m) mid)
                                   (assoc m
                                          :status "completed"
                                          :winner (if winning-player (:name winning-player) "Draw")
                                          :winner-id (when winning-player (:id winning-player))
                                          :winner-color winner-col
                                          :reason (:reason finished-room))

                                   (and next-mid (= (:id m) next-mid) winning-player)
                                   (let [slotted (if (= next-slot :p1)
                                                   (assoc m :p1 {:id (:id winning-player) :name (:name winning-player)})
                                                   (assoc m :p2 {:id (:id winning-player) :name (:name winning-player)}))]
                                     (if (and (:p1 slotted) (:p2 slotted))
                                       (assoc slotted :status "ready")
                                       slotted))

                                   :else m))
                               cur-matches))
                        t-with-matches (assoc tourney :matches updated-matches)
                        spawn-res (spawn-ready-matches-in-parallel hub t-with-matches)
                        hub2 (:hub spawn-res)
                        t2 (:tourney spawn-res)
                        all-done? (empty? (filter (fn [m] (not= (:status m) "completed")) (:matches t2)))
                        standings (if (= (:format t2) "round-robin")
                                    (compute-rr-standings (:players t2) (:matches t2))
                                    [])
                        champion (when all-done?
                                   (if (= (:format t2) "round-robin")
                                     (:name (first standings))
                                     (:winner (last (:matches t2)))))
                        t-final (assoc t2
                                       :standings standings
                                       :status (if all-done? "completed" (:status t2))
                                       :champion champion)]
                    (assoc-in hub2 [:tournaments tid] t-final)))))))))))

;; ── 6. Clock Flag-Fall Adjudication & Background Watchdog ───────────────────

(defn adjudicate-room-clock! [rid]
  "Checks if the active player's clock in room `rid` has reached 0ms, and if so,
   marks the game as :status 'timeout' and awards victory to the opponent."
  (let [cur-ms (now-ms)
        flagged-room (atom nil)]
    (swap! *hub*
      (fn [hub]
        (let [rm (get-in hub [:rooms rid])]
          (if (or (nil? rm)
                  (not= (:status rm) "playing")
                  (not (get-in rm [:time-control :enabled]))
                  (not (get-in rm [:clocks :running]))
                  (nil? (get-in rm [:clocks :last-tick-ms])))
            hub
            (let [clocks (:clocks rm)
                  elapsed (max 0 (- cur-ms (:last-tick-ms clocks)))
                  turn (:turn rm)
                  k (if (= turn "w") :w-ms :b-ms)
                  rem-ms (max 0 (- (or (get clocks k) 0) elapsed))]
              (if (> rem-ms 0)
                (assoc-in hub [:rooms rid :clocks]
                          (assoc clocks k rem-ms :last-tick-ms cur-ms))
                (let [winner-col (opp-color turn)
                      winner-p (get-in rm [:players (if (= winner-col "w") :w :b)])
                      loser-p (get-in rm [:players (if (= turn "w") :w :b)])
                      updated-rm (assoc rm
                                        :status "timeout"
                                        :winner winner-col
                                        :winner-name (if winner-p (:name winner-p) (if (= winner-col "w") "White" "Black"))
                                        :reason (str "⏱️ Time Out! "
                                                     (if loser-p (:name loser-p) (if (= turn "w") "White" "Black"))
                                                     " ran out of time. "
                                                     (if winner-p (:name winner-p) (if (= winner-col "w") "White" "Black"))
                                                     " wins on time!")
                                        :legal-moves {}
                                        :clocks (assoc clocks k 0 :running false :last-tick-ms cur-ms)
                                        :updated-at cur-ms)]
                  (reset! flagged-room updated-rm)
                  (assoc-in hub [:rooms rid] updated-rm))))))))
    (when (deref flagged-room)
      (sync-tournament-on-room-finish! rid (deref flagged-room))
      (broadcast-hub! rid)
      true)))

(defn check-all-active-clocks! []
  (let [rids (keys (:rooms (deref *hub*)))]
    (doseq [rid rids]
      (adjudicate-room-clock! rid))))

;; Background 1-second watchdog thread for active clocks
(spawn
  (fn []
    (loop []
      (sleep 1000)
      (try (check-all-active-clocks!) (catch e nil))
      (recur))))

;; ── 7. HTTP API Handlers ────────────────────────────────────────────────────

(defn parse-req-body [req]
  (cond
    (:edn-body req) (:edn-body req)
    (and (:body req) (not= (:body req) ""))
    (try (read-string (:body req)) (catch e {}))
    :else {}))

(defn resolve-room-id [hub body]
  (let [req-rid (str/trim (str (or (:room-id body) "")))
        rooms (:rooms hub)]
    (if (and (not= req-rid "") (get rooms req-rid))
      req-rid
      (or (first (:room-order hub))
          (first (keys rooms))
          "room-paw-1"))))

(defn handle-get-state [req]
  {:status 200
   :headers {"Content-Type" "application/edn"}
   :body (pr-str (build-client-payload nil))})

(defn handle-set-time-control [req]
  "Updates the time control (official preset or custom base-min + inc-sec) on a room
   and resets the room clocks."
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)
        tc (resolve-time-control (:time-control body) (:base-min body) (:inc-sec body))]
    (swap! *hub*
      (fn [h]
        (let [rm (get-in h [:rooms rid])]
          (if (nil? rm)
            h
            (let [running? (= (:status rm) "playing")
                  new-clocks (fresh-clocks tc running?)]
              (assoc-in h [:rooms rid]
                        (assoc rm
                               :time-control tc
                               :clocks new-clocks
                               :updated-at (now-ms))))))))
    (broadcast-hub! rid)
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload rid {:ok true}))}))

(defn handle-clock-check [req]
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)]
    (adjudicate-room-clock! rid)
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload rid {:ok true}))}))

(defn handle-create-room [req]
  (let [body (parse-req-body req)
        raw-name (str/trim (str (or (:name body) "")))
        cid (str/trim (str (or (:client-id body) "")))
        pname (str/trim (str (or (:player-name body) "")))
        auto-join? (= (:auto-join body) true)
        tc-spec (or (:time-control body) "10+0")
        rid (next-uid "room")
        rname (if (= raw-name "")
                (str "🎲 Cozy Table #" (+ (count (:room-order (deref *hub*))) 1))
                raw-name)
        init-players (if (and auto-join? (not= cid ""))
                       {:w {:id cid :name (if (= pname "") "Player 1" pname) :joined-at (now-ms)}
                        :b nil}
                       {:w nil :b nil})
        new-room (make-room rid rname {:players init-players
                                       :time-control tc-spec
                                       :base-min (:base-min body)
                                       :inc-sec (:inc-sec body)})]
    (swap! *hub*
      (fn [hub]
        (-> hub
            (assoc-in [:rooms rid] new-room)
            (update :room-order (fn [ro] (conj (or ro []) rid))))))
    (broadcast-hub! rid)
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload rid {:ok true :created-room-id rid}))}))

(defn handle-delete-room [req]
  (let [body (parse-req-body req)
        rid (str/trim (str (or (:room-id body) "")))]
    (if (and (not= rid "") (> (count (:room-order (deref *hub*))) 1))
      (do
        (swap! *hub*
          (fn [hub]
            (-> hub
                (update :rooms dissoc rid)
                (update :room-order (fn [ro] (into [] (filter (fn [x] (not= x rid)) ro)))))))
        (broadcast-hub! nil)
        {:status 200
         :headers {"Content-Type" "application/edn"}
         :body (pr-str (build-client-payload nil {:ok true}))})
      {:status 400
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false :error "Cannot delete the last remaining room."})})))

(defn handle-reclaim-seat [req]
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)
        cid (str/trim (str (or (:client-id body) "")))
        seat-col (str/trim (str (or (:color body) "w")))
        req-name (str/trim (str (or (:name body) "")))
        seat-key (if (= seat-col "b") :b :w)
        room (get-in hub [:rooms rid])
        cur-seat (when room (get-in room [:players seat-key]))]
    (if (and room cur-seat (not= cid ""))
      (let [new-name (if (= req-name "") (:name cur-seat) req-name)]
        (swap! *hub*
          (fn [h]
            (-> h
                (assoc-in [:rooms rid :players seat-key :id] cid)
                (assoc-in [:rooms rid :players seat-key :name] new-name)
                (update-in [:rooms rid :spectators]
                           (fn [sps] (into [] (filter (fn [sp] (not= (:id sp) cid)) (or sps []))))))))
        (broadcast-hub! rid)
        {:status 200
         :headers {"Content-Type" "application/edn"}
         :body (pr-str (build-client-payload rid {:ok true :reclaimed-color seat-col}))})
      {:status 400
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false :error "Seat not found to reclaim."})})))

(defn handle-join [req]
  (let [body (parse-req-body req)
        raw-cid (str/trim (str (or (:client-id body) "")))
        cid (if (= raw-cid "") (str "anon-" (now-ms)) raw-cid)
        raw-name (str/trim (str (or (:name body) "")))
        preferred-seat (str/trim (str (or (:seat body) "auto")))
        rid (resolve-room-id (deref *hub*) body)
        role-assigned (atom "spectator")]
    (swap! *hub*
      (fn [hub]
        (let [cur (get-in hub [:rooms rid])]
          (if (nil? cur)
            hub
            (let [wp (get-in cur [:players :w])
                  bp (get-in cur [:players :b])
                  is-w? (and wp (or (= (:id wp) cid)
                                    (and (not= raw-name "")
                                         (= (str/lower-case (:name wp)) (str/lower-case raw-name)))))
                  is-b? (and bp (or (= (:id bp) cid)
                                    (and (not= raw-name "")
                                         (= (str/lower-case (:name bp)) (str/lower-case raw-name)))))
                  updated-room
                  (cond
                    (and is-w? (not= preferred-seat "spectator"))
                    (let [nm (if (= raw-name "") (:name wp) raw-name)]
                      (reset! role-assigned "w")
                      (-> cur
                          (assoc-in [:players :w :id] cid)
                          (assoc-in [:players :w :name] nm)))

                    (and is-b? (not= preferred-seat "spectator"))
                    (let [nm (if (= raw-name "") (:name bp) raw-name)]
                      (reset! role-assigned "b")
                      (-> cur
                          (assoc-in [:players :b :id] cid)
                          (assoc-in [:players :b :name] nm)))

                    (and (= (:status cur) "waiting")
                         (not= preferred-seat "spectator")
                         (or (nil? wp) (nil? bp)))
                    (let [seat (cond
                                 (and (= preferred-seat "b") (nil? bp)) :b
                                 (and (= preferred-seat "w") (nil? wp)) :w
                                 (nil? wp) :w
                                 :else :b)
                          default-nm (if (= seat :w) "Player 1" "Player 2")
                          nm (if (= raw-name "") default-nm raw-name)
                          player-entry {:id cid :name nm :joined-at (now-ms)}
                          next-players (assoc (:players cur) seat player-entry)
                          both-ready? (and (:w next-players) (:b next-players))
                          tc (or (:time-control cur) (resolve-time-control "10+0"))
                          next-clocks (fresh-clocks tc both-ready?)
                          next-specs (into [] (filter (fn [sp] (not= (:id sp) cid)) (or (:spectators cur) [])))]
                      (reset! role-assigned (if (= seat :w) "w" "b"))
                      (assoc cur
                             :players next-players
                             :spectators next-specs
                             :clocks next-clocks
                             :status (if both-ready? "playing" "waiting")
                             :updated-at (now-ms)))

                    :else
                    (let [nm (if (= raw-name "") "Spectator" raw-name)
                          old-specs (or (:spectators cur) [])
                          exists? (some (fn [sp] (= (:id sp) cid)) old-specs)
                          next-specs (if exists?
                                       (into [] (map (fn [sp] (if (= (:id sp) cid) {:id cid :name nm} sp)) old-specs))
                                       (conj old-specs {:id cid :name nm}))]
                      (reset! role-assigned "spectator")
                      (assoc cur :spectators next-specs)))]
              (assoc-in hub [:rooms rid] updated-room))))))
    (broadcast-hub! rid)
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload rid {:ok true :assigned-role (deref role-assigned)}))}))

(defn handle-move [req]
  "Validates and executes a chess move in the target room, deducting elapsed clock time,
   enforcing flag-fall timeout, adding Fischer increment (+inc-sec), and detecting
   Check, Checkmate, and Stalemate."
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)
        cid (str/trim (str (or (:client-id body) "")))
        from-sq (:from body)
        to-sq (:to body)
        promo-choice (or (:promote body) "Q")
        ;; First check if the clock already expired!
        _ (adjudicate-room-clock! rid)
        st (get-in (deref *hub*) [:rooms rid])]
    (if (or (nil? st) (not= (:status st) "playing"))
      {:status 400
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false
                      :error (cond
                               (and st (= (:status st) "waiting")) "Waiting for 2 players to join before starting the game!"
                               (and st (= (:status st) "timeout")) (:reason st)
                               :else "This game has already ended. Start a new game or switch rooms!")})}
      (let [turn (:turn st)
            w-player (get-in st [:players :w])
            b-player (get-in st [:players :b])
            expected-player (if (= turn "w") w-player b-player)
            is-spectator? (and (not= cid (:id w-player)) (not= cid (:id b-player)))
            wrong-turn? (and (not is-spectator?) (not= cid (:id expected-player)))]
        (cond
          is-spectator?
          {:status 403
           :headers {"Content-Type" "application/edn"}
           :body (pr-str {:ok false
                          :error "👀 You are watching the ongoing game as a spectator. (If you are one of the players, click '🔑 Reclaim Seat' on your name bar!)"})}

          wrong-turn?
          {:status 400
           :headers {"Content-Type" "application/edn"}
           :body (pr-str {:ok false
                          :error (str "⏳ Wait for your turn! It is currently " (:name expected-player) "'s (" (if (= turn "w") "White" "Black") ") turn.")})}

          (or (not (vector? from-sq)) (not (vector? to-sq))
              (< (count from-sq) 2) (< (count to-sq) 2))
          {:status 400
           :headers {"Content-Type" "application/edn"}
           :body (pr-str {:ok false :error "Invalid move coordinates."})}

          :else
          (let [r1 (int (nth from-sq 0))
                c1 (int (nth from-sq 1))
                r2 (int (nth to-sq 0))
                c2 (int (nth to-sq 1))
                board (:board st)
                castling (:castling st)
                en-passant (:en-passant st)
                legals (legal-moves-at board r1 c1 castling en-passant)
                matched-move (first (filter (fn [m]
                                              (let [[tr tc] (:to m)]
                                                (and (= tr r2) (= tc c2))))
                                            legals))]
            (if (nil? matched-move)
              (let [reason (explain-impossible-move board r1 c1 r2 c2 turn castling en-passant)]
                {:status 400
                 :headers {"Content-Type" "application/edn"}
                 :body (pr-str {:ok false
                                :impossible true
                                :from [r1 c1]
                                :to [r2 c2]
                                :error reason})})
              (let [cur-ms (now-ms)
                    tc (or (:time-control st) (resolve-time-control "10+0"))
                    clocks (or (:clocks st) (fresh-clocks tc true))
                    moving-piece (board-get board r1 c1)
                    ptype (piece-type moving-piece)
                    kind (:kind matched-move)
                    direct-cap (board-get board r2 c2)
                    captured-piece (if (= kind "en-passant")
                                     (board-get board r1 c2)
                                     direct-cap)
                    promo-rank (if (= turn "w") 0 7)
                    promoted? (and (= ptype "P") (= r2 promo-rank))
                    clean-promo (let [pr (str/upper-case (str promo-choice))]
                                  (if (or (= pr "Q") (= pr "R") (= pr "B") (= pr "N")) pr "Q"))
                    next-board (apply-move-to-board board matched-move clean-promo)
                    next-castling (update-castling-rights castling r1 c1 r2 c2 moving-piece)
                    next-ep (if (= kind "pawn-double")
                              [(int (/ (+ r1 r2) 2)) c1]
                              nil)
                    next-turn (opp-color turn)
                    next-in-check? (in-check? next-board next-turn)
                    next-legals (compute-all-legal-moves next-board next-turn next-castling next-ep)
                    no-moves? (= (:total-for-turn next-legals) 0)
                    checkmate? (and no-moves? next-in-check?)
                    stalemate? (and no-moves? (not next-in-check?))
                    game-over? (or checkmate? stalemate?)
                    ;; Deduct elapsed ms and add Fischer increment (+inc-sec * 1000)
                    elapsed (if (and (:enabled tc) (:running clocks) (:last-tick-ms clocks))
                              (max 0 (- cur-ms (:last-tick-ms clocks)))
                              0)
                    inc-ms (if (and (:enabled tc) (not game-over?))
                             (* (or (:inc-sec tc) 0) 1000)
                             0)
                    turn-clock-key (if (= turn "w") :w-ms :b-ms)
                    prev-rem (or (get clocks turn-clock-key) (* (or (:base-sec tc) 600) 1000))
                    new-rem (+ (max 1 (- prev-rem elapsed)) inc-ms)
                    next-clocks (assoc clocks
                                       turn-clock-key new-rem
                                       :last-tick-ms cur-ms
                                       :running (if (and (:enabled tc) (not game-over?)) true false))
                    next-status (cond
                                  checkmate? "checkmate"
                                  stalemate? "stalemate"
                                  :else "playing")
                    winner (cond
                             checkmate? turn
                             stalemate? "draw"
                             :else nil)
                    winner-name (cond
                                  checkmate? (:name expected-player)
                                  stalemate? "Draw"
                                  :else nil)
                    reason-str (cond
                                 checkmate? (str "Checkmate! " (:name expected-player) " (" (if (= turn "w") "White" "Black") ") wins!")
                                 stalemate? "Stalemate! The game is a draw (no legal moves)."
                                 :else "")
                    notation (format-move-notation moving-piece r1 c1 r2 c2 kind captured-piece promoted? clean-promo next-in-check? checkmate?)
                    move-record {:num (+ (count (:history st)) 1)
                                 :color turn
                                 :player (:name expected-player)
                                 :piece moving-piece
                                 :from [r1 c1]
                                 :to [r2 c2]
                                 :kind kind
                                 :captured captured-piece
                                 :promoted (if promoted? clean-promo nil)
                                 :notation notation
                                 :check? next-in-check?
                                 :checkmate? checkmate?}
                    next-cap-w (if (and (= turn "w") (not= captured-piece ""))
                                 (conj (or (:captured-by-w st) []) captured-piece)
                                 (or (:captured-by-w st) []))
                    next-cap-b (if (and (= turn "b") (not= captured-piece ""))
                                 (conj (or (:captured-by-b st) []) captured-piece)
                                 (or (:captured-by-b st) []))
                    updated-room (assoc st
                                        :board next-board
                                        :turn next-turn
                                        :castling next-castling
                                        :en-passant next-ep
                                        :in-check (if next-in-check? next-turn false)
                                        :clocks next-clocks
                                        :status next-status
                                        :winner winner
                                        :winner-name winner-name
                                        :reason reason-str
                                        :last-move move-record
                                        :history (conj (or (:history st) []) move-record)
                                        :captured-by-w next-cap-w
                                        :captured-by-b next-cap-b
                                        :legal-moves (:by-square next-legals)
                                        :updated-at cur-ms)]
                (swap! *hub* assoc-in [:rooms rid] updated-room)
                (when game-over?
                  (sync-tournament-on-room-finish! rid updated-room))
                (broadcast-hub! rid)
                {:status 200
                 :headers {"Content-Type" "application/edn"}
                 :body (pr-str (build-client-payload rid {:ok true}))}))))))))

(defn handle-resign [req]
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)
        cid (str/trim (str (or (:client-id body) "")))
        st (get-in hub [:rooms rid])
        w-player (when st (get-in st [:players :w]))
        b-player (when st (get-in st [:players :b]))
        is-w? (and w-player (= (:id w-player) cid))
        is-b? (and b-player (= (:id b-player) cid))]
    (if (and st (= (:status st) "playing") (or is-w? is-b?))
      (let [winner-col (if is-w? "b" "w")
            winner-p (if is-w? b-player w-player)
            loser-p (if is-w? w-player b-player)
            updated-room (assoc st
                                :status "resigned"
                                :winner winner-col
                                :winner-name (:name winner-p)
                                :reason (str (:name loser-p) " resigned. " (:name winner-p) " wins!")
                                :clocks (assoc (or (:clocks st) {}) :running false)
                                :legal-moves {}
                                :updated-at (now-ms))]
        (swap! *hub* assoc-in [:rooms rid] updated-room)
        (sync-tournament-on-room-finish! rid updated-room)
        (broadcast-hub! rid)
        {:status 200
         :headers {"Content-Type" "application/edn"}
         :body (pr-str (build-client-payload rid {:ok true}))})
      {:status 400
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false :error "Only an active player can resign during an ongoing game."})})))

(defn handle-new-game [req]
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)
        keep? (= (:keep-players body) true)
        st (get-in hub [:rooms rid])]
    (if st
      (let [old-w (get-in st [:players :w])
            old-b (get-in st [:players :b])
            swapped-players (if (and keep? old-w old-b)
                              {:w old-b :b old-w}
                              {:w nil :b nil})
            nxt (make-room rid (:name st)
                  {:kind (:kind st)
                   :tournament-id (:tournament-id st)
                   :tournament-name (:tournament-name st)
                   :match-id (:match-id st)
                   :round-label (:round-label st)
                   :time-control (:time-control st)
                   :locked-seats? (and keep? (:locked-seats? st))
                   :players swapped-players
                   :spectators (if keep? (:spectators st) [])})]
        (swap! *hub* assoc-in [:rooms rid] nxt)
        (broadcast-hub! rid)
        {:status 200
         :headers {"Content-Type" "application/edn"}
         :body (pr-str (build-client-payload rid {:ok true}))})
      {:status 404
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false :error "Room not found"})})))

(defn handle-leave [req]
  (let [body (parse-req-body req)
        hub (deref *hub*)
        rid (resolve-room-id hub body)
        cid (str/trim (str (or (:client-id body) "")))]
    (swap! *hub*
      (fn [h]
        (let [cur (get-in h [:rooms rid])]
          (if (nil? cur)
            h
            (let [wp (get-in cur [:players :w])
                  bp (get-in cur [:players :b])
                  is-w? (and wp (= (:id wp) cid))
                  is-b? (and bp (= (:id bp) cid))]
              (if (or is-w? is-b?)
                (assoc-in h [:rooms rid] (make-room rid (:name cur) {:time-control (:time-control cur)}))
                h))))))
    (broadcast-hub! rid)
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload rid {:ok true}))}))

;; ── 8. Tournament HTTP API Handlers ─────────────────────────────────────────

(defn normalize-tourney-players [raw-players]
  (loop [ps (or raw-players []) idx 1 acc []]
    (if (empty? ps)
      acc
      (let [item (first ps)
            nm (str/trim (str (if (map? item) (or (:name item) "") item)))
            pid (if (and (map? item) (:id item) (not= (str/trim (str (:id item))) ""))
                  (str/trim (str (:id item)))
                  (str "tp-" (now-ms) "-" idx))]
        (if (= nm "")
          (recur (rest ps) idx acc)
          (recur (rest ps) (+ idx 1) (conj acc {:id pid :name nm})))))))

(defn handle-create-tournament [req]
  (let [body (parse-req-body req)
        raw-name (str/trim (str (or (:name body) "")))
        t-format (let [f (str/trim (str (or (:format body) "knockout-4")))]
                   (if (or (= f "knockout-4") (= f "knockout-8") (= f "round-robin"))
                     f
                     "knockout-4"))
        target-size (cond
                      (= t-format "knockout-8") 8
                      (= t-format "knockout-4") 4
                      :else (int (or (:max-players body) 4)))
        tc (resolve-time-control (or (:time-control body) "5+3") (:base-min body) (:inc-sec body))
        initial-players (normalize-tourney-players (:players body))
        auto-start? (= (:auto-start body) true)
        tid (next-uid "tourney")
        tname (if (= raw-name "")
                (str "🏆 Paw & Crown Cup #" (+ (count (:tournament-order (deref *hub*))) 1))
                raw-name)
        base-tourney {:id tid
                      :name tname
                      :format t-format
                      :time-control tc
                      :target-size target-size
                      :status "registration"
                      :players initial-players
                      :matches []
                      :standings []
                      :champion nil
                      :created-at (now-ms)}]
    (swap! *hub*
      (fn [hub]
        (let [h1 (-> hub
                     (assoc-in [:tournaments tid] base-tourney)
                     (update :tournament-order (fn [to] (conj (or to []) tid))))]
          (if (and auto-start?
                   (or (and (= t-format "knockout-4") (>= (count initial-players) 4))
                       (and (= t-format "knockout-8") (>= (count initial-players) 8))
                       (and (= t-format "round-robin") (>= (count initial-players) 3))))
            (let [ps (if (= t-format "knockout-4")
                       (into [] (take 4 initial-players))
                       (if (= t-format "knockout-8")
                         (into [] (take 8 initial-players))
                         initial-players))
                  init-matches (cond
                                 (= t-format "knockout-4") (build-knockout-4-matches ps)
                                 (= t-format "knockout-8") (build-knockout-8-matches ps)
                                 :else (build-round-robin-matches ps))
                  t-ready (assoc base-tourney
                                 :players ps
                                 :status "playing"
                                 :matches init-matches
                                 :standings (if (= t-format "round-robin")
                                              (compute-rr-standings ps init-matches)
                                              []))
                  spawn-res (spawn-ready-matches-in-parallel h1 t-ready)]
              (assoc-in (:hub spawn-res) [:tournaments tid] (:tourney spawn-res)))
            h1))))
    (broadcast-hub! nil)
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload nil {:ok true :tournament-id tid}))}))

(defn handle-join-tournament [req]
  (let [body (parse-req-body req)
        tid (str/trim (str (or (:tournament-id body) "")))
        cid (let [c (str/trim (str (or (:client-id body) "")))]
              (if (= c "") (next-uid "tp") c))
        nm (str/trim (str (or (:name body) "")))]
    (if (and (not= tid "") (not= nm ""))
      (do
        (swap! *hub*
          (fn [hub]
            (let [t (get-in hub [:tournaments tid])]
              (if (or (nil? t) (not= (:status t) "registration"))
                hub
                (let [ps (or (:players t) [])
                      already? (some (fn [p]
                                       (or (= (:id p) cid)
                                           (= (str/lower-case (:name p)) (str/lower-case nm))))
                                     ps)
                      next-ps (if already?
                                ps
                                (conj ps {:id cid :name nm}))]
                  (assoc-in hub [:tournaments tid :players] next-ps))))))
        (broadcast-hub! nil)
        {:status 200
         :headers {"Content-Type" "application/edn"}
         :body (pr-str (build-client-payload nil {:ok true :tournament-id tid}))})
      {:status 400
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false :error "Tournament ID and player name are required."})})))

(defn handle-start-tournament [req]
  (let [body (parse-req-body req)
        tid (str/trim (str (or (:tournament-id body) "")))
        tourney (get-in (deref *hub*) [:tournaments tid])]
    (if (nil? tourney)
      {:status 404
       :headers {"Content-Type" "application/edn"}
       :body (pr-str {:ok false :error "Tournament not found."})}
      (let [t-format (:format tourney)
            min-needed (cond
                         (= t-format "knockout-8") 8
                         (= t-format "knockout-4") 4
                         :else 3)
            cur-ps (or (:players tourney) [])]
        (if (< (count cur-ps) min-needed)
          {:status 400
           :headers {"Content-Type" "application/edn"}
           :body (pr-str {:ok false
                          :error (str "Need at least " min-needed " players to start this tournament (currently " (count cur-ps) " registered).")})}
          (do
            (swap! *hub*
              (fn [hub]
                (let [t (get-in hub [:tournaments tid])
                      ps (cond
                           (= t-format "knockout-4") (into [] (take 4 (:players t)))
                           (= t-format "knockout-8") (into [] (take 8 (:players t)))
                           :else (:players t))
                      init-matches (cond
                                     (= t-format "knockout-4") (build-knockout-4-matches ps)
                                     (= t-format "knockout-8") (build-knockout-8-matches ps)
                                     :else (build-round-robin-matches ps))
                      t-ready (assoc t
                                     :players ps
                                     :status "playing"
                                     :matches init-matches
                                     :standings (if (= t-format "round-robin")
                                                  (compute-rr-standings ps init-matches)
                                                  []))
                      spawn-res (spawn-ready-matches-in-parallel hub t-ready)]
                  (assoc-in (:hub spawn-res) [:tournaments tid] (:tourney spawn-res)))))
            (broadcast-hub! nil)
            {:status 200
             :headers {"Content-Type" "application/edn"}
             :body (pr-str (build-client-payload nil {:ok true :tournament-id tid}))}))))))

(defn handle-delete-tournament [req]
  (let [body (parse-req-body req)
        tid (str/trim (str (or (:tournament-id body) "")))]
    (when (not= tid "")
      (swap! *hub*
        (fn [hub]
          (let [t (get-in hub [:tournaments tid])
                m-room-ids (if t
                             (into [] (filter (fn [x] (not (nil? x))) (map :room-id (:matches t))))
                             [])
                next-rooms (loop [rids m-room-ids rm (:rooms hub)]
                             (if (empty? rids)
                               rm
                               (recur (rest rids) (dissoc rm (first rids)))))
                next-r-order (into []
                               (filter (fn [rid]
                                         (not (some (fn [mrid] (= mrid rid)) m-room-ids)))
                                       (:room-order hub)))]
            (-> hub
                (assoc :rooms next-rooms)
                (assoc :room-order next-r-order)
                (update :tournaments dissoc tid)
                (update :tournament-order (fn [to] (into [] (filter (fn [x] (not= x tid)) to))))))))
      (broadcast-hub! nil))
    {:status 200
     :headers {"Content-Type" "application/edn"}
     :body (pr-str (build-client-payload nil {:ok true}))}))

(def api-handler
  (-> (conimo/router
        [{:method "GET"  :path "/api/state"              :handler handle-get-state}
         {:method "POST" :path "/api/join"               :handler handle-join}
         {:method "POST" :path "/api/move"               :handler handle-move}
         {:method "POST" :path "/api/resign"             :handler handle-resign}
         {:method "POST" :path "/api/new-game"           :handler handle-new-game}
         {:method "POST" :path "/api/leave"              :handler handle-leave}
         {:method "POST" :path "/api/room/create"        :handler handle-create-room}
         {:method "POST" :path "/api/room/delete"        :handler handle-delete-room}
         {:method "POST" :path "/api/room/reclaim"       :handler handle-reclaim-seat}
         {:method "POST" :path "/api/room/time-control"  :handler handle-set-time-control}
         {:method "POST" :path "/api/room/clock-check"   :handler handle-clock-check}
         {:method "POST" :path "/api/tournament/create"  :handler handle-create-tournament}
         {:method "POST" :path "/api/tournament/join"    :handler handle-join-tournament}
         {:method "POST" :path "/api/tournament/start"   :handler handle-start-tournament}
         {:method "POST" :path "/api/tournament/delete"  :handler handle-delete-tournament}])
      (conimo/wrap-edn-body)))

;; ── 9. SSR HTML Entrypoint ──────────────────────────────────────────────────

(def *boot-ts* (str (now-ms)))

(defn app-page [req]
  [:html {:lang "en"}
    [:head
      [:title "Paw & Crown — Cute 2D Chess Rooms, Clocks & Tournaments"]
      [:meta {:charset "utf-8"}]
      [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
      [:link {:rel "preconnect" :href "https://fonts.googleapis.com"}]
      [:link {:rel "preconnect" :href "https://fonts.gstatic.com" :crossorigin "true"}]
      [:link {:rel "stylesheet" :href "https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&family=Quicksand:wght@500;600;700&family=JetBrains+Mono:wght@500;600;700&display=swap"}]
      [:script {:src (str "/coni_runtime.js?v=" *boot-ts*)}]
      [:link {:rel "stylesheet" :href (str "/style.css?v=" *boot-ts*)}]
      [:script {:type "module"} (str "window.bootConiAOT('/app.wasm?v=" *boot-ts* "');")]]
    [:body
      [:div {:id "app"}
        [:div {:style "display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fffbeb;color:#451a03;font-family:'Fredoka',sans-serif;"}
          [:div {:style "text-align:center;padding:2rem;background:#ffffff;border:3px solid #fde68a;border-radius:24px;box-shadow:0 10px 25px rgba(180,83,9,0.08);"}
            [:div {:style "font-size:3rem;margin-bottom:0.5rem;"} "🐾👑⏱️"]
            [:h2 {:style "font-weight:700;font-size:1.4rem;margin:0 0 0.4rem 0;color:#78350f;"} "Paw & Crown Cute 2D Chess"]
            [:p {:style "color:#92400e;font-size:0.95rem;margin:0;"} "Loading Game Rooms, FIDE Clocks & Tournament Arena..."]]]]]])

;; ── 10. Boot HTTP & WebSocket Server ────────────────────────────────────────

(let [port-env (try (sys-env-get "CONIMO_PORT") (catch e nil))
      port (if (and port-env (not= port-env "")) (read-string port-env) 3080)
      ws-port (+ port 1)
      s-dir (if (io/exists? "frontend") "frontend/" "chess/frontend/")]
  (conimo/start-app
    {:port port
     :ws-port ws-port
     :static-dir s-dir
     :ssr-component app-page
     :api-router api-handler}))
