#!/bin/bash

# omarchy:summary=Launch a floating pinned app (youtube) or bring its window to the focused monitor's bottom-left corner.

set -uo pipefail

# Usage: omarchy-summon [youtube]
#
# Each profile is one app kept as a picture-in-picture window: the window
# rule in hypr/hyprland.lua floats, pins, sizes and parks it when it first
# opens, so a plain launch is enough when no window exists. When one does,
# this script carries it to the focused monitor and hands it to omarchy-pip
# to fit it there again: the two panels differ in logical size, and Hyprland
# keeps a floating window's pixel size and offset across a monitor move.
#
# PATTERN is an ERE over the window class. A web app's picture-in-picture
# overlay shares the class, so windows titled Picture-in-Picture are skipped
# (Omarchy's own pip rule owns those).
case ${1:-youtube} in
youtube)
  # Chromium derives the class from the app URL, and the same web app has
  # shown up under more than one host spelling (youtube.com vs
  # www.youtube.com) once a video is playing, so match the family.
  PATTERN='^brave-(www\.)?youtube\.com__.*$'
  LAUNCH="gtk-launch YouTube"
  ;;
*)
  echo "usage: ${0##*/} [youtube]" >&2
  exit 2
  ;;
esac

# Lua dispatcher first, classic name as the pre-lua fallback (same shape as
# the other omarchy-* scripts here).
hypr_dispatch() {
  local lua="$1"
  shift
  hyprctl dispatch "$lua" >/dev/null 2>&1 || hyprctl dispatch "$@" >/dev/null
}

ADDRESS=$(hyprctl clients -j | jq -r --arg re "$PATTERN" '
  first(.[] | select((.class | test($re)) and ((.title | test("Picture.?in.?[Pp]icture")) | not)))
  | .address // empty')

if [[ -z $ADDRESS ]]; then
  exec setsid uwsm-app -- $LAUNCH >/dev/null 2>&1
fi

WINDOW="address:$ADDRESS"
MON_NAME=$(hyprctl monitors -j | jq -r '.[] | select(.focused) | .name')
[[ -n $MON_NAME ]] || exit 1

hypr_dispatch "hl.dsp.window.move({ monitor = \"$MON_NAME\", window = \"$WINDOW\" })" movewindow "mon:$MON_NAME,$WINDOW"
omarchy-pip on "$WINDOW"
hypr_dispatch "hl.dsp.focus({ window = \"$WINDOW\" })" focuswindow "$WINDOW"
