;; ---------------------------------------------------------------------------
;; L2: State Machine — traffic light
;; ---------------------------------------------------------------------------
(defisland ()
  (let ((state (signal "red"))
        (transitions (dict "red" "green" "green" "yellow" "yellow" "red"))
        (auto (signal false)))
    (let ((_eff (effect (fn ()
            (when (deref auto)
              (let ((delay (if (= (deref state) "yellow") 1000 2500)))
                (let ((id (set-timeout
                    (fn () (reset! state (get transitions (deref state))))
                    delay)))
                  (fn () (clear-timeout id)))))))))
      (div (~tw :tokens "rounded border border-violet-200 bg-violet-50 p-4 my-4")
        (div (~tw :tokens "flex items-center gap-6")
          ;; Traffic light
          (div (~tw :tokens "flex flex-col gap-2 p-3 bg-stone-800 rounded-lg")
            (div :class (str "w-10 h-10 rounded-full transition-colors "
                  (if (= (deref state) "red") "bg-red-500 shadow-lg shadow-red-500/50" "bg-red-900/30")))
            (div :class (str "w-10 h-10 rounded-full transition-colors "
                  (if (= (deref state) "yellow") "bg-yellow-400 shadow-lg shadow-yellow-400/50" "bg-yellow-900/30")))
            (div :class (str "w-10 h-10 rounded-full transition-colors "
                  (if (= (deref state) "green") "bg-green-500 shadow-lg shadow-green-500/50" "bg-green-900/30"))))
          ;; Controls
          (div (~tw :tokens "space-y-3")
            (div (~tw :tokens "flex items-center gap-2")
              (span (~tw :tokens "text-sm font-medium text-stone-700") "State:")
              (span (~tw :tokens "text-sm font-mono text-violet-700") (deref state)))
            (div (~tw :tokens "flex items-center gap-2")
              (button (~tw :tokens "px-3 py-1 rounded bg-violet-600 text-white text-sm font-medium hover:bg-violet-700")
                :on-click (fn (e)
                  (reset! state (get transitions (deref state))))
                "Next")
              (button :class (str "px-3 py-1 rounded text-sm font-medium "
                      (if (deref auto)
                        "bg-amber-500 text-white hover:bg-amber-600"
                        "bg-stone-300 text-stone-700 hover:bg-stone-400"))
                :on-click (fn (e) (swap! auto not))
                (if (deref auto) "Auto: ON" "Auto: OFF")))))))))
