<?php

namespace Tests\Feature\Livewire;

use App\Livewire\SidebarMenu;
use App\Models\User;
use Livewire\Livewire;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class SidebarMenuTest extends TestCase
{
    /**
     * Test that the sidebar menu component renders.
     */
    public function test_sidebar_menu_component_renders(): void
    {
        // Create a user with admin role
        $role = Role::firstOrCreate(['name' => 'super_admin']);
        $user = User::factory()->create();
        $user->assignRole($role);

        $this->actingAs($user);

        Livewire::test(SidebarMenu::class)
            ->assertStatus(200)
            ->assertSee('layout-menu'); // The component should render the aside with layout-menu class
    }

    /**
     * Test that the sidebar menu shows user profile when authenticated.
     */
    public function test_sidebar_menu_shows_user_profile(): void
    {
        $role = Role::firstOrCreate(['name' => 'super_admin']);
        $user = User::factory()->create([
            'first_name' => 'Test',
            'last_name' => 'User',
        ]);
        $user->assignRole($role);

        $this->actingAs($user);

        Livewire::test(SidebarMenu::class)
            ->assertStatus(200)
            ->assertSee('Test User')
            ->assertSee('My Profile');
    }

    /**
     * Test active route detection method.
     */
    public function test_sidebar_menu_detects_active_route(): void
    {
        $role = Role::firstOrCreate(['name' => 'super_admin']);
        $user = User::factory()->create();
        $user->assignRole($role);

        $this->actingAs($user);

        $component = Livewire::test(SidebarMenu::class);
        $sidebarMenu = $component->instance();

        // Test isActive method with mock menu item
        $menuItem = (object) ['slug' => 'dashboard'];
        $this->assertIsBool($sidebarMenu->isActive($menuItem));

        // Test with array slug
        $menuItemWithArraySlug = (object) ['slug' => ['dashboard', 'home']];
        $this->assertIsBool($sidebarMenu->isActive($menuItemWithArraySlug));
    }

    /**
     * Test visibility check method.
     */
    public function test_sidebar_menu_visibility_check(): void
    {
        $role = Role::firstOrCreate(['name' => 'super_admin']);
        $user = User::factory()->create();
        $user->assignRole($role);

        $this->actingAs($user);

        $component = Livewire::test(SidebarMenu::class);
        $sidebarMenu = $component->instance();

        // Test isVisible method with a simple menu item (no addon)
        $menuItem = (object) ['name' => 'Test Menu'];
        $this->assertTrue($sidebarMenu->isVisible($menuItem));

        // Test with a disabled addon
        $menuItemWithDisabledAddon = (object) ['name' => 'Test', 'addon' => 'NonExistentModule'];
        $this->assertFalse($sidebarMenu->isVisible($menuItemWithDisabledAddon));
    }
}
