#!/bin/bash
# capture user locale before forcing LANG=C for predictable tool output
_loc="${LC_ALL:-${LC_MESSAGES:-${LANG:-$LANGUAGE}}}"; case "$_loc" in it*) IT=1;; *) IT=0;; esac
export LANG=C
norm(){ echo "$1" | tr 'a-f' 'A-F' | tr -d ':_-'; }
# translate internal category key -> displayed label (IT keys are the internal ones)
disp(){
  [ "$IT" = 1 ] && { echo "$1"; return; }
  case "$1" in
    Tastiera) echo "Keyboard";; Telefono) echo "Phone";; Altro) echo "Other";; *) echo "$1";;
  esac
}
declare -A BAT
while IFS= read -r d; do
  info=$(upower -i "$d" 2>/dev/null)
  echo "$info" | grep -qi 'percentage' || continue
  ser=$(echo "$info" | sed -n 's/.*serial:[[:space:]]*//p' | head -1)
  per=$(echo "$info" | sed -n 's/.*percentage:[[:space:]]*\([0-9]\+\).*/\1/p' | head -1)
  [ -n "$ser" ] && [ -n "$per" ] && BAT["$(norm "$ser")"]="$per"
done < <(upower -e 2>/dev/null | grep -viE 'DisplayDevice|line_power')
declare -A CAT
while read -r _ mac name; do
  [ -z "$mac" ] && continue
  info=$(bluetoothctl info "$mac" 2>/dev/null)
  icon=$(echo "$info" | sed -n 's/.*Icon:[[:space:]]*//p' | head -1)
  case "$icon" in
    input-gaming) c="Gamepad" ;;
    audio-*) c="Audio" ;;
    input-keyboard) c="Tastiera" ;;
    input-mouse|input-tablet) c="Mouse" ;;
    phone) c="Telefono" ;;
    computer) c="PC" ;;
    *) c="Altro" ;;
  esac
  b="${BAT[$(norm "$mac")]}"
  [ -z "$b" ] && b=$(echo "$info" | sed -n 's/.*Battery Percentage:.*(\([0-9]\+\)).*/\1/p' | head -1)
  line=" $name"; [ -n "$b" ] && line=" $name  ${b}%"
  CAT["$c"]+="$line"$'\n'
done < <(bluetoothctl devices Connected 2>/dev/null)
any=0
for c in Gamepad Audio Tastiera Mouse Telefono PC Altro; do
  if [ -n "${CAT[$c]}" ]; then
    any=1
    printf '${color D8A849}%s${color F1E3C6}\n' "$(disp "$c")"
    printf '%s' "${CAT[$c]}"
  fi
done
[ "$any" = 0 ] && { [ "$IT" = 1 ] && echo "(nessuno collegato)" || echo "(none connected)"; }
