PLUGIN_DIR="$HOME/.local/share/zsh/plugins"
mkdir -p "$PLUGIN_DIR"

# Install plugins (only if missing)
plugins=(
  "romkatv/zsh-defer"
  "zsh-users/zsh-autosuggestions"
  "hlissner/zsh-autopair"
  "zsh-users/zsh-history-substring-search"
  "Aloxaf/fzf-tab"
  "junegunn/fzf"
  "subnixr/minimal"
  "zap-zsh/vim"
  "zsh-users/zsh-syntax-highlighting"
)

# Plugin management function
zap() {
  echo "⚡ Updating plugins..."

  # Update plugins sequentially (clean output)
  for plugin in "${plugins[@]}"; do
    plugin_name=${plugin##*/}
    
    if [ ! -d "$PLUGIN_DIR/$plugin_name" ]; then
      echo "Installing $plugin_name"
      git clone --quiet "https://github.com/$plugin" "$PLUGIN_DIR/$plugin_name" --depth=1
    else
      old_hash=$(git -C "$PLUGIN_DIR/$plugin_name" rev-parse HEAD 2>/dev/null)
      
      git -C "$PLUGIN_DIR/$plugin_name" fetch --quiet
      git -C "$PLUGIN_DIR/$plugin_name" reset --hard origin/HEAD --quiet
      
      new_hash=$(git -C "$PLUGIN_DIR/$plugin_name" rev-parse HEAD 2>/dev/null)
      
      if [ "$old_hash" = "$new_hash" ]; then
        echo "✓ $plugin_name (up to date)"
      else
        echo "↑ $plugin_name (${old_hash:0:7} → ${new_hash:0:7})"
      fi
    fi
  done
  
  for dir in "$PLUGIN_DIR"/*; do
    if [ -d "$dir" ]; then
      plugin_name=$(basename "$dir")
      if [[ ! " ${plugins[@]##*/} " =~ " $plugin_name " ]]; then
        echo "Removing unused plugin: $plugin_name"
        rm -rf "$dir"
      fi
    fi
  done
  
  echo "Plugin update complete!"
}

for plugin in "${plugins[@]}"; do
  plugin_name=${plugin##*/}
  [ -d "$PLUGIN_DIR/$plugin_name" ] || git clone --quiet "https://github.com/$plugin" "$PLUGIN_DIR/$plugin_name" --depth=1
done

# Source plugins
source "$PLUGIN_DIR/zsh-defer/zsh-defer.plugin.zsh"

# Defer heavy plugins for faster startup
zsh-defer source "$PLUGIN_DIR/zsh-autosuggestions/zsh-autosuggestions.zsh"
zsh-defer source "$PLUGIN_DIR/zsh-autopair/autopair.zsh"
zsh-defer source "$PLUGIN_DIR/zsh-history-substring-search/zsh-history-substring-search.zsh"
zsh-defer source "$PLUGIN_DIR/fzf-tab/fzf-tab.plugin.zsh"
zsh-defer source "$PLUGIN_DIR/fzf/shell/completion.zsh"
zsh-defer source "$PLUGIN_DIR/fzf/shell/key-bindings.zsh"
zsh-defer source "$PLUGIN_DIR/vim/vim.plugin.zsh"

source "$PLUGIN_DIR/minimal/minimal.zsh"

# Source config files
source "$ZDOTDIR/opts.zsh"
source "$ZDOTDIR/rose-pine.sh"
source "$ZDOTDIR/maintenance.zsh"

# Defer loading
zsh-defer source "$PLUGIN_DIR/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
for config in mise.zsh tmux.zsh functions.zsh alias.zsh keymap.zsh path.zsh pnpm.zsh; do
  zsh-defer source "$ZDOTDIR/$config"
done