#!/usr/bin/env bash
# ffind-preview — preview + clipboard helper for ffind (called by fzf)
#
# Usage:
#   ffind-preview <line-from-fzf>   show a preview of the file/line
#   ffind-preview --copy <line>     copy the file path to the clipboard
#
# The line is either "file:line:text" (content match) or "file" (filename
# match). The file path is always the first colon-separated field.

set -euo pipefail

copy_path() {
    local file="$1"
    if command -v wl-copy >/dev/null 2>&1; then
        printf '%s' "$file" | wl-copy 2>/dev/null && return 0
    fi
    if command -v xclip >/dev/null 2>&1; then
        printf '%s' "$file" | xclip -selection clipboard 2>/dev/null && return 0
    fi
    if command -v xsel >/dev/null 2>&1; then
        printf '%s' "$file" | xsel -b 2>/dev/null && return 0
    fi
    if command -v pbcopy >/dev/null 2>&1; then
        printf '%s' "$file" | pbcopy 2>/dev/null && return 0
    fi
    return 1
}

if [ "${1:-}" = "--copy" ]; then
    shift
    line="$*"
    file=$(printf '%s' "$line" | cut -d: -f1)
    if copy_path "$file"; then
        printf 'Copied: %s\n' "$file"
    else
        printf 'No clipboard tool found (install wl-clipboard, xclip, or xsel)\n' >&2
        exit 1
    fi
    exit 0
fi

line="$*"
file=$(printf '%s' "$line" | cut -d: -f1)
num=$(printf '%s' "$line" | cut -d: -f2 2>/dev/null)

if [ -n "$num" ] && [ "$num" -eq "$num" ] 2>/dev/null; then
    # Content match: show context around the matched line
    printf '\033[1m%s:%s\033[0m\n\n' "$file" "$num"
    rg --color=always -n "^" "$file" 2>/dev/null | head -n $((num + 15)) | tail -n 30
else
    # Filename only: show file preview
    printf '\033[1m%s\033[0m\n\n' "$file"
    head -60 "$file" 2>/dev/null
fi
