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

let
  cfg = config.samfelag.modules.system.kanata;
in
{
  options.samfelag.modules.system.kanata = {
    enable = lib.mkEnableOption "kanata";
  };

  config = lib.mkIf cfg.enable {
    users.users.${config.user.name}.extraGroups = [
      "input"
      "uinput"
    ];
    services.kanata = {
      enable = true;
      keyboards = {
        internalKeyboard = {
          extraDefCfg = "process-unmapped-keys yes";
          config = ''
            (defsrc
              caps a s d f h j k l
            )
            (defvar
              tap-time 200
              hold-time 250
            )
            (defalias
              caps (tap-hold $tap-time $hold-time caps (layer-while-held arrows))
              a (tap-hold $tap-time $hold-time a lalt)
              s (tap-hold $tap-time $hold-time s lsft)
              d (tap-hold $tap-time $hold-time d lmet)
              f (tap-hold $tap-time $hold-time f lctl)
              h (tap-hold $tap-time $hold-time h rctl)
              j (tap-hold $tap-time $hold-time j rmet)
              k (tap-hold $tap-time $hold-time k rsft)
              l (tap-hold $tap-time $hold-time l ralt)
            )

            (deflayer base
              @caps @a  @s  @d  @f  @h  @j  @k  @l
            )

            (deflayer arrows
              _ _ _ _ _ left down up right
            )
          '';
        };
      };
    };
  };
}
