/**
 * Cincinnati Fire Department Portal — Broadcastify Radio Toggle
 * Persists radio on/off state per user.
 */
(function() {
    'use strict';

    const P = window.CFD_PORTAL || {};
    const toggle = document.getElementById('radioToggle');
    const player = document.getElementById('radioPlayer');
    const iframe = document.getElementById('radioIframe');
    const fallback = document.getElementById('radioFallbackLink');
    if (!toggle || !player) return;

    const broadcastifyUrl = `https://www.broadcastify.com/webPlayer/${P.broadcastifyId || '5184'}`;
    let isOn = P.user && P.user.radio_enabled;

    // Initialize state
    if (isOn) enableRadio();

    toggle.addEventListener('click', () => {
        if (isOn) {
            disableRadio();
        } else {
            enableRadio();
        }
        saveState(isOn);
    });

    function enableRadio() {
        isOn = true;
        toggle.classList.add('active');
        player.style.display = 'block';

        if (iframe) {
            iframe.src = broadcastifyUrl;
            // Check if iframe loaded or got blocked
            iframe.onload = function() {
                try {
                    // If we can access contentWindow, it loaded
                    void iframe.contentWindow.location.href;
                } catch (e) {
                    // Cross-origin = loaded fine (broadcastify domain)
                }
            };
            iframe.onerror = function() {
                showFallback();
            };
        }

        // After 3 seconds, check if iframe is blank (blocked)
        setTimeout(() => {
            if (iframe && iframe.offsetHeight < 50) {
                showFallback();
            }
        }, 3000);
    }

    function disableRadio() {
        isOn = false;
        toggle.classList.remove('active');
        player.style.display = 'none';
        if (iframe) iframe.src = '';
    }

    function showFallback() {
        if (iframe) iframe.style.display = 'none';
        if (fallback) fallback.style.display = 'inline-flex';
    }

    async function saveState(enabled) {
        const formData = new FormData();
        formData.append('enabled', enabled ? '1' : '0');
        formData.append('csrf_token', P.csrfToken);

        await fetch(P.apiPath + '/radio-toggle.php', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: formData
        });
    }
})();
