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

with lib;

let
  cfg = config.noctaliaSystem;
in
{
  # Import Noctalia's NixOS module for systemd service
  imports = [
    inputs.noctalia.nixosModules.default
  ];

  options.noctaliaSystem = {
    enable = mkEnableOption "Noctalia shell system-level configuration";

    enableSystemdService = mkOption {
      type = types.bool;
      default = true;
      description = "Enable the Noctalia systemd service (starts after graphical-session.target)";
    };
  };

  config = mkIf cfg.enable {
    # Enable the systemd service if requested
    # Override package with calendar support for evolution-data-server integration
    services.noctalia-shell = {
      enable = cfg.enableSystemdService;
      package = inputs.noctalia.packages.${pkgs.stdenv.hostPlatform.system}.default.override {
        calendarSupport = true;
      };
    };

    # Required system services for Noctalia features
    # Evolution data server and Evolution - for calendar events support in Noctalia
    services.gnome.evolution-data-server.enable = mkDefault true;
    environment.systemPackages = [ pkgs.evolution ];

    # Workaround for intermittent spamassassin test failure pulled in by evolution.
    # The t/spamd_ssl.t test is racy/flaky upstream; the package already excludes
    # spamd_ssl_accept_fail.t for the same reason. See:
    # https://github.com/NixOS/nixpkgs/issues/401737
    # https://bz.apache.org/SpamAssassin/show_bug.cgi?id=8068
    nixpkgs.overlays = [
      (final: prev: {
        spamassassin = prev.spamassassin.overrideAttrs (old: {
          preCheck = (old.preCheck or "") + ''
            checkFlagsArray+=(TEST_FILES='$(shell find t -name *.t -not -name spamd_ssl_accept_fail.t -not -name spamd_ssl.t)')
          '';
        });
      })
    ];

    # NetworkManager - for wifi widget
    networking.networkmanager.enable = mkDefault true;

    # Bluetooth - for bluetooth widget
    hardware.bluetooth.enable = mkDefault true;

    # UPower - for battery widget
    services.upower.enable = mkDefault true;

    # Power profiles daemon - for power profile switching in Noctalia
    # Note: This conflicts with auto-cpufreq, so we use power_manager module's option
    services.power-profiles-daemon.enable = mkDefault true;
  };
}
