<?php

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

// Debug navigation issue
use App\Framework\Console\Components\TuiState;
use App\Framework\Console\Components\TuiInputHandler;
use App\Framework\Console\Components\TuiCommandExecutor;
use App\Framework\Console\CommandHistory;
use App\Framework\Console\TuiView;
use App\Framework\Console\TuiKeyCode;

echo "Debugging TUI Navigation Issue...\n";
echo "=================================\n\n";

try {
    // Create mock executor
    $mockExecutor = new class implements \App\Framework\Console\Components\TuiCommandExecutor {
        public function executeSelectedCommand(object $command): void {
            echo "Mock: Execute command\n";
        }
        public function executeCommand(string $commandName): void {
            echo "Mock: Execute command: $commandName\n";
        }
        public function validateSelectedCommand(object $command): void {
            echo "Mock: Validate command\n";
        }
        public function validateCommand(string $commandName): void {
            echo "Mock: Validate command: $commandName\n";
        }
        public function showSelectedCommandHelp(object $command): void {
            echo "Mock: Show help\n";
        }
        public function showCommandHelp(string $commandName): void {
            echo "Mock: Show help: $commandName\n";
        }
        public function showAllCommandsHelp(): void {
            echo "Mock: Show all commands help\n";
        }
        public function startInteractiveForm(object $command, \App\Framework\Console\Components\TuiState $state): void {
            echo "Mock: Start form\n";
        }
        public function findCommandObject(string $commandName): ?object {
            return null;
        }
    };

    $state = new TuiState();
    $history = new CommandHistory();
    $inputHandler = new TuiInputHandler($mockExecutor);

    // Setup realistic test categories like in real TUI
    $categories = [
        0 => [
            'name' => 'Database',
            'description' => 'Database commands',
            'icon' => '🗄️',
            'commands' => [],
            'priority' => 100
        ],
        1 => [
            'name' => 'Cache',
            'description' => 'Cache commands',
            'icon' => '⚡',
            'commands' => [],
            'priority' => 90
        ],
        2 => [
            'name' => 'Testing',
            'description' => 'Testing commands',
            'icon' => '🧪',
            'commands' => [],
            'priority' => 80
        ],
        3 => [
            'name' => 'MCP',
            'description' => 'MCP commands',
            'icon' => '🤖',
            'commands' => [],
            'priority' => 70
        ]
    ];

    $state->setCategories($categories);
    $state->setCurrentView(TuiView::CATEGORIES);
    $state->setRunning(true);

    echo "✓ Initial Setup:\n";
    echo "  Categories: " . count($categories) . "\n";
    echo "  Current View: " . $state->getCurrentView()->name . "\n";
    echo "  Selected Category: " . $state->getSelectedCategory() . "\n";
    echo "  Category Name: '{$categories[$state->getSelectedCategory()]['name']}'\n\n";

    // Test step-by-step navigation
    echo "🔍 Testing Navigation Step-by-Step:\n\n";

    // Test 1: Arrow Down
    echo "Test 1: Arrow DOWN\n";
    echo "  Before: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";
    echo "  Input Key: '" . TuiKeyCode::ARROW_DOWN->value . "' (hex: " . bin2hex(TuiKeyCode::ARROW_DOWN->value) . ")\n";

    $inputHandler->handleInput(TuiKeyCode::ARROW_DOWN->value, $state, $history);

    echo "  After: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";
    echo "  ✓ Expected: Should move from Database (0) to Cache (1)\n\n";

    // Test 2: Arrow Down again
    echo "Test 2: Arrow DOWN again\n";
    echo "  Before: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";

    $inputHandler->handleInput(TuiKeyCode::ARROW_DOWN->value, $state, $history);

    echo "  After: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";
    echo "  ✓ Expected: Should move from Cache (1) to Testing (2)\n\n";

    // Test 3: Arrow Up
    echo "Test 3: Arrow UP\n";
    echo "  Before: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";

    $inputHandler->handleInput(TuiKeyCode::ARROW_UP->value, $state, $history);

    echo "  After: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";
    echo "  ✓ Expected: Should move from Testing (2) to Cache (1)\n\n";

    // Test 4: Boundary testing - go to end
    echo "Test 4: Go to last category and test boundary\n";
    $state->setSelectedCategory(3); // MCP
    echo "  Set to: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";

    $inputHandler->handleInput(TuiKeyCode::ARROW_DOWN->value, $state, $history);

    echo "  After Arrow DOWN: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";
    echo "  ✓ Expected: Should stay at MCP (3) - boundary protection\n\n";

    // Test 5: Boundary testing - go to beginning
    echo "Test 5: Go to first category and test boundary\n";
    $state->setSelectedCategory(0); // Database
    echo "  Set to: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";

    $inputHandler->handleInput(TuiKeyCode::ARROW_UP->value, $state, $history);

    echo "  After Arrow UP: Category {$state->getSelectedCategory()} ('{$categories[$state->getSelectedCategory()]['name']}')\n";
    echo "  ✓ Expected: Should stay at Database (0) - boundary protection\n\n";

    // Debug the TuiState navigation methods directly
    echo "🔍 Testing TuiState Navigation Methods Directly:\n\n";

    echo "Direct TuiState Testing:\n";
    $state->setSelectedCategory(1); // Cache
    echo "  Set to: {$state->getSelectedCategory()}\n";

    echo "  Calling navigateDown()...\n";
    $state->navigateDown();
    echo "  Result: {$state->getSelectedCategory()}\n";

    echo "  Calling navigateUp()...\n";
    $state->navigateUp();
    echo "  Result: {$state->getSelectedCategory()}\n\n";

    echo "✅ Navigation Debug Test COMPLETED\n";

} catch (\Throwable $e) {
    echo "\n❌ Navigation Debug Test FAILED:\n";
    echo "Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "\nStack trace:\n" . $e->getTraceAsString() . "\n";
}