#!/bin/bash

# omarchy:summary=Toggle to pop-out a tile to stay fixed on a display basis.
# omarchy:args=[width height x y]

width=${1:-1300}
height=${2:-900}
x=${3:-}
y=${4:-}

read -r pinned addr < <(hyprctl activewindow -j | jq -r '"\(.pinned // false) \(.address // "")"')
[[ -n $addr ]] || exit 0
window="address:$addr"

hypr_dispatch() {
  local lua="$1"
  shift

  hyprctl dispatch "$lua" >/dev/null 2>&1 || hyprctl dispatch "$@" >/dev/null
}

hypr_batch() {
  local joined="" cmd out line total=0 ok_count=0
  for cmd in "$@"; do
    joined+="${joined:+ ; }dispatch $cmd"
  done
  out=$(hyprctl --batch "$joined" 2>/dev/null) || return 1
  while IFS= read -r line; do
    [[ -n $line ]] || continue
    (( ++total ))
    [[ $line == "ok" ]] && (( ++ok_count ))
  done <<<"$out"
  if (( total == $# && ok_count == $# )); then
    return 0
  elif (( ok_count == 0 )); then
    return 1
  fi
  return 2
}

if [[ $pinned == "true" ]]; then
  status=0
  hypr_batch \
    "hl.dsp.window.pin({ window = \"$window\" })" \
    "hl.dsp.window.float({ window = \"$window\", action = \"toggle\" })" \
    "hl.dsp.window.tag({ window = \"$window\", tag = \"-pop\" })" || status=$?
  if (( status == 1 )); then
    hypr_dispatch "hl.dsp.window.pin({ window = \"$window\" })" pin "$window"
    hypr_dispatch "hl.dsp.window.float({ window = \"$window\", action = \"toggle\" })" togglefloating "$window"
    hypr_dispatch "hl.dsp.window.tag({ window = \"$window\", tag = \"-pop\" })" tagwindow -pop "$window"
  elif (( status != 0 )); then
    exit 1
  fi
else
  if [[ -n $x && -n $y ]]; then
    move_lua="hl.dsp.window.move({ window = \"$window\", x = $x, y = $y })"
  else
    move_lua="hl.dsp.window.center({ window = \"$window\" })"
  fi

  status=0
  hypr_batch \
    "hl.dsp.window.float({ window = \"$window\", action = \"toggle\" })" \
    "hl.dsp.window.resize({ window = \"$window\", x = $width, y = $height })" \
    "$move_lua" \
    "hl.dsp.window.pin({ window = \"$window\" })" \
    "hl.dsp.window.alter_zorder({ window = \"$window\", mode = \"top\" })" \
    "hl.dsp.window.tag({ window = \"$window\", tag = \"+pop\" })" || status=$?
  if (( status == 1 )); then
    hypr_dispatch "hl.dsp.window.float({ window = \"$window\", action = \"toggle\" })" togglefloating "$window"
    hypr_dispatch "hl.dsp.window.resize({ window = \"$window\", x = $width, y = $height })" resizeactive exact "$width" "$height" "$window"

    if [[ -n $x && -n $y ]]; then
      hypr_dispatch "$move_lua" moveactive "$x" "$y" "$window"
    else
      hypr_dispatch "$move_lua" centerwindow "$window"
    fi

    hypr_dispatch "hl.dsp.window.pin({ window = \"$window\" })" pin "$window"
    hypr_dispatch "hl.dsp.window.alter_zorder({ window = \"$window\", mode = \"top\" })" alterzorder top "$window"
    hypr_dispatch "hl.dsp.window.tag({ window = \"$window\", tag = \"+pop\" })" tagwindow +pop "$window"
  elif (( status != 0 )); then
    exit 1
  fi
fi
