function rlStopEmbed(wrap, btn) {
    // Tear the <iframe> out of the DOM entirely rather than just
    // hiding it or resetting its src, that is what actually and
    // reliably stops playback (YouTube/Vimeo players run their own
    // JS inside the iframe, so merely hiding the wrapper does not
    // stop the audio).
    wrap.classList.add("hidden");
    wrap.innerHTML = "";
    if (btn) {
        btn.innerHTML = "&#9654; Play here";
    }
}

function rlPlayEmbed(wrap, btn) {
    var src = wrap.getAttribute("data-embed-src");
    if (!src) { return; }

    // Build the <iframe> fresh every time it is opened, instead of
    // rendering it once (hidden) and toggling visibility. A hidden
    // (display:none) iframe with loading="lazy" never gets picked up
    // by the browser lazy-load check, so the previous approach
    // would hang on the first attempt to open a second video.
    var iframe = document.createElement("iframe");
    iframe.setAttribute("src", src);
    iframe.setAttribute("allow", "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture");
    iframe.setAttribute("allowfullscreen", "");
    wrap.innerHTML = "";
    wrap.appendChild(iframe);
    wrap.classList.remove("hidden");
    if (btn) {
        btn.innerHTML = "&#10006; Hide player";
    }
}

document.addEventListener("click", function (e) {
    var btn = e.target.closest(".rl-play-toggle");
    if (!btn) { return; }
    var wrap = document.getElementById(btn.getAttribute("data-target"));
    if (!wrap) { return; }
    var isPlaying = !wrap.classList.contains("hidden");

    if (isPlaying) {
        rlStopEmbed(wrap, btn);
        return;
    }

    // Only one video should play at a time, stop/close any other
    // open player before showing this one.
    document.querySelectorAll(".rl-embed-wrap").forEach(function (openWrap) {
        if (openWrap === wrap || openWrap.classList.contains("hidden")) { return; }
        var openBtn = document.querySelector('.rl-play-toggle[data-target="' + openWrap.id + '"]');
        rlStopEmbed(openWrap, openBtn);
    });

    rlPlayEmbed(wrap, btn);
});
