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

let
  cfg = config.sydnix.users.crumb.firefox;
in {
  options.sydnix.users.crumb.firefox.enable =
    lib.mkEnableOption "Firefox, à la crumb";

  config = lib.mkIf cfg.enable {
    # We are very granular about which Firefox files are persisted.  While there
    # is a lot of mutable state (e.g. search history), it is mixed with less
    # mutable configuration that we force ourselves to manage declaratively.
    #
    # For an overview of important files in the profile directory, see
    # https://support.mozilla.org/en-US/kb/recovering-important-data-from-an-old-profile.
    sydnix.impermanence =
      { directories = [ ".mozilla/firefox/msyds" ]; };
      # let p = ".mozilla/firefox/msyds";
      # in {
      #     files = [
      #       # Passwords
      #       "${p}/key4.db"
      #       "${p}/logins.json"
      #       "${p}/logins-backup.json"
      #       # Site-specific permissions
      #       "${p}/permissions.sqlite"
      #       # Bookmarks, downloads and browsing history
      #       "${p}/places.sqlite"
      #       # Cached favicons for use in the history menu.
      #       "${p}/favicons.sqlite"
      #       # Cookies
      #       "${p}/cookies.sqlite"
      #       # Security certificate settings
      #       "${p}/cert9.db"
      #       # Form history (for completions)
      #       "${p}/formhistory.sqlite"
      #     ];
      #   };

    stylix.targets.firefox.profileNames = [ "msyds" ];

    programs.firefox = {
      enable = true;

      # Available language codes can be found on the releases page:
      # https://releases.mozilla.org/pub/firefox/releases/134.0.2/linux-x86_64/xpi/.
      # The string `134.0.2` may be substituted for any other Firefox release
      # number.
      languagePacks = [
        "en-US"
        "en-GB"
      ];

      # Available options can be found at
      # https://mozilla.github.io/policy-templates/.
      policies = {
        DisableTelemetry = true;
        DisableFirefoxStudies = false;
        EnableTrackingProtection = {
          Value = true;
          Locked = true;
          Cryptomining = true;
          Fingerprinting = true;
        };
        FirefoxHome = {
          Search = true;
          TopSites = true;
          SponsoredTopSites = false;
          Highlights = false;
          Pocket = false;
          SponsoredPocket = false;
          Snippets = false;
          Locked = false;
        };
        # Weird advertiser shit.
        FirefoxSuggest = {
          WebSuggestions = false;
          SponsoredSuggestions = false;
          ImproveSuggest = false;
          Locked = false;
        };
        # Weird advertiser shit.
        DisablePocket = true;
        DisableFirefoxAccounts = true;
        DisableAccounts = true;
        # Firefox has an in-built screenshot tool that I do not need.
        DisableFirefoxScreenshots = true;
        # Disable pop-up windows that appear after installation and updates.
        OverrideFirstRunPage = "";
        OverridePostUpdatePage = "";
        # You think you're so important, don't you, Firefox?
        DontCheckDefaultBrowser = true;
        # Only tabs not yet visiting a page.  Alternatives: `always`, `never`,
        # `newtab`.
        DisplayBookmarksToolbar = "newtab";
        # Alternatives: `always`, `never`, `default-on`, `default-on`.
        DisplayMenuBar = "default-off";
        # Alternative: `unified`, `separate`.
        SearchBar = "unified";
      };

      profiles."msyds" = {
        bookmarks = {
          force = true;
          settings = [
            {
              name = "Nix";
              toolbar = true;
              bookmarks = [
                {
                  name = "Home-manager options";
                  tags = [ "nix" "docs" "reference" ];
                  url = "https://nix-community.github.io/home-manager/options.xhtml";
                }
                {
                  name = "Nixpkgs manual";
                  tags = [ "nix" "docs" ];
                  url = "https://ryantm.github.io/nixpkgs";
                }
              ];
            }
            {
              name = "Clojure";
              toolbar = true;
              bookmarks = [
                {
                  name = "Clojure cheatsheet";
                  tags = [ "clojure" "docs" "reference" ];
                  url = "https://clojure.org/api/cheatsheet";
                }
                {
                  name = "Babashka book";
                  tags = [ "clojure" "babashka" "docs" ];
                  url = "https://book.babashka.org/";
                }
                {
                  name = "ClojureDocs";
                  tags = [ "clojure" "docs" ];
                  url = "https://clojuredocs.org/";
                }
              ];
            }
          ];
        };

        # Check about:support for extension/add-on ID strings.
        extensions = {
          # Override non-declared settings.
          force = true;
          packages =
            let pkgs' = import inputs.nixpkgs {
                  system = args.system;
                  overlays = [ inputs.nur.overlays.default ];
                };
            in
              # https://nur.nix-community.org/repos/rycee/
              with pkgs'.nur.repos.rycee.firefox-addons; [
                ublock-origin
                darkreader
                privacy-badger
                vimium
                kagi-search
                duckduckgo-privacy-essentials
                textern
                copy-as-org-mode
                clearurls
                sidebery
                adaptive-tab-bar-colour
                adnauseam
                # tree-style-tab
                # tab-unload-for-tree-style-tab
                # tst-tab-search
                # tst-more-tree-commands
                # tst-lock-tree-collapsed
                # tst-fade-old-tabs
                # tst-bookmarks-subpanel
                # move-unloaded-tabs-for-tst
                tab-stash
                unpaywall
                sourcegraph
                sponsorblock
                cookies-txt
                copy-selected-tabs-to-clipboard
                copy-link-text
                df-youtube
              ];
        };

        # https://github.com/mbnuqw/sidebery/wiki/Firefox-Styles-Snippets-(via-userChrome.css)
        userChrome = ''
          /* Hide the tab bar in favour of that provided by the tree-style tabs
           * addon */
          /**
            * Dynamic Horizontal Tabs Toolbar (with animations)
            * sidebar.verticalTabs: false (with native horizontal tabs)
            */
           #main-window #TabsToolbar > .toolbar-items {
             overflow: hidden;
             transition: height 0.3s 0.3s !important;
           }
           /* Default state: Set initial height to enable animation */
           #main-window #TabsToolbar > .toolbar-items { height: 3em !important; }
           #main-window[uidensity="touch"] #TabsToolbar > .toolbar-items { height: 3.35em !important; }
           #main-window[uidensity="compact"] #TabsToolbar > .toolbar-items { height: 2.7em !important; }
           /* Hidden state: Hide native tabs strip */
           #main-window[titlepreface*="\200b"] #TabsToolbar > .toolbar-items { height: 0 !important; }
           /* Hidden state: Fix z-index of active pinned tabs */
           #main-window[titlepreface*="\200b"] #tabbrowser-tabs { z-index: 0 !important; }
           /* Hidden state: Hide window buttons in tabs-toolbar */
           #main-window[titlepreface*="\200b"] #TabsToolbar .titlebar-spacer,
           #main-window[titlepreface*="\200b"] #TabsToolbar .titlebar-buttonbox-container {
             display: none !important;
           }
           /* [Optional] Uncomment block below to show window buttons in nav-bar
            * (maybe, I didn't test it on non-linux-i3wm env) */
           /* #main-window[titlepreface*="\200b"] #nav-bar > .titlebar-buttonbox-container,
           #main-window[titlepreface*="\200b"] #nav-bar > .titlebar-buttonbox-container > .titlebar-buttonbox {
             display: flex !important;
           } */
           /* [Optional] Uncomment one of the line below if you need space near
            * window buttons */
           /* #main-window[titlepreface*="\200b"] #nav-bar > .titlebar-spacer[type="pre-tabs"] { display: flex !important; } */
           /* #main-window[titlepreface*="\200b"] #nav-bar > .titlebar-spacer[type="post-tabs"] { display: flex !important; } */
        '';

        search = {
          # Override non-declared settings.
          force = true;
          # Precedence of search engines.
          order = [ "Kagi" "ddg" ];
          default = "Kagi";
          privateDefault = "ddg";
          engines = {
            "Kagi" = {
              urls = [{
                template = "https://kagi.com/search";
                params = [
                  { name = "q"; value = "{searchTerms}"; }
                ];
              }];
            };
            "Nixopts" = {
              urls = [{
                template = "https://search.nixos.org/options";
                params = [
                  { name = "channel"; value = "unstable"; }
                  { name = "query"; value = "{searchTerms}"; }
                ];
              }];
              icon =
                "${pkgs.nixos-icons}/share/icons/hicolor/scalable/apps/nix-snowflake.svg";
              definedAliases = [ "!no" ];
            };
            "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 = [ "!np" ];
            };
          };
        };

        # See `about:config` in Firefox for available settings.
        settings = {
          # Disable suggestions.
          "browser.search.suggest.enabled" = false;
          # Enable dark theme for non-website UI; the URL bar and such.
          "extensions.activeThemeID" = "firefox-compact-dark@mozilla.org";
          "browser.theme.content-theme" = 0;
          "browser.theme.toolbar-theme" = 0;
          "browser.in-content.dark-mode" = true;
          "ui.systemUsesDarkTheme" = 1;
          # Disable sponsored suggestions.
          "browser.newtabpage.activity-stream.showSponsoredTopSites" = false;
          "browser.newtabpage.activity-stream.system.showSponsored" = false;
          "browser.newtabpage.activity-stream.showSponsored" = false;
          "browser.urlbar.sponsoredTopSites" = false;
          "services.sync.prefs.sync.browser.newtabpage.activity-stream.showSponsored"
            = false;
          "services.sync.prefs.sync.browser.newtabpage.activity-stream.showSponsoredTopSites"
            = false;
          "browser.sessionstore.persist_closed_tabs_between_sessions" = true;
          "browser.download.always_ask_before_handling_new_types" = true;
          # Enable userChrome.css.
          "toolkit.legacyUserProfileCustomizations.stylesheets" = true;
        };
      };
    };
  };
}
