#!/bin/bash
# Handle notification click: focus app → invoke action → close
# Called by mako with notification ID as parameter

ID="$1"

if [ -z "$ID" ]; then
    exit 0
fi

# Get app name from notification using makoctl
APPNAME=$(makoctl list | grep -A 2 "^Notification $ID" | grep "App name:" | cut -d: -f2- | xargs)

# Step 1: Focus the application window in Sway (if app name found)
if [ -n "$APPNAME" ]; then
    # Get the workspace of the window
    WORKSPACE=$(swaymsg -t get_tree | jq -r ".. | select(.app_id?==\"$APPNAME\" or .window_properties?.class?==\"$APPNAME\") | .workspace" | head -1)

    # If workspace not found, try case-insensitive
    if [ -z "$WORKSPACE" ] || [ "$WORKSPACE" = "null" ]; then
        WORKSPACE=$(swaymsg -t get_tree | jq -r ".. | select(.app_id?|test(\"$APPNAME\";\"i\") or .window_properties?.class?|test(\"$APPNAME\";\"i\")) | .workspace" | head -1)
    fi

    # Switch to the workspace if found
    if [ -n "$WORKSPACE" ] && [ "$WORKSPACE" != "null" ]; then
        swaymsg workspace "$WORKSPACE" 2>/dev/null
        sleep 0.1
    fi

    # Now focus the window
    swaymsg "[app_id=\"$APPNAME\"]" focus 2>/dev/null || \
    swaymsg "[app_id=\"(?i)$APPNAME\"]" focus 2>/dev/null || \
    swaymsg "[class=\"$APPNAME\"]" focus 2>/dev/null || \
    swaymsg "[class=\"(?i)$APPNAME\"]" focus 2>/dev/null

    sleep 0.1
fi

# Step 2: Invoke the notification's default action (if any)
makoctl invoke -n "$ID" 2>/dev/null

# Step 3: Dismiss the notification
makoctl dismiss -n "$ID" 2>/dev/null
