# Set the directory to store zinit and plugins
ZINIT_HOME="${XDG_DATA_HOME:-${HOME}/.locale/share}/zinit/zinit.git"

# Download Zinit if not present
if [ ! -d "$ZINIT_HOME" ]; then
  mkdir -p "$(dirname $ZINIT_HOME)"
  git clone https://github.com/zdharma-continuum/zinit.git "$ZINIT_HOME"
fi

# Source Zinit and your other configuration files
source "${ZINIT_HOME}/zinit.zsh"
source ~/.aliases.zsh
source ~/.plugins.zsh
source ~/.export.zsh

# Initialization settings for zsh-vi-mode
ZVM_INIT_MODE=sourcing

# CONSOLIDATED FUNCTION: All zsh-vi-mode logic must be in one place [2]
function zvm_after_init() {
  # Fix fzf interaction
  source <(fzf --zsh)
  
  # Bind Atuin search for both Insert and Normal modes [9]
  zvm_bindkey viins '^R' atuin-search
  zvm_bindkey vicmd '^R' atuin-search
  
  # Re-bind autosuggest-accept
  bindkey '^@' autosuggest-accept
}

# Load completions
autoload -U compinit && compinit

# Oh My Posh initialization
eval "$(oh-my-posh init zsh --config $HOME/.config/ohmyposh/zen.toml)"

# Pyenv setup
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"

# Custom Keybinds
bindkey -s '^T' ' tea^M ^M'

# Completion styling
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
zstyle ':fzf-tab:complete:cd:*' fzf-preview 'ls --color $realpath'

# Tool initializations
eval "$(fzf --zsh)"
eval "$(zoxide init --cmd cd zsh)"
eval "$(thefuck --alias)"
eval "$(navi widget zsh)"
eval "$(pyenv init -)"

# FZF Run command customizations
_fzf_comprun() {
  local command=$1
  shift
  case "$command" in
    cd)             fzf --preview 'eza --tree --color=always {} | head -200' "$@" ;;
    export|unset)   fzf --preview "eval 'echo \$' {}"   "$@" ;;
    ssh)            fzf --preview 'dig {}'              "$@" ;;
    *)              fzf --preview "--preview 'bat -n --color=always --line-range :10 {}'" "$@" ;;
  esac
}

# Yazi function
function y() {
  local tmp="$(mktemp -t "yazi-cwd.XXXXXX")" cwd
  yazi "$@" --cwd-file="$tmp"
  if cwd="$(command cat -- "$tmp")" && [ -n "$cwd" ] && [ "$cwd" != "$PWD" ]; then
    builtin cd -- "$cwd"
  fi
  rm -f -- "$tmp"
}


zinit ice depth=1
# Zinit Annexes
zinit light-mode for \
  zdharma-continuum/zinit-annex-as-monitor \
  zdharma-continuum/zinit-annex-bin-gem-node \
  zdharma-continuum/zinit-annex-patch-dl \
  zdharma-continuum/zinit-annex-rust

# Path exports
export PATH="$HOME/.local/bin:$PATH"
export PATH=/home/liph/.opencode/bin:$PATH

# Atuin Initialization [10]
# Must be at the very end to ensure hooks are applied correctly [1]
# . "$HOME/.atuin/bin/env"
eval "$(atuin init zsh)"
