<?php

declare(strict_types=1);

use App\Filament\Resources\ManagedEnvironmentResource;
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',
    ]);
    createUserWithTenant(tenant: $tenant, user: $member, role: 'readonly');

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

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

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

    $membershipsPage = visit(ManagedEnvironmentResource::getUrl('memberships', ['record' => $tenant->getRouteKey()], panel: 'admin'));

    $membershipsPage
        ->assertNoJavaScriptErrors()
        ->assertSee('Manage environment access scope')
        ->assertSee('Back to environment overview')
        ->assertSee('Workspace membership defines the role. Explicit environment scopes only narrow which workspace members can see this environment.');

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

    $membershipsPage
        ->waitForText('Add explicit access scope')
        ->assertNoJavaScriptErrors()
        ->assertSee('Manage environment access scope')
        ->assertSee('Add explicit access scope')
        ->assertSee('browser-tenant-member@example.test')
        ->assertSee('Remove explicit scope');
});
