import Quickshell
import Quickshell.Bluetooth
import QtQuick
import QtQuick.Layouts
import "../shared" as Shared

// Bar pill for the bluetooth manager popout. Reflects adapter power state and
// the number of connected devices. Only mounted when Config.hasBluetooth.
BarPill {
    id: root
    groupName: "bluetooth"

    readonly property BluetoothAdapter adapter: Bluetooth.defaultAdapter
    readonly property bool powered: adapter ? adapter.enabled : false

    property int connectedCount: 0
    function recount() {
        let n = 0;
        const devs = Bluetooth.devices ? Bluetooth.devices.values : [];
        for (let i = 0; i < devs.length; i++)
            if (devs[i] && devs[i].connected) n++;
        connectedCount = n;
    }

    Component.onCompleted: recount()
    // Re-count on device connect/disconnect AND list add/remove (pair/forget).
    Instantiator {
        model: Bluetooth.devices
        delegate: QtObject {
            required property var modelData
            readonly property bool c: modelData.connected
            onCChanged: root.recount()
            Component.onCompleted: root.recount()
            Component.onDestruction: root.recount()
        }
    }

    accentColor: !powered
        ? Shared.Theme.overlay0
        : (connectedCount > 0 ? Shared.Theme.green : Shared.Theme.blue)

    content: [
        Text {
            Layout.alignment: Qt.AlignHCenter
            text: !root.powered ? "\u{f00b2}"             // bluetooth-off
                : root.connectedCount > 0 ? "\u{f00b1}"   // bluetooth-connect
                : "\u{f00af}"                              // bluetooth
            color: root.accentColor
            font.pixelSize: Shared.Theme.fontLarge
            font.family: Shared.Theme.iconFont
        },
        Text {
            Layout.alignment: Qt.AlignHCenter
            visible: root.connectedCount > 0
            text: root.connectedCount.toString()
            color: Shared.Theme.text
            font.pixelSize: Shared.Theme.fontSmall
            font.family: Shared.Theme.fontFamily
            font.bold: true
        }
    ]
}
