<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use App\Models\User;

class SimpleConsoleTest extends DuskTestCase
{

    /** @test */
    public function it_captures_console_errors_on_subjects_page()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🔍 SIMPLE CONSOLE ERROR TEST\n";
            echo "=" . str_repeat("=", 50) . "\n";

            // Use existing admin user from seeder
            $admin = User::where('email', 'admin@example.com')->first();
            if (!$admin) {
                $admin = User::where('role', 'admin')->first();
            }

            try {
                $browser->loginAs($admin)
                        ->visit('/subjects');

                // Wait a bit for page to load
                $browser->pause(3000);

                echo "✅ Successfully visited /subjects\n";

                // Get page title
                $title = $browser->driver->getTitle();
                echo "📄 Page title: {$title}\n";

                // Get current URL
                $url = $browser->driver->getCurrentURL();
                echo "🔗 Current URL: {$url}\n";

                // Check if we're on login page (authentication issue)
                $pageSource = $browser->driver->getPageSource();
                if (strpos($pageSource, 'login') !== false || strpos($pageSource, 'Login') !== false) {
                    echo "⚠️ Redirected to login page - authentication issue\n";
                } else {
                    echo "✅ Not on login page\n";
                }

                // Capture console logs
                $logs = $browser->driver->manage()->getLog('browser');

                echo "\n📋 CONSOLE LOGS:\n";
                echo "-" . str_repeat("-", 30) . "\n";

                if (empty($logs)) {
                    echo "✅ No console logs found\n";
                } else {
                    foreach ($logs as $log) {
                        $level = $log['level'];
                        $message = $log['message'];
                        $timestamp = date('H:i:s', $log['timestamp'] / 1000);

                        $icon = match($level) {
                            'SEVERE' => '❌',
                            'WARNING' => '⚠️',
                            'INFO' => 'ℹ️',
                            default => '📝'
                        };

                        echo "{$icon} [{$level}] {$timestamp}: {$message}\n";
                    }
                }

                // Check page source for specific errors
                echo "\n🔍 PAGE SOURCE ANALYSIS:\n";
                echo "-" . str_repeat("-", 30) . "\n";

                if (strpos($pageSource, 'TypeError') !== false) {
                    echo "❌ TypeError found in page source\n";
                }
                if (strpos($pageSource, 'ReferenceError') !== false) {
                    echo "❌ ReferenceError found in page source\n";
                }
                if (strpos($pageSource, 'SyntaxError') !== false) {
                    echo "❌ SyntaxError found in page source\n";
                }
                if (strpos($pageSource, 'useToast') !== false) {
                    echo "✅ useToast found in page source\n";
                } else {
                    echo "❌ useToast not found in page source\n";
                }
                if (strpos($pageSource, 'ToastContainer') !== false) {
                    echo "✅ ToastContainer found in page source\n";
                } else {
                    echo "❌ ToastContainer not found in page source\n";
                }

                // Check for Vue and Inertia
                echo "\n⚡ JAVASCRIPT GLOBALS:\n";
                echo "-" . str_repeat("-", 30) . "\n";

                try {
                    $vueExists = $browser->script('return typeof window.Vue !== "undefined"')[0];
                    echo $vueExists ? "✅ Vue is available\n" : "❌ Vue not available\n";
                } catch (\Exception $e) {
                    echo "❌ Error checking Vue: {$e->getMessage()}\n";
                }

                try {
                    $inertiaExists = $browser->script('return typeof window.Inertia !== "undefined"')[0];
                    echo $inertiaExists ? "✅ Inertia is available\n" : "❌ Inertia not available\n";
                } catch (\Exception $e) {
                    echo "❌ Error checking Inertia: {$e->getMessage()}\n";
                }

                // Check for specific elements
                echo "\n🎯 ELEMENT CHECK:\n";
                echo "-" . str_repeat("-", 30) . "\n";

                $elements = [
                    'h1' => 'Page heading',
                    'table' => 'Data table',
                    '.toast-container' => 'Toast container',
                    '.fixed.top-4.right-4' => 'Toast position container',
                    '[data-testid]' => 'Test elements'
                ];

                foreach ($elements as $selector => $description) {
                    try {
                        $element = $browser->element($selector);
                        echo $element ? "✅ {$description} found\n" : "❌ {$description} not found\n";
                    } catch (\Exception $e) {
                        echo "❌ Error checking {$description}: {$e->getMessage()}\n";
                    }
                }

            } catch (\Exception $e) {
                echo "❌ Error during test: {$e->getMessage()}\n";
                echo "Stack trace: {$e->getTraceAsString()}\n";
            }

            echo "\n✅ Console error test completed\n";
        });
    }

    /** @test */
    public function it_tests_basic_navigation()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🧭 BASIC NAVIGATION TEST\n";
            echo "=" . str_repeat("=", 50) . "\n";

            // Use existing admin user from seeder
            $admin = User::where('email', 'admin@example.com')->first();
            if (!$admin) {
                $admin = User::where('role', 'admin')->first();
            }

            $pages = [
                '/dashboard' => 'Dashboard',
                '/subjects' => 'Subjects',
                '/classrooms' => 'Classrooms',
                '/academic-years' => 'Academic Years'
            ];

            foreach ($pages as $url => $name) {
                try {
                    echo "\n📄 Testing {$name} ({$url})...\n";

                    $browser->loginAs($admin)
                            ->visit($url)
                            ->pause(2000);

                    $currentUrl = $browser->driver->getCurrentURL();
                    $title = $browser->driver->getTitle();

                    echo "   🔗 URL: {$currentUrl}\n";
                    echo "   📄 Title: {$title}\n";

                    // Check for errors
                    $logs = $browser->driver->manage()->getLog('browser');
                    $errorCount = count(array_filter($logs, fn($log) => $log['level'] === 'SEVERE'));

                    if ($errorCount > 0) {
                        echo "   ❌ {$errorCount} console errors found\n";
                        foreach ($logs as $log) {
                            if ($log['level'] === 'SEVERE') {
                                echo "      - {$log['message']}\n";
                            }
                        }
                    } else {
                        echo "   ✅ No console errors\n";
                    }

                } catch (\Exception $e) {
                    echo "   ❌ Error: {$e->getMessage()}\n";
                }
            }

            echo "\n✅ Navigation test completed\n";
        });
    }
}
