{ lib, config, pkgs, ... }:
with lib;
let
  cfg = config.modules.web.qutebrowser;
in
{
  options.modules.web.qutebrowser = {
    enable = mkEnableOption "enable Qutebrowser web browser";

    enableNixGL = mkOption {
      type = types.bool;
      default = false;
      description = "Use NixGL to start Qutebrowser";
    };

  };
  config = mkIf cfg.enable {
    xdg.desktopEntries."org.qutebrowser.qutebrowser" = mkIf cfg.enableNixGL {
      name = "QuteBrowser NixGL Powered";

      exec = "${pkgs.nixgl.nixGLMesa}/bin/nixGLMesa qutebrowser %u";
      icon = "qutebrowser";
      terminal = false;
      type = "Application";
      startupNotify = true;
      actions = {
        "preference" = {
          exec = "${pkgs.nixgl.nixGLMesa}/bin/nixGLMesa qutebrowser \"qute://settings\"";
          name = "Preferences";
        };
      };
    };
    programs.qutebrowser = {
      enable = true;
      loadAutoconfig = true;
      settings = {

        qt.args = [
          "autoplay-policy=user-gesture-required"
          "ignore-gpu-blocklist"
          "enable-accelerated-video-decode"
          "enable-features=VaapiVideoDecoder"
          "enable-features=WebRTCPipeWireCapturer"
        ];
        # Try to reduce memury usage
        qt.chromium.low_end_device_mode = "always";
        qt.chromium.process_model = "process-per-site";

        fonts.default_family = "Fira Code Nerd Font Mono";
        fonts.completion.category = "default_size default_family";

        tabs.title.format = "{index}:{audio:1} {current_title}";
        tabs.select_on_remove = "last-used";
        colors.webpage.preferred_color_scheme = "dark";

        #Privacy
        content.canvas_reading = true;
        content.headers.do_not_track = true;
        content.cookies.accept = "no-3rdparty";
        content.geolocation = false;
        content.headers.referer = "same-domain";
        content.blocking.enabled = true;
        content.blocking.method = "both";
        content.blocking.adblock.lists = [
          https://easylist.to/easylist/easylist.txt
          https://easylist.to/easylist/easyprivacy.txt
          https://www.i-dont-care-about-cookies.eu/abp/
          https://secure.fanboy.co.nz/fanboy-cookiemonster.txt
        ];

        content.plugins = false;
        downloads.location.directory = "~/downloads";
        completion.open_categories = [
          "quickmarks"
          "history"
        ];
      };
      extraConfig = ( builtins.readFile ./files/theme.py);
      keyBindings = {
        normal = {
          ",M" = "hint links spawn mpv {hint-url}";
          ",m" = "spawn mpv {url}";
        };
      };
    };
  };
}
