/**
 * Premium Radio Tuner - Frontend Station Cards Integration
 */
(function($) {
    "use strict";

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

    if (window.plugtuner_station_cards_initialized) {
        if (typeof window.plugtuner_tuner.rebindPublicStationButtons === 'function') {
            window.plugtuner_tuner.rebindPublicStationButtons();
        }
        return;
    }
    window.plugtuner_station_cards_initialized = true;

    // Bind play buttons on the page to trigger the global persistent footer player
    window.plugtuner_tuner.rebindPublicStationButtons = function() {
        const $playBtns = $('.card-play-btn, .sp-card-play-btn, .btn-row-play');

        $playBtns.off('click').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            if (window.plugtuner_tuner.tuningAudio && !window.plugtuner_tuner.tuningAudio.paused) {
                return; // Currently scanning
            }

            const streamUrl = $(this).attr('data-stream-url') || $(this).attr('data-url');
            if (!streamUrl) return;

            const audioPlayer = window.plugtuner_tuner.audioPlayer;
            if (audioPlayer && audioPlayer.src === streamUrl && !audioPlayer.paused) {
                // Pause if playing
                audioPlayer.pause();
                if (typeof window.plugtuner_tuner.setPlayState === 'function') {
                    window.plugtuner_tuner.setPlayState(false);
                }
            } else {
                // Play new stream
                if (typeof window.plugtuner_tuner.playStationStream === 'function') {
                    window.plugtuner_tuner.playStationStream(streamUrl);
                } else if (audioPlayer) {
                    audioPlayer.src = streamUrl;
                    audioPlayer.play().catch(err => console.error("Playback failed:", err));
                    if (typeof window.plugtuner_tuner.setPlayState === 'function') {
                        window.plugtuner_tuner.setPlayState(true);
                    }
                }
            }
        });
    };

    // Update play button icons on cards to sync with global player state
    window.plugtuner_tuner.syncStationButtonsUI = function(isPlaying) {
        const audioPlayer = window.plugtuner_tuner.audioPlayer;
        const activeUrl = audioPlayer ? audioPlayer.src : '';

        $('.card-play-btn, .sp-card-play-btn, .btn-row-play').each(function() {
            const btnUrl = $(this).attr('data-stream-url') || $(this).attr('data-url');
            const $card = $(this).closest('.station-card, .stations-page-card, tr');

            if (isPlaying && btnUrl && (activeUrl === btnUrl || activeUrl.includes(btnUrl))) {
                $(this).addClass('playing').html('<i class="fa-solid fa-pause"></i>');
                if ($card.length) $card.addClass('is-playing row-playing');
            } else {
                $(this).removeClass('playing').html('<i class="fa-solid fa-play"></i>');
                if ($card.length) $card.removeClass('is-playing row-playing');
            }
        });
    };

    // Hook sync into player play state events with robust fallback loaders
    function initPublicStationCards() {
        if (window.plugtuner_station_cards_initialized_dom) return;
        window.plugtuner_station_cards_initialized_dom = true;

        if (window.plugtuner_tuner && typeof window.plugtuner_tuner.rebindPublicStationButtons === 'function') {
            window.plugtuner_tuner.rebindPublicStationButtons();
        }

        const audioPlayer = window.plugtuner_tuner && window.plugtuner_tuner.audioPlayer;
        if (audioPlayer) {
            audioPlayer.addEventListener('playing', () => {
                if (window.plugtuner_tuner && typeof window.plugtuner_tuner.syncStationButtonsUI === 'function') {
                    window.plugtuner_tuner.syncStationButtonsUI(true);
                }
            });
            audioPlayer.addEventListener('pause', () => {
                if (window.plugtuner_tuner && typeof window.plugtuner_tuner.syncStationButtonsUI === 'function') {
                    window.plugtuner_tuner.syncStationButtonsUI(false);
                }
            });
            // Initial sync
            if (window.plugtuner_tuner && typeof window.plugtuner_tuner.syncStationButtonsUI === 'function') {
                window.plugtuner_tuner.syncStationButtonsUI(!audioPlayer.paused);
            }
        }
    }

    // Try immediately
    initPublicStationCards();

    // Fallback 1: DOMContentLoaded
    window.addEventListener('DOMContentLoaded', initPublicStationCards);

    // Fallback 2: jQuery Ready
    $(document).ready(initPublicStationCards);

})(jQuery);
