<?php

namespace App\Livewire\Portal;

use App\Livewire\Portal\Concerns\PortalScreen;
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.
 *
 * It carries PortalScreen for the same reason the screens do, even though it
 * has no mount() to authorise: it is rendered inside layouts.portal and its
 * select() is its own Livewire round-trip, which arrives on Livewire's update
 * route rather than on `portal.*`. Without the trait's boot hook a staff
 * account that is also a parent would find the switcher listing only the
 * children who happen to train at the branch they are working in — which is
 * the one control on the portal that must never be narrowed.
 */
class ProfileSwitcher extends Component
{
    use PortalScreen;

    public function select(int $participantId): void
    {
        // PortalContext::set() ignores an id this account does not speak for,
        // so a crafted payload changes nothing.
        $this->portal()->set($participantId);

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

    public function render()
    {
        $portal = $this->portal();

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