{
  pkgs,
  config,
  lib,
  ...
}:
let
  inherit (lib) mkIf mkOption;

  cfg = config.programs.cavalier;

  iniFmt = pkgs.formats.ini { };

  jsonFmt = pkgs.formats.json { };

in
{
  meta.maintainers = [ lib.maintainers.bricked ];

  options.programs.cavalier = {
    enable = lib.mkEnableOption "Cava audio visualizer GUI";

    package = lib.mkPackageOption pkgs "cavalier" { nullable = true; };

    settings = {
      general = mkOption {
        type = jsonFmt.type;
        default = { };
        example = lib.literalExpression ''
          {
            ShowControls = true;
            ColorProfiles = [
              {
                Name = "Default";
                FgColors = [
                  "#ffed333b"
                  "#ffffa348"
                  "#fff8e45c"
                  "#ff57e389"
                  "#ff62a0ea"
                  "#ffc061cb"
                ];
                BgColors = [
                  "#ff1e1e2e"
                ];
                Theme = 1;
              }
            ];
            ActiveProfile = 0;
          }
        '';
        description = ''
          Settings to be written to the Cavalier configuration file. See
          <https://github.com/NickvisionApps/Cavalier/blob/main/NickvisionCavalier.Shared/Models/Configuration.cs>
          for all available options.
        '';
      };

      cava = mkOption {
        type = iniFmt.type;
        default = { };
        example = lib.literalExpression ''
          {
            general.framerate = 60;
            input.method = "alsa";
            smoothing.noise_reduction = 88;
            color = {
              background = "'#000000'";
              foreground = "'#FFFFFF'";
            };
          }
        '';
        description = ''
          Settings to be written to the underlying Cava configuration file. See
          <https://github.com/karlstav/cava/blob/master/example_files/config> for
          all available options.
        '';
      };
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      (lib.hm.assertions.assertPlatform "programs.cavalier" pkgs lib.platforms.linux)
    ];

    home.packages = lib.mkIf (cfg.package != null) [ cfg.package ];

    xdg.configFile = {
      "Nickvision Cavalier/config.json" = mkIf (cfg.settings.general != { }) {
        text = ''
          ${lib.generators.toJSON { } cfg.settings.general}
        '';
      };

      "Nickvision Cavalier/cava_config" = mkIf (cfg.settings.cava != { }) {
        text = ''
          ; Generated by Home Manager

          ${lib.generators.toINI { } cfg.settings.cava}
        '';
      };
    };
  };
}
