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

# Drop concurrent invocations, but recover from stale locks (dead processes)
LOCK="/tmp/eww_panel_toggle.lock"
if [ -f "$LOCK" ] && kill -0 "$(cat "$LOCK" 2>/dev/null)" 2>/dev/null; then
  exit 0
fi
echo $$ > "$LOCK"
trap 'rm -f "$LOCK"' EXIT

CURRENT=$(eww get active-panel 2>/dev/null | tr -d '"')

open_popup() {
  local screen
  screen=$(hyprctl monitors -j 2>/dev/null | jq -r '.[] | select(.focused == true) | .name' | head -n1)
  if [ -n "$screen" ]; then
    eww open popup --screen "$screen"
  else
    eww open popup
  fi
}

if [ "$CURRENT" = "$PANEL" ]; then
  eww update active-panel=""
  eww close popup 2>/dev/null
else
  eww update active-panel="$PANEL"
  open_popup
fi
