@php
    /** @var \App\Support\Workspaces\WorkspaceContext $workspaceContext */
    $workspaceContext = app(\App\Support\Workspaces\WorkspaceContext::class);

    $user = auth()->user();
    $currentWorkspaceId = $workspaceContext->currentWorkspaceId(request());

    $workspaces = collect();
    if ($user instanceof \App\Models\User) {
        $workspaces = \App\Models\Workspace::query()
            ->whereIn('id', function ($query) use ($user): void {
                $query->from('workspace_memberships')
                    ->select('workspace_id')
                    ->where('user_id', $user->getKey());
            })
            ->whereNull('archived_at')
            ->orderBy('name')
            ->get();
    }
@endphp

@if ($workspaces->isNotEmpty())
    <x-filament::dropdown.list>
        <div class="px-3 py-2">
            <form method="POST" action="{{ route('admin.switch-workspace') }}" class="space-y-2">
                @csrf

                <div class="text-xs font-medium text-gray-500 dark:text-gray-400">Switch workspace</div>

                <select
                    name="workspace_id"
                    class="fi-input fi-select w-full"
                    x-data
                    x-on:change="$el.form.submit()"
                >
                    @foreach ($workspaces as $workspace)
                        <option value="{{ $workspace->getKey() }}" {{ (int) $workspace->getKey() === (int) $currentWorkspaceId ? 'selected' : '' }}>
                            {{ $workspace->name }}
                        </option>
                    @endforeach
                </select>

                <div class="text-xs text-gray-500 dark:text-gray-400">Select a workspace to switch context.</div>
            </form>
        </div>
    </x-filament::dropdown.list>
@endif
