#!/usr/bin/env bash
set -euo pipefail

WALLPAPER_DIR="${HOME}/Pictures/wallpaper"
EXTENSIONS="jpg|jpeg|png|gif|webp|bmp|tiff|tga|svg|avif"

declare -A wall_map

while IFS= read -r -d '' path; do
  name="$(basename "$path")"
  wall_map["$name"]="$path"
done < <(
  find "$WALLPAPER_DIR" -maxdepth 1 -type f \
    -regextype posix-extended \
    -iregex ".*\.(${EXTENSIONS})" \
    -print0 | sort -z
)

chosen="$(
  for name in "${!wall_map[@]}"; do
    printf '%s\0icon\x1fthumbnail://%s\n' "$name" "${wall_map[$name]}"
  done | sort | rofi \
    -dmenu \
    -show-icons \
    -i \
    -p "wallpaper" \
    -theme "$HOME/.config/rofi/wallpaper.rasi" \
    -kb-accept-entry "Return,KP_Enter" \
    -kb-element-next "Tab" \
    -kb-element-prev "ISO_Left_Tab"
)"

[[ -z "${chosen:-}" ]] && exit 0

full_path="${wall_map[$chosen]:-}"
if [[ -z "${full_path}" || ! -f "${full_path}" ]]; then
  notify-send "wallpaper-picker" "Not found: $chosen" --urgency=critical
  exit 1
fi

awww img "$full_path" --transition-type grow --transition-step 90

persist="$HOME/.config/niri/wallpaper-restore.sh"
mkdir -p "$(dirname "$persist")"

cat > "$persist" <<EOF
#!/usr/bin/env bash
pgrep -x awww-daemon >/dev/null || awww-daemon &
sleep 0.5
awww img "$full_path" --transition-type simple
EOF

chmod +x "$persist"

notify-send "Wallpaper" "$chosen" --urgency=low
