<?php

declare(strict_types=1);

use App\Filament\Resources\TenantResource;
use App\Models\User;
use App\Support\Workspaces\WorkspaceContext;

pest()->browser()->timeout(15_000);

it('renders tenant memberships only on the dedicated memberships page after scroll hydration', function (): void {
    [$owner, $tenant] = createUserWithTenant(role: 'owner');

    $member = User::factory()->create([
        'email' => 'browser-tenant-member@example.test',
    ]);
    $member->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'readonly'],
    ]);

    $this->actingAs($owner)->withSession([
        WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
    ]);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    $viewPage = visit(TenantResource::getUrl('view', ['record' => $tenant->getRouteKey()], panel: 'admin'));

    $viewPage
        ->assertNoJavaScriptErrors()
        ->assertSee((string) $tenant->name)
        ->assertSee('Manage memberships')
        ->assertScript("document.body.innerText.includes('Add member')", false)
        ->assertScript("document.body.innerText.includes('browser-tenant-member@example.test')", false);

    $membershipsPage = $viewPage->click('Manage memberships');

    $membershipsPage
        ->assertNoJavaScriptErrors()
        ->assertSee('Manage tenant memberships')
        ->assertSee('Back to tenant overview')
        ->assertSee('Tenant access is managed here. Use the tenant overview for provider state, verification, and operational context.');

    $membershipsPage->script(<<<'JS'
window.scrollTo(0, document.body.scrollHeight);
JS);

    $membershipsPage
        ->waitForText('Add member')
        ->assertNoJavaScriptErrors()
        ->assertSee('Manage tenant memberships')
        ->assertSee('Add member')
        ->assertSee('browser-tenant-member@example.test')
        ->assertSee('Change role')
        ->assertSee('Remove');
});
