#!/usr/bin/env bash
PANEL="$1"

# Atomic lock: flock acquires exclusively or exits immediately.
# Released automatically when the process exits (no trap needed).
exec 9>"/tmp/eww_panel_toggle.lock"
flock -n 9 || exit 0

# Every eww call must run with fd 9 closed (9>&-): `eww open` daemonizes and
# would inherit the fd, holding the flock forever and wedging all later toggles.
CURRENT=$(eww get active-panel 2>/dev/null 9>&- | tr -d '"')

if [ "$CURRENT" = "$PANEL" ]; then
  eww update active-panel="" 9>&-
  eww close popup 2>/dev/null 9>&-
else
  eww update active-panel="$PANEL" 9>&-
  eww close popup 2>/dev/null 9>&-
  eww-open-on-current-screen popup 9>&-
fi
