{ config
, lib
, inputs
, pkgs
, ...
}:

with lib;
let
  cfg = config.my.programs.firefox;
  arkenfox = builtins.readFile "${inputs.arkenfox-userjs}/user.js";
in
{
  options.my.programs.firefox = {
    enable = mkEnableOption "firefox";
    arkenfox = {
      enable = mkEnableOption "arkenfox";
      overrides = mkOption {
        default = { };
        type = with types; attrsOf (oneOf [ str bool int ]);
        apply = overrides: concatStrings (
          mapAttrsToList
            (
              name: value: ''
                user_pref("${name}", ${builtins.toJSON value});
              ''
            )
            overrides
        );
      };
    };
    package = mkOption {
      type = types.package;
      default = pkgs.firefox;
      example = pkgs.firefox-esr;
    };
  };

  config = mkIf cfg.enable {
    home-manager.users.moritz.programs.firefox = {
      enable = true;
      policies =
        let
          removeExtensions = [ "Google" "Amazon.de" "Bing" "Amazon" "Wikipedia (en)" "Wikipedia (de)" ];
          convertName = name:
            let
              lower = toLower name;
              escaped = replaceStrings [ "." ] [ "dot" ] lower;
              sanitized = head (splitString " " escaped);
            in
            "${sanitized}@search.mozilla.org";
        in
        {
          SearchEngines = mkIf (hasInfix "esr" cfg.package) {
            Default = "Kagi";
            Remove = removeExtensions;
          };
          ExtensionSettings = genAttrs
            (map convertName removeExtensions)
            (_: { installation_mode = "blocked"; });
        };
      profiles."default" = {
        extraConfig = mkIf cfg.arkenfox.enable ''
          // Arkenfox user.js
          ${arkenfox}

          // Overrides
          ${cfg.arkenfox.overrides}
        '';
        extensions = with pkgs.nur.repos.rycee.firefox-addons; [
          darkreader
          firefox-color
          istilldontcareaboutcookies
          kagi-search
          keepassxc-browser
          languagetool
          multi-account-containers
          sponsorblock
          temporary-containers
          ublock-origin
          vimium
        ];
        settings = {
          # Disable Pocket
          "extensions.pocket.enabled" = false;

          # Disable Activity Stream
          # https://wiki.mozilla.org/Firefox/Activity_Stream
          "browser.newtabpage.activity-stream.enabled" = false;
          "browser.newtabpage.activity-stream.telemetry" = false;
          "browser.newtabpage.activity-stream.feeds.discoverystreamfeed" = false;
          "browser.newtabpage.activity-stream.feeds.section.topstories" = false;
          "browser.newtabpage.activity-stream.section.highlights.includePocket" = false;
          "browser.newtabpage.activity-stream.showSponsored" = false;
          "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts.havePinned" = "";
          "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts.searchEngines" = "";
          "browser.newtabpage.pinned" = "[]";

          # Disable new tab tile ads & preload
          # http://www.thewindowsclub.com/disable-remove-ad-tiles-from-firefox
          # http://forums.mozillazine.org/viewtopic.php?p=13876331#p13876331
          # https://wiki.mozilla.org/Tiles/Technical_Documentation#Ping
          # https://gecko.readthedocs.org/en/latest/browser/browser/DirectoryLinksProvider.html#browser-newtabpage-directory-source
          # https://gecko.readthedocs.org/en/latest/browser/browser/DirectoryLinksProvider.html#browser-newtabpage-directory-ping
          "browser.newtabpage.enhanced" = false;
          "browser.newtabpage.introShown" = true;
          "browser.newtab.preload" = false;
          "browser.newtabpage.directory.ping" = "";
          "browser.newtabpage.directory.source" = "data:text/plain,{}";

          # Disable some not so useful functionality.
          "browser.disableResetPrompt" = true; # "Looks like you haven't started Firefox in a while."
          "browser.onboarding.enabled" = false; # "New to Firefox? Let's get started!" tour
          "browser.aboutConfig.showWarning" = false; # Warning when opening about:config
          "extensions.shield-recipe-client.enabled" = false;

          # do not offer to save passwords = nor allow the user to enable the feature
          "signon.rememberSignons" = false;
          "signon.rememberSignons.visibilityToggle" = false;

          # send do not track header
          "privacy.donottrackheader.enabled" = true;

          # Hide bookmarks
          "browser.toolbars.bookmarks.visibility" = "never";

          # Smooth scrolling
          "general.smoothScroll.lines.durationMaxMS" = 125;
          "general.smoothScroll.lines.durationMinMS" = 125;
          "general.smoothScroll.mouseWheel.durationMaxMS" = 200;
          "general.smoothScroll.mouseWheel.durationMinMS" = 100;
          "general.smoothScroll.msdPhysics.enabled" = true;
          "general.smoothScroll.other.durationMaxMS" = 125;
          "general.smoothScroll.other.durationMinMS" = 125;
          "general.smoothScroll.pages.durationMaxMS" = 125;
          "general.smoothScroll.pages.durationMinMS" = 125;
          "mousewheel.min_line_scroll_amount" = 40;
          "mousewheel.system_scroll_override_on_root_content.enabled" = true;
          "mousewheel.system_scroll_override_on_root_content.horizontal.factor" = 175;
          "mousewheel.system_scroll_override_on_root_content.vertical.factor" = 175;
          "toolkit.scrollbox.horizontalScrollDistance" = 6;
          "toolkit.scrollbox.verticalScrollDistance" = 2;

          # Do not check if Firefox is the default browser
          "browser.shell.checkDefaultBrowser" = false;

          # Reduce search engine noise in the urlbar's completion window. The
          # shortcuts and suggestions will still work, but Firefox won't clutter
          # its UI with reminders that they exist.
          "browser.urlbar.suggest.searches" = false;
          "browser.urlbar.shortcuts.bookmarks" = false;
          "browser.urlbar.shortcuts.history" = false;
          "browser.urlbar.shortcuts.tabs" = false;
          "browser.urlbar.showSearchSuggestionsFirst" = false;
          "browser.urlbar.speculativeConnect.enabled" = false;

          # https://bugzilla.mozilla.org/1642623
          "browser.urlbar.dnsResolveSingleWordsAfterSearch" = 0;
          # https://blog.mozilla.org/data/2021/09/15/data-and-firefox-suggest/
          "browser.urlbar.suggest.quicksuggest.nonsponsored" = false;
          "browser.urlbar.suggest.quicksuggest.sponsored" = false;

          # Show whole URL in address bar
          "browser.urlbar.trimURLs" = false;

          # auto enable addons
          "extensions.autoDisableScopes" = 0;

          # Disable Form autofill
          # https://wiki.mozilla.org/Firefox/Features/Form_Autofill
          "browser.formfill.enable" = false;
          "extensions.formautofill.addresses.enabled" = false;
          "extensions.formautofill.available" = "off";
          "extensions.formautofill.creditCards.available" = false;
          "extensions.formautofill.creditCards.enabled" = false;
          "extensions.formautofill.heuristics.enabled" = false;
        };
      };
    };
  };
}