#!/usr/bin/env bash
# Consume TANINUX's panel/dock settings (panel.json) into eww.
#   apply           push settings live (eww update + imperative autohide)
#   watch           apply now, then re-apply whenever panel.json changes
#   get <jq-path>   read a value (used by clock.sh / dock.sh)
#
# Contract file: ~/.local/share/taninux/panel.json  (see docs/eww-panel-dock-integration.md)
set -u
CFG="${XDG_DATA_HOME:-$HOME/.local/share}/taninux/panel.json"

# seed defaults if missing, so eww always has something to read
if [ ! -f "$CFG" ]; then
  mkdir -p "$(dirname "$CFG")"
  cat > "$CFG" <<'EOF'
{
  "version": 1,
  "dock": { "autohide": true, "icon_size": 42, "hide_delay": 1.2 },
  "bar":  { "clock_format": "%H:%M %A, %d.%m.%Y",
            "modules": { "music": true, "sys": true, "updates": true, "net": true, "bt": true, "vol": true } }
}
EOF
fi

. "$(dirname "$0")/wm.sh"   # niri helpers
j() { jq -r "$1" "$CFG" 2>/dev/null; }

apply() {
  # --- live vars (no reload) ---
  local icon modules
  icon=$(j '.dock.icon_size // 42'); case "$icon" in ''|*[!0-9]*) icon=42;; esac
  [ "$icon" -lt 24 ] && icon=24; [ "$icon" -gt 64 ] && icon=64
  modules=$(jq -c '.bar.modules // {}' "$CFG" 2>/dev/null); [ -z "$modules" ] && modules='{}'
  eww update cfg-icon-size="$icon" "cfg-modules=$modules" 2>/dev/null

  # --- autohide --- the dock window stays mapped; we flip dock-open (revealer)
  # and the hover trigger. autohide off = parked open; on = hover to reveal.
  eww open dock 2>/dev/null
  if [ "$(j 'if .dock.autohide == false then "false" else "true" end')" = "false" ]; then
    eww update dock-open=true 2>/dev/null; eww close dock-trigger 2>/dev/null   # always visible
  else
    eww update dock-open=false 2>/dev/null; eww open dock-trigger 2>/dev/null   # hover to reveal
  fi
  # clock_format + hide_delay are read on demand by clock.sh / dock.sh.
}

case "${1:-apply}" in
  get)   j "${2:-.}" ;;
  apply) apply ;;
  toggle-autohide)
    cur=$(j 'if .dock.autohide == false then "false" else "true" end')
    new=$([ "$cur" = "false" ] && echo true || echo false)
    tmp=$(mktemp)
    jq ".dock.autohide = $new" "$CFG" > "$tmp" 2>/dev/null && mv "$tmp" "$CFG"
    apply
    ;;
  watch)
    apply
    last=$(stat -c %Y "$CFG" 2>/dev/null || echo 0)
    while :; do
      sleep 2
      now=$(stat -c %Y "$CFG" 2>/dev/null || echo 0)
      [ "$now" != "$last" ] && { last="$now"; apply; }
    done ;;
esac
