local wezterm = require 'wezterm'
local config = wezterm.config_builder()
local act = wezterm.action
local io = require 'io'
local os = require 'os'

-- config.default_prog = { 'fish', '-l' }

wezterm.on('trigger-emacs-with-scrollback', function(window, pane)
  -- Retrieve the text from the pane
  local text = pane:get_lines_as_text(pane:get_dimensions().scrollback_rows)

  -- Create a temporary file to pass to vim
  local name = os.tmpname()
  local f = io.open(name, 'w+')
  f:write(text)
  f:flush()
  f:close()

  -- Open a new window running vim and tell it to open the file
  window:perform_action(
    act.SpawnCommandInNewWindow {
      args = { 'em', name },
    },
    pane
  )

  -- Wait "enough" time for vim to read the file before we remove it.
  -- The window creation and process spawn are asynchronous wrt. running
  -- this script and are not awaitable, so we just pick a number.
  --
  -- Note: We don't strictly need to remove this file, but it is nice
  -- to avoid cluttering up the temporary directory.
  wezterm.sleep_ms(1000)
  os.remove(name)
end)

-- plugins
local domains = wezterm.plugin.require("https://github.com/DavidRR-F/quick_domains.wezterm")
local tabline = wezterm.plugin.require("https://github.com/michaelbrusegard/tabline.wez")
local workspace_switcher = wezterm.plugin.require("https://github.com/MLFlexer/smart_workspace_switcher.wezterm")

config.enable_wayland = false;
-- config.front_end = "WebGpu";

config.audible_bell = "Disabled";

config.warn_about_missing_glyphs = false;

config.font_size = 14
config.font = wezterm.font {
  family = 'IBM Plex Mono',
  -- weight = ''
}

config.use_ime = false

config.freetype_load_flags = 'NO_HINTING'

-- config.color_scheme = 'One Dark (Gogh)'
config.color_scheme = 'One Half Black (Gogh)'
-- config.color_scheme = 'Adventure'
-- config.color_scheme = 'Monokai Pro Ristretto (Gogh)'
-- config.color_scheme = 'Afterglow'
config.colors = {
  background = "#111111"
}

config.background = {
  {
    source = {
      Color = '#111111'
    },
    width = "100%",
    height = "100%",
    opacity = 1
  }
}

config.check_for_updates = false
config.window_decorations = "RESIZE"

config.window_padding = {
  left = "6px",
  right = "6px",
  top = "6px",
  bottom = "6px",
}

config.cursor_thickness = 2
config.default_cursor_style = 'SteadyBar'

config.use_fancy_tab_bar = false
config.tab_bar_at_bottom = true

-- config.enable_kitty_keyboard = true

config.unzoom_on_switch_pane = true

config.mouse_bindings = {
  {
    event = { Up = { streak = 1, button = 'Left' } },
    mods = 'NONE',
    action = act.OpenLinkAtMouseCursor,
  },
}

-- config.leader = { key = 'Space', mods = 'SHIFT', timeout_milliseconds = 1000 }

config.keys = {
  {
    key = 'Enter',
    mods = 'CTRL',
    action = act.SplitVertical { domain = 'CurrentPaneDomain' },
  },
  {
    key = 'Enter',
    mods = 'CTRL|SHIFT',
    action = act.SplitHorizontal { domain = 'CurrentPaneDomain' },
  },
  {
    key = 'w',
    mods = 'CTRL',
    action = wezterm.action.CloseCurrentTab { confirm = true },
  },
  {
    key = 'w',
    mods = 'CTRL|SHIFT',
    action = act.DetachDomain 'CurrentPaneDomain',
  },
  {
    key = 'k',
    mods = 'CTRL|SHIFT',
    action = act.Multiple {
      act.ClearScrollback 'ScrollbackAndViewport',
      act.SendKey { key = 'L', mods = 'CTRL' },
    },
  },
  {
    key = 'z',
    mods = 'CTRL|META',
    action = wezterm.action.TogglePaneZoomState,
  },
  {
    key = 'E',
    mods = 'CTRL|SHIFT',
    action = act.EmitEvent 'trigger-emacs-with-scrollback',
  },
  {
    key = 'o',
    mods = 'CTRL',
    action = wezterm.action.ShowLauncher
  },

  { key="Backspace", mods="CTRL", action=act.SendKey { key="Backspace", mods="META" } },

  { key='t', mods='CTRL', action=act { SpawnCommandInNewTab = { cwd = wezterm.home_dir } } },

  { key="LeftArrow",  mods="CTRL|META", action=act.ActivateTabRelative(-1) },
  { key="RightArrow",  mods="CTRL|META", action=act.ActivateTabRelative(1) },

  { key="UpArrow",  mods="CTRL|META", action=act.ActivatePaneDirection("Prev") },
  { key="DownArrow",  mods="CTRL|META", action=act.ActivatePaneDirection("Next") },

  { key="h",  mods="CTRL|META", action=act.ActivateTabRelative(-1) },
  { key="l",  mods="CTRL|META", action=act.ActivateTabRelative(1) },

  { key="k",  mods="CTRL|META", action=act.ActivatePaneDirection("Prev") },
  { key="j",  mods="CTRL|META", action=act.ActivatePaneDirection("Next") },

  {
    key = "s",
    mods = "CTRL|SHIFT",
    action = workspace_switcher.switch_workspace(),
  },
  {
    key = "s",
    mods = "CTRL|META",
    action = workspace_switcher.switch_to_prev_workspace(),
  }
}

for i = 1, 8 do
  -- CTRL + number to activate that tab
  table.insert(config.keys, {
    key = tostring(i),
    mods = 'CTRL',
    action = act.ActivateTab(i - 1),
  })
end

tabline.setup({
    options = {
      theme_overrides = {
        background = "#282c34",
        tab = {
          active = { fg = '#eeeeee', bg = '#111111' },
          inactive = { fg = '#979eab', bg = '#282c34' },
          inactive_hover = { fg = '#cccccc', bg = '#282c34' },
        },
        normal_mode = {
          a = { bg = "#282c34", fg = "#eeeeee" },
          b = { bg = "#282c34", fg = "#eeeeee" },
          c = { bg = "#282c34", fg = "#eeeeee" },
          x = { bg = "#282c34", fg = "#eeeeee" },
          y = { bg = "#282c34", fg = "#eeeeee" },
          z = { bg = "#282c34", fg = "#eeeeee" },
        },
        copy_mode = {
          a = { bg = "#e5c07b", fg = "#282c34" },
          b = { bg = "#282c34", fg = "#eeeeee" },
          c = { bg = "#282c34", fg = "#eeeeee" },
          x = { bg = "#282c34", fg = "#eeeeee" },
          y = { bg = "#282c34", fg = "#eeeeee" },
          z = { bg = "#e5c07b", fg = "#282c34" },
        },
      },
      section_separators = {
        left = " ",
        right = " ",
      },
      component_separators = {
        left = " ",
        right = " ",
      },
      tab_separators = {
        left = " ",
        right = " ",
      },
      icons_enabled = true,
      tabs_enabled = true,
    },
    sections = {
      tabline_a = { 'workspace' },
      tabline_b = { '' },
      tabline_c = { '' },
      tab_active = {
        'index',
        { 'process', icons_only = true, process_to_icon = { ['fish'] = wezterm.nerdfonts.cod_terminal } },
        { 'parent', padding = 0 },
        '/',
        { 'cwd', padding = { left = 0, right = 1 } },
        { 'zoomed', padding = 0 },
      },
      tab_inactive = {
        'index',
        { 'process', process_to_icon = { ['fish'] = wezterm.nerdfonts.cod_terminal } },
        { 'parent', padding = 0 },
        '/',
        { 'cwd', padding = { left = 0, right = 1 } },
        { 'zoomed', padding = 0 },
      },
      tabline_x = { '' },
      tabline_y = { '' },
      tabline_z = { 'domain' },
    },
    extensions = {
      smart_workspace_switcher,
      quick_domains
    },
})

tabline.apply_to_config(config)

domains.apply_to_config(
  config,
  {
    keys = {
      -- open domain in new tab
      attach = {
        -- mod keys for fuzzy domain finder
        mods = 'CTRL|SHIFT',
        -- base key for fuzzy domain finder
        key = 'a',
        -- key table to insert key map to if any
        tbl = '',
      },
      -- open domain in split pane
      -- excludes remote domains
      -- add remote domains as exec domain for split binds
      vsplit = {
        key  = 'v',
        mods = 'CTRL',
        tbl  = 'tmux'
      },
      hsplit = {
        key  = 'h',
        mods = 'CTRL',
        tbl  = 'tmux'
      }
    },
    auto = {
      ssh_ignore = false,
      exec_ignore = {
        ssh = true
      }
    }
  }
)

workspace_switcher.apply_to_config(config)

return config
