#!/bin/bash

# omarchy:summary=Toggle the scratchpad, starting the kitty/herdr scratch terminal when it holds no windows.

set -uo pipefail

NAME="scratchpad"
WORKSPACE="special:$NAME"
CLASS="kitty-herdr"
LAUNCH="kitty --class=$CLASS --config $HOME/.config/kitty/herdr.conf"

# Windows living on the scratchpad, whether it is shown or hidden.
scratch_windows() {
  hyprctl clients -j | jq --arg ws "$WORKSPACE" '[.[] | select(.workspace.name == $ws)] | length'
}

# True when some monitor currently displays the scratchpad.
scratch_visible() {
  hyprctl monitors -j | jq -e --arg ws "$WORKSPACE" 'any(.[]; .specialWorkspace.name == $ws)' >/dev/null
}

# Hyprland's lua config takes lua expressions on `hyprctl dispatch`; the
# classic dispatcher is the pre-lua fallback (same shape as omarchy-cycle).
toggle() {
  hyprctl dispatch "hl.dsp.workspace.toggle_special(\"$NAME\")" >/dev/null 2>&1 ||
    hyprctl dispatch togglespecialworkspace "$NAME" >/dev/null
}

if (($(scratch_windows) > 0)); then
  toggle
  exit 0
fi

# Empty scratchpad: there is nothing to toggle into view, so start the herdr
# terminal instead. hypr/hyprland.lua pins kitty-herdr to the scratchpad, so
# only the reveal is left here — and deciding it after the window lands keeps
# this correct whether or not the rule already showed the workspace.
setsid uwsm-app -- $LAUNCH >/dev/null 2>&1 &

for _ in {1..40}; do
  sleep 0.1
  (($(scratch_windows) > 0)) && break
done

scratch_visible || toggle
