#!/bin/bash

screensaver_in_focus() {
  hyprctl activewindow -j | jq -e '.class == "com.omarchy.screensaver"' >/dev/null 2>&1
}

exit_screensaver() {
  # Clear and reset terminal
  printf '\033[2J\033[H\033[0m'
  hyprctl keyword cursor:invisible false
  pkill -x tte 2>/dev/null
  exit 0
}

trap exit_screensaver SIGINT SIGTERM SIGHUP SIGQUIT

# Set background and cursor colors using OSC escape sequences
printf '\033]11;rgb:00/00/00\007'  # Background color to black
printf '\033]12;rgb:00/00/00\007'  # Cursor color to black

# Clear screen and fill with black background
printf '\033[48;2;0;0;0m\033[2J\033[H'

hyprctl keyword cursor:invisible true &>/dev/null

while true; do
  effect=$(tte 2>&1 | grep -oP '{\K[^}]+' | tr ',' ' ' | tr ' ' '\n' | sed -n '/^beams$/,$p' | sort -u | shuf -n1)

  tte -i ~/.config/omarchy/branding/screensaver.txt \
    --frame-rate 240 --canvas-width 0 --canvas-height 0 --anchor-canvas c --anchor-text c --no-eol \
    "$effect" &

  while pgrep -x tte >/dev/null; do
    if read -n 1 -t 3 || ! screensaver_in_focus; then
      exit_screensaver
    fi
  done
done
