{
  config,
  pkgs,
  lib,
  ...
}: let
  schema = "org.gnome.desktop.a11y.applications";
  key = "screen-keyboard-enabled";

  squeekboard_toggle = pkgs.writeShellScriptBin "squeekboard_toggle" ''
    if [ "$(gsettings get ${schema} ${key})" == "true" ]; then
      gsettings set ${schema} ${key} false
    else
      gsettings set ${schema} ${key} true
    fi
  '';

  squeekboard_format = pkgs.writeShellScriptBin "squeekboard_format" ''
    if [ "$(gsettings get ${schema} ${key})" == "true" ]; then
      echo '{ "text": "󰌌", "tooltip": "enabled", "percentage": 100 }'
    else
      echo '{ "text": "󰌐", "tooltip": "disabled", "percentage": 0 }'
    fi
  '';

  rotate_lisgd = pkgs.writeShellScriptBin "rotate_lisgd" ''
    # PREV_ORIENTATION and ORIENTATION are given by rot8

    LISGD_INPUT=/dev/input/event14
    # open nwggrid by swiping up from the bottom edge
    LISGD_ACTIONS=("1,DU,B,*,R,${pkgs.sway}/bin/swaymsg exec ${pkgs.nwg-launchers}/bin/nwggrid -client")
    # close window by swiping down with 3 fingers
    LISGD_ACTIONS+=("3,UD,*,L,R,${pkgs.sway}/bin/swaymsg kill")

    # move window left by swiping left with 2 fingers
    LISGD_ACTIONS+=("2,UD,*,*,R,${pkgs.sway}/bin/swaymsg move left")
    # move window down by swiping down with 2 fingers
    LISGD_ACTIONS+=("2,UD,*,*,R,${pkgs.sway}/bin/swaymsg move down")
    # move window up by swiping up with 2 fingers
    LISGD_ACTIONS+=("2,UD,*,*,R,${pkgs.sway}/bin/swaymsg move up")
    # move window right by swiping right with 2 fingers
    LISGD_ACTIONS+=("2,UD,*,*,R,${pkgs.sway}/bin/swaymsg move right")

    LISGD_ACTION_OPTIONS=()
    for str in "''${LISGD_ACTIONS[@]}"; do
     LISGD_ACTION_OPTIONS+=("-g" "$str")
    done

    ${pkgs.killall}/bin/killall lisgd

    ${pkgs.lisgd}/bin/lisgd -v -d "$LISGD_INPUT" "''${LISGD_ACTION_OPTIONS[@]}" &
  '';

  # bash script to let dbus know about impotant env variables and
  # propagate them to relevent services run at the end of sway config
  dbus-sway-environment = pkgs.writeShellScriptBin "dbus-sway-environment" ''
    dbus-update-activation-environment --systemd WAYLAND_DISPLAY XDG_CURRENT_DESKTOP=sway
    systemctl --user stop pipewire pipewire-media-session xdg-desktop-portal xdg-desktop-portal-wlr
    systemctl --user start pipewire pipewire-media-session xdg-desktop-portal xdg-desktop-portal-wlr
  '';

  # currently, there is some friction between sway and gtk:
  # https://github.com/swaywm/sway/wiki/GTK-3-settings-on-Wayland
  configure-gtk = pkgs.writeShellScriptBin "configure-gtk" ''
    gnome_schema=org.gnome.desktop.interface
    gsettings set $gnome_schema gtk-theme 'Dracula'
  '';
in {
  home.packages = with pkgs; [
    waybar # status bar
    swaylock # screen locking
    swayidle # automatic screen locking after system idle time
    kanshi # hotswap displays
    foot # terminal
    keepassxc # used for secrets instead of gnome-keyring
  ];

  wayland.windowManager.sway = {
    enable = true;
    systemd = {
      enable = true;
      xdgAutostart = false;
    };

    wrapperFeatures = {
      gtk = true;
    };

    config = {
      output = let
        bgdir = "~/Documents/Blender/desktop background Informatiker";
        bg1080 = bgdir + "/render 1080p new color.png";
        bg1080vert = bgdir + "/render 1080p hochkant new.png";
        bg4k = bgdir + "/render 4K new color.png";
      in {
        eDP-1 = {
          bg = "'${bg1080}' fit";
        };
        HDMI-A-1 = {
          bg = "'${bg4k}' fit";
        };
        DP-3 = {
          bg = "'${bg1080}' fit";
        };
        DP-4 = {
          bg = "'${bg1080}' fit";
        };
        DP-5 = {
          bg = "'${bg1080vert}' fit";
        };
        DP-6 = {
          bg = "'${bg1080}' fit";
        };
        DP-7 = {
          bg = "'${bg1080vert}' fit";
        };
      };

      input = {
        "*" = {
          xkb_layout = "de";
          xkb_options = "caps:ctrl_modifier";
          xkb_numlock = "enable";
        };
        "type:touchpad" = {
          tap = "enable";
          natural_scroll = "enable";
        };
        # map laptop touchscreen to laptop display
        "1267:11676:ELAN2513:00_04F3:2D9C" = {
          map_to_output = "'AU Optronics 0x4B2D Unknown'";
        };
        # map laptop stylus to laptop display
        "1267:11676:ELAN2513:00_04F3:2D9C_Stylus" = {
          map_to_output = "'AU Optronics 0x4B2D Unknown'";
        };
      };

      modifier = "Mod4";
      keybindings = let
        modifier = config.wayland.windowManager.sway.config.modifier;
      in
        lib.mkOptionDefault {
          # special workspaces
          "${modifier}+1" = "workspace main";
          "${modifier}+2" = "workspace term";
          "${modifier}+3" = "workspace msg";
          "${modifier}+4" = "workspace music";
          "${modifier}+Shift+1" = "move container to workspace main";
          "${modifier}+Shift+2" = "move container to workspace term";
          "${modifier}+Shift+3" = "move container to workspace msg";
          "${modifier}+Shift+4" = "move container to workspace music";

          # screen capture
          "${modifier}+Print" = ''exec ${pkgs.grim}/bin/grim -g "$(${pkgs.slurp}/bin/slurp)" - | ${pkgs.wl-clipboard}/bin/wl-copy'';
          "${modifier}+Shift+Print" = ''exec ${pkgs.wf-recorder}/bin/wf-recorder -g "$(${pkgs.slurp}/bin/slurp)" -f "$HOME/Videos/screencapture_$(${pkgs.coreutils}/bin/date +%F-%T).mp4"'';

          # brightness
          "XF86MonBrightnessDown" = "exec ${pkgs.light}/bin/light -U 5";
          "XF86MonBrightnessUp" = "exec ${pkgs.light}/bin/light -A 5";
          # volume
          "XF86AudioRaiseVolume" = "exec '${pkgs.pulseaudio}/bin/pactl set-sink-volume @DEFAULT_SINK@ +1%'";
          "XF86AudioLowerVolume" = "exec '${pkgs.pulseaudio}/bin/pactl set-sink-volume @DEFAULT_SINK@ -1%'";
          "XF86AudioMute" = "exec '${pkgs.pulseaudio}/bin/pactl set-sink-mute @DEFAULT_SINK@ toggle'";

          # custom pause mode similar to typical system shutdown menus
          "${modifier}+F12" = "mode pause-break";
        };
      menu = "${pkgs.nwg-launchers}/bin/nwggrid -client";

      # use foot as default terminal
      terminal = "foot";
      assigns = {
        "main" = [{app_id = "firefox";}];
        "term" = [{app_id = "foot-startup";}];
        "msg" = [{title = "\\[Locked\\] - KeePassXC$";}];
      };
      bars = [];

      fonts = {
        names = ["FiraCode Nerd Font"];
        size = 11.0;
      };

      modes = {
        pause-break = {
          e = "exec --no-startup-id swaymsg exit, mode default";
          s = "exec --no-startup-id ${pkgs.dash}/bin/dash -c '${pkgs.swaylock}/bin/swaylock & systemctl suspend-then-hibernate', mode default";
          r = "exec --no-startup-id systemctl reboot";
          End = "exec --no-startup-id systemctl poweroff";
          Return = "mode default";
          Escape = "mode default";
        };
      };

      startup = [
        {command = "${dbus-sway-environment}/bin/dbus-sway-environment";}
        {command = "${configure-gtk}/bin/configure-gtk";}
        {command = "${pkgs.squeekboard}/bin/squeekboard";}
        {command = "${pkgs.rot8}/bin/rot8 -n 10 -h ${rotate_lisgd}/bin/rotate_lisgd";}
        {command = "${rotate_lisgd}/bin/rotate_lisgd";}
        {command = "${pkgs.nwg-launchers}/bin/nwggrid-server -fp";}
        {command = "${pkgs.keepassxc}/bin/keepassxc";}
        {command = "${pkgs.waybar}/bin/waybar";}
        {command = "${pkgs.foot}/bin/foot -a foot-startup";}
        {command = "${pkgs.networkmanagerapplet}/bin/nm-applet";}
      ];

      defaultWorkspace = "main";
      workspaceAutoBackAndForth = true;
      workspaceOutputAssign = [
        {
          workspace = "main";
          output = ["DP-3" "DP-4" "DP-6" "HDMI-A-1" "eDP-1"];
        }
        {
          workspace = "term";
          output = ["DP-5" "DP-4" "DP-7" "eDP-1"];
        }
        {
          workspace = "msg";
          output = ["eDP-1"];
        }
        {
          workspace = "music";
          output = ["eDP-1"];
        }
        {
          workspace = "5";
          output = ["DP-3" "DP-4" "DP-6" "HDMI-A-1" "eDP-1"];
        }
      ];

      colors = {
        background = "#00000000";
        focused = {
          border = "#00FFEE";
          background = "#4477AA";
          text = "#F0F0F0";
          childBorder = "#00FFEE";
          indicator = "#00AA88";
        };
        focusedInactive = {
          border = "#626262";
          background = "#444444";
          text = "#F0F0F0";
          childBorder = "#626262";
          indicator = "#00AA88";
        };
        placeholder = {
          border = "#313131";
          background = "#222222";
          text = "#F0F0F0";
          childBorder = "#313131";
          indicator = "#005544";
        };
        unfocused = {
          border = "#313131";
          background = "#222222";
          text = "#F0F0F0";
          childBorder = "#313131";
          indicator = "#00AA88";
        };
        urgent = {
          border = "#FF3131";
          background = "#882222";
          text = "#F0F0F0";
          childBorder = "#FF3131";
          indicator = "#00AA88";
        };
      };

      focus.mouseWarping = true;

      gaps = {
        inner = 5;
        smartGaps = true;
        smartBorders = "no_gaps";
      };
      window.titlebar = false;
    };

    extraConfig = ''
      bindswitch --reload --locked lid:on exec "[ $(${pkgs.sway}/bin/swaymsg -t get_outputs | ${pkgs.jq}/bin/jq '. | length') -gt 1 ] && ${pkgs.sway}/bin/swaymsg output eDP-1 disable"
      bindswitch --reload --locked lid:off output eDP-1 enable
    '';
  };

  programs.waybar = {
    enable = true;
    settings = {
      mainBar = {
        layer = "top";
        position = "top";
        height = 26;
        modules-left = ["sway/workspaces" "sway/mode"];
        modules-center = ["sway/window"];
        modules-right = ["mpd" "tray" "custom/squeekboard" "sway/language" "clock" "backlight" "battery" "network"];

        "sway/workspaces" = {
          disable-scroll = true;
          all-outputs = false;
          format = "<span size='150%'>{icon}</span> {name}";
          format-icons = {
            "main" = "󰈹";
            "term" = "";
            "msg" = "󰷹";
            "music" = "󰫔";
            "urgent" = "";
            "focused" = "";
            "default" = "";
          };
        };

        "mpd" = {
          format = "{stateIcon}{consumeIcon}{randomIcon}{repeatIcon}{singleIcon} {title} ({elapsedTime:%M:%S}/{totalTime:%M:%S}) {volume}";
          format-stopped = "{stateIcon}{randomIcon}{repeatIcon}{singleIcon} Stopped {volume}";
          format-disconnected = "";
          unkown-tag = "N/A";
          interval = 2;
          consume-icons = {
            on = "󰮯 ";
            off = "";
          };
          random-icons = {
            on = "󰒟 ";
            off = "󰒞 ";
          };
          repeat-icons = {
            on = "󰑖 ";
            off = "󰑗 ";
          };
          single-icons = {
            on = "󰑘 ";
            off = "";
          };
          state-icons = {
            paused = "󰏤 ";
            playing = "󰐊 ";
          };
          max-length = 50;
        };

        "tray" = {
          spacing = 10;
        };

        "custom/squeekboard" = {
          format = "{}";
          exec = "${squeekboard_format}/bin/squeekboard_format";
          return-type = "json";
          exec-on-event = true;
          interval = 2;
          on-click = "${squeekboard_toggle}/bin/squeekboard_toggle";
        };

        "sway/language" = {
          format = "{shortDescription}";
          tooltip = false;
        };

        "clock" = {
          interval = 60;
          format = "{:%a %d.%m %I:%M}";
        };

        "backlight" = {
          format = "{percent}% {icon}";
          format-icons = ["󰹐" "󱩎" "󱩏" "󱩐" "󱩑" "󱩒" "󱩓" "󱩔" "󱩕" "󱩖" "󰛨"];
        };

        "battery" = {
          format = "{capacity}% {icon}";
          format-icons = ["󰂎" "󰁺" "󰁻" "󰁼" "󰁽" "󰁾" "󰁿" "󰂀" "󰂁" "󰂂" "󰁹"];
        };

        "network" = {
          format-wifi = "{essid} ({signalStrength}%) 󰖩";
          format-ethernet = "{ipaddr}/{cidr} 󰈀";
          tooltip-format = "{ifname} via {gwaddr} 󰌘";
          format-disconnected = "󰌙";
        };
      };
    };
    style = ./waybar.css;
  };

  services.kanshi = {
    enable = true;
    profiles = {
      laptop.outputs = [
        {
          criteria = "eDP-1";
          position = "0,0";
        }
      ];
      dock_luhbots = {
        outputs = [
          {
            criteria = "eDP-1";
            position = "0,1080";
          }
          {
            criteria = "Dell Inc. DELL U2422HE GRCPH83";
            position = "0,0";
          }
          {
            criteria = "NEC Corporation E243WMi 7X313185NB";
            transform = "90";
            position = "1920,0";
          }
        ];
        exec = [
          "${pkgs.sway}/bin/swaymsg workspace 1, move workspace to DP-4"
          "${pkgs.sway}/bin/swaymsg workspace 2, move workspace to DP-5"
          "${pkgs.sway}/bin/swaymsg workspace 3, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 4, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 5, move workspace to DP-4"
        ];
      };
      dock_luhbots2 = {
        outputs = [
          {
            criteria = "eDP-1";
            position = "1080,1080";
          }
          {
            criteria = "Dell Inc. DELL U2422HE 8YCPH83";
            position = "1080,0";
          }
          {
            criteria = "NEC Corporation E243WMi 59118576NB";
            transform = "90";
            position = "0,0";
          }
        ];
        exec = [
          "${pkgs.sway}/bin/swaymsg workspace 1, move workspace to DP-4"
          "${pkgs.sway}/bin/swaymsg workspace 2, move workspace to DP-5"
          "${pkgs.sway}/bin/swaymsg workspace 3, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 4, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 5, move workspace to DP-4"
        ];
      };
      dock_luhbots3 = {
        outputs = [
          {
            criteria = "eDP-1";
            position = "0,1080";
          }
          {
            criteria = "Dell Inc. DELL U2422HE 53DCH83";
            position = "0,0";
          }
          {
            criteria = "Dell Inc. DELL U2412M 0FFXD46I4U5S";
            transform = "90";
            position = "1920,0";
          }
        ];
        exec = [
          "${pkgs.sway}/bin/swaymsg workspace 1, move workspace to DP-6"
          "${pkgs.sway}/bin/swaymsg workspace 2, move workspace to DP-7"
          "${pkgs.sway}/bin/swaymsg workspace 3, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 4, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 5, move workspace to DP-6"
        ];
      };
      dock_luhbots4 = {
        outputs = [
          {
            criteria = "eDP-1";
            position = "1080,1080";
          }
          {
            criteria = "Dell Inc. DELL P2422HE 4BXL9M3";
            position = "1080,0";
          }
          {
            criteria = "NEC Corporation E243WMi 75309334NB";
            transform = "90";
            position = "0,0";
          }
        ];
        exec = [
          "${pkgs.sway}/bin/swaymsg workspace 1, move workspace to DP-3"
          "${pkgs.sway}/bin/swaymsg workspace 2, move workspace to DP-4"
          "${pkgs.sway}/bin/swaymsg workspace 3, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 4, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 5, move workspace to DP-3"
        ];
      };
      laptop_hannspree = {
        outputs = [
          {
            criteria = "eDP-1";
            position = "320,1440";
          }
          {
            criteria = "HannStar Display Corp HC281UPB ";
            position = "0,0";
            mode = "3840x2160@60";
            scale = 1.5;
          }
        ];
        exec = [
          "${pkgs.sway}/bin/swaymsg workspace 1, move workspace to HDMI-A-1"
          "${pkgs.sway}/bin/swaymsg workspace 2, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 3, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 4, move workspace to eDP-1"
          "${pkgs.sway}/bin/swaymsg workspace 5, move workspace to HDMI-A-1"
        ];
      };
    };
  };

  # Theming
  gtk = {
    enable = true;
    cursorTheme = {
      package = pkgs.capitaine-cursors;
      name = "capitaine-cursors-white";
      size = 24;
    };
    iconTheme = {
      package = pkgs.whitesur-icon-theme;
      name = "WhiteSur-dark";
    };
    theme = {
      package = pkgs.whitesur-gtk-theme;
      name = "WhiteSur-Dark";
    };
    gtk3.extraConfig = {
      gtk-dialogs-use-header = false;
      gtk-cursor-theme-size = 0;
      gtk-toolbar-style = "GTK_TOOLBAR_BOTH_HORIZ";
      gtk-toolbar-icon-style = "GTK_ICON_SIZE_LARGE_TOOLBAR";
      gtk-button-images = 0;
      gtk-menu-images = 0;
      gtk-enable-event-sounds = 0;
      gtk-enable-input-feedback-sounds = 1;
      gtk-xft-antialias = 1;
      gtk-xft-hinting = 1;
      gtk-xft-hintstyle = "hintslight";
      gtk-xft-rgba = "none";
    };
  };
  home.pointerCursor = {
    package = pkgs.capitaine-cursors;
    name = "capitaine-cursors-white";
    size = 24;
    x11.enable = true;
    x11.defaultCursor = "capitaine-cursors-white";
  };
  xsession.enable = true;

  home.file."tofi" = {
    enable = true;
    target = ".config/tofi/config";
    text = ''
      # fullscreen theming
      width = 100%
      height = 100%
      border-width = 0
      outline-width = 0
      padding-top = 32
      result-spacing = 25
      font = FiraCode Nerd Font
      background-color = #000D
      text-color = #00FFEE
      selection-color = #EEFF00
      hint-font = false

      # search behavior
      history = true
      fuzzy-match = true
    '';
  };

  services.mako = {
    enable = true;
    actions = true;
    anchor = "top-right";

    backgroundColor = "#313131";
    borderColor = "#00FFEE";
    progressColor = "#338833";
    textColor = "#e0e0e0";
    extraConfig = ''
      [urgency=low]
      border-color=#008877
    '';

    borderRadius = 10;
    borderSize = 2;
    height = 100;
    width = 400;

    defaultTimeout = 10000; # ms
    font = "FiraCode Nerd Font 11";
    icons = true;
    markup = true;
  };
}