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

let
  cfg = config.local.programs.terminals.ghostty;
  themeCfg = config.local.themes."${config.local.theme.name}";
in
{
  options.local.programs.terminals.ghostty = with lib; {
    enable = mkEnableOption "ghostty";
    package = mkPackageOption pkgs "ghostty" { };
    fontSize = mkOption {
      type = types.number;
      default = 10.0;
      description = "Ghostty font size";
    };
  };

  config = lib.mkIf cfg.enable {
    programs.ghostty = {
      enable = true;
      package = cfg.package;
      settings = {
        theme = "nixos-theme";
        font-family = "monospace";
        font-size = cfg.fontSize;
        window-decoration = false;
        cursor-style-blink = false;
        shell-integration-features = "no-cursor";
        gtk-single-instance = false; # It required to provide working-directory
      };
      enableZshIntegration = config.programs.zsh.enable;
      themes = {
        "nixos-theme" = {
          palette = [
            "0=${themeCfg.window.regular.color0}"
            "1=${themeCfg.window.regular.color1}"
            "2=${themeCfg.window.regular.color2}"
            "3=${themeCfg.window.regular.color3}"
            "4=${themeCfg.window.regular.color4}"
            "5=${themeCfg.window.regular.color5}"
            "6=${themeCfg.window.regular.color6}"
            "7=${themeCfg.window.regular.color7}"
            "8=${themeCfg.window.bold.color8}"
            "9=${themeCfg.window.bold.color9}"
            "10=${themeCfg.window.bold.color10}"
            "11=${themeCfg.window.bold.color11}"
            "12=${themeCfg.window.bold.color12}"
            "13=${themeCfg.window.bold.color13}"
            "14=${themeCfg.window.bold.color14}"
            "15=${themeCfg.window.bold.color15}"
            "16=${themeCfg.window.extended.color16}"
            "17=${themeCfg.window.extended.color17}"
            "18=${themeCfg.window.extended.color18}"
            "19=${themeCfg.window.extended.color19}"
          ];
          background = themeCfg.window.background;
          foreground = themeCfg.window.mainText;
          cursor-color = themeCfg.window.cursor;
          cursor-text = themeCfg.window.cursorText;
          selection-background = themeCfg.window.selection;
          selection-foreground = themeCfg.window.selectionText;
        };
      };
    };
  };
}