local wezterm = require 'wezterm'
local config = {}
local themes = require('theme/init')

-- Watch theme-state file so wezterm auto-reloads when toggle script writes to it
wezterm.add_to_config_reload_watch_list(
  os.getenv("HOME") .. "/.config/theme-state"
)

-- Determine current theme from state file
local function get_theme()
  local f = io.open(os.getenv("HOME") .. "/.config/theme-state", "r")
  if f then
    local state = f:read("*a"):gsub("%s+", "")
    f:close()
    if state == "light" then return themes.light end
  end
  return themes.main
end

local theme = get_theme()

-- Font configuration
config.font = wezterm.font 'JetBrainsMono Nerd Font'
config.font_size = 11.0

config.colors = theme.colors()
config.window_frame = theme.window_frame()

-- Window
config.enable_tab_bar = true
config.window_close_confirmation = 'NeverPrompt'

-- Only show tab bar when there are multiple tabs
wezterm.on('update-right-status', function(window, pane)
  local overrides = window:get_config_overrides() or {}
  local tabs = window:mux_window():tabs()
  local show = #tabs > 1
  if overrides.enable_tab_bar ~= show then
    overrides.enable_tab_bar = show
    window:set_config_overrides(overrides)
  end
end)

-- Wayland specific fixes
config.enable_wayland = true

-- Enable Kitty keyboard protocol for better key disambiguation (Ctrl+I vs Tab)
config.enable_kitty_keyboard = true

-- Keybindings
config.keys = {
  { key = 'LeftArrow', mods = 'CTRL|SHIFT', action = wezterm.action.ActivateTabRelative(-1) },
  { key = 'RightArrow', mods = 'CTRL|SHIFT', action = wezterm.action.ActivateTabRelative(1) },
  {
      key = 'n',
      mods = 'CTRL|SHIFT',
      action = wezterm.action_callback(function(win, pane)
          local tab, window = pane:move_to_new_window()
      end),
  },
}

-- Machine-local overrides (not tracked in dotfiles)
-- Create ~/.config/wezterm/local.lua returning a function that mutates config
local ok, local_config = pcall(require, 'local')
if ok then local_config(config) end

return config
