{
  pkgs,
  config,
  lib,
  myConfig,
  ...
}: let
  # TODO: rewrite
  wallpaperDir = "${config.home.homeDirectory}/.config/nixos/assets/Wallpapers";
  defaultWallpaper = "${wallpaperDir}/${myConfig.hyprland.wallpaper}";
  cacheWallpaper = "${config.home.homeDirectory}/.cache/current_wallpaper";

  switch-wallpaper = pkgs.writeShellScriptBin "hakase-wallpaper-switch" ''
    if [[ "$1" != "run" ]]; then
      if command -v ghostty &> /dev/null; then
         ghostty --class="org.hakase.switch-wallpaper" --title="Wallpaper Selector" -e bash -c "hakase-wallpaper-switch run || read -p 'Hit Enter to close...'"
         exit 0
      elif command -v kitty &> /dev/null; then
         kitty --class org.hakase.switch-wallpaper --title "Wallpaper Selector" -e bash -c "hakase-wallpaper-switch run || read -p 'Hit Enter to close...'"
         exit 0
      fi
    fi

    tmp_file=$(mktemp)
    target_dir="$HOME/Pictures/Wallpapers"
    if [ ! -d "$target_dir" ]; then
      target_dir="$HOME"
    fi

    # Ensure we are in a terminal that supports yazi
    ${pkgs.yazi}/bin/yazi "$target_dir" --chooser-file="$tmp_file"

    if [ ! -f "$tmp_file" ]; then
      echo "No selection file created."
      exit 1
    fi

    WALLPAPER=$(cat "$tmp_file")
    rm -f "$tmp_file"

    if [ -z "$WALLPAPER" ]; then
        echo "No wallpaper selected."
        exit 0
    fi

    # Persistence logic
    CACHE_FILE="$HOME/.cache/current_wallpaper"
    cp "$WALLPAPER" "$CACHE_FILE"

    # Reload hyprpaper
    ${pkgs.hyprland}/bin/hyprctl hyprpaper unload all
    ${pkgs.hyprland}/bin/hyprctl hyprpaper preload "$CACHE_FILE"
    ${pkgs.hyprland}/bin/hyprctl hyprpaper wallpaper ",$CACHE_FILE"

    exec matugen image "$CACHE_FILE"
  '';
in {
  wayland.windowManager.hyprland.settings = {
    exec-once = [
      "uwsm app -- hyprpaper"
    ];
  };

  services.hyprpaper = {
    enable = true;
    settings = {
      preload = [cacheWallpaper];
      wallpaper = [
        ",${cacheWallpaper}"
      ];
    };
  };

  home.packages = [
    switch-wallpaper
  ];

  home.activation.setupWallpaper = lib.hm.dag.entryAfter ["writeBoundary"] ''
    if [ ! -f "${cacheWallpaper}" ]; then
      mkdir -p "$(dirname "${cacheWallpaper}")"
      if [ -f "${defaultWallpaper}" ]; then
        cp "${defaultWallpaper}" "${cacheWallpaper}"
      else
        echo "Default wallpaper not found at ${defaultWallpaper}"
        touch "${cacheWallpaper}"
      fi
    fi
  '';

  systemd.user.startServices = "sd-switch";
}
