<?php

require_once __DIR__ . '/vendor/autoload.php';

echo "Arrow Key Test\n";
echo "==============\n\n";
echo "Press arrow keys to test input reading.\n";
echo "Press 'q' to quit.\n\n";

// Enable raw mode
shell_exec('stty -icanon -echo');

function readKey(): string
{
    $key = fgetc(STDIN);
    if ($key === false) {
        return '';
    }

    // Handle escape sequences (arrow keys, etc.)
    if ($key === "\033") {
        $sequence = $key;

        // Read the next character
        $next = fgetc(STDIN);
        if ($next === false) {
            return $key; // Just escape
        }
        $sequence .= $next;

        // If it's a bracket, read more
        if ($next === '[') {
            $third = fgetc(STDIN);
            if ($third !== false) {
                $sequence .= $third;

                // Some sequences have more characters (like Page Up/Down)
                if ($third === '5' || $third === '6' || $third === '3') {
                    $fourth = fgetc(STDIN);
                    if ($fourth !== false) {
                        $sequence .= $fourth;
                    }
                }
            }
        }

        return $sequence;
    }

    return $key;
}

try {
    while (true) {
        $key = readKey();

        if ($key === 'q') {
            break;
        }

        $hexKey = bin2hex($key);
        echo "Key pressed: '$key' (hex: $hexKey)\n";

        switch ($key) {
            case "\033[A":
                echo "  -> Arrow UP detected!\n";
                break;
            case "\033[B":
                echo "  -> Arrow DOWN detected!\n";
                break;
            case "\033[C":
                echo "  -> Arrow RIGHT detected!\n";
                break;
            case "\033[D":
                echo "  -> Arrow LEFT detected!\n";
                break;
            case "\n":
                echo "  -> ENTER detected!\n";
                break;
            case " ":
                echo "  -> SPACE detected!\n";
                break;
            case "\033":
                echo "  -> ESC detected!\n";
                break;
            default:
                echo "  -> Regular key: '$key'\n";
                break;
        }
    }
} finally {
    // Restore terminal
    shell_exec('stty icanon echo');
    echo "\nTerminal restored. Goodbye!\n";
}