#!/usr/bin/env bash
# fzf and ggrep with switch keys for modes (macOS version)
# https://github.com/junegunn/fzf/blob/master/ADVANCED.md#switching-between-ripgrep-mode-and-fzf-mode

# Switch between Ripgrep launcher mode (CTRL-R) and fzf filtering mode (CTRL-F)
RG_PREFIX="rg --column --line-number --no-heading --color=always --smart-case "
INITIAL_QUERY=""

# Capture the first selected line; macOS /bin/bash lacks read -a.
selected_output="$(
  FZF_DEFAULT_COMMAND="$RG_PREFIX $(printf %q "$INITIAL_QUERY") || true" \
  fzf --ansi \
      --color "hl:-1:underline,hl+:-1:underline:reverse" \
      --disabled --query "$INITIAL_QUERY" \
      --bind "change:reload:sleep 0.1; $RG_PREFIX {q} || true" \
      --bind "ctrl-f:unbind(change,ctrl-f)+change-prompt(2. fzf> )+enable-search+clear-query+rebind(ctrl-r)" \
      --bind "ctrl-r:unbind(ctrl-r)+change-prompt(1. ripgrep> )+disable-search+reload($RG_PREFIX {q} || true)+rebind(change,ctrl-f)" \
      --prompt '1. ripgrep> ' \
      --delimiter : \
      --header '╱ CTRL-R (ripgrep mode) ╱ CTRL-F (fzf mode) ╱' \
      --preview 'bat --color=always {1} --highlight-line {2}' \
      --preview-window 'up,60%,border-bottom,+{2}+3/3,~3'
)"
fzf_status=$?

# Cancel exits (Esc/Ctrl-C) should succeed quietly. This script can be sourced
# by the shell wrapper, so it must fall through instead of calling exit.
if [ "$fzf_status" -eq 0 ] && [ -n "$selected_output" ]; then
  # Work with the first selected match.
  IFS=$'\n' read -r first_line _ <<<"$selected_output"
  IFS=: read -r file line column _ <<<"$first_line"

  if [ -n "$file" ] && [ -n "$line" ]; then
    hx "${file}:${line}:${column}"
  fi
fi
