#!/hint/zsh
emulate -L zsh -o extended_glob

zmodload zsh/mapfile

# receive arguments
local pid=$1 header_lines=$2 active_group_style=$3 tmp_dir=$4 offset=$5

# read completion list
local -a list=(${(f)mapfile[$tmp_dir/completions.$pid]})

# --- group marker detection (fzf-tab groups) ---------------------------------
# When groups exist, fzf-tab prefixes each entry with a group SGR like $'\e[94m'.
# When no groups exist (often file lists), entries may start with $'\e[0m'
# (reset for LS_COLORS). Treat that as "no groups".
local -Ua group_sgr_prefixes
if (( $#list > 10000 && $+commands[grep] )); then
  group_sgr_prefixes=(${(f)"$(print -l -- ${list:$header_lines} | command grep -a -o $'^\x1b\\[[0-9;]*m')"})
else
  group_sgr_prefixes=(${(M)${list:$header_lines}#$'\x1b['[0-9;]#*m})
fi

# if the only marker is reset, there are no real groups
if (( $#group_sgr_prefixes == 1 )) && [[ $group_sgr_prefixes[1] == $'\e[0m' ]]; then
  group_sgr_prefixes=()
fi

# calculate and persist current group index
# the index starts from 2, because switching from "all" to "group 1" looks weird
local current=2
if (( $#group_sgr_prefixes > 0 )) && [[ -f $tmp_dir/current-group.$pid ]]; then
  current=$(( $(<$tmp_dir/current-group.$pid) + offset ))
fi
(( current > $#group_sgr_prefixes )) && current=1
(( current == 0 )) && current=$#group_sgr_prefixes
echo $current > $tmp_dir/current-group.$pid

# configure style of active header
local sgr_on='' sgr_off=''
case $active_group_style in
  (bold)          sgr_on=$'\x1b[1m';    sgr_off=$'\x1b[22m' ;;
  (underline)     sgr_on=$'\x1b[4m';    sgr_off=$'\x1b[24m' ;;
  (bold,underline) sgr_on=$'\x1b[1;4m'; sgr_off=$'\x1b[22;24m' ;;
  (none)          sgr_on='';            sgr_off='' ;;
  (*)             sgr_on=$'\x1b[1m';    sgr_off=$'\x1b[22m' ;;  # fallback
esac

# The ANSI SGR code that marks every line in the currently selected group.
local current_prefix=$group_sgr_prefixes[current]

# print headers
if (( header_lines != 0 )); then
  # Apply style only to the group label (excluding trailing spaces), then disable it
  print -l ${${(S)list[1,header_lines]/(#b)($current_prefix*)($'\x1b[00m')/${match[1]/%(#b)( #)/$sgr_off$match}$match[2]}/$current_prefix/$current_prefix$sgr_on}
fi

if (( $#list > 10000 && $+commands[grep] )); then
  print -l -- ${list:$header_lines} | command grep -a -F -- "${group_sgr_prefixes[current]}"
else
  print -l -- ${(M)${list:$header_lines}:#${group_sgr_prefixes[current]}*}
fi
