pragma Singleton

import Quickshell
import Quickshell.Services.Mpris
import QtQuick

// Single source of truth for "which MPRIS player is active", so the bar pill and
// the popout never disagree when several players are open.
Singleton {
    id: root

    property var activePlayer: null

    readonly property bool hasPlayer: activePlayer !== null
    readonly property bool isPlaying: activePlayer?.isPlaying ?? false

    // Choose the active player with stickiness: keep the current one while it
    // still exists and is playing; otherwise prefer a playing player (scanning
    // newest-first), else keep a valid current, else fall back to the first.
    function reevaluate() {
        let players = Mpris.players.values;
        if (players.length === 0) { root.activePlayer = null; return; }

        let cur = root.activePlayer;
        let curValid = cur && players.indexOf(cur) >= 0;
        if (curValid && cur.isPlaying) return;

        for (let i = players.length - 1; i >= 0; i--) {
            if (players[i].isPlaying) { root.activePlayer = players[i]; return; }
        }

        if (curValid) return;
        root.activePlayer = players[0];
    }

    // Re-evaluate when the set of players changes…
    Connections {
        target: Mpris.players
        function onValuesChanged() { root.reevaluate(); }
    }

    // …and when any individual player's playback state changes.
    Instantiator {
        model: Mpris.players
        delegate: Connections {
            required property var modelData
            target: modelData
            function onPlaybackStateChanged() { root.reevaluate(); }
        }
    }

    Component.onCompleted: reevaluate()
}
