{pkgs, ...}: let
  workspace-toggle = pkgs.writeShellScriptBin "workspace-toggle" ''
    #!/usr/bin/env bash
    target_workspace="$1"

    # activeworkspace always returns the underlying workspace, even when a special
    # workspace is open. Check the monitor's specialWorkspace field instead.
    special=$(${pkgs.hyprland}/bin/hyprctl monitors -j | ${pkgs.jq}/bin/jq -r '.[] | select(.focused) | .specialWorkspace.name')

    if [[ -n "$special" ]]; then
      ${pkgs.hyprland}/bin/hyprctl dispatch togglespecialworkspace "''${special#special:}"
      current=$(${pkgs.hyprland}/bin/hyprctl activeworkspace -j | ${pkgs.jq}/bin/jq -r '.id')
      if [[ $current -ne $target_workspace ]]; then
        ${pkgs.hyprland}/bin/hyprctl dispatch focusworkspaceoncurrentmonitor "$target_workspace"
      fi
    else
      current=$(${pkgs.hyprland}/bin/hyprctl activeworkspace -j | ${pkgs.jq}/bin/jq -r '.id')
      if [[ $current -eq $target_workspace ]]; then
        ${pkgs.hyprland}/bin/hyprctl dispatch workspace previous
      else
        ${pkgs.hyprland}/bin/hyprctl dispatch split:workspace "$target_workspace"
      fi
    fi
  '';
in {
  home.packages = [workspace-toggle];
}
