# ===== History Navigation =====
# Setup fuzzy history search with up/down keys

# Up arrow/k - search history forward
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search

# Down arrow/j - search history backward
autoload -U down-line-or-beginning-search
zle -N down-line-or-beginning-search

# Bind keys in both vicmd and viins modes
# vicmd = vi command mode, viins = vi insert mode
bindkey -M vicmd "k" up-line-or-beginning-search
bindkey -M vicmd "^k" up-line-or-beginning-search
bindkey -M viins "^k" up-line-or-beginning-search
bindkey -M viins "^[[A" up-line-or-beginning-search  # Up arrow key

bindkey -M vicmd "j" down-line-or-beginning-search
bindkey -M vicmd "^j" down-line-or-beginning-search
bindkey -M viins "^j" down-line-or-beginning-search
bindkey -M viins "^[[B" down-line-or-beginning-search  # Down arrow key

# ===== System Clipboard Integration =====
# Enhanced yank that copies to system clipboard

function vi-yank-clipboard() {
   # First perform the normal vi-yank operation
   zle vi-yank

   # Only copy if there's content in the cut buffer
   if [[ -n "$CUTBUFFER" ]]; then
     # Detect the environment and use appropriate clipboard command
     if [[ "$XDG_SESSION_TYPE" == "wayland" ]] && command -v wl-copy >/dev/null; then
       echo -n "$CUTBUFFER" | wl-copy
     elif command -v xclip >/dev/null; then
       echo -n "$CUTBUFFER" | xclip -selection clipboard
     elif command -v pbcopy >/dev/null; then
       # For macOS
       echo -n "$CUTBUFFER" | pbcopy
     fi
   fi
}

# Register the function and bind it
zle -N vi-yank-clipboard
bindkey -M vicmd "y" vi-yank-clipboard

# ===== Command Line Editing =====
# Edit command in external editor

# Load the function and register it
autoload -U edit-command-line
zle -N edit-command-line

# Bind 'v' in command mode to open editor
bindkey -M vicmd "v" edit-command-line

# ===== Additional Useful Bindings =====

# Ctrl+Space to accept autosuggestion
bindkey '^ ' autosuggest-accept

# Ctrl+e to edit command in editor from any mode
bindkey '^e' edit-command-line

# Ensure backspace and delete work as expected
bindkey '^?' backward-delete-char
bindkey "^[[3~" delete-char

# Home/End keys
bindkey "^[[H" beginning-of-line
bindkey "^[[F" end-of-line
bindkey "^[[1~" beginning-of-line
bindkey "^[[4~" end-of-line
