#!/usr/bin/env bash
# Toggle an eww panel with a click-outside backdrop. One panel open at a time.
#   toggle <window>   open it (closing others) or close it if already open
#   close             close the open panel + backdrop
#
# IMPORTANT (niri/eww): eww KILLS an event-handler process as soon as it lingers
# (a `sleep`). So the panel buttons / backdrop call this script, and we must NOT
# rely on a sleep surviving inside it: the **backdrop is always closed FIRST and
# instantly** (so a kill can never strand a full-screen click-eater → no lockout),
# and the only sleep (for the slide animation) runs in a DETACHED `setsid`
# process that eww can't kill.
set -u

PANELS="control-center calendar music sysmon updates"

# detached slide helper: $1 = panel-open target, rest = windows to close after anim
_defer_close() {  # usage: _defer_close "win win2 ..."
  # Wait the full fade (100ms) + a margin BEFORE unmapping, so the window never
  # pops away while still partly visible (that read as a "hard" cut on close).
  setsid -f sh -c "sleep 0.2; eww close $1" >/dev/null 2>&1
}

case "${1:-close}" in
  toggle)
    win="${2:-}"
    [ -n "$win" ] || exit 0
    if eww active-windows 2>/dev/null | grep -q "^${win}:"; then
      # already open → dismiss (backdrop first, then animated close)
      eww close panel-backdrop 2>/dev/null
      eww update panel-open=false 2>/dev/null
      _defer_close "$win"
    else
      eww close $PANELS panel-backdrop 2>/dev/null   # only one at a time
      eww update panel-open=false 2>/dev/null         # start collapsed
      eww open panel-backdrop 2>/dev/null             # backdrop first (below)
      eww open "$win" 2>/dev/null                     # panel on top (collapsed)
      # reveal AFTER realize, in a detached process so an eww-killed handler
      # can't leave the panel stuck collapsed under an open backdrop.
      setsid -f sh -c 'sleep 0.12; eww update panel-open=true' >/dev/null 2>&1
    fi
    ;;
  close)
    eww close panel-backdrop 2>/dev/null              # kill any lockout instantly
    eww update panel-open=false 2>/dev/null           # slide out
    _defer_close "$PANELS"
    ;;
esac
