local M = {}

local ns_id = vim.api.nvim_create_namespace('private_mode')
local enabled = false
local concealed_char = '•' -- Character to show instead of text

local function conceal_buffer()
  local buf = vim.api.nvim_get_current_buf()
  local line_count = vim.api.nvim_buf_line_count(buf)
  
  vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)
  
  for i = 0, line_count - 1 do
    local line = vim.api.nvim_buf_get_lines(buf, i, i + 1, false)[1]
    if line and #line > 0 then
      -- Conceal each character individually
      for col = 0, #line - 1 do
        vim.api.nvim_buf_set_extmark(buf, ns_id, i, col, {
          end_col = col + 1,
          conceal = concealed_char,
        })
      end
    end
  end
end

local function reveal_current_line()
  local buf = vim.api.nvim_get_current_buf()
  local cursor = vim.api.nvim_win_get_cursor(0)
  local current_line = cursor[1] - 1
  
  -- Clear concealment for current line only
  vim.api.nvim_buf_clear_namespace(buf, ns_id, current_line, current_line + 1)
end

local function update_display()
  if not enabled then return end
  
  conceal_buffer()
  local mode = vim.fn.mode()
  
  -- Reveal current line in insert mode
  if mode == 'i' or mode == 'R' then
    reveal_current_line()
  end
end

function M.toggle()
  enabled = not enabled
  
  if enabled then
    -- Set concealment options
    vim.opt_local.conceallevel = 2
    vim.opt_local.concealcursor = 'nvc'
    
    -- Initial concealment
    update_display()
    
    -- Set up autocommands
    local group = vim.api.nvim_create_augroup('PrivateMode', { clear = true })
    
    vim.api.nvim_create_autocmd({'ModeChanged', 'CursorMoved', 'CursorMovedI', 'TextChanged', 'TextChangedI'}, {
      group = group,
      callback = update_display,
    })
    
    print("Private mode enabled")
  else
    -- Clear all concealment
    local buf = vim.api.nvim_get_current_buf()
    vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)
    
    -- Clear autocommands
    vim.api.nvim_create_augroup('PrivateMode', { clear = true })
    
    print("Private mode disabled")
  end
end

function M.setup(opts)
  opts = opts or {}
  concealed_char = opts.conceal_char or '•'
  
  -- Create user command
  vim.api.nvim_create_user_command('PrivateMode', function()
    M.toggle()
  end, {})
  
  -- Optional: Set up a keybinding
  if opts.keymap then
    vim.keymap.set('n', opts.keymap, M.toggle, { desc = 'Toggle private mode' })
  end
end

return M
