{ pkgs, config, nur, ... }:
let
  # FireFox theme, based on https://github.com/Dook97/firefox-qutebrowser-userchrome
  themeFont = ''
    --tab-font: '${config.look.fonts.main}';
    --urlbar-font: '${config.look.fonts.main}';
  '';
  themeJim = ''
    :root {
      --tab-active-bg-color: #${config.look.colors.prime};
      --tab-hover-bg-color: #${config.look.colors.accent};
      --tab-inactive-bg-color: #${config.look.colors.dark};
      --tab-active-fg-fallback-color: #FFFFFF;
      --tab-inactive-fg-fallback-color: #${config.look.colors.text};
      --urlbar-focused-bg-color: #${config.look.colors.dark};
      --urlbar-not-focused-bg-color: #${config.look.colors.dark};
      --toolbar-bgcolor: #${config.look.colors.dark} !important;
  '';
  themeAlt = ''
    :root {
      --tab-active-bg-color: #${config.look.colors.dark};
      --tab-hover-bg-color: #${config.look.colors.accent};
      --tab-inactive-bg-color: #${config.look.colors.prime};
      --tab-active-fg-fallback-color: #${config.look.colors.text};
      --tab-inactive-fg-fallback-color: #FFFFFF;
      --urlbar-focused-bg-color: #${config.look.colors.prime};
      --urlbar-not-focused-bg-color: #${config.look.colors.prime};
      --toolbar-bgcolor: #${config.look.colors.prime} !important;
  '';
in {
  # Enable Librewolf and extensions
  programs.firefox = let
    commonExtensions = with pkgs.nur.repos.rycee.firefox-addons; [
      ublock-origin
      bitwarden
      darkreader
      sponsorblock
      return-youtube-dislikes
      simple-tab-groups
      vimium
    ];
    commonSearch = {
      force = true;
      default = "Ecosia";
      order = [
        "Ecosia"
	"NixPKGs"
	"MyNixOS"
	"YouTube"
      ];
      engines = {
        "Ecosia" = {
          urls = [
            {
              template = "https://www.ecosia.org/search";
              params = [
                {
                  name = "q";
                  value = "{searchTerms}";
                }
              ];
            }
          ];
          definedAliases = [ "@e" ];
        };
        "NixPKGs" = {
          urls = [
            {
              template = "https://search.nixos.org/packages";
              params = [
                {
                  name = "type";
                  value = "packages";
                }
                {
                  name = "query";
                  value = "{searchTerms}";
                }
              ];
            }
          ];
          icon = "${pkgs.nixos-icons}/share/icons/hicolor/scalable/apps/nix-snowflake.svg";
          definedAliases = [ "@pkgs" ];
        };
        "MyNixOS" = {
          urls = [
            {
              template = "https://mynixos.com/search";
              params = [
                {
                  name = "q";
                  value = "{searchTerms}";
                }
              ];
            }
          ];
          definedAliases = [ "@my" ];
        };
        "YouTube" = {
          urls = [
            {
              template = "https://www.youtube.com/results";
              params = [
                {
                  name = "search_query";
                  value = "{searchTerms}";
                }
              ];
            }
          ];
          definedAliases = [ "@y" ];
        };
      };
    };
    commonBookmarks = [
      {
        name = "Jimbo";
        url = "https://jimbosfiles.com";
      }
      {
        name = "Corn";
        url = "https://freecorn1854.win";
      }
      {
        name = "Luna";
        url = "https://www.lunamoonlight.xyz";
      }
      {
        name = "Kernel";
        url = "https://www.kernel.org";
      }
      {
        name = "Github";
        url = "https://github.com";
      }
    ];
    commonSettings = {
      "general.autoScroll" = true;

      "places.history.enabled" = false;

      "font.name.serif.x-western" = config.look.fonts.main;
      "font.name.sans-serif.x-western" = config.look.fonts.main;
      "font.name.monospace.x-western" = config.look.fonts.nerd;

      "browser.uidensity" = 1;
      "browser.compactmode.show" = true;
      "browser.send_pings" = false;
      "browser.shell.checkDefaultBrowser" = false;
      "browser.toolbars.bookmarks.visibility" = "never";
      "browser.contentblocking.category" = "strict";
      "browser.helperApps.deleteTempFileOnExit" = true;
      "browser.search.separatePrivateDefault" = false;
      "browser.download.useDownloadDir" = true;
      "browser.aboutConfig.showWarning" = false;
      "browser.startup.page" = 3;
      "browser.theme.content-theme" = 0;
      "browser.theme.toolbar-theme" = 0;
      "browser.newtabpage.enabled" = false;
      "browser.newtabpage.activity-stream.showSponsoredTopSites" = false;
      "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons" = false;
      "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features" = false;
      "browser.tabs.inTitlebar" = 0;
      "browser.tabs.closeWindowWithLastTab" = false;
      "browser.urlbar.speculativeConnect.enabled" = false;
      "browser.discovery.enabled" = false;

      "browser.safebrowsing.downloads.enabled" = false;
      "browser.safebrowsing.downloads.remote.enabled" = false;
      "browser.safebrowsing.downloads.remote.block_uncommon" = false;
      "browser.safebrowsing.downloads.remote.block_potentially_unwanted" = false;
      "browser.safebrowsing.malware.enabled" = false;
      "browser.safebrowsing.phishing.enabled" = false;
      "browser.safebrowsing.blockedURIs.enabled" = false;
      "browser.safebrowsing.provider.google4.gethashURL" = false;
      "browser.safebrowsing.provider.google4.updateURL" = false;
      "browser.safebrowsing.provider.google.gethashURL" = false;
      "browser.safebrowsing.provider.google.updateURL" = false;

      "extensions.pocket.enabled" = false;
      "extensions.autoDisableScopes" = 0;
      "extensions.activeThemeID" = "firefox-compact-dark@mozilla.org";
      "extensions.formautofill.addresses.enabled" = false;
      "extensions.formautofill.creditCards.enabled" = false;
      "extensions.getAddons.showPane" = false;
      "extensions.webservice.discoverURL" = "";
      "extensions.getAddons.discovery.api_url" = "";
      "extensions.htmlaboutaddons.discover.enabled" = false;
      "extensions.htmlaboutaddons.recommendations.enabled" = false;

      "toolkit.legacyUserProfileCustomizations.stylesheets" = true;
      "toolkit.tabbox.switchByScrolling" = true;

      "privacy.resistFingerprinting" = true;
      "privacy.resistFingerprinting.autoDeclineNoUserInputCanvasPrompts" = true;
      "privacy.firstparty.isolate" = true;
      "privacy.fingerprintingProtection" = true;
      "privacy.donottrackheader.enabled" = true;
      "privacy.globalprivacycontrol.enabled" = true;
      "privacy.globalprivacycontrol.functionality.enabled" = true;
      "privacy.clearOnShutdown.history" = true;
      "privacy.clearOnShutdown.cookies" = false;
      "privacy.clearOnShutdown_v2.cookiesAndStorage" = false;
      "privacy.clearOnShutdown_v2.historyFormDataAndDownloads" = true;

      "urlclassifier.trackingSkipURLs" = "*.reddit.com, *.twitter.com, *.twimg.com, *.tiktok.com";
      "urlclassifier.features.socialtracking.skipURLs" = "*.instagram.com, *.twitter.com, *.twimg.com";

      "network.trr.mode" = 3;
      "network.trr.uri" = "https://wikimedia-dns.org/dns-query";
      "network.cookie.cookieBehavior" = 1;
      "network.cookie.sameSite.noneRequiresSecure" = true;
      "network.http.referer.XOriginPolicy" = 2;
      "network.http.referer.XOriginTrimmingPolicy" = 2;
      "network.http.referer.trimmingPolicy" = 2;

      "media.ffmpeg.vaapi.enabled" = true;
      "media.rdd-ffmpeg.enabled" = true;
      "media.hardware-video-decoding.force-enabled" = true;

      "gfx.webrender.all" = true;
      "gfx.x11-egl.force-enabled" = true;

      "signon.rememberSignons" = false;
      "signon.management.page.breach-alerts.enabled" = false;

      "dom.private-attribution.submission.enabled" = false;
      "dom.battery.enabled" = false;
      "dom.security.https_only_mode" = true;
      "dom.security.https_only_mode.upgrade_local" = true;
      "dom.security.https_only_mode_ever_enabled" = true;
      "dom.security.https_only_mode_ever_enabled_pbm" = true;

      "clipboard.autocopy" = false;
      "middlemouse.paste" = false;

      "identity.fxaccounts.enabled" = false;
      "datareporting.healthreport.uploadEnabled" = false;
      "svg.context-properties.content.enabled" = true;
      "services.sync.engine.addresses.available" = false;
      "device.sensors.motion.enabled" = false;
      "security.OCSP.require" = true;
      "gnomeTheme.hideSingleTab" = true;
      "webgl.disabled" = false;
    };
  in {
    enable = true;
    package = pkgs.librewolf;
    profiles = {
      Main = {
        id = 0;
	isDefault = true;
        extensions = commonExtensions;
        search = commonSearch;
	bookmarks = commonBookmarks;
        settings = commonSettings;
        userChrome = ''
          ${themeJim}
          ${themeFont}
          ${builtins.readFile ./quteFox.css}
        '';
      };
      Alt = {
        id = 1;
        extensions = commonExtensions;
        search = commonSearch;
	bookmarks = commonBookmarks;
        settings = commonSettings;
        userChrome = ''
          ${themeAlt}
          ${themeFont}
          ${builtins.readFile ./quteFox.css}
        '';
      };
      Misc = {
        id = 2;
        extensions = commonExtensions;
        search = commonSearch;
	bookmarks = commonBookmarks;
        settings = commonSettings;
      };
    };
  };

  # Fixes
  home.file = {
    # Symlinks to Librewolf
    ".librewolf".source = config.lib.file.mkOutOfStoreSymlink "/home/${config.home.username}/.mozilla/firefox";
    
    # Gnome theme
    ".mozilla/firefox/Misc/chrome".source = fetchTarball {
      url = "https://github.com/rafaelmardojai/firefox-gnome-theme/archive/refs/tags/v132.zip";
      sha256 = "095sv1ann2v7q5bfy65i118ylhp2vkpbgyf6fz84nd9yrx14rzwm";
    };
  };
}
