<?php

namespace Tests\Feature;

use App\Models\Creative;
use App\Models\PromptLandingPage;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class UnifiedLayoutTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test that all authenticated pages render the unified sidebar and header.
     */
    public function test_all_authenticated_pages_render_unified_sidebar_and_header(): void
    {
        $user = User::factory()->create();

        $routes = [
            'home',
            'profile',
            'chat.show',
            'creatives.index',
            'landing-pages.index',
            'google-ads.setup',
            'google-ads.create',
            'google-ads.campaigns',
        ];

        // Ensure /dashboard redirects to /home
        $dashResponse = $this->actingAs($user)->get(route('dashboard'));
        $dashResponse->assertRedirect(route('home'));

        foreach ($routes as $route) {
            $response = $this->actingAs($user)->get(route($route));

            $this->assertSame(200, $response->getStatusCode(), "Route {$route} redirected to {$response->headers->get('Location')}");
            $response->assertSee('class="mb-sidebar"', escape: false);
            $response->assertSee('class="mb-header"', escape: false);
            $response->assertSee('class="mb-shell"', escape: false);
            $response->assertSee('id="shell"', escape: false);
            $response->assertSee('data-action="toggle-sidebar"', escape: false);
            $response->assertDontSee('.mb-sidebar { width: 260px; min-width: 260px;', escape: false);
            $response->assertSee('<div class="mb-crumb"><strong>AdMedia</strong>', escape: false);
            $response->assertDontSee('<div class="mb-crumb"><strong>Laravel</strong>', escape: false);
            $response->assertSee('data-action="toggle-theme"', escape: false);
            $response->assertSee(route('home'));
            $response->assertSee(route('creatives.index'));
            $response->assertSee(route('landing-pages.index'));
            $response->assertSee(route('profile'));
            $response->assertDontSee('class="navbar navbar-expand-sm', escape: false);
        }
    }

    /**
     * Test that the sidebar includes the Home navigation link, icon, and New chat link.
     */
    public function test_sidebar_includes_home_and_new_chat_links(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->get(route('home'));

        $response->assertOk();
        $response->assertSee('title="Home"', escape: false);
        $response->assertSee('bi-house-door', escape: false);
        $response->assertSee('href="'.route('home').'"', escape: false);
        $response->assertSee('title="Chats"', escape: false);
        $response->assertSee('href="'.route('chats.index').'" class="mb-nav', escape: false);
        $response->assertSee('data-action="open-chat-search"', escape: false);
        $response->assertSee('id="chatSearch"', escape: false);
        $response->assertSee('id="chatSearchInput"', escape: false);
        $response->assertSee('title="New chat"', escape: false);
        $response->assertSee('href="'.route('chat.new').'"', escape: false);
        $response->assertSee('title="Campaign performance"', escape: false);
        $response->assertSee('href="'.route('campaigns.performance').'"', escape: false);
        $response->assertSee('bi-graph-up-arrow', escape: false);
    }

    /**
     * Test that the user popover menu includes a link to the user profile.
     */
    public function test_user_menu_includes_profile_link(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->get(route('home'));

        $response->assertOk();
        $response->assertSee('href="'.route('profile').'"', escape: false);
        $response->assertSee('Profile', escape: false);
    }

    /**
     * Test that each section has an All button and only one section expands at a time based on page context.
     */
    public function test_all_buttons_and_contextual_single_section_expansion(): void
    {
        $user = User::factory()->create();

        // 1. On Chat page: chatNav open, creativeNav & landingPageNav closed. All is inside chatNav.
        $chatResponse = $this->actingAs($user)->get(route('chat.show'));
        $chatResponse->assertOk();
        $chatResponse->assertSee('class="mb-chats-panel"', escape: false);
        $chatResponse->assertSee('class="mb-nav-panel is-closed" id="creativeNav"', escape: false);
        $chatResponse->assertSee('class="mb-nav-panel is-closed" id="landingPageNav"', escape: false);
        $chatResponse->assertSee('href="'.route('chats.index').'" class="mb-side-head-link', escape: false);

        // 2. On Creatives page: creativeNav open, chatNav & landingPageNav closed
        $creativesResponse = $this->actingAs($user)->get(route('creatives.index'));
        $creativesResponse->assertOk();
        $creativesResponse->assertSee('class="mb-nav-panel" id="creativeNav"', escape: false);
        $creativesResponse->assertSee('class="mb-chats-panel is-closed" id="chatNav"', escape: false);
        $creativesResponse->assertSee('class="mb-nav-panel is-closed" id="landingPageNav"', escape: false);
        $creativesResponse->assertSee('href="'.route('creatives.index').'" class="mb-side-head-link', escape: false);

        // 3. On Landing Pages page: landingPageNav open, chatNav & creativeNav closed
        $landingResponse = $this->actingAs($user)->get(route('landing-pages.index'));
        $landingResponse->assertOk();
        $landingResponse->assertSee('class="mb-nav-panel" id="landingPageNav"', escape: false);
        $landingResponse->assertSee('class="mb-chats-panel is-closed" id="chatNav"', escape: false);
        $landingResponse->assertSee('class="mb-nav-panel is-closed" id="creativeNav"', escape: false);
        $landingResponse->assertSee('href="'.route('landing-pages.index').'" class="mb-side-head-link', escape: false);
    }

    /**
     * Test that /chats renders the chats listing page and supports search.
     */
    public function test_chats_listing_page_renders_and_searches(): void
    {
        $user = User::factory()->create();

        DB::table('agent_conversations')->insert([
            'id' => 'conv-alpha-001',
            'participant_type' => $user->getMorphClass(),
            'participant_id' => $user->getKey(),
            'title' => 'Alpha Campaign Chat',
            'created_at' => now()->subHour(),
            'updated_at' => now()->subHour(),
        ]);

        DB::table('agent_conversations')->insert([
            'id' => 'conv-beta-002',
            'participant_type' => $user->getMorphClass(),
            'participant_id' => $user->getKey(),
            'title' => 'Beta Product Discussion',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Listing view
        $response = $this->actingAs($user)->get(route('chats.index'));
        $response->assertOk();
        $response->assertSee('Alpha Campaign Chat');
        $response->assertSee('Beta Product Discussion');
        $response->assertSee('class="mb-chats-panel"', escape: false); // Expanded on /chats
        $response->assertSee('class="mb-nav-panel is-closed" id="creativeNav"', escape: false);

        // Search query: filters listing table
        $searchResponse = $this->actingAs($user)->get(route('chats.index', ['q' => 'Alpha']));
        $searchResponse->assertOk();
        $searchResponse->assertSee('Alpha Campaign Chat');
        $searchResponse->assertSee('value="Alpha"', escape: false);
        $searchResponse->assertSee('id="chatSearchInput"', escape: false);
        $searchResponse->assertDontSee('href="'.route('chat.show', ['conversation' => 'conv-beta-002']).'" class="mb-btn-secondary', escape: false);
    }

    /**
     * Test that sidebar has working collapsible chats toggle and limits items to 5.
     */
    public function test_sidebar_chats_collapse_toggle_and_five_item_limit(): void
    {
        $user = User::factory()->create();

        // Create 7 conversations
        for ($i = 1; $i <= 7; $i++) {
            DB::table('agent_conversations')->insert([
                'id' => "conv-test-{$i}",
                'participant_type' => $user->getMorphClass(),
                'participant_id' => $user->getKey(),
                'title' => "Test Chat {$i}",
                'created_at' => now()->addMinutes($i),
                'updated_at' => now()->addMinutes($i),
            ]);
        }

        // Create 7 creatives
        for ($i = 1; $i <= 7; $i++) {
            Creative::create([
                'user_id' => $user->id,
                'type' => 'video',
                'status' => 'completed',
                'source' => 'prompt',
                'title' => "Test Creative {$i}",
                'created_at' => now()->addMinutes($i),
            ]);
        }

        // Create 7 prompt landing pages
        for ($i = 1; $i <= 7; $i++) {
            PromptLandingPage::create([
                'user_id' => $user->id,
                'title' => "Test Landing Page {$i}",
                'website_url' => 'https://example.com',
                'purpose' => 'Leads Page',
                'status' => 'approved',
                'created_at' => now()->addMinutes($i),
            ]);
        }

        $response = $this->actingAs($user)->get(route('home'));

        $response->assertOk();
        $response->assertSee('data-action="toggle-nav"', escape: false);
        $response->assertSee('data-target="chatNav"', escape: false);
        $response->assertSee('id="chatNav"', escape: false);

        // Chats: only the latest 5 should be shown
        $response->assertSee('Test Chat 7');
        $response->assertSee('class="mb-chat-row"', escape: false);
        $response->assertSee('class="mb-hist-dot"', escape: false);
        $response->assertSee('Test Chat 6');
        $response->assertSee('Test Chat 5');
        $response->assertSee('Test Chat 4');
        $response->assertSee('Test Chat 3');
        $response->assertDontSee('Test Chat 2');
        $response->assertDontSee('Test Chat 1');

        // Creatives: only the latest 5 should be shown
        $response->assertSee('Test Creative 7');
        $response->assertSee('Test Creative 6');
        $response->assertSee('Test Creative 5');
        $response->assertSee('Test Creative 4');
        $response->assertSee('Test Creative 3');
        $response->assertDontSee('Test Creative 2');
        $response->assertDontSee('Test Creative 1');

        // Landing Pages: only the latest 5 should be shown
        $response->assertSee('Test Landing Page 7');
        $response->assertSee('Test Landing Page 6');
        $response->assertSee('Test Landing Page 5');
        $response->assertSee('Test Landing Page 4');
        $response->assertSee('Test Landing Page 3');
        $response->assertDontSee('Test Landing Page 2');
        $response->assertDontSee('Test Landing Page 1');
    }

    public function test_profile_page_renders_with_functional_sidebar_and_unobstructed_modal(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->get(route('profile'));
        $response->assertOk();
        $response->assertSee('Profile');
        $response->assertSee(route('home'));
        // Modal component must not render static 'd-flex' or block the page when closed
        $response->assertDontSee('class="position-fixed top-0 start-0 w-100 h-100 d-flex', escape: false);
        $response->assertSee('display: none !important', escape: false);
    }
}
