#compdef trash

# Helper function to complete files from the trash bin
_trash_files_in_bin() {
  # Find the FreeDesktop.org trash "files" directory
  local trash_dir="${XDG_DATA_HOME:-$HOME/.local/share}/Trash/files"
  
  # Use _path_files to complete files from within that directory
  # -/ : complete all files
  # -W : complete files from *within* the specified directory, not the CWD
  _path_files -W "$trash_dir"
}

local curcontext=$curcontext state line ret=1
declare -A opt_args
declare -a args

args=(
  # rm-like options 
  '(-f --force)'{-f,--force}'[Don'\''t prompt and ignore errors]'

  # Group interactive flags
  '(-i -I --interactive --interact-once)'{-i,--interactive}'[Ask before each deletion]'
  '(-i -I --interactive --interact-once)'{-I,--interact-once}'[Ask before deleting 3+ files or recursively]'

  '(-r -R --recursive)'{-r,-R,--recursive}'[Delete directories and their contents recursively]'
  '(-d --dir)'{-d,--dir}'[Remove empty directories]'
  '(-v --verbose)'{-v,--verbose}'[Print more information]'

  # Info options 
  '(-h --help)'{-h,--help}'[Show help information]'
  '--version[Output the version and exit]'

  # Trash-specific actions (no args) 
  '--list[List out the files in the trash]'
  '--orphans[List orphaned files in the trash]'
  '--empty[Empty the trash bin]'

  # Trash-specific actions (with args) 
  '--delete[Delete a specific file from the trash]:file from trash:_trash_files_in_bin'
  '--restore[Restore a specific file from the trash]:file to restore:_trash_files_in_bin'
  '--rm[Permanently delete files (escape hatch)]:files:->files'

  # Default argument (files to trash) 
  # This transitions to the 'files' state
  '*::files to trash:->files'
)

_arguments -C -s -S \
  $args && ret=0

# This 'case' block handles completion for the 'files' state,
# which is triggered by --rm or by the default action.
case $state in
  (files)
    # This logic is copied from the rm completion to correctly
    # handle filenames with special characters
    (( CURRENT > 0 )) && line[CURRENT]=()
    line=( ${line//(#m)[\[\]()\\*?#<>~\^\|]/\\$MATCH} )
    _files -F line && ret=0
    ;;
esac

return $ret
