<?php
/** @var \App\Customization $customization */

$assets->load('Vue_InlinePlayer');
?>

let inlinePlayer, currentUrl = null;

const stopText = <?=$this->escapeJs(__('Stop')) ?>;
const playText = <?=$this->escapeJs(__('Play')) ?>;

function redrawPlayIcons () {
    $('.btn-audio').each(function () {
        if (!$(this).hasClass('has-listener')) {
            $(this).on('click', function (e) {
                e.preventDefault();
                inlinePlayer.$eventHub.$emit('player_toggle', $(this).data('url'));
                return false;
            });
            $(this).addClass('has-listener');
        }

        let playIcon = $(this).find('i.material-icons');

        if (null !== currentUrl && $(this).is('[data-url="' + currentUrl + '"]')) {
            $(this).addClass('playing')
                .attr('title', stopText)
                .attr('aria-label', stopText);

            playIcon.text('stop_circle');
        } else {
            $(this).removeClass('playing')
                .attr('title', playText)
                .attr('aria-label', playText);

            playIcon.text('play_circle');
        }
    });
}

$(function () {
    inlinePlayer = new Vue({
        el: '#radio-player-controls',
        render: function (createElement) {
            return createElement(InlinePlayer.default);
        }
    });

    redrawPlayIcons();

    inlinePlayer.$eventHub.$on('player_stopped', function () {
        currentUrl = null;
        redrawPlayIcons();
    });

    inlinePlayer.$eventHub.$on('player_playing', function (audio_source) {
        currentUrl = audio_source.split(/[?#]/)[0];
        redrawPlayIcons();
    });

    // The "content_changed" event fires from other components when they redraw portions of a page.
    inlinePlayer.$eventHub.$on('content_changed', function () {
        redrawPlayIcons();
    });
});
