/**
 * Premium Radio Tuner - Public Navigation and PJAX Controller
 */
(function($) {
    "use strict";

    window.plugtuner_tuner = window.plugtuner_tuner || {};

    if (window.plugtuner_main_initialized) {
        return;
    }
    window.plugtuner_main_initialized = true;

    // Rebind all tuner and public card components after page transitions
    function rebindAllPublicScripts() {
        // Remove duplicate player cards before moving/binding
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.removeDuplicatePlayers === 'function') {
            window.plugtuner_tuner.removeDuplicatePlayers();
        }

        // Move the floating player card directly to the body to escape any parent stacking contexts in themes
        $('.floating-player-card.rtp-floating-player').appendTo('body');

        // Re-read scale needle labels
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.initScaleLabels === 'function') {
            window.plugtuner_tuner.initScaleLabels();
        }
        
        // Rebind dial needle, volume slider, and track equalizer events
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.initRadioEvents === 'function') {
            window.plugtuner_tuner.initRadioEvents();
        }

        // Rebind scale needle UI
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.rebindRadioUI === 'function') {
            window.plugtuner_tuner.rebindRadioUI();
        }

        // Sync plays/pause UI
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.setPlayState === 'function') {
            const audioPlayer = window.plugtuner_tuner.audioPlayer;
            const isPlaying = audioPlayer && !audioPlayer.paused;
            window.plugtuner_tuner.setPlayState(isPlaying);
        }

        // Rebind page play/pause card buttons
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.rebindPublicStationButtons === 'function') {
            window.plugtuner_tuner.rebindPublicStationButtons();
        }

        // Sync card buttons icons
        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.syncStationButtonsUI === 'function') {
            const audioPlayer = window.plugtuner_tuner.audioPlayer;
            const isPlaying = audioPlayer && !audioPlayer.paused;
            window.plugtuner_tuner.syncStationButtonsUI(isPlaying);
        }

        // Re-run theme initialization if present (e.g. for carousels, tabs, toggles on dynamic page load)
        if (typeof window.plugtuner_theme_init === 'function') {
            window.plugtuner_theme_init();
        }
    }

    // Only run PJAX if explicitly enabled in settings
    if (plugtuner_public_vars.enable_pjax !== '1') {
        return;
    }


    // Helper: Identify main wrapper selector of the theme
    function getPjaxContainerSelector() {
        if ($('#page').length) return '#page';
        if ($('#content').length) return '#content';
        if ($('#main').length) return '#main';
        if ($('.site').length) return '.site';
        return 'body';
    }

    // Intercept internal page transitions
    $(document).on('click', 'a', function(e) {
        const link = this;
        const currentUrl = window.location.href;
        
        // Skip external links, hashes, non-HTTP links, downloads, and target="_blank"
        if (link.hostname !== window.location.hostname ||
            link.protocol.indexOf('http') !== 0 ||
            $(link).attr('target') === '_blank' ||
            $(link).attr('download') !== undefined ||
            link.href.indexOf('#') > -1 && link.pathname === window.location.pathname
        ) {
            return;
        }

        // Skip WordPress default admin, login, and customize links
        if (link.pathname.indexOf('/wp-admin') > -1 ||
            link.pathname.indexOf('/wp-login.php') > -1 ||
            link.href.indexOf('customize.php') > -1
        ) {
            return;
        }

        e.preventDefault();
        loadPageViaAJAX(link.href, true);
    });

    // Handle browser back/forward buttons
    window.addEventListener('popstate', function() {
        loadPageViaAJAX(window.location.href, false);
    });

    function loadPageViaAJAX(url, pushState) {
        const selector = getPjaxContainerSelector();
        const $container = $(selector);
        const $playerCard = $('#rtp-player-card');

        if (!$container.length) {
            window.location.href = url;
            return;
        }

        // Temporarily move the player card out of the container so it doesn't get destroyed
        if ($playerCard.length && $.contains($container[0], $playerCard[0])) {
            $playerCard.appendTo('body');
        }

        // Visual fade out indicator
        $container.css('opacity', '0.55');

        fetch(url)
            .then(res => {
                if (!res.ok) throw new Error(`HTTP Error ${res.status}`);
                return res.text();
            })
            .then(html => {
                const parser = new DOMParser();
                const newDoc = parser.parseFromString(html, 'text/html');
                const $newContainer = $(newDoc).find(selector);

                if (!$newContainer.length) {
                    window.location.href = url;
                    return;
                }

                // Update Title
                document.title = newDoc.title;

                // Update Body Classes
                const newBodyClass = newDoc.body.className;
                if (typeof newBodyClass === 'string') {
                    document.body.className = newBodyClass;
                }

                // Replace Content
                $container.html($newContainer.html());
                $container.css('opacity', '1');

                // Update history
                if (pushState) {
                    history.pushState(null, '', url);
                }

                // Scroll to top
                window.scrollTo(0, 0);

                // Re-append the player to its footer location if the new container supports footer elements
                // (Otherwise it remains appended to body, which is perfectly safe and functional)
                
                // Sync localized variables from the newly loaded page
                let newScript = newDoc.getElementById('rtp-radio-js-extra');
                if (!newScript) {
                    const scripts = newDoc.querySelectorAll('script');
                    for (let i = 0; i < scripts.length; i++) {
                        if (scripts[i].textContent && scripts[i].textContent.indexOf('plugtuner_public_vars') !== -1) {
                            newScript = scripts[i];
                            break;
                        }
                    }
                }
                if (newScript) {
                    const scriptContent = newScript.textContent || newScript.innerText;
                    const match = scriptContent.match(/var\s+plugtuner_public_vars\s*=\s*({[\s\S]*?});/);
                    if (match) {
                        try {
                            const newVars = JSON.parse(match[1]);
                            window.plugtuner_public_vars = newVars;
                            if (window.plugtuner_tuner && typeof window.plugtuner_tuner.updateStationsArray === 'function') {
                                window.plugtuner_tuner.updateStationsArray(newVars.stations || []);
                            }
                        } catch (e) {
                        }
                    }
                }

                // Rebind event handlers for new elements
                rebindAllPublicScripts();
            })
            .catch(err => {
                console.error('PJAX navigation failed, reloading page standard:', err);
                window.location.href = url;
            });
    }

})(jQuery);
