{pkgs, ...}: let
  # Max window size (leave room for waybar/hyprbars)
  maxW = 2800;
  maxH = 1100;

  swayimg-wrapper = pkgs.writeShellScriptBin "swayimg-wrapper" ''
    if [ -z "$1" ]; then
      exec ${pkgs.swayimg}/bin/swayimg
    fi

    # Get image dimensions
    dims=$(${pkgs.file}/bin/file -b "$1" | ${pkgs.gnugrep}/bin/grep -oP '\d+ ?x ?\d+' | head -1 | tr -d ' ')
    if [ -z "$dims" ]; then
      # Fallback if file doesn't report dimensions
      exec ${pkgs.swayimg}/bin/swayimg "$@"
    fi

    imgW=$(echo "$dims" | cut -dx -f1)
    imgH=$(echo "$dims" | cut -dx -f2)

    # Calculate scale to fit within max bounds while preserving aspect ratio
    scaleW=$(echo "scale=4; ${toString maxW} / $imgW" | ${pkgs.bc}/bin/bc)
    scaleH=$(echo "scale=4; ${toString maxH} / $imgH" | ${pkgs.bc}/bin/bc)

    # Use the smaller scale factor
    if [ $(echo "$scaleW < $scaleH" | ${pkgs.bc}/bin/bc) -eq 1 ]; then
      scale=$scaleW
    else
      scale=$scaleH
    fi

    # Only scale down, not up
    if [ $(echo "$scale >= 1" | ${pkgs.bc}/bin/bc) -eq 1 ]; then
      exec ${pkgs.swayimg}/bin/swayimg "$@"
    fi

    # Calculate new size
    newW=$(echo "$imgW * $scale / 1" | ${pkgs.bc}/bin/bc)
    newH=$(echo "$imgH * $scale / 1" | ${pkgs.bc}/bin/bc)

    exec ${pkgs.swayimg}/bin/swayimg --size="$newW,$newH" "$@"
  '';
in {
  home.packages = [pkgs.swayimg swayimg-wrapper];

  xdg.mimeApps = {
    enable = true;
    defaultApplications = {
      "image/png" = "swayimg-wrapper.desktop";
      "image/jpeg" = "swayimg-wrapper.desktop";
      "image/gif" = "swayimg-wrapper.desktop";
      "image/webp" = "swayimg-wrapper.desktop";
      "image/bmp" = "swayimg-wrapper.desktop";
      "image/svg+xml" = "swayimg-wrapper.desktop";
      "image/tiff" = "swayimg-wrapper.desktop";
    };
  };

  xdg.desktopEntries.swayimg-wrapper = {
    name = "Swayimg";
    exec = "swayimg-wrapper %f";
    terminal = false;
    type = "Application";
    mimeType = ["image/png" "image/jpeg" "image/gif" "image/webp" "image/bmp" "image/svg+xml" "image/tiff"];
  };

  # swayimg config
  xdg.configFile."swayimg/config".text = ''
    [viewer]
    scale = fit

    [info]
    show = no
  '';

  wayland.windowManager.hyprland.settings.windowrule = [
    # --- IMAGE VIEWER (swayimg) ---
    "match:class ^(swayimg)$, float on"
    "match:class ^(swayimg)$, center on"
  ];
}
