
        let caseCurrentUserId = null;

        async function ensureCaseCurrentUserId() {
            if (caseCurrentUserId !== null) return caseCurrentUserId;
            try {
                const res = await fetch('/api/v1/auth/me', { credentials: 'include' });
                if (!res.ok) return null;
                const me = await res.json();
                caseCurrentUserId = Number(me?.id) || null;
                return caseCurrentUserId;
            } catch (e) {
                return null;
            }
        }

        async function ringOutFromCase(number) {
            const clean = String(number || '').trim();
            if (!clean || clean === '-') {
                alert('Intet gyldigt nummer at ringe til');
                return;
            }

            const userId = await ensureCaseCurrentUserId();
            try {
                const res = await fetch('/api/v1/telefoni/click-to-call', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({ number: clean, user_id: userId })
                });

                if (!res.ok) {
                    const t = await res.text();
                    alert('Ring ud fejlede: ' + t);
                    return;
                }
                alert('Ringer ud via Yealink...');
            } catch (e) {
                alert('Kunne ikke starte opkald');
            }
        }
    