#!/bin/bash
# Handle notification click: focus the app that sent it → invoke action → dismiss
# Called by mako with the notification ID as argument

ID="$1"
[ -z "$ID" ] && exit 0

# Pull the app name out of makoctl list, scoped to this notification ID
APP=$(makoctl list 2>/dev/null | awk -v id="$ID" '
    $1 == "Notification" { if (seen) exit; if ($2 == id) seen = 1; next }
    seen && /^  App name:/ { sub(/^  App name: /, ""); print; exit }')

# Find a sway window matching the app and focus it.
# Exact app_id match first, then X11 class, then partial app_id as fallback.
if [ -n "$APP" ]; then
    TREE=$(swaymsg -t get_tree 2>/dev/null)

    CID=$(echo "$TREE" | jq -r --arg app "$APP" '
        [ .. | objects | select(.type? == "con")
          | select((.app_id? // "") != "")
          | select((.app_id | ascii_downcase) == ($app | ascii_downcase))
          | .id ][0] // empty')

    if [ -z "$CID" ]; then
        CID=$(echo "$TREE" | jq -r --arg app "$APP" '
            [ .. | objects | select(.type? == "con")
              | select((.window_properties?.class? // "") != "")
              | select((.window_properties.class | ascii_downcase) == ($app | ascii_downcase))
              | .id ][0] // empty')
    fi

    if [ -z "$CID" ]; then
        CID=$(echo "$TREE" | jq -r --arg app "$APP" '
            [ .. | objects | select(.type? == "con")
              | select((.app_id? // "") != "")
              | select((.app_id | ascii_downcase) | contains($app | ascii_downcase))
              | .id ][0] // empty')
    fi

    if [ -n "$CID" ]; then
        swaymsg "[con_id=$CID]" focus >/dev/null 2>&1
    fi
fi

# Invoke the notification's default action (may open/focus the app), then dismiss
makoctl invoke -n "$ID" >/dev/null 2>&1
makoctl dismiss -n "$ID" >/dev/null 2>&1
