#!/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

# Function to move cursor to (Row, Col)
cursor_to() {
    local r=$1
    local c=$2
    printf "${ESC}[${r};${c}H"
}

# Function to clean up terminal on exit
cleanup() {
    printf "${SHOW_CURSOR}${RESET}${CLEAR_SCREEN}"
    cursor_to 1 1
    clear
}
# Trap Ctrl+C and normal Exit to ensure cursor returns
trap cleanup EXIT

# Function to draw the horizontal bar
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
}

# Function to execute the chosen command
run_option() {
    # Move cursor 2 lines below menu to avoid overwriting it
    cursor_to $((ROW + 2)) $COL
    
    # Clear line before printing
    printf "${ESC}[2K"

    case $selected in
        0)
            # Add your actual command here
            ./igROGUE -l
	    cat logo.ans
            ;;
        1)
            # Example: tail -n 5 /var/log/syslog
            ./igROGUE -r
	    cat logo.ans
            ;;
        2)
	    cat logo.ans
            exit
            ;;
#        3)
#            exit 0
#            ;;
    esac
    
    # Wait for user input before clearing
    cursor_to $((ROW + 4)) $COL
    read -n 1 -s -r -p "Press any key to continue..."
    
    # Clear the output area so the menu looks clean again
    cursor_to $((ROW + 2)) 1
    printf "${ESC}[J" # Clear from cursor to end of screen
}

# --- 4. Main Loop ---

# Clear screen and hide cursor initially
printf "${CLEAR_SCREEN}${HIDE_CURSOR}"

cat logo.ans
while true; do
    draw_menu

    # Read 1 character silently
    read -rsn1 key

    # Check for Escape Sequence (Arrow keys send Esc+[+Letter)
    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
