<?php

namespace App\Livewire\Portal;

use App\Domain\Shared\Context\PortalContext;
use Livewire\Component;

/**
 * The profile switcher is a scope control, not a screen.
 *
 * It writes one session key and dispatches a browser event; every screen reads
 * the value back through PortalContext, which re-validates it against
 * GuardianResolver. Nothing here trusts the id it was handed.
 */
class ProfileSwitcher extends Component
{
    public function select(int $participantId): void
    {
        // PortalContext::set() ignores an id this account does not speak for,
        // so a crafted payload changes nothing.
        app(PortalContext::class)->set($participantId);

        $this->dispatch('portal-profile-changed');
        $this->redirect(request()->header('Referer') ?: route('portal.home'), navigate: true);
    }

    public function render()
    {
        $portal = app(PortalContext::class);

        return view('livewire.portal.profile-switcher', [
            'profiles' => $portal->switchableProfiles(),
            'activeId' => $portal->participantId(),
        ]);
    }
}
