{{--
    Mints (or rebinds) the Quick PIN "trusted device" token for the current
    user, mirroring leolanka-inertia's useDeviceToken() hook: runs once per
    fresh login, comparing the stored device's user id against the live one
    covers both "first login on this browser" and "a different staff member
    just logged in here". Server-side already guarantees this never renders
    during impersonation (see TenantPanelProvider::renderDeviceTokenScript()).

    A token is only minted for accounts Quick PIN can actually serve (PIN set,
    no stronger second factor — see User::canUseQuickLogin()). For everyone
    else — including accounts that once had a PIN and still carry a stale
    token in this browser — the stored device is cleared so the login page
    never resurrects a PIN pad nobody can use.
--}}
<script>
    (function () {
        var currentUserId = {{ (int) $userId }};
        var hasPin = {{ $hasPin ? 'true' : 'false' }};
        var stored = null;

        try {
            stored = JSON.parse(localStorage.getItem('quickPinDevice') || 'null');
        } catch (e) {
            stored = null;
        }

        if (! hasPin) {
            if (stored && stored.user && stored.user.id === {{ (int) $userId }}) {
                localStorage.removeItem('quickPinDevice');
            }
            return;
        }

        if (stored && stored.user && stored.user.id === currentUserId) {
            return;
        }

        fetch('{{ route('device-token.store') }}', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
        })
            .then(function (res) { return res.ok ? res.json() : null; })
            .then(function (data) {
                if (data && data.token) {
                    localStorage.setItem('quickPinDevice', JSON.stringify({ token: data.token, user: data.user }));
                }
            })
            .catch(function () {
                // Best-effort: Quick PIN login simply won't be offered next visit.
            });
    })();
</script>
