local wezterm = require 'wezterm'
local config = wezterm.config_builder()

local registry = dofile(wezterm.config_dir .. '/themes/registry.lua')

-- Fields that can vary between themes and must be hot-swappable.
local THEME_FIELDS = {
  'colors',
  'window_background_opacity',
  'window_background_gradient',
  'cursor_blink_rate',
}

local function apply_theme(cfg, theme)
  for _, field in ipairs(THEME_FIELDS) do
    if theme[field] ~= nil then
      cfg[field] = theme[field]
    end
  end
end

apply_theme(config, registry.current())

-- Font
config.font = wezterm.font_with_fallback({
  'JetBrains Mono',
  'Nerd Font Symbols',
})
config.font_size = 14.0

-- Window
config.window_padding = { left = 10, right = 10, top = 10, bottom = 10 }
config.window_close_confirmation = 'AlwaysPrompt'
config.scrollback_lines = 10000

-- Tab bar
config.enable_tab_bar = true
config.use_fancy_tab_bar = false
config.tab_bar_at_bottom = false
config.hide_tab_bar_if_only_one_tab = false
config.show_tab_index_in_tab_bar = true

-- Keybindings
local act = wezterm.action

config.keys = {
  {
    key = 'h',
    mods = 'CTRL|SHIFT',
    action = wezterm.action_callback(function(window, pane)
      local next_theme = registry.next()
      registry.save(next_theme)

      local overrides = {}
      for _, field in ipairs(THEME_FIELDS) do
        if next_theme[field] ~= nil then
          overrides[field] = next_theme[field]
        end
      end
      window:set_config_overrides(overrides)

      window:toast_notification('Tema', next_theme.label, nil, 1500)
      window:perform_action(act.EmitEvent('update-right-status'), pane)
    end),
  },
}

-- Status bar
wezterm.on('update-right-status', function(window, _)
  local theme = registry.current()
  window:set_right_status(wezterm.format({
    { Text = '  ' },
    { Foreground = { Color = theme.colors.cursor_bg } },
    { Text = '> ' },
    { Foreground = { Color = theme.colors.ansi[4] } },
    { Attribute = { Intensity = 'Bold' } },
    { Text = theme.label },
    { Attribute = { Intensity = 'Normal' } },
    { Text = '  ' },
    { Foreground = { Color = theme.colors.ansi[2] } },
    { Text = wezterm.hostname() },
    { Text = '  ' },
    { Foreground = { Color = theme.colors.ansi[3] } },
    { Text = wezterm.strftime('%H:%M') },
    { Text = '  ' },
  }))
end)

return config