// Active sidebar link on scroll for settings.html
(function() {
    var sections = document.querySelectorAll('.card[id]');
    var links = document.querySelectorAll('.settings-sidebar a[href^="#"]');

    if (!sections.length || !links.length) return;

    var observer = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                links.forEach(function(link) {
                    link.classList.remove('active');
                    if (link.getAttribute('href') === '#' + entry.target.id) {
                        link.classList.add('active');
                    }
                });
            }
        });
    }, { rootMargin: '-20% 0px -60% 0px' });

    sections.forEach(function(section) { observer.observe(section); });

    // Smooth scroll on sidebar click
    links.forEach(function(link) {
        link.addEventListener('click', function(e) {
            var target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });

    // Magic login toggle — AJAX with optimistic UI
    var toggle = document.getElementById('magicLoginToggle');
    if (toggle) {
        toggle.addEventListener('change', function() {
            var targetState = this.checked;
            fetch('/settings/security/magic-login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ enabled: targetState })
            }).then(function(r) { return r.json(); }).then(function(data) {
                if (data.status !== 'ok') {
                    // Revert on failure
                    toggle.checked = !targetState;
                    alert('Failed to update magic login preference.');
                }
            }).catch(function() {
                toggle.checked = !targetState;
                alert('Failed to update magic login preference.');
            });
        });
    }
})();
