#!/usr/bin/env bash

ESC=$'\033'
RESET="${ESC}[0m"
BLUE_BG="${ESC}[44m"
WHITE_TXT="${ESC}[97m"
BLUE_TXT="${ESC}[94m"
HIDE_CURSOR="${ESC}[?25l"
SHOW_CURSOR="${ESC}[?25h"
CLEAR_SCREEN="${ESC}[2J"

OPTIONS=(" 1. Login To Server " " 2. Register New User " " 3. Exit igROGUE ")
NUM_OPTIONS=${#OPTIONS[@]}

ROW=10
COL=10

selected=0

cursor_to() {
    local r=$1
    local c=$2
    printf "${ESC}[${r};${c}H"
}

cleanup() {
    printf "${SHOW_CURSOR}${RESET}${CLEAR_SCREEN}"
    cursor_to 1 1
    clear
}
trap cleanup EXIT

draw_menu() {
    cursor_to $ROW $COL
    
    for ((i=0; i<NUM_OPTIONS; i++)); do
        if [ $i -eq $selected ]; then
            # Selected: Blue Background + White Text
            printf "${BLUE_BG}${BLUE_TXT}${OPTIONS[$i]}${RESET}"
        else
            # Unselected: Normal Text
            printf "${OPTIONS[$i]}"
        fi
        # Add a spacer between items
        printf "  "
    done
}

run_option() {
    # Move cursor 2 lines below menu to avoid overwriting it
    cursor_to $((ROW + 2)) $COL
    
    printf "${ESC}[2K"

    case $selected in
        0)
            ./igROGUE -l
	    cat logo.ans
            ;;
        1)
            ./igROGUE -r
	    cat logo.ans
            ;;
        2)
	    cat logo.ans
            exit
            ;;
#        3)
#            exit 0
#            ;;
    esac
    
    cursor_to $((ROW + 4)) $COL
    read -n 1 -s -r -p "Press any key to continue..."
    
    cursor_to $((ROW + 2)) 1
    printf "${ESC}[J" # Clear from cursor to end of screen
}

printf "${CLEAR_SCREEN}${HIDE_CURSOR}"

cat logo.ans
while true; do
    draw_menu

    # Read 1 character silently
    read -rsn1 key

    if [[ "$key" == "$ESC" ]]; then
        read -rsn2 key # Read the next 2 chars
        case "$key" in
            '[D') # Left Arrow
                ((selected--))
                if [ $selected -lt 0 ]; then selected=$((NUM_OPTIONS - 1)); fi
                ;;
            '[C') # Right Arrow
                ((selected++))
                if [ $selected -ge $NUM_OPTIONS ]; then selected=0; fi
                ;;
        esac
    elif [[ "$key" == "" ]]; then
        # Enter key was pressed
        run_option
    fi
done
