local M = {}

vim.opt.fillchars = { diff = ' ', eob = ' ', stlnc = '─', stl = '─', vert = '│', msgsep = '‾' }

-- custom highlights
vim.api.nvim_set_hl(0, 'User1', { fg = '#458588', bg = 'NONE' })
vim.api.nvim_set_hl(0, 'User2', { fg = '#fe8019', bg = '#1d2021' })
vim.api.nvim_set_hl(0, 'User3', { fg = '#fb4934', bg = '#1d2021' })
vim.api.nvim_set_hl(0, 'User4', { fg = '#fabd2f', bg = '#1d2021' })
vim.api.nvim_set_hl(0, 'User5', { fg = '#83a598', bg = '#1d2021' })
vim.api.nvim_set_hl(0, 'User6', { fg = '#d3869b', bg = '#1d2021' })
vim.api.nvim_set_hl(0, 'User8', { fg = '#ebdbb2', bg = 'NONE' })

-- statusline colors
M.colors = {
  flags = '%#User8#',
  inactive = '%#StatusLineNC#',
  line_col = '%#User1#',
}

-- setup truncation limits
M.trunc_width = setmetatable({
  filename = 140,
  line_col = 60,
}, {
  __index = function()
    return 80
  end,
})

-- is buffer horizontally truncated
M.is_truncated = function(_, width)
  local current_width = vim.api.nvim_win_get_width(0)
  return current_width < width
end

-- get current line/col
M.get_line_col = function(self)
  if self:is_truncated(self.trunc_width.line_col) then
    return ' %l:%c'
  else
    return ' :%l/%L ─ :%c/%-2{virtcol("$") - 1} ─ %p%%'
  end
end

M.get_flags = function()
  return '%h%w%m '
end

M.get_words = function()
  if vim.o.filetype == 'text' then
    if vim.fn.has_key(vim.fn.wordcount(), 'visual_words') == 1 then
      return 'W:' .. vim.fn.wordcount().visual_words .. '/' .. vim.fn.wordcount().words .. ' '
    else
      return 'W:' .. vim.fn.wordcount().cursor_words .. '/' .. vim.fn.wordcount().words .. ' '
    end
  else
    return ''
  end
end

-- get current file name
M.get_filename = function(self)
  local filename = vim.fn.expand '%:t'
  local fullname = '%<%F'
  if filename == '' then
    return ''
  end
  if self:is_truncated(self.trunc_width.filename) then
    return ' ' .. filename .. ' '
  else
    return ' ' .. fullname .. ' '
  end
end

-- create active statusline
M.set_active = function(self)
  local palabras = self.colors.flags .. self:get_words()
  local flags = self.colors.flags .. self:get_flags()
  local filename = string.format('%s%s', self.colors.filename or '', self:get_filename())
  local line_col = self.colors.line_col .. self:get_line_col()

  return table.concat {
    palabras,
    flags,
    '%=',
    filename,
    '%=',
    line_col,
  }
end

-- create inactive statusline
M.set_inactive = function(self)
  return self.colors.inactive .. '%= %m %F %='
end

-- set statusline
Statusline = setmetatable(M, {
  __call = function(self, mode)
    return self['set_' .. mode](self)
  end,
})

vim.cmd [[
  augroup Statusline
  au!
  au WinEnter,BufEnter * setlocal statusline=%!v:lua.Statusline('active')
  au WinLeave,BufLeave * setlocal statusline=%!v:lua.Statusline('inactive')
  augroup END
]]
