repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nuguland/PopoutHost.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Wayland
import Quickshell.Widgets
import "Util.js" as Util
import "caldav.js" as Ical
import "sysinfo.js" as Sys

PanelWindow {
    id: root

    required property QtObject theme
    required property QtObject surfaces
    required property QtObject niriService
    required property QtObject timeService
    property QtObject caldavService
    required property QtObject resourceService
    required property QtObject notificationService
    required property QtObject trayService
    required property QtObject mediaService
    required property QtObject clipboardService
    required property QtObject launcherService
    required property QtObject audioService
    required property QtObject brightnessService
    required property QtObject networkService
    required property QtObject bluetoothService
    required property QtObject powerService
    required property QtObject lockService
    required property var barWindow
    readonly property var contentSize: surfaces ? surfaces.popoutContentSize(surfaces.popoutName) : ({
        "width": 320,
        "height": 180
    })
    readonly property var popupAnchorRect: surfaces ? surfaces.popupWindowAnchorRect() : ({
        "x": 0,
        "y": 0,
        "width": 320,
        "height": 1
    })
    readonly property var cardFrame: surfaces ? surfaces.popupCardFrame(surfaces.popoutProgress) : ({
        "currentRect": {
            "x": 8,
            "y": 8,
            "width": 304,
            "height": 164
        },
        "opacity": 1
    })
    readonly property var currentRect: cardFrame.currentRect
    readonly property string activeName: surfaces ? surfaces.popoutName : ""
    readonly property string removingName: surfaces ? surfaces.removingLoaderName : ""
    readonly property bool vertical: surfaces && surfaces.orientation === "vertical"
    // subtract the bar on whichever axis it occupies (top for horizontal, left
    // for vertical) so the popout surface covers only the free region.
    readonly property int surfaceWidth: surfaces && surfaces.screenWidth > 0 ? (root.vertical ? Math.max(1, surfaces.screenWidth - surfaces.barHeight) : surfaces.screenWidth) : contentSize.width
    readonly property int surfaceHeight: surfaces && surfaces.screenHeight > 0 ? (root.vertical ? surfaces.screenHeight : Math.max(1, surfaces.screenHeight - surfaces.barHeight)) : contentSize.height

    function contentComponent(name) {
        switch (String(name)) {
        case "clock":
            return clockContent;
        case "system":
            return systemContent;
        case "notifications":
            return notificationsContent;
        case "tray":
            return trayContent;
        case "media":
            return mediaContent;
        case "clipboard":
            return clipboardContent;
        case "launcher":
            return launcherContent;
        case "audio":
            return audioContent;
        case "brightness":
            return brightnessContent;
        case "connectivity":
            return connectivityContent;
        case "power":
            return powerContent;
        default:
            return helpContent;
        }
    }

    visible: surfaces && (surfaces.popoutOpen || surfaces.popoutClosing)
    screen: root.barWindow ? root.barWindow.screen : null
    implicitWidth: root.surfaceWidth
    implicitHeight: root.surfaceHeight
    color: "transparent"
    exclusionMode: ExclusionMode.Ignore
    WlrLayershell.layer: WlrLayer.Overlay
    WlrLayershell.namespace: "nuguland-popout"
    WlrLayershell.keyboardFocus: root.visible ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None
    onVisibleChanged: {
        if (!visible && root.surfaces && root.surfaces.popoutOpen && !root.surfaces.popoutClosing)
            root.surfaces.closePopout("focus-grab-outside");

    }
    onClosed: {
        if (root.surfaces)
            root.surfaces.closePopout("popup-closed");

    }

    anchors {
        top: true
        left: true
        right: true
        bottom: true
    }

    Shortcut {
        sequence: "Escape"
        context: Qt.WindowShortcut
        onActivated: {
            if (root.surfaces)
                root.surfaces.closePopout("escape-key");

        }
    }

    Item {
        id: popoutInputRegion

        // origin sits just past the bar: below it (horizontal) or right of it
        // (vertical), so clicks on the bar itself are never captured here.
        x: root.vertical && root.surfaces ? root.surfaces.barHeight : 0
        y: root.vertical || !root.surfaces ? 0 : root.surfaces.barHeight
        width: Math.max(1, parent.width - x)
        height: Math.max(1, parent.height - y)
    }

    MouseArea {
        id: outsideDismissLayer

        x: popoutInputRegion.x
        y: popoutInputRegion.y
        width: popoutInputRegion.width
        height: popoutInputRegion.height
        acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton
        onPressed: (mouse) => {
            // mouse.x/y are layer-local; the card rect is in root coords. The
            // layer origin is offset on both axes (below the top bar, or right
            // of the left bar), so convert both before the hit test.
            const rootX = mouse.x + outsideDismissLayer.x;
            const rootY = mouse.y + outsideDismissLayer.y;
            const inside = rootX >= card.x && rootX <= card.x + card.width && rootY >= card.y && rootY <= card.y + card.height;
            if (!inside && root.surfaces) {
                mouse.accepted = true;
                root.surfaces.closePopout("outside");
            }
        }
    }

    Rectangle {
        id: card

        x: Math.round(root.currentRect.x)
        y: Math.round(root.currentRect.y)
        width: Math.round(root.currentRect.width)
        height: Math.round(root.currentRect.height)
        clip: true
        color: root.theme ? root.theme.ui.backdrop : "transparent"
        border.width: 0
        border.color: root.theme ? root.theme.ui.accent : "transparent"
        radius: 14
        opacity: root.cardFrame.opacity
        transformOrigin: Item.Top
        focus: root.visible
        onVisibleChanged: {
            if (visible)
                forceActiveFocus();

        }
        Keys.onEscapePressed: (event) => {
            event.accepted = true;
            if (root.surfaces)
                root.surfaces.closePopout("escape-key");

        }

        Column {
            anchors.fill: parent
            anchors.margins: 16
            spacing: 10

            Item {
                id: loaderStack

                width: parent.width
                height: parent.height - y
                clip: true

                Loader {
                    id: removingLoader

                    anchors.fill: parent
                    active: root.removingName.length > 0
                    opacity: active ? Math.max(0, 1 - (root.surfaces ? root.surfaces.popoutProgress : 1)) : 0
                    sourceComponent: active ? root.contentComponent(root.removingName) : null

                    Behavior on opacity {
                        NumberAnimation {
                            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
                            easing.type: Easing.OutCubic
                        }

                    }

                }

                Loader {
                    id: activeLoader

                    anchors.fill: parent
                    opacity: root.surfaces ? root.surfaces.popoutProgress : 1
                    sourceComponent: root.contentComponent(root.activeName)

                    Behavior on opacity {
                        NumberAnimation {
                            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
                            easing.type: Easing.OutCubic
                        }

                    }

                }

            }

        }

        Behavior on y {
            NumberAnimation {
                duration: root.theme && root.theme.lowPowerMode ? 0 : 130
                easing.type: Easing.InOutCubic
            }

        }

        Behavior on opacity {
            NumberAnimation {
                duration: root.theme && root.theme.lowPowerMode ? 0 : 90
                easing.type: Easing.InOutCubic
            }

        }

    }

    Component {
        id: clockContent

        Column {
            id: clockCol

            property var state: root.timeService ? Util.parseJson(root.timeService.stateJson(), {
            }) : ({
            })
            property date localNow: new Date()
            property var calendar: root.timeService ? Util.parseJson(root.timeService.calendar(localNow.getFullYear(), localNow.getMonth() + 1, localNow.getDate()), {
                "weeks": []
            }) : ({
                "weeks": []
            })
            property var days: calendar.weeks ? [].concat.apply([], calendar.weeks) : []

            readonly property bool setupMode: root.caldavService && root.caldavService.status === "needs-setup"

            // grid sizing: big square day cells, grid centered in the popout
            readonly property int gridSpacing: 6
            readonly property int cellW: 48
            readonly property int cellH: 48
            readonly property real pitchX: cellW + gridSpacing
            readonly property real pitchY: cellH + gridSpacing
            readonly property real gridW: cellW * 7 + gridSpacing * 6

            // iso "YYYY-MM-DD" -> array of single-day markers {color, allDay}.
            // Multi-day events (coveredDates>1) are drawn as bands, not markers.
            readonly property var caldavEvents: root.caldavService ? root.caldavService.events : []
            readonly property var eventsByDate: {
                const map = {};
                const evs = caldavEvents || [];
                for (let i = 0; i < evs.length; i++) {
                    const ev = evs[i];
                    const dates = Ical.coveredDates(ev);
                    if (dates.length !== 1)
                        continue;
                    const iso = dates[0];
                    (map[iso] || (map[iso] = [])).push({
                        "color": ev.color,
                        "allDay": ev.allDay || ev.kind === "task"
                    });
                }
                // all-day pills before timed dots within each day
                for (const k in map)
                    map[k].sort(function (a, b) { return (b.allDay ? 1 : 0) - (a.allDay ? 1 : 0); });
                return map;
            }

            // multi-day events as week-split band segments (Ical.buildSegments)
            readonly property var bandLayout: {
                const gs = root.caldavService ? root.caldavService.gridStartDate() : null;
                if (!gs)
                    return { "segments": [], "laneCount": 0 };
                return Ical.buildSegments(caldavEvents || [], gs);
            }

            readonly property string todayIso: {
                const d = clockCol.localNow;
                function p(n) { return (n < 10 ? "0" : "") + n; }
                return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate());
            }
            // today's events + tasks, sorted: all-day/untimed first, then by start time
            readonly property var todayItems: {
                const evs = caldavEvents || [];
                const out = [];
                for (let i = 0; i < evs.length; i++) {
                    if (Ical.coveredDates(evs[i]).indexOf(todayIso) >= 0)
                        out.push(evs[i]);
                }
                out.sort(function (a, b) {
                    const ta = (a.allDay || a.startMs == null) ? -1 : a.startMs;
                    const tb = (b.allDay || b.startMs == null) ? -1 : b.startMs;
                    return ta - tb;
                });
                return out;
            }

            spacing: 8
            width: parent ? parent.width : 0

            Component.onCompleted: if (root.caldavService) root.caldavService.refresh()

            NuguText {
                width: parent ? parent.width : 0
                horizontalAlignment: Text.AlignHCenter
                theme: root.theme
                variant: "title"
                text: clockCol.state.clock ? clockCol.state.clock.statusDisplay : "--:--:--"
            }

            NuguText {
                width: parent ? parent.width : 0
                horizontalAlignment: Text.AlignHCenter
                theme: root.theme
                variant: "meta"
                text: (clockCol.state.date ? clockCol.state.date.line : "calendar") + (root.caldavService && root.caldavService.stale ? "  ·" : "")
            }

            // centered calendar block: weekday header + month grid + bands
            Item {
                visible: !clockCol.setupMode
                width: parent ? parent.width : 0
                height: calStack.height

                Column {
                    id: calStack

                    anchors.horizontalCenter: parent.horizontalCenter
                    spacing: clockCol.gridSpacing

                    // single-letter weekday header, Monday-first; weekend dimmed
                    Row {
                        spacing: clockCol.gridSpacing

                        Repeater {
                            model: ["M", "D", "M", "D", "F", "S", "S"]

                            Item {
                                width: clockCol.cellW
                                height: hdr.height

                                NuguText {
                                    id: hdr

                                    anchors.horizontalCenter: parent.horizontalCenter
                                    theme: root.theme
                                    variant: "meta"
                                    text: modelData
                                    opacity: index >= 5 ? 0.4 : 0.7
                                }

                            }

                        }

                    }

                    Item {
                        width: monthGrid.width
                        height: monthGrid.height

                Grid {
                    id: monthGrid

                    objectName: "calendar-grid"
                    columns: 7
                    spacing: clockCol.gridSpacing

                    Repeater {
                        model: clockCol.days

                        Item {
                            id: cell

                        readonly property var markers: clockCol.eventsByDate[modelData.iso] || []

                        width: clockCol.cellW
                        height: clockCol.cellH

                        // today: filled accent circle behind the number
                        Rectangle {
                            visible: !!modelData.today
                            anchors.horizontalCenter: parent.horizontalCenter
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.verticalCenterOffset: -5
                            width: 34
                            height: 34
                            radius: 17
                            color: root.theme ? root.theme.ui.accent : "transparent"
                        }

                        NuguText {
                            anchors.horizontalCenter: parent.horizontalCenter
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.verticalCenterOffset: -5
                            theme: root.theme
                            variant: "body"
                            text: modelData.day ? String(modelData.day) : ""
                            color: modelData.today && root.theme ? root.theme.content.backdrop : (root.theme ? root.theme.content.normal : "white")
                            opacity: modelData.inMonth ? 1 : 0.3
                        }

                        // marker strip: all-day pills + timed dots, max 3 then "+"
                        Row {
                            anchors.horizontalCenter: parent.horizontalCenter
                            anchors.bottom: parent.bottom
                            anchors.bottomMargin: 7
                            spacing: 3

                            Repeater {
                                model: Math.min(cell.markers.length, 3)

                                Rectangle {
                                    readonly property var m: cell.markers[index]
                                    readonly property bool overflow: index === 2 && cell.markers.length > 3

                                    width: overflow ? 5 : (m.allDay ? 8 : 4)
                                    height: 3
                                    radius: 1.5
                                    color: overflow ? (root.theme ? root.theme.content.minor : "gray") : m.color
                                }

                            }

                        }

                        }

                    }

                }

                // multi-day band overlay: thin lane-stacked bars over the grid.
                // pitch derives from the live cell size; bands sit near the
                // cell bottom, stacking upward per lane.
                Item {
                    anchors.fill: monthGrid
                    z: 2

                    Repeater {
                        model: clockCol.bandLayout.segments

                        Rectangle {
                            readonly property var seg: modelData

                            x: seg.colStart * clockCol.pitchX
                            y: seg.row * clockCol.pitchY + clockCol.cellH - 17 - seg.lane * 9
                            width: (seg.colEnd - seg.colStart + 1) * clockCol.pitchX - clockCol.gridSpacing
                            height: 6
                            color: Qt.alpha(seg.color, 0.9)
                            topLeftRadius: seg.roundLeft ? 3 : 0
                            bottomLeftRadius: seg.roundLeft ? 3 : 0
                            topRightRadius: seg.roundRight ? 3 : 0
                            bottomRightRadius: seg.roundRight ? 3 : 0
                        }

                    }

                }

                }

                }

            }

            // today's agenda: events + tasks, ○ for open tasks, ✓ for done; centered
            Item {
                visible: !clockCol.setupMode
                width: parent ? parent.width : 0
                height: agendaCol.height

                Column {
                    id: agendaCol

                    anchors.horizontalCenter: parent.horizontalCenter
                    width: clockCol.gridW
                    spacing: 4

                Repeater {
                    model: clockCol.todayItems

                    Row {
                        spacing: 6

                        Rectangle {
                            anchors.verticalCenter: parent.verticalCenter
                            width: 6
                            height: 6
                            radius: 3
                            color: modelData.color
                        }

                        NuguText {
                            theme: root.theme
                            variant: "body"
                            text: {
                                const ev = modelData;
                                const mark = ev.kind === "task" ? (ev.done ? "✓ " : "○ ") : "";
                                let t = "";
                                if (!ev.allDay && ev.startMs != null) {
                                    const d = new Date(ev.startMs);
                                    const p = function (n) { return (n < 10 ? "0" : "") + n; };
                                    t = p(d.getHours()) + ":" + p(d.getMinutes()) + " ";
                                }
                                return t + mark + (ev.summary || "(ohne Titel)");
                            }
                        }

                    }

                }

                NuguText {
                    visible: clockCol.todayItems.length === 0
                    theme: root.theme
                    variant: "meta"
                    text: "Keine Termine"
                }

                }

            }

            // setup form: shown when the service has no usable config yet.
            // Keystrokes need the popout to hold keyboard focus; the IPC
            // saveSetup path is the verified entry point.
            Column {
                id: setupForm

                visible: clockCol.setupMode
                width: parent ? parent.width : 0
                spacing: 8

                // grab keyboard focus into the first field once the card has
                // finished claiming the surface focus (callLater wins the race)
                onVisibleChanged: if (visible) Qt.callLater(urlField.field.forceActiveFocus)
                Component.onCompleted: if (visible) Qt.callLater(urlField.field.forceActiveFocus)

                component Field: Rectangle {
                    property alias field: ti
                    property string placeholder: ""
                    property bool secret: false

                    width: setupForm.width
                    height: 30
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.14) : "transparent"

                    TextInput {
                        id: ti

                        anchors.fill: parent
                        anchors.leftMargin: 10
                        anchors.rightMargin: 10
                        verticalAlignment: TextInput.AlignVCenter
                        color: root.theme ? root.theme.content.normal : "white"
                        selectionColor: root.theme ? root.theme.ui.focus : "#ffffff"
                        selectedTextColor: root.theme ? root.theme.content.backdrop : "black"
                        font.family: "IBM Plex Sans"
                        font.pixelSize: 13
                        echoMode: parent.secret ? TextInput.Password : TextInput.Normal
                        clip: true
                    }

                    NuguText {
                        anchors.left: parent.left
                        anchors.leftMargin: 10
                        anchors.verticalCenter: parent.verticalCenter
                        visible: ti.text.length === 0
                        theme: root.theme
                        variant: "meta"
                        text: parent.placeholder
                    }

                }

                NuguText {
                    theme: root.theme
                    variant: "meta"
                    text: "CalDAV einrichten"
                }

                Field {
                    id: urlField

                    placeholder: "https://host/remote.php/dav"
                }

                Field {
                    id: userField

                    placeholder: "Benutzername"
                }

                Field {
                    id: pwField

                    placeholder: "App-Passwort"
                    secret: true
                }

                Rectangle {
                    width: parent.width
                    height: 30
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.2) : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: "Speichern"
                    }

                    MouseArea {
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        onClicked: if (root.caldavService) root.caldavService.saveSetup(urlField.field.text, userField.field.text, pwField.field.text)
                    }

                }

                NuguText {
                    visible: root.caldavService && root.caldavService.secretError.length > 0
                    theme: root.theme
                    variant: "meta"
                    color: root.theme ? root.theme.error : "red"
                    text: root.caldavService ? root.caldavService.secretError : ""
                }

            }

        }

    }

    Component {
        id: systemContent

        Column {
            id: systemPanel

            // service handle; identity facts and the live issue ARRAY come straight
            // off Resources.qml (no per-frame JSON parse).
            readonly property var rs: root.resourceService
            readonly property var identity: rs ? rs.identity : ({
            })
            // touch the inputs so the band re-evaluates when the slow/rare loops
            // mutate them; issues() itself is a plain function call.
            readonly property var issueList: {
                if (!rs)
                    return [];

                rs.failedUnits;
                rs.cpuTemperatureC;
                rs.diskUsage;
                rs.updateCount;
                rs.memoryUsage;
                rs.swapGrowing;
                rs.loadOne;
                rs.healthPercentage;
                return rs.issues();
            }

            spacing: 10
            width: parent ? parent.width : 0

            // popoutOpen is a WRITE contract: it gates the slow + rare loops.
            Component.onCompleted: {
                if (rs)
                    rs.popoutOpen = true;

            }
            Component.onDestruction: {
                if (rs)
                    rs.popoutOpen = false;

            }

            // ---- two rounded cards: identity | live, split on the golden ratio
            // (live gets the larger ~0.618 share — that's where the live data lives) ----
            Row {
                id: cardRow

                readonly property real avail: Math.max(1, width - spacing)
                readonly property real machineW: avail * 0.382
                readonly property real liveW: avail * 0.618

                width: parent.width
                height: 292
                spacing: 10

                // ===== MACHINE IDENTITY =====
                Rectangle {
                    width: cardRow.machineW
                    height: cardRow.height
                    radius: 14
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"

                    Column {
                        anchors.fill: parent
                        anchors.margins: 14
                        spacing: 6

                        Row {
                            spacing: 8

                            Text {
                                text: ""
                                color: root.theme ? root.theme.ui.accent : "white"
                                font.family: "Symbols Nerd Font Mono"
                                font.pixelSize: 15
                            }

                            NuguText {
                                theme: root.theme
                                variant: "title"
                                text: "machine"
                            }

                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.host || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.model || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.distro || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.kernel || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.wm || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.packages ? `${systemPanel.identity.packages} packages` : "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.shell || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            value: systemPanel.identity.uptime || "—"
                        }

                        IdentityRow {
                            theme: root.theme
                            glyph: ""
                            // battery row hidden entirely when there is no laptop battery
                            visible: systemPanel.rs && systemPanel.rs.isLaptopBattery
                            value: {
                                if (!systemPanel.rs)
                                    return "—";

                                const p = systemPanel.rs.batteryPercent;
                                const st = systemPanel.rs.batteryStatus;
                                const h = systemPanel.rs.healthPercentage;
                                let s = (p === null || p === undefined) ? "battery n/a" : `battery ${p}%`;
                                if (st)
                                    s += ` · ${st}`;
                                if (h !== null && h !== undefined)
                                    s += ` · health ${Math.round(Number(h))}%`;
                                return s;
                            }
                        }

                    }

                }

                // ===== LIVE STATS =====
                Rectangle {
                    width: cardRow.liveW
                    height: cardRow.height
                    radius: 14
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"

                    Column {
                        anchors.fill: parent
                        anchors.margins: 14
                        spacing: 8

                        Row {
                            spacing: 8

                            Text {
                                text: ""
                                color: root.theme ? root.theme.ui.accent : "white"
                                font.family: "Symbols Nerd Font Mono"
                                font.pixelSize: 15
                            }

                            NuguText {
                                theme: root.theme
                                variant: "title"
                                text: "live"
                            }

                        }

                        MetricRow {
                            theme: root.theme
                            label: "cpu"
                            value: systemPanel.rs ? `${Math.round(systemPanel.rs.cpuUsage * 100)}%` : "—"
                            fraction: systemPanel.rs ? systemPanel.rs.cpuUsage : 0
                            barColor: root.theme ? root.theme.ui.accent : "#d86dd8"
                            ring: systemPanel.rs ? systemPanel.rs.cpuRing : []
                            sparkScaleMax: 1
                        }

                        MetricRow {
                            theme: root.theme
                            label: "mem"
                            value: systemPanel.rs ? `${Math.round(systemPanel.rs.memoryUsage * 100)}% · ${Sys.formatBytes(Math.max(0, systemPanel.rs.memTotal - systemPanel.rs.memAvailable))}` : "—"
                            fraction: systemPanel.rs ? systemPanel.rs.memoryUsage : 0
                            barColor: root.theme ? root.theme.ui.focus : "#9aabae"
                            ring: systemPanel.rs ? systemPanel.rs.memRing : []
                            sparkScaleMax: 1
                        }

                        MetricRow {
                            theme: root.theme
                            label: "swap"
                            value: {
                                if (!systemPanel.rs || systemPanel.rs.swapTotal <= 0)
                                    return "off";

                                return `${Math.round(systemPanel.rs.swapUsage * 100)}% · ${Sys.formatBytes(Math.max(0, systemPanel.rs.swapTotal - systemPanel.rs.swapFree))}`;
                            }
                            fraction: systemPanel.rs ? systemPanel.rs.swapUsage : 0
                            barColor: root.theme ? root.theme.warning : "#f0ee69"
                            showSpark: false
                            ring: []
                        }

                        MetricRow {
                            theme: root.theme
                            label: "temp"
                            value: {
                                if (!systemPanel.rs)
                                    return "n/a";

                                const t = systemPanel.rs.cpuTemperatureC;
                                const f = systemPanel.rs.fanRpm;
                                const ts = (t === null || t === undefined) ? "n/a" : `${Math.round(Number(t))}°C`;
                                const fs = (f === null || f === undefined) ? "" : ` · ${Math.round(Number(f))} rpm`;
                                return ts + fs;
                            }
                            fraction: {
                                if (!systemPanel.rs)
                                    return 0;

                                const t = systemPanel.rs.cpuTemperatureC;
                                if (t === null || t === undefined)
                                    return 0;

                                return Math.max(0, Math.min(1, Number(t) / Math.max(1, systemPanel.rs.tempHighC)));
                            }
                            barColor: root.theme ? root.theme.error : "#ec6376"
                            // sparkline hidden when the sensor is unavailable (null)
                            showSpark: systemPanel.rs && systemPanel.rs.cpuTemperatureC !== null
                            ring: systemPanel.rs ? systemPanel.rs.tempRing : []
                            sparkScaleMax: systemPanel.rs ? Math.max(1, systemPanel.rs.tempHighC) : 1
                        }

                        MetricRow {
                            theme: root.theme
                            label: "net"
                            value: systemPanel.rs ? `↓ ${Sys.formatRate(systemPanel.rs.networkRxRate)}  ↑ ${Sys.formatRate(systemPanel.rs.networkTxRate)}` : "—"
                            // net/disk have no natural ceiling: scale against the ring's own max
                            fraction: {
                                if (!systemPanel.rs)
                                    return 0;

                                const ring = systemPanel.rs.netRing || [];
                                let m = 0;
                                for (let i = 0; i < ring.length; i++) m = Math.max(m, Number(ring[i]) || 0)
                                const cur = systemPanel.rs.networkRxRate + systemPanel.rs.networkTxRate;
                                return m > 0 ? Math.min(1, cur / m) : 0;
                            }
                            // directional spark: ↑ upload (accent) above the line,
                            // ↓ download (info) below; fill-bar stays combined.
                            barColor: root.theme ? root.theme.ui.accent : "#d86dd8"
                            splitSpark: true
                            ring: systemPanel.rs ? systemPanel.rs.netTxRing : []
                            ringDown: systemPanel.rs ? systemPanel.rs.netRxRing : []
                            barColorDown: root.theme ? root.theme.info : "#3ec5e3"
                        }

                        MetricRow {
                            theme: root.theme
                            label: "disk"
                            value: systemPanel.rs ? `R ${Sys.formatRate(systemPanel.rs.diskReadRate)}  W ${Sys.formatRate(systemPanel.rs.diskWriteRate)}` : "—"
                            fraction: {
                                if (!systemPanel.rs)
                                    return 0;

                                const ring = systemPanel.rs.diskRing || [];
                                let m = 0;
                                for (let i = 0; i < ring.length; i++) m = Math.max(m, Number(ring[i]) || 0)
                                const cur = systemPanel.rs.diskReadRate + systemPanel.rs.diskWriteRate;
                                return m > 0 ? Math.min(1, cur / m) : 0;
                            }
                            // directional spark: R read (accent) above the line,
                            // W write (info) below; fill-bar stays combined.
                            barColor: root.theme ? root.theme.ui.accent : "#d86dd8"
                            splitSpark: true
                            ring: systemPanel.rs ? systemPanel.rs.diskReadRing : []
                            ringDown: systemPanel.rs ? systemPanel.rs.diskWriteRing : []
                            barColorDown: root.theme ? root.theme.info : "#3ec5e3"
                        }

                        NuguText {
                            theme: root.theme
                            variant: "meta"
                            text: systemPanel.rs ? `load ${systemPanel.rs.loadOne.toFixed(2)} · ${systemPanel.rs.loadFive.toFixed(2)} · ${systemPanel.rs.loadFifteen.toFixed(2)}  (${systemPanel.rs.cores} cores)` : "load —"
                        }

                    }

                }

            }

            // ---- issues band ----
            Column {
                width: parent.width
                spacing: 6

                // all-clear: a single green check row (the service emits NO synthetic
                // green issue — the view renders it when the array is empty).
                Rectangle {
                    visible: systemPanel.issueList.length === 0
                    width: parent.width
                    height: 30
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"

                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 12
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 8

                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            text: ""
                            color: "#8bd17a"
                            font.family: "Symbols Nerd Font Mono"
                            font.pixelSize: 14
                        }

                        NuguText {
                            anchors.verticalCenter: parent.verticalCenter
                            theme: root.theme
                            variant: "meta"
                            text: "disk · memory · battery · updates ok"
                        }

                    }

                }

                Repeater {
                    model: systemPanel.issueList

                    delegate: Rectangle {
                        id: issueCard

                        required property var modelData

                        readonly property color sevColor: {
                            const s = modelData.severity;
                            if (s === "error")
                                return root.theme ? root.theme.error : "#ec6376";

                            if (s === "warning")
                                return root.theme ? root.theme.warning : "#f0ee69";

                            return root.theme ? root.theme.info : "#3ec5e3";
                        }

                        width: parent.width
                        height: 40
                        radius: 10
                        clip: true
                        color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"

                        // severity-colored left accent bar (strong signal, matches card aesthetic)
                        Rectangle {
                            anchors.left: parent.left
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom
                            width: 4
                            color: issueCard.sevColor
                        }

                        Rectangle {
                            id: sevDot

                            anchors.left: parent.left
                            anchors.leftMargin: 14
                            anchors.verticalCenter: parent.verticalCenter
                            width: 9
                            height: 9
                            radius: 4.5
                            color: issueCard.sevColor
                        }

                        Text {
                            id: issGlyph

                            anchors.left: sevDot.right
                            anchors.leftMargin: 10
                            anchors.verticalCenter: parent.verticalCenter
                            text: String(issueCard.modelData.icon || "")
                            color: issueCard.sevColor
                            font.family: "Symbols Nerd Font Mono"
                            font.pixelSize: 14
                        }

                        Column {
                            anchors.left: issGlyph.right
                            anchors.leftMargin: 10
                            anchors.right: actBtn.visible ? actBtn.left : parent.right
                            anchors.rightMargin: 10
                            anchors.verticalCenter: parent.verticalCenter
                            spacing: 1

                            NuguText {
                                theme: root.theme
                                width: parent.width
                                text: String(issueCard.modelData.label || "")
                            }

                            NuguText {
                                theme: root.theme
                                variant: "meta"
                                width: parent.width
                                text: String(issueCard.modelData.detail || "")
                            }

                        }

                        Rectangle {
                            id: actBtn

                            visible: !!issueCard.modelData.action
                            anchors.right: parent.right
                            anchors.rightMargin: 12
                            anchors.verticalCenter: parent.verticalCenter
                            width: 62
                            height: 24
                            radius: 7
                            // ghost button: transparent with a severity-tinted border + text,
                            // faint fill on hover — consistent with the dark card aesthetic.
                            color: actMouse.containsMouse && root.theme ? root.theme.withAlpha(issueCard.sevColor, 0.22) : "transparent"
                            border.width: 1
                            border.color: root.theme ? root.theme.withAlpha(issueCard.sevColor, 0.55) : issueCard.sevColor

                            Text {
                                anchors.centerIn: parent
                                text: "open"
                                color: issueCard.sevColor
                                font.family: "IBM Plex Sans"
                                font.pixelSize: 13
                            }

                            MouseArea {
                                id: actMouse

                                anchors.fill: parent
                                hoverEnabled: true
                                cursorShape: Qt.PointingHandCursor
                                onClicked: {
                                    if (systemPanel.rs)
                                        systemPanel.rs.runIssueAction(issueCard.modelData.id);

                                }
                            }

                        }

                    }

                }

            }

            // ---- compact top-processes row (chips) ----
            Flow {
                width: parent.width
                spacing: 8

                Repeater {
                    model: systemPanel.rs ? systemPanel.rs.processes : []

                    delegate: Rectangle {
                        id: procChip

                        required property var modelData

                        height: 22
                        width: procRow.implicitWidth + 18
                        radius: 8
                        color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.16) : "transparent"

                        Row {
                            id: procRow

                            anchors.centerIn: parent
                            spacing: 6

                            NuguText {
                                theme: root.theme
                                variant: "meta"
                                text: String(procChip.modelData.name || "?")
                            }

                            NuguText {
                                theme: root.theme
                                variant: "meta"
                                color: root.theme ? root.theme.ui.accent : "white"
                                text: `${Number(procChip.modelData.cpu || 0).toFixed(0)}%`
                            }

                        }

                    }

                }

            }

        }

    }

    Component {
        id: notificationsContent

        NotificationGroup {
            theme: root.theme
            notificationService: root.notificationService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: trayContent

        TrayPanel {
            theme: root.theme
            trayService: root.trayService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: mediaContent

        MediaPanel {
            theme: root.theme
            mediaService: root.mediaService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: clipboardContent

        ClipboardPanel {
            theme: root.theme
            clipboardService: root.clipboardService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: launcherContent

        LauncherPanel {
            theme: root.theme
            launcherService: root.launcherService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: audioContent

        AudioPanel {
            theme: root.theme
            audioService: root.audioService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: brightnessContent

        BrightnessPanel {
            theme: root.theme
            brightnessService: root.brightnessService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: connectivityContent

        ConnectivityPanel {
            theme: root.theme
            resourceService: root.resourceService
            networkService: root.networkService
            bluetoothService: root.bluetoothService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: powerContent

        PowerPanel {
            theme: root.theme
            powerService: root.powerService
            width: parent ? parent.width : 0
        }

    }

    Component {
        id: helpContent

        Column {
            spacing: 8
            width: parent ? parent.width : 0

            NuguText {
                theme: root.theme
                text: "no popout content."
                width: parent.width
                wrapMode: Text.WordWrap
            }

        }

    }

    mask: Region {
        item: popoutInputRegion
    }

    component NuguText: Text {
        required property QtObject theme
        property string variant: "body"
        property bool selected: false

        color: !theme ? "transparent" : (selected ? theme.content.backdrop : (variant === "title" ? theme.ui.important_global : (variant === "meta" ? theme.ui.normal : theme.content.normal)))
        font.family: variant === "mono" ? "IBM Plex Mono" : "IBM Plex Sans"
        font.pixelSize: variant === "title" ? 15 : (variant === "meta" ? 13 : 14)
        font.bold: variant === "title"
        elide: Text.ElideRight
    }

    Behavior on implicitWidth {
        NumberAnimation {
            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
            easing.type: Easing.OutCubic
        }

    }

    Behavior on implicitHeight {
        NumberAnimation {
            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
            easing.type: Easing.OutCubic
        }

    }

    component IdentityRow: Row {
        id: irow

        required property QtObject theme
        property string glyph: ""
        property string value: ""

        width: parent ? parent.width : 0
        spacing: 9

        Text {
            width: 18
            text: irow.glyph
            color: irow.theme ? irow.theme.ui.minor : "white"
            font.family: "Symbols Nerd Font Mono"
            font.pixelSize: 13
        }

        NuguText {
            theme: irow.theme
            variant: "meta"
            text: irow.value
            width: Math.max(1, parent.width - 27)
        }

    }

    // thin Rectangle sparkline over a ring buffer (no Canvas, no shader). Single
    // series fills up from the bottom; in `split` mode `values` grows up and
    // `valuesDown` grows down from the centerline — used for the directional net
    // spark (↑ upload above the line, ↓ download below).
    component Sparkline: Item {
        id: spark

        required property QtObject theme
        property var values: []
        property var valuesDown: []
        property color barColor: theme ? theme.ui.accent : "white"
        property color barColorDown: theme ? theme.info : "#3ec5e3"
        // absolute ceiling for bounded metrics (cpu/mem=1, temp=tempHighC); 0 = auto
        // window-max for unbounded metrics (net/disk). Keeps bars consistent with the fill-bar.
        property real scaleMax: 0
        property bool split: false

        // dense 2px pitch (touching bars); show the most recent samples that fit
        readonly property int shown: Math.max(1, Math.floor(width / 2))
        function tail(v) {
            const a = v || [];
            return a.length > spark.shown ? a.slice(a.length - spark.shown) : a;
        }
        readonly property var slice: spark.tail(spark.values)
        readonly property var sliceDown: spark.tail(spark.valuesDown)
        readonly property real maxV: {
            if (spark.scaleMax > 0)
                return spark.scaleMax;
            let m = 0;
            const a = spark.slice;
            for (let i = 0; i < a.length; i++) m = Math.max(m, Number(a[i]) || 0)
            if (spark.split) {
                const b = spark.sliceDown;
                for (let j = 0; j < b.length; j++) m = Math.max(m, Number(b[j]) || 0)
            }
            return m;
        }
        // bar budget: half (minus a 1px centerline gap) in split mode, else full
        readonly property real budget: spark.split ? (spark.height - 1) / 2 : spark.height

        // up series (the only series when not split)
        Row {
            anchors.right: parent.right
            anchors.bottom: spark.split ? parent.verticalCenter : parent.bottom
            anchors.bottomMargin: spark.split ? 1 : 0
            height: spark.budget
            spacing: 0

            Repeater {
                model: spark.slice

                delegate: Item {
                    required property var modelData

                    width: 2
                    height: spark.budget

                    Rectangle {
                        anchors.bottom: parent.bottom
                        width: parent.width
                        radius: 1
                        height: Math.max(spark.split ? 0 : 1, spark.budget * (spark.maxV > 0 ? Math.min(1, (Number(modelData) || 0) / spark.maxV) : 0))
                        color: spark.barColor
                    }

                }

            }

        }

        // down series (split only): grows downward from the centerline
        Row {
            visible: spark.split
            anchors.right: parent.right
            anchors.top: parent.verticalCenter
            anchors.topMargin: 1
            height: spark.budget
            spacing: 0

            Repeater {
                model: spark.split ? spark.sliceDown : []

                delegate: Item {
                    required property var modelData

                    width: 2
                    height: spark.budget

                    Rectangle {
                        anchors.top: parent.top
                        width: parent.width
                        radius: 1
                        height: Math.max(0, spark.budget * (spark.maxV > 0 ? Math.min(1, (Number(modelData) || 0) / spark.maxV) : 0))
                        color: spark.barColorDown
                    }

                }

            }

        }

    }

    // one live metric: label · value · rounded fill-bar (track + fill) · sparkline.
    component MetricRow: Item {
        id: mrow

        required property QtObject theme
        property string label: ""
        property string value: ""
        property real fraction: 0
        property color barColor: theme ? theme.ui.accent : "white"
        property var ring: []
        property var ringDown: []
        property color barColorDown: theme ? theme.info : "#3ec5e3"
        property bool splitSpark: false
        property real sparkScaleMax: 0
        property bool showSpark: true

        width: parent ? parent.width : 0
        height: 24

        NuguText {
            id: mlabel

            anchors.left: parent.left
            anchors.verticalCenter: parent.verticalCenter
            theme: mrow.theme
            variant: "meta"
            text: mrow.label
            width: 38
        }

        NuguText {
            id: mvalue

            anchors.left: mlabel.right
            anchors.leftMargin: 4
            anchors.verticalCenter: parent.verticalCenter
            theme: mrow.theme
            variant: "meta"
            text: mrow.value
            width: 132
        }

        Sparkline {
            id: mspark

            anchors.right: parent.right
            anchors.verticalCenter: parent.verticalCenter
            theme: mrow.theme
            visible: mrow.showSpark
            values: mrow.ring
            valuesDown: mrow.ringDown
            split: mrow.splitSpark
            scaleMax: mrow.sparkScaleMax
            barColor: mrow.barColor
            barColorDown: mrow.barColorDown
            width: 176
            height: 24
        }

        Rectangle {
            id: mtrack

            anchors.left: mvalue.right
            anchors.leftMargin: 8
            anchors.right: mspark.left
            anchors.rightMargin: 8
            anchors.verticalCenter: parent.verticalCenter
            height: 6
            radius: 3
            color: mrow.theme ? mrow.theme.withAlpha(mrow.theme.ui.minor, 0.28) : "#333333"

            Rectangle {
                width: parent.width * Math.max(0, Math.min(1, mrow.fraction))
                height: parent.height
                radius: parent.radius
                color: mrow.barColor

                Behavior on width {
                    NumberAnimation {
                        duration: mrow.theme && mrow.theme.lowPowerMode ? 0 : 160
                        easing.type: Easing.OutCubic
                    }

                }

            }

        }

    }

    component LauncherPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject launcherService
        property string query: ""
        property var state: launcherService ? Util.parseJson(launcherService.search(query), {
            "results": [],
            "selectedIndex": -1,
            "providerIntent": "all",
            "query": ""
        }) : ({
            "results": [],
            "selectedIndex": -1,
            "providerIntent": "all",
            "query": ""
        })
        readonly property var results: state.results || []
        // fixed row geometry, shared so the programmatic scroll stride can't drift
        readonly property int rowHeight: 54
        readonly property int rowSpacing: 6
        readonly property int rowStride: rowHeight + rowSpacing


        function refresh() {
            if (launcherService)
                state = Util.parseJson(launcherService.search(query), state);

        }

        function setQuery(text) {
            query = String(text || "");
            refresh();
        }

        function select(index) {
            if (results.length === 0)
                return ;

            const i = Math.max(0, Math.min(results.length - 1, Number(index)));
            const next = Object.assign({
            }, state);
            next.selectedIndex = i;
            state = next;
            // keep the chosen row inside the non-interactive Flickable's viewport
            const top = i * rowStride;
            const bottom = top + rowHeight;
            if (top < resultsFlick.contentY)
                resultsFlick.contentY = top;
            else if (bottom > resultsFlick.contentY + resultsFlick.height)
                resultsFlick.contentY = bottom - resultsFlick.height;
        }

        function wheelSelect(deltaY) {
            if (results.length <= 1)
                return ;

            const current = Math.max(0, Math.min(results.length - 1, Number(state.selectedIndex || 0)));
            // wheel up/away (deltaY >= 0) moves selection up, matching the Up arrow.
            const direction = Number(deltaY) >= 0 ? -1 : 1;
            const next = Math.max(0, Math.min(results.length - 1, current + direction));
            select(next);
        }

        function providerColor(provider) {
            if (!theme)
                return "white";

            if (provider === "calculator")
                return theme.info;

            if (provider === "action")
                return theme.warning;

            if (provider === "clipboard")
                return theme.ui.focus;

            if (provider === "window")
                return theme.content.accent;

            return theme.ui.accent;
        }

        width: parent ? parent.width : 0
        spacing: 10

        WheelHandler {
            target: root
            onWheel: (event) => {
                event.accepted = true;
                root.wheelSelect(event.angleDelta.y);
            }
        }

        // Full-width scrollable result list. The Flickable is non-interactive:
        // the wheel is owned by the root WheelHandler (-> wheelSelect), and
        // select() drives contentY programmatically to keep the chosen row in view.
        Flickable {
            id: resultsFlick
            objectName: "launcherResultList"

            width: parent.width
            // fill the popout budget minus the docked search field (42) + hint
            // (~18) + the two 10px Column gaps; clamped so it never collapses.
            height: Math.max(120, (root.parent ? root.parent.height : 460) - 84)
            contentHeight: resultColumn.implicitHeight
            interactive: false
            clip: true
            boundsBehavior: Flickable.StopAtBounds

            Behavior on contentY {
                NumberAnimation {
                    duration: root.theme && root.theme.lowPowerMode ? 0 : 140
                    easing.type: Easing.OutCubic
                }
            }

            Column {
                id: resultColumn

                width: resultsFlick.width
                spacing: root.rowSpacing

                Repeater {
                    model: root.results.slice(0, 60)

                    delegate: Rectangle {
                        id: rrow

                        required property int index
                        required property var modelData
                        readonly property bool isSelected: index === (root.state.selectedIndex || 0)
                        readonly property bool isCalc: modelData.provider === "calculator"
                        readonly property color tint: root.providerColor(modelData.provider)

                        width: parent.width
                        height: root.rowHeight
                        radius: 12
                        // solid dark card — the popup frame is light, so a translucent
                        // tint washes out (white bleeds through). Provider identity is
                        // carried by the left accent bar + border; selection by focus.
                        color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, rrow.isSelected ? 0.82 : 0.55) : "transparent"
                        border.width: rrow.isSelected ? 2 : 1
                        border.color: root.theme ? (rrow.isSelected ? root.theme.ui.focus : root.theme.withAlpha(rrow.tint, 0.45)) : "transparent"

                        // provider-colored left accent bar (identity at a glance)
                        Rectangle {
                            anchors.left: parent.left
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom
                            anchors.margins: 2
                            width: 3
                            radius: 2
                            color: rrow.tint
                            opacity: rrow.isSelected ? 1 : 0.7
                        }

                        // leading 32px icon slot: real themed app icon, else the
                        // provider Nerd Font glyph. Glyph also covers the app
                        // fallback when the icon name fails to resolve (status
                        // never reaches Image.Ready -> glyph stays visible).
                        Item {
                            id: iconSlot

                            anchors.left: parent.left
                            anchors.leftMargin: 10
                            anchors.verticalCenter: parent.verticalCenter
                            width: 32
                            height: 32

                            IconImage {
                                id: appIcon

                                anchors.fill: parent
                                visible: rrow.modelData.provider === "app" && appIcon.status === Image.Ready
                                source: (rrow.modelData.provider === "app" && String(rrow.modelData.icon || "").length > 0) ? Quickshell.iconPath(String(rrow.modelData.icon), true) : ""
                            }

                            Text {
                                anchors.centerIn: parent
                                visible: !appIcon.visible
                                text: String(rrow.modelData.glyph || "")
                                font.family: "Symbols Nerd Font Mono"
                                font.pixelSize: 18
                                color: rrow.tint
                            }

                        }

                        // calculator row: expression small, value large + mono
                        Column {
                            visible: rrow.isCalc
                            anchors.left: iconSlot.right
                            anchors.leftMargin: 12
                            anchors.right: parent.right
                            anchors.rightMargin: 12
                            anchors.verticalCenter: parent.verticalCenter
                            spacing: 1

                            NuguText {
                                theme: root.theme
                                variant: "meta"
                                text: rrow.modelData.subtitle || rrow.modelData.id || "expression"
                                width: parent.width
                                opacity: 0.8
                            }

                            Text {
                                width: parent.width
                                text: String(rrow.modelData.value || rrow.modelData.title || "0")
                                color: rrow.isSelected && root.theme ? root.theme.content.backdrop : (root.theme ? root.theme.content.normal : "white")
                                font.family: "IBM Plex Mono"
                                font.pixelSize: 22
                                font.bold: true
                                elide: Text.ElideRight
                            }

                        }

                        // standard row: title + muted `verb · subtitle` meta
                        Column {
                            visible: !rrow.isCalc
                            anchors.left: iconSlot.right
                            anchors.leftMargin: 12
                            anchors.right: parent.right
                            anchors.rightMargin: 12
                            anchors.verticalCenter: parent.verticalCenter
                            spacing: 2

                            NuguText {
                                theme: root.theme
                                selected: rrow.isSelected
                                text: rrow.modelData.title || rrow.modelData.id || "result"
                                width: parent.width
                            }

                            NuguText {
                                theme: root.theme
                                variant: "meta"
                                text: `${rrow.modelData.verb || "activate"} · ${rrow.modelData.subtitle || rrow.modelData.provider}`
                                width: parent.width
                                opacity: 0.78
                            }

                        }

                        MouseArea {
                            anchors.fill: parent
                            onClicked: root.select(rrow.index)
                            onWheel: (wheel) => {
                                wheel.accepted = true;
                                root.wheelSelect(wheel.angleDelta.y);
                            }
                        }

                    }

                }

            }

        }

        Rectangle {
            objectName: "searchFieldDockedBottom"
            width: parent.width
            height: 42
            radius: 21
            color: root.theme ? root.theme.withAlpha(root.theme.ui.focus, 0.14) : "transparent"
            border.width: 0
            border.color: root.theme ? root.theme.ui.focus : "transparent"

            NuguText {
                anchors.left: parent.left
                anchors.leftMargin: 14
                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                variant: "meta"
                text: "search"
                opacity: 0.7
            }

            TextInput {
                anchors.left: parent.left
                anchors.leftMargin: 72
                anchors.right: parent.right
                anchors.rightMargin: 14
                anchors.verticalCenter: parent.verticalCenter
                color: root.theme ? root.theme.content.normal : "white"
                selectionColor: root.theme ? root.theme.ui.focus : "#ffffff"
                selectedTextColor: root.theme ? root.theme.content.backdrop : "black"
                font.family: "IBM Plex Mono"
                text: root.query
                focus: false
                onTextChanged: {
                    if (text !== root.query)
                        root.setQuery(text);

                }
                Keys.onUpPressed: root.select((root.state.selectedIndex || 0) - 1)
                Keys.onDownPressed: root.select((root.state.selectedIndex || 0) + 1)
                Keys.onReturnPressed: (event) => {
                    event.accepted = true;
                }
                Keys.onEnterPressed: (event) => {
                    event.accepted = true;
                }
            }

        }

        NuguText {
            objectName: "keyboardNavigation"
            theme: root.theme
            variant: "meta"
            text: "↑↓ select · Enter activate"
            width: parent.width
            elide: Text.ElideRight
        }

    }

    component NotificationGroup: Column {
        id: root

        required property QtObject theme
        required property QtObject notificationService
        property var state: notificationService ? Util.parseJson(notificationService.stateJson(), {"groups": [], "dnd": false, "activeCount": 0}) : ({"groups": [], "dnd": false, "activeCount": 0})
        readonly property var groups: state.groups || []

        // mutators trigger side-effects only; never assign to `state` — that
        // would destroy the binding above and freeze the open popup, so
        // externally-arriving notifications would stop appearing until reopen.
        // stateJson() reads reactive props (notifications/dnd/expandedGroups/…)
        // so the binding re-evaluates on its own after every mutation.
        function runAction(id, actionId) {
            if (notificationService)
                notificationService.runAction(id, actionId);
        }
        function sendReply(id, text) {
            if (notificationService)
                notificationService.sendReply(id, text);
        }
        function toggleGroup(appName) {
            if (notificationService)
                notificationService.toggleGroup(appName);
        }
        function toggleDnd() {
            if (notificationService)
                notificationService.toggleDnd();
        }
        function clearAll() {
            if (notificationService)
                notificationService.discardAllNotifications();
        }

        spacing: 8
        width: parent ? parent.width : 0

        Item {
            width: parent.width
            height: 28
            NuguText {
                anchors.left: parent.left
                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                variant: "title"
                text: `Notifications${root.state.activeCount ? " · " + root.state.activeCount : ""}`
            }
            Row {
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                spacing: 8
                Rectangle {
                    width: dndLabel.implicitWidth + 18
                    height: 24
                    radius: 8
                    color: root.theme ? root.theme.withAlpha(root.state.dnd ? root.theme.ui.accent : root.theme.ui.minor, root.state.dnd ? 0.3 : 0.12) : "transparent"
                    NuguText { id: dndLabel; anchors.centerIn: parent; theme: root.theme; variant: "meta"; text: root.state.dnd ? "DND on" : "DND" }
                    MouseArea { anchors.fill: parent; onClicked: root.toggleDnd() }
                }
                Rectangle {
                    width: clearLabel.implicitWidth + 18
                    height: 24
                    radius: 8
                    visible: (root.state.activeCount || 0) > 0
                    color: clearArea.containsMouse && root.theme ? root.theme.withAlpha(root.theme.error, 0.24) : (root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.12) : "transparent")
                    NuguText { id: clearLabel; anchors.centerIn: parent; theme: root.theme; variant: "meta"; text: "Clear all" }
                    MouseArea { id: clearArea; anchors.fill: parent; hoverEnabled: true; onClicked: root.clearAll() }
                }
            }
        }

        // History can outgrow the popup; the header stays fixed and everything
        // below scrolls. The Loader hosting this Column forces a concrete
        // root.height, so the viewport can bound on it.
        Item {
            id: scrollArea
            width: parent.width
            height: Math.max(0, root.height - 28 - root.spacing)

            Flickable {
                id: scroll
                anchors.fill: parent
                contentHeight: scrollColumn.height
                clip: true
                interactive: contentHeight > height
                boundsBehavior: Flickable.StopAtBounds
                flickableDirection: Flickable.VerticalFlick

                Column {
                    id: scrollColumn
                    width: scroll.width
                    spacing: 8

                    Item {
                        width: parent.width
                        height: 220
                        visible: root.groups.length === 0
                        Column {
                            anchors.centerIn: parent
                            spacing: 8
                            NuguText { anchors.horizontalCenter: parent.horizontalCenter; theme: root.theme; variant: "title"; text: "No notifications" }
                            NuguText { anchors.horizontalCenter: parent.horizontalCenter; theme: root.theme; variant: "meta"; text: "You're all caught up" }
                        }
                    }

                    Repeater {
                        model: root.groups
                        delegate: Column {
                            id: groupDelegate
                            required property var modelData
                            width: root.width
                            spacing: 6

                // collapsible group header: an obvious interactive pill with a
                // hover background and an explicit "Show N more" / "Show less"
                // label so the collapse affordance reads as a button, not decor.
                Rectangle {
                    id: groupHeader
                    width: parent.width
                    height: (groupDelegate.modelData.count || 0) > 1 ? 26 : 0
                    visible: (groupDelegate.modelData.count || 0) > 1
                    radius: 8
                    color: grpArea.containsMouse && root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.16) : "transparent"
                    Behavior on color { ColorAnimation { duration: root.theme && root.theme.lowPowerMode ? 0 : 120 } }
                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 6
                        NuguText { theme: root.theme; variant: "meta"; text: groupDelegate.modelData.appName || "" }
                        NuguText { theme: root.theme; variant: "meta"; text: `· ${groupDelegate.modelData.count}` }
                    }
                    Row {
                        anchors.right: parent.right
                        anchors.rightMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 4
                        NuguText {
                            theme: root.theme
                            variant: "meta"
                            opacity: grpArea.containsMouse ? 1 : 0.7
                            text: groupDelegate.modelData.expanded ? "Show less" : `Show ${Math.max(1, (groupDelegate.modelData.count || 1) - (groupDelegate.modelData.previewCount || 1))} more`
                        }
                        NuguText {
                            theme: root.theme
                            variant: "mono"
                            opacity: grpArea.containsMouse ? 1 : 0.7
                            text: groupDelegate.modelData.expanded ? "⌃" : "⌄"
                        }
                    }
                    MouseArea { id: grpArea; anchors.fill: parent; hoverEnabled: true; onClicked: root.toggleGroup(groupDelegate.modelData.appName || "") }
                }

                Repeater {
                    model: groupDelegate.modelData.visibleNotifications || []
                    delegate: Item {
                        id: cardWrap
                        required property var modelData
                        width: root.width
                        implicitHeight: cardInner.implicitHeight
                        height: implicitHeight
                        NotificationCard {
                            id: cardInner
                            width: parent.width
                            theme: root.theme
                            modelData: cardWrap.modelData
                            onDismiss: (id) => root.runAction(id, "close")
                            onInvokeAction: (id, actionId) => root.runAction(id, actionId)
                            onSendReply: (id, text) => root.sendReply(id, text)
                        }
                    }
                }
            }
                        }
                    }
                }

            // slim scroll indicator, overlaid (outside the Flickable so it
            // doesn't scroll with content); shown only when content overflows.
            Rectangle {
                anchors.right: parent.right
                width: 3
                radius: 2
                visible: scroll.contentHeight > scroll.height + 1
                color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.5) : "transparent"
                height: Math.max(24, scrollArea.height * scrollArea.height / Math.max(1, scroll.contentHeight))
                y: scroll.contentY * scrollArea.height / Math.max(1, scroll.contentHeight)
            }
        }
    }

    component FailureShake: Item {
        id: shakeRoot

        default property alias content: contentItem.data
        property bool active: false
        property real boundedDistance: 12
        readonly property var shakeOffsets: [0, -boundedDistance, boundedDistance, -boundedDistance / 2, boundedDistance / 2, 0]

        implicitWidth: contentItem.implicitWidth
        implicitHeight: contentItem.implicitHeight
        onActiveChanged: {
            if (active)
                shake.restart();

        }

        Item {
            id: contentItem

            anchors.fill: parent
            implicitWidth: childrenRect.width
            implicitHeight: childrenRect.height
        }

        SequentialAnimation {
            id: shake

            running: false
            alwaysRunToEnd: true

            ScriptAction {
                script: translation.x = shakeRoot.shakeOffsets[0]
            }

            NumberAnimation {
                target: translation
                property: "x"
                to: shakeRoot.shakeOffsets[1]
                duration: root.theme && root.theme.lowPowerMode ? 0 : 50
                easing.type: Easing.OutCubic
            }

            NumberAnimation {
                target: translation
                property: "x"
                to: shakeRoot.shakeOffsets[2]
                duration: root.theme && root.theme.lowPowerMode ? 0 : 50
                easing.type: Easing.OutCubic
            }

            NumberAnimation {
                target: translation
                property: "x"
                to: shakeRoot.shakeOffsets[3]
                duration: root.theme && root.theme.lowPowerMode ? 0 : 40
                easing.type: Easing.OutCubic
            }

            NumberAnimation {
                target: translation
                property: "x"
                to: shakeRoot.shakeOffsets[4]
                duration: root.theme && root.theme.lowPowerMode ? 0 : 40
                easing.type: Easing.OutCubic
            }

            NumberAnimation {
                target: translation
                property: "x"
                to: shakeRoot.shakeOffsets[5]
                duration: root.theme && root.theme.lowPowerMode ? 0 : 30
                easing.type: Easing.OutCubic
            }

        }

        transform: Translate {
            id: translation

            x: 0
        }

    }

    component ClipboardPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject clipboardService
        property string query: ""
        property var state: clipboardService ? Util.parseJson(clipboardService.stateJson(), {
            "rows": [],
            "privateMode": false,
            "privateRole": "ui.accent",
            "lastAction": {
            }
        }) : ({
            "rows": [],
            "privateMode": false,
            "privateRole": "ui.accent",
            "lastAction": {
            }
        })
        readonly property var rows: state.rows || []


        function refreshFrom(text) {
            state = Util.parseJson(text, state);
        }

        function search(text) {
            query = String(text);
            if (clipboardService)
                refreshFrom(clipboardService.search(query));

        }

        function copy(id) {
            if (clipboardService)
                refreshFrom(clipboardService.copy(id));

        }

        function paste(id) {
            if (clipboardService)
                refreshFrom(clipboardService.paste(id));

        }

        function togglePin(id) {
            if (clipboardService)
                refreshFrom(clipboardService.togglePin(id));

        }

        function deleteRow(id) {
            if (clipboardService)
                refreshFrom(clipboardService.deleteRow(id));

        }

        function setPrivateMode(enabled) {
            if (clipboardService)
                refreshFrom(clipboardService.setPrivateMode(enabled));

        }

        spacing: 10
        width: parent ? parent.width : 0

        Row {
            width: parent.width
            spacing: 8

            Rectangle {
                objectName: "searchField"
                width: parent.width - 108
                height: 32
                radius: 12
                color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.14) : "transparent"
                border.width: 0
                border.color: root.theme ? root.theme.ui.accent : "transparent"

                Text {
                    id: searchGlyph

                    anchors.left: parent.left
                    anchors.leftMargin: 11
                    anchors.verticalCenter: parent.verticalCenter
                    text: ""
                    color: root.theme ? root.theme.ui.minor : "white"
                    font.family: "Symbols Nerd Font Mono"
                    font.pixelSize: 13
                }

                TextInput {
                    id: input

                    anchors.fill: parent
                    anchors.leftMargin: 32
                    anchors.rightMargin: 12
                    verticalAlignment: TextInput.AlignVCenter
                    color: root.theme ? root.theme.content.normal : "white"
                    selectionColor: root.theme ? root.theme.ui.focus : "#ffffff"
                    selectedTextColor: root.theme ? root.theme.content.backdrop : "black"
                    font.family: "IBM Plex Sans"
                    font.pixelSize: 13
                    text: root.query
                    clip: true
                    onTextEdited: root.search(text)
                }

                NuguText {
                    anchors.left: parent.left
                    anchors.leftMargin: 32
                    anchors.verticalCenter: parent.verticalCenter
                    visible: input.text.length === 0
                    theme: root.theme
                    variant: "meta"
                    text: "search clipboard"
                }

            }

            Rectangle {
                objectName: "privateModeChip"
                width: 100
                height: 32
                radius: 12
                color: root.theme ? root.theme.withAlpha(root.state.privateMode ? root.theme.warning : root.theme.ui.accent, 0.2) : "transparent"
                border.width: 0
                border.color: root.theme ? (root.state.privateMode ? root.theme.warning : root.theme.ui.accent) : "transparent"

                Row {
                    anchors.centerIn: parent
                    spacing: 6

                    Text {
                        anchors.verticalCenter: parent.verticalCenter
                        text: root.state.privateMode ? "" : ""
                        color: root.theme ? (root.state.privateMode ? root.theme.warning : root.theme.ui.accent) : "white"
                        font.family: "Symbols Nerd Font Mono"
                        font.pixelSize: 13
                    }

                    NuguText {
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        variant: "meta"
                        text: root.state.privateMode ? "private" : "normal"
                    }

                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: root.setPrivateMode(!root.state.privateMode)
                }

            }

        }

        Rectangle {
            objectName: "clipboardHistoryPanel"
            width: parent.width
            height: Math.min(440, Math.max(120, rowColumn.implicitHeight + 16))
            radius: 14
            clip: true
            color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.7) : "transparent"
            border.width: 0
            border.color: root.theme ? root.theme.ui.accent : "transparent"

            Flickable {
                id: list

                anchors.fill: parent
                anchors.margins: 8
                contentHeight: rowColumn.implicitHeight
                clip: true
                boundsBehavior: Flickable.StopAtBounds

                Column {
                    id: rowColumn

                    width: list.width
                    spacing: 6

                    Repeater {
                        model: root.rows

                        delegate: Rectangle {
                            id: clipRow

                            required property var modelData

                            objectName: "clipRow"
                            width: rowColumn.width
                            height: 56
                            radius: 13
                            color: root.theme ? root.theme.withAlpha(clipRow.modelData.pinned ? root.theme.ui.focus : root.theme.ui.minor, clipRow.modelData.pinned ? 0.22 : 0.1) : "transparent"
                            border.width: clipRow.modelData.pinned ? 1 : 0
                            border.color: root.theme ? root.theme.withAlpha(root.theme.ui.focus, 0.5) : "transparent"

                            // Single hover detector covering the whole card. NoButton
                            // lets clicks fall through to the action buttons (later
                            // siblings); the buttons keep hoverEnabled off so they
                            // never steal containsMouse from this detector.
                            MouseArea {
                                id: rowHover

                                anchors.fill: parent
                                hoverEnabled: true
                                acceptedButtons: Qt.NoButton
                            }

                            Item {
                                id: leadingSlot

                                anchors.left: parent.left
                                anchors.leftMargin: 9
                                anchors.verticalCenter: parent.verticalCenter
                                width: 36
                                height: 36

                                Image {
                                    id: thumb

                                    anchors.fill: parent
                                    visible: clipRow.modelData.isImage && thumb.status !== Image.Error
                                    // encodeURI keeps "/" but escapes spaces/specials so screenshot
                                    // paths ("/tmp/Screenshot from ….png") resolve as valid file:// URLs
                                    source: clipRow.modelData.isImage ? "file://" + encodeURI(clipRow.modelData.imagePath || "") : ""
                                    sourceSize.width: 36
                                    sourceSize.height: 36
                                    fillMode: Image.PreserveAspectCrop
                                    asynchronous: true
                                    clip: true
                                    smooth: true
                                }

                                Rectangle {
                                    id: swatch

                                    anchors.fill: parent
                                    visible: !clipRow.modelData.isImage && !!clipRow.modelData.swatch
                                    radius: 9
                                    color: clipRow.modelData.swatch ? clipRow.modelData.swatch : "transparent"
                                    border.width: 1
                                    border.color: root.theme ? root.theme.withAlpha(root.theme.ui.normal, 0.25) : "transparent"
                                }

                                // Type-icon fallback: shown for non-image/non-color
                                // rows, and when the image thumbnail fails to load.
                                Text {
                                    anchors.centerIn: parent
                                    visible: !swatch.visible && !thumb.visible
                                    text: clipRow.modelData.icon
                                    color: root.theme ? root.theme.ui.accent : "white"
                                    font.family: "Symbols Nerd Font Mono"
                                    font.pixelSize: 18
                                }

                            }

                            Column {
                                anchors.left: leadingSlot.right
                                anchors.right: actionRail.left
                                anchors.verticalCenter: parent.verticalCenter
                                anchors.leftMargin: 11
                                anchors.rightMargin: 8
                                spacing: 3

                                NuguText {
                                    theme: root.theme
                                    text: clipRow.modelData.title
                                    width: parent.width
                                    elide: Text.ElideRight
                                }

                                NuguText {
                                    theme: root.theme
                                    variant: "meta"
                                    text: clipRow.modelData.kind + " · " + clipRow.modelData.age
                                    width: parent.width
                                    elide: Text.ElideRight
                                }

                            }

                            // Pin badge, hidden while the action rail is revealed.
                            Text {
                                id: pinBadge

                                anchors.right: parent.right
                                anchors.rightMargin: 11
                                anchors.top: parent.top
                                anchors.topMargin: 8
                                visible: clipRow.modelData.pinned && !rowHover.containsMouse
                                text: ""
                                color: root.theme ? root.theme.ui.focus : "white"
                                font.family: "Symbols Nerd Font Mono"
                                font.pixelSize: 11
                            }

                            Row {
                                id: actionRail

                                anchors.right: parent.right
                                anchors.rightMargin: 8
                                anchors.verticalCenter: parent.verticalCenter
                                spacing: 5
                                opacity: rowHover.containsMouse ? 1 : 0
                                enabled: rowHover.containsMouse

                                Behavior on opacity {
                                    NumberAnimation {
                                        duration: root.theme && root.theme.lowPowerMode ? 0 : 120
                                        easing.type: Easing.OutCubic
                                    }

                                }

                                Repeater {
                                    model: ["copy", "paste", "pin", "delete"]

                                    delegate: Rectangle {
                                        id: actionButton

                                        required property string modelData

                                        readonly property bool isDelete: actionButton.modelData === "delete"
                                        readonly property bool isPin: actionButton.modelData === "pin"
                                        readonly property bool pinActive: actionButton.isPin && clipRow.modelData.pinned
                                        readonly property string tint: !root.theme ? "transparent" : (actionButton.isDelete ? root.theme.error : (actionButton.pinActive ? root.theme.ui.focus : root.theme.ui.accent))

                                        width: 30
                                        height: 30
                                        radius: 10
                                        color: root.theme ? root.theme.withAlpha(actionButton.tint, actionButton.pinActive ? 0.32 : 0.16) : "transparent"
                                        border.width: 0
                                        border.color: "transparent"

                                        Text {
                                            anchors.centerIn: parent
                                            text: actionButton.modelData === "copy" ? "" : actionButton.modelData === "paste" ? "" : actionButton.isPin ? "" : ""
                                            color: actionButton.isDelete ? (root.theme ? root.theme.error : "white") : (root.theme ? (actionButton.pinActive ? root.theme.ui.focus : root.theme.ui.normal) : "white")
                                            font.family: "Symbols Nerd Font Mono"
                                            font.pixelSize: 13
                                        }

                                        MouseArea {
                                            anchors.fill: parent
                                            onClicked: {
                                                if (actionButton.modelData === "copy")
                                                    root.copy(clipRow.modelData.id);
                                                else if (actionButton.modelData === "paste")
                                                    root.paste(clipRow.modelData.id);
                                                else if (actionButton.isPin)
                                                    root.togglePin(clipRow.modelData.id);
                                                else
                                                    root.deleteRow(clipRow.modelData.id);
                                            }
                                        }

                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

    }

    component BrightnessPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject brightnessService
        property var state: brightnessService ? Util.parseJson(brightnessService.stateJson(), {
            "level": 0,
            "compact": {
                "label": "Bright"
            },
            "shader": {
            }
        }) : ({
            "level": 0,
            "compact": {
                "label": "Bright"
            },
            "shader": {
            }
        })

        spacing: 12
        padding: 14

        Rectangle {
            width: Math.max(1, root.width - 28)
            height: 36
            radius: 10
            color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.88) : "#242424"
            border.width: 0
            border.color: root.theme ? root.theme.ui.accent : "white"

            Rectangle {
                anchors.left: parent.left
                anchors.top: parent.top
                anchors.bottom: parent.bottom
                width: parent.width * Math.max(0, Math.min(1, Number(root.state.level || 0)))
                radius: parent.radius
                color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.55) : "white"
            }

            Text {
                anchors.centerIn: parent
                text: `${Math.round(Number(root.state.level || 0) * 100)}%`
                color: root.theme ? root.theme.content.normal : "white"
                font.family: "IBM Plex Mono"
                font.pixelSize: 14
            }

        }

        Row {
            spacing: 8

            Repeater {
                model: [0.25, 0.5, 0.75, 1]

                delegate: Rectangle {
                    width: 88
                    height: 30
                    radius: 8
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.18) : "#333333"
                    border.width: 0
                    border.color: root.theme ? root.theme.ui.focus : "white"

                    Text {
                        anchors.centerIn: parent
                        text: `${Math.round(modelData * 100)}%`
                        color: root.theme ? root.theme.content.normal : "white"
                        font.family: "IBM Plex Sans"
                        font.pixelSize: 13
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.brightnessService.setLevel(modelData)
                    }

                }

            }

        }

    }

    component ConnectivityPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject resourceService
        required property QtObject networkService
        required property QtObject bluetoothService
        property var networkState: networkService ? Util.parseJson(networkService.stateJson(), {
            "knownNetworks": [],
            "connectivityPanelContract": {
            },
            "wifi": {
            }
        }) : ({
            "knownNetworks": [],
            "connectivityPanelContract": {
            },
            "wifi": {
            }
        })
        property var bluetoothState: bluetoothService ? Util.parseJson(bluetoothService.stateJson(), {
            "devices": [],
            "adapter": {
            }
        }) : ({
            "devices": [],
            "adapter": {
            }
        })
        readonly property var panel: networkState.connectivityPanelContract || ({
        })


        function refreshNetwork(text) {
            networkState = Util.parseJson(text, networkState);
        }

        function refreshBluetooth(text) {
            bluetoothState = Util.parseJson(text, bluetoothState);
        }

        function toggleWifi() {
            if (networkService)
                refreshNetwork(networkService.toggleWifi(!(networkState.wifi && networkState.wifi.enabled)));

        }

        function scanWifi() {
            if (networkService)
                refreshNetwork(networkService.scan());

        }

        function selectNetwork(id) {
            if (networkService)
                refreshNetwork(networkService.select(id));

        }

        function forgetNetwork(id) {
            if (networkService)
                refreshNetwork(networkService.forget(id));

        }

        function toggleBluetooth() {
            if (bluetoothService)
                refreshBluetooth(bluetoothService.toggle(!(bluetoothState.adapter && bluetoothState.adapter.state === "powered")));

        }

        function scanBluetooth() {
            if (bluetoothService)
                refreshBluetooth(bluetoothService.scan());

        }

        function bluetoothAction(kind, id) {
            if (bluetoothService)
                refreshBluetooth(bluetoothService.deviceAction(kind, id));

        }

        function roleColor(role) {
            if (!theme)
                return "white";

            if (role === "warning")
                return theme.warning;

            if (role === "error")
                return theme.error;

            if (role === "ui.minor")
                return theme.ui.minor;

            return theme.ui.accent;
        }

        spacing: 10
        width: parent ? parent.width : 0

        Row {
            objectName: "networkRateRow"
            width: parent.width
            spacing: 8

            NuguText {
                theme: root.theme
                text: root.resourceService ? `↓ ${Sys.formatRate(root.resourceService.networkRxRate)}` : "↓ 0 B/s"
                color: root.theme ? root.theme.ui.accent : "white"
            }

            NuguText {
                theme: root.theme
                text: root.resourceService ? `↑ ${Sys.formatRate(root.resourceService.networkTxRate)}` : "↑ 0 B/s"
                color: root.theme ? root.theme.ui.focus : "white"
            }

        }

        Column {
            objectName: "wifiToggleScanList"
            width: parent.width
            spacing: 6

            Row {
                width: parent.width
                spacing: 6

                NuguText {
                    theme: root.theme
                    variant: "title"
                    text: "wireless"
                    width: parent.width - 132
                }

                Rectangle {
                    width: 58
                    height: 26
                    radius: 9
                    color: root.theme ? root.theme.withAlpha(root.networkState.wifi && root.networkState.wifi.enabled ? root.theme.ui.focus : root.theme.ui.minor, 0.22) : "transparent"
                    border.width: 0
                    border.color: root.roleColor(root.networkState.compact ? root.networkState.compact.role : "ui.minor")

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: root.networkState.wifi && root.networkState.wifi.enabled ? "on" : "off"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.toggleWifi()
                    }

                }

                Rectangle {
                    width: 58
                    height: 26
                    radius: 9
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, root.networkState.scanning ? 0.32 : 0.16) : "transparent"
                    border.width: 0
                    border.color: root.theme ? root.theme.ui.accent : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: root.networkState.scanning ? "scan…" : "scan"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.scanWifi()
                    }

                }

            }

            Repeater {
                model: root.networkState.knownNetworks || []

                delegate: Rectangle {
                    id: wifiRow

                    required property var modelData
                    readonly property bool active: modelData.state === "connected" || modelData.state === "Connected"

                    width: root.width
                    height: 34
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(active ? root.theme.ui.focus : root.theme.ui.minor, active ? 0.24 : 0.1) : "transparent"
                    border.width: 0
                    border.color: root.roleColor(active ? "ui.accent" : modelData.state === "connecting" ? "warning" : "ui.minor")

                    NuguText {
                        anchors.left: parent.left
                        anchors.leftMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        text: wifiRow.modelData.ssid
                        width: parent.width - 122
                        elide: Text.ElideRight
                    }

                    NuguText {
                        anchors.right: parent.right
                        anchors.rightMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        variant: "meta"
                        text: `${wifiRow.modelData.signal}% ${wifiRow.modelData.security}`
                    }

                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.LeftButton | Qt.MiddleButton
                        onClicked: (event) => {
                            if (event.button === Qt.MiddleButton)
                                root.forgetNetwork(wifiRow.modelData.id);
                            else
                                root.selectNetwork(wifiRow.modelData.id);
                        }
                    }

                }

            }

        }

        Rectangle {
            width: parent.width
            height: 1
            color: root.theme ? root.theme.ui.accent : "transparent"
        }

        Column {
            objectName: "bluetoothToggleScanList"
            width: parent.width
            spacing: 6

            Row {
                width: parent.width
                spacing: 6

                NuguText {
                    theme: root.theme
                    variant: "title"
                    text: "bluetooth"
                    width: parent.width - 132
                }

                Rectangle {
                    width: 58
                    height: 26
                    radius: 9
                    color: root.theme ? root.theme.withAlpha(root.bluetoothState.adapter && root.bluetoothState.adapter.state === "powered" ? root.theme.ui.focus : root.theme.ui.minor, 0.22) : "transparent"
                    border.width: 0
                    border.color: root.roleColor(root.bluetoothState.compact ? root.bluetoothState.compact.role : "ui.minor")

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: root.bluetoothState.adapter && root.bluetoothState.adapter.state === "powered" ? "on" : "off"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.toggleBluetooth()
                    }

                }

                Rectangle {
                    width: 58
                    height: 26
                    radius: 9
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, root.bluetoothState.adapter && root.bluetoothState.adapter.discovering ? 0.32 : 0.16) : "transparent"
                    border.width: 0
                    border.color: root.theme ? root.theme.ui.accent : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: root.bluetoothState.adapter && root.bluetoothState.adapter.discovering ? "scan…" : "scan"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.scanBluetooth()
                    }

                }

            }

            Repeater {
                model: root.bluetoothState.devices || []

                delegate: Rectangle {
                    id: deviceRow

                    required property var modelData

                    width: root.width
                    height: 36
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(modelData.connected ? root.theme.ui.focus : root.theme.ui.minor, modelData.connected ? 0.24 : 0.1) : "transparent"
                    border.width: 0
                    border.color: root.roleColor(modelData.blocked ? "error" : modelData.connected ? "ui.accent" : "ui.minor")

                    NuguText {
                        anchors.left: parent.left
                        anchors.leftMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        text: deviceRow.modelData.name
                        width: parent.width - 136
                        elide: Text.ElideRight
                    }

                    NuguText {
                        objectName: "batteryBadges"
                        anchors.right: parent.right
                        anchors.rightMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        variant: "meta"
                        text: deviceRow.modelData.battery >= 0 ? `${deviceRow.modelData.battery}%` : "--"
                    }

                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.LeftButton | Qt.MiddleButton | Qt.RightButton
                        onClicked: (event) => {
                            if (event.button === Qt.MiddleButton)
                                root.bluetoothAction("forget", deviceRow.modelData.id);
                            else if (event.button === Qt.RightButton)
                                root.bluetoothAction(deviceRow.modelData.trusted ? "block" : "trust", deviceRow.modelData.id);
                            else
                                root.bluetoothAction(deviceRow.modelData.connected ? "disconnect" : "connect", deviceRow.modelData.id);
                        }
                    }

                }

            }

        }

    }

    component TrayPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject trayService
        property var state: trayService ? Util.parseJson(trayService.stateJson(), {
            "items": []
        }) : ({
            "items": []
        })
        readonly property var items: state.items || []
        readonly property bool hasItems: items.length > 0

        function refreshFrom(text) {
            state = Util.parseJson(text, state);
        }

        function activate(id) {
            if (trayService)
                refreshFrom(trayService.activateRow(id));

        }

        spacing: 10
        width: parent ? parent.width : 0

        Flow {
            objectName: "trayItems"
            visible: root.hasItems
            width: parent.width
            spacing: 8

            Repeater {
                model: root.items

                delegate: Rectangle {
                    id: itemCell

                    required property var modelData
                    readonly property bool attention: modelData.status === "NeedsAttention"

                    width: 168
                    height: 46
                    radius: 12
                    color: root.theme ? root.theme.withAlpha(attention ? root.theme.info : root.theme.ui.accent, attention ? 0.2 : 0.12) : "transparent"
                    border.width: 0
                    border.color: root.theme ? (attention ? root.theme.info : root.theme.ui.accent) : "transparent"

                    Row {
                        anchors.fill: parent
                        anchors.leftMargin: 11
                        anchors.rightMargin: 11
                        spacing: 10

                        Image {
                            anchors.verticalCenter: parent.verticalCenter
                            width: 24
                            height: 24
                            sourceSize.width: 24
                            sourceSize.height: 24
                            fillMode: Image.PreserveAspectFit
                            source: itemCell.modelData.icon || ""
                            visible: status === Image.Ready
                        }

                        NuguText {
                            anchors.verticalCenter: parent.verticalCenter
                            theme: root.theme
                            variant: "meta"
                            selected: itemCell.attention
                            text: itemCell.modelData.title
                            width: parent.width - 34
                            elide: Text.ElideRight
                        }

                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.activate(itemCell.modelData.id)
                    }

                }

            }

        }

        Item {
            objectName: "trayEmptyState"
            visible: !root.hasItems
            width: parent.width
            height: 300

            Column {
                anchors.centerIn: parent
                spacing: 12

                Rectangle {
                    anchors.horizontalCenter: parent.horizontalCenter
                    width: 68
                    height: 68
                    radius: 34
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.16) : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "title"
                        selected: true
                        text: "⌁"
                    }

                }

                NuguText {
                    anchors.horizontalCenter: parent.horizontalCenter
                    theme: root.theme
                    variant: "title"
                    text: "No tray icons"
                }

                NuguText {
                    anchors.horizontalCenter: parent.horizontalCenter
                    theme: root.theme
                    variant: "meta"
                    text: "Background apps show up here"
                }

            }

        }

    }

    component PowerPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject powerService
        property var state: powerService ? Util.parseJson(powerService.stateJson(), {
            "battery": {
            },
            "externalDevices": [],
            "powerPanelContract": {
            },
            "session": {
            }
        }) : ({
            "battery": {
            },
            "externalDevices": [],
            "powerPanelContract": {
            },
            "session": {
            }
        })
        readonly property var battery: state.battery || ({
        })
        readonly property var devices: state.externalDevices || []
        readonly property var panel: state.powerPanelContract || ({
        })
        readonly property var sessionActions: ["lock", "suspend", "monitor-off", "monitor-on", "logout", "reboot", "poweroff"]
        readonly property var profileRows: ["power-saver", "balanced", "performance"]


        function refreshFrom(text) {
            state = Util.parseJson(text, state);
        }

        function setProfile(profile) {
            if (powerService)
                refreshFrom(powerService.setProfile(profile));

        }

        function runSession(action) {
            if (powerService)
                refreshFrom(powerService.sessionAction(action));

        }

        function confirm(action) {
            if (powerService)
                refreshFrom(powerService.confirmAction(action));

        }

        function cancel() {
            if (powerService)
                refreshFrom(powerService.cancelAction());

        }

        function roleColor(role) {
            if (!theme)
                return "white";

            if (role === "warning")
                return theme.warning;

            if (role === "error")
                return theme.error;

            if (role === "ui.minor")
                return theme.ui.minor;

            return theme.ui.accent;
        }

        function actionLabel(action) {
            if (action === "monitor-off")
                return "mon off";

            if (action === "monitor-on")
                return "mon on";

            if (action === "poweroff")
                return "power";

            return action;
        }

        spacing: 10
        width: parent ? parent.width : 0
        focus: true
        Keys.onEscapePressed: root.cancel()
        Keys.onReturnPressed: root.state.pendingConfirmation ? root.confirm(root.state.pendingConfirmation) : root.runSession("lock")
        Keys.onEnterPressed: root.state.pendingConfirmation ? root.confirm(root.state.pendingConfirmation) : root.runSession("lock")

        Rectangle {
            objectName: "batteryHero"
            width: parent.width
            height: 78
            radius: 15
            color: root.theme ? root.theme.withAlpha(root.roleColor(root.battery.role || "ui.accent"), 0.16) : "transparent"
            border.width: 0
            border.color: root.roleColor(root.battery.role || "ui.accent")

            Column {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 7

                Row {
                    width: parent.width
                    spacing: 8

                    NuguText {
                        theme: root.theme
                        variant: "title"
                        text: `${root.battery.percent || 0}%`
                        width: parent.width - 118
                    }

                    NuguText {
                        theme: root.theme
                        variant: "meta"
                        text: root.battery.state || "unknown"
                        width: 110
                        horizontalAlignment: Text.AlignRight
                    }

                }

                Rectangle {
                    width: parent.width
                    height: 10
                    radius: 5
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.28) : "transparent"

                    Rectangle {
                        anchors.left: parent.left
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        width: Math.round(parent.width * Math.max(0, Math.min(1, Number(root.battery.percent || 0) / 100)))
                        radius: parent.radius
                        color: root.roleColor(root.battery.role || "ui.accent")
                    }

                }

                Row {
                    width: parent.width
                    spacing: 8

                    NuguText {
                        theme: root.theme
                        variant: "meta"
                        text: `remaining ${root.battery.timeEstimate || "unknown"}`
                        width: parent.width - 96
                    }

                    NuguText {
                        theme: root.theme
                        variant: "meta"
                        visible: root.battery.health >= 0
                        text: `health ${root.battery.health}%`
                        width: 88
                        horizontalAlignment: Text.AlignRight
                    }

                }

            }

        }

        Row {
            objectName: "powerProfileSelector"
            width: parent.width
            spacing: 6

            Repeater {
                model: root.profileRows

                delegate: Rectangle {
                    id: profileButton

                    required property string modelData
                    readonly property bool active: root.state.profile === modelData

                    width: Math.floor((root.width - 12) / 3)
                    height: 30
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(active ? root.theme.ui.focus : root.theme.ui.minor, active ? 0.28 : 0.12) : "transparent"
                    border.width: 0
                    border.color: root.theme ? (active ? root.theme.ui.focus : root.theme.ui.accent) : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        selected: profileButton.active
                        text: profileButton.modelData
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.setProfile(profileButton.modelData)
                    }

                }

            }

        }

        Column {
            objectName: "externalDeviceBatteryRows"
            width: parent.width
            spacing: 6
            visible: root.devices.length > 0

            Repeater {
                model: root.devices

                delegate: Rectangle {
                    id: deviceRow

                    required property var modelData

                    width: root.width
                    height: 32
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.1) : "transparent"
                    border.width: 0
                    border.color: root.theme ? root.theme.ui.accent : "transparent"

                    NuguText {
                        anchors.left: parent.left
                        anchors.leftMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        text: `${deviceRow.modelData.name}`
                        width: parent.width - 78
                        elide: Text.ElideRight
                    }

                    NuguText {
                        anchors.right: parent.right
                        anchors.rightMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        variant: "meta"
                        text: `${deviceRow.modelData.percent}%`
                    }

                }

            }

        }

        Grid {
            objectName: "keyboardActionGrid"
            width: parent.width
            columns: 4
            columnSpacing: 6
            rowSpacing: 6
            focus: true

            Repeater {
                model: root.sessionActions

                delegate: Rectangle {
                    id: actionButton

                    required property string modelData
                    readonly property bool destructive: ["logout", "reboot", "poweroff"].indexOf(modelData) >= 0
                    readonly property bool pending: root.state.pendingConfirmation === modelData

                    width: Math.floor((root.width - 18) / 4)
                    height: 38
                    radius: pending ? 14 : 11
                    color: root.theme ? root.theme.withAlpha(pending ? root.theme.warning : destructive ? root.theme.error : root.theme.ui.accent, pending ? 0.28 : 0.14) : "transparent"
                    border.width: 0
                    border.color: root.theme ? (pending ? root.theme.warning : destructive ? root.theme.error : root.theme.ui.accent) : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        selected: actionButton.pending || actionButton.modelData === "lock"
                        text: root.actionLabel(actionButton.modelData)
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.runSession(actionButton.modelData)
                    }

                }

            }

        }

        Rectangle {
            objectName: "confirmationStrip"
            width: parent.width
            height: root.state.pendingConfirmation ? 36 : 26
            radius: 11
            color: root.theme ? root.theme.withAlpha(root.state.pendingConfirmation ? root.theme.warning : root.theme.ui.minor, root.state.pendingConfirmation ? 0.2 : 0.1) : "transparent"
            border.width: 0
            border.color: root.theme ? (root.state.pendingConfirmation ? root.theme.warning : root.theme.ui.minor) : "transparent"

            NuguText {
                anchors.left: parent.left
                anchors.leftMargin: 8
                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                variant: "meta"
                text: root.state.pendingConfirmation ? `Confirm ${root.state.pendingConfirmation}? · Enter` : "Enter locks · Esc closes"
                width: parent.width - (root.state.pendingConfirmation ? 128 : 16)
                elide: Text.ElideRight
            }

            Row {
                anchors.right: parent.right
                anchors.rightMargin: 6
                anchors.verticalCenter: parent.verticalCenter
                spacing: 5
                visible: !!root.state.pendingConfirmation

                Rectangle {
                    width: 56
                    height: 24
                    radius: 8
                    color: root.theme ? root.theme.withAlpha(root.theme.warning, 0.18) : "transparent"
                    border.width: 0
                    border.color: root.theme ? root.theme.warning : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: "yes"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.confirm(root.state.pendingConfirmation)
                    }

                }

                Rectangle {
                    width: 56
                    height: 24
                    radius: 8
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.14) : "transparent"
                    border.width: 0
                    border.color: root.theme ? root.theme.ui.minor : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        text: "cancel"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.cancel()
                    }

                }

            }

        }

    }

    component AudioPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject audioService
        property var state: audioService ? Util.parseJson(audioService.stateJson(), {
            "sinks": [],
            "sources": [],
            "streams": [],
            "defaults": {
            }
        }) : ({
            "sinks": [],
            "sources": [],
            "streams": [],
            "defaults": {
            }
        })
        readonly property var sinks: state.sinks || []
        readonly property var sources: state.sources || []
        readonly property var streams: state.streams || []


        function refreshFrom(text) {
            state = Util.parseJson(text, state);
        }

        function setVolume(id, ratio) {
            if (audioService)
                refreshFrom(audioService.setVolume(id, Math.max(0, Math.min(1.5, ratio))));

        }

        function toggleMute(id) {
            if (audioService)
                refreshFrom(audioService.toggleMute(id));

        }

        function selectSink(id) {
            if (audioService)
                refreshFrom(audioService.setDefaultSink(id));

        }

        function selectSource(id) {
            if (audioService)
                refreshFrom(audioService.setDefaultSource(id));

        }

        function roleColor(role) {
            if (!theme)
                return "white";

            if (role === "warning")
                return theme.warning;

            if (role === "error")
                return theme.error;

            if (role === "ui.minor")
                return theme.ui.minor;

            return theme.ui.accent;
        }

        spacing: 10
        width: parent ? parent.width : 0

        // output devices (sinks). solid-dark cards — the popup frame is light,
        // so a translucent tint fill washes to near-white. Identity is carried
        // by the left accent bar + border; default = ui.accent.
        Column {
            objectName: "outputSection"
            width: parent.width
            spacing: 6

            NuguText {
                theme: root.theme
                variant: "title"
                text: "output"
            }

            Repeater {
                model: root.sinks

                delegate: Rectangle {
                    id: sinkRow

                    required property var modelData

                    width: parent.width
                    height: 48
                    radius: 12
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, sinkRow.modelData.isDefault ? 0.82 : 0.55) : "transparent"
                    border.width: sinkRow.modelData.isDefault ? 2 : 1
                    border.color: root.theme ? (sinkRow.modelData.isDefault ? root.theme.ui.accent : root.theme.withAlpha(root.theme.ui.minor, 0.45)) : "transparent"

                    // row click: left selects default sink, middle toggles mute.
                    // declared first so the slider-track MouseArea (later sibling,
                    // higher z) wins on the track region; glyph/name Text items have
                    // no MouseArea so their clicks fall through to here.
                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.LeftButton | Qt.MiddleButton
                        onClicked: (event) => {
                            if (event.button === Qt.MiddleButton)
                                root.toggleMute(sinkRow.modelData.id);
                            else
                                root.selectSink(sinkRow.modelData.id);
                        }
                    }

                    // left accent bar — only on the default device
                    Rectangle {
                        anchors.left: parent.left
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        anchors.margins: 2
                        width: 3
                        radius: 2
                        color: root.theme ? root.theme.ui.accent : "transparent"
                        opacity: sinkRow.modelData.isDefault ? 1 : 0
                    }

                    Text {
                        id: sinkGlyph

                        anchors.left: parent.left
                        anchors.leftMargin: 12
                        anchors.verticalCenter: parent.verticalCenter
                        font.family: "Symbols Nerd Font Mono"
                        font.pixelSize: 18
                        text: sinkRow.modelData.glyph
                        color: root.roleColor(sinkRow.modelData.role)
                        opacity: sinkRow.modelData.muted ? 0.5 : 1
                    }

                    NuguText {
                        theme: root.theme
                        text: sinkRow.modelData.name
                        anchors.left: sinkGlyph.right
                        anchors.leftMargin: 10
                        anchors.right: sinkTrack.left
                        anchors.rightMargin: 10
                        anchors.verticalCenter: parent.verticalCenter
                        elide: Text.ElideRight
                        opacity: sinkRow.modelData.muted ? 0.5 : 1
                    }

                    NuguText {
                        id: sinkTrailing

                        anchors.right: parent.right
                        anchors.rightMargin: 12
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        variant: "meta"
                        text: sinkRow.modelData.muted ? "muted" : `${sinkRow.modelData.percent}%`
                        color: root.roleColor(sinkRow.modelData.muted ? "ui.minor" : sinkRow.modelData.role)
                    }

                    // inline slider: 0..1.5 volume mapped onto the track (percent/150)
                    Rectangle {
                        id: sinkTrack

                        anchors.right: sinkTrailing.left
                        anchors.rightMargin: 10
                        anchors.verticalCenter: parent.verticalCenter
                        width: 96
                        height: 8
                        radius: 4
                        color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.28) : "transparent"

                        Rectangle {
                            anchors.left: parent.left
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom
                            width: parent.width * (sinkRow.modelData.percent / 150)
                            radius: parent.radius
                            color: root.roleColor(sinkRow.modelData.role)
                            visible: !sinkRow.modelData.muted
                        }

                        MouseArea {
                            anchors.fill: parent
                            onClicked: (event) => {
                                return root.setVolume(sinkRow.modelData.id, event.x / Math.max(1, width));
                            }
                            onPositionChanged: (event) => {
                                if (pressed)
                                    root.setVolume(sinkRow.modelData.id, event.x / Math.max(1, width));
                            }
                        }

                    }

                }

            }

        }

        // input devices (sources)
        Column {
            objectName: "inputSection"
            width: parent.width
            spacing: 6

            NuguText {
                theme: root.theme
                variant: "title"
                text: "input"
            }

            Repeater {
                model: root.sources

                delegate: Rectangle {
                    id: sourceRow

                    required property var modelData

                    width: parent.width
                    height: 48
                    radius: 12
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, sourceRow.modelData.isDefault ? 0.82 : 0.55) : "transparent"
                    border.width: sourceRow.modelData.isDefault ? 2 : 1
                    border.color: root.theme ? (sourceRow.modelData.isDefault ? root.theme.ui.accent : root.theme.withAlpha(root.theme.ui.minor, 0.45)) : "transparent"

                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.LeftButton | Qt.MiddleButton
                        onClicked: (event) => {
                            if (event.button === Qt.MiddleButton)
                                root.toggleMute(sourceRow.modelData.id);
                            else
                                root.selectSource(sourceRow.modelData.id);
                        }
                    }

                    Rectangle {
                        anchors.left: parent.left
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        anchors.margins: 2
                        width: 3
                        radius: 2
                        color: root.theme ? root.theme.ui.accent : "transparent"
                        opacity: sourceRow.modelData.isDefault ? 1 : 0
                    }

                    Text {
                        id: sourceGlyph

                        anchors.left: parent.left
                        anchors.leftMargin: 12
                        anchors.verticalCenter: parent.verticalCenter
                        font.family: "Symbols Nerd Font Mono"
                        font.pixelSize: 18
                        text: sourceRow.modelData.glyph
                        color: root.roleColor(sourceRow.modelData.role)
                        opacity: sourceRow.modelData.muted ? 0.5 : 1
                    }

                    NuguText {
                        theme: root.theme
                        text: sourceRow.modelData.name
                        anchors.left: sourceGlyph.right
                        anchors.leftMargin: 10
                        anchors.right: sourceTrack.left
                        anchors.rightMargin: 10
                        anchors.verticalCenter: parent.verticalCenter
                        elide: Text.ElideRight
                        opacity: sourceRow.modelData.muted ? 0.5 : 1
                    }

                    NuguText {
                        id: sourceTrailing

                        anchors.right: parent.right
                        anchors.rightMargin: 12
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        variant: "meta"
                        text: sourceRow.modelData.muted ? "muted" : `${sourceRow.modelData.percent}%`
                        color: root.roleColor(sourceRow.modelData.muted ? "ui.minor" : sourceRow.modelData.role)
                    }

                    Rectangle {
                        id: sourceTrack

                        anchors.right: sourceTrailing.left
                        anchors.rightMargin: 10
                        anchors.verticalCenter: parent.verticalCenter
                        width: 96
                        height: 8
                        radius: 4
                        color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.28) : "transparent"

                        Rectangle {
                            anchors.left: parent.left
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom
                            width: parent.width * (sourceRow.modelData.percent / 150)
                            radius: parent.radius
                            color: root.roleColor(sourceRow.modelData.role)
                            visible: !sourceRow.modelData.muted
                        }

                        MouseArea {
                            anchors.fill: parent
                            onClicked: (event) => {
                                return root.setVolume(sourceRow.modelData.id, event.x / Math.max(1, width));
                            }
                            onPositionChanged: (event) => {
                                if (pressed)
                                    root.setVolume(sourceRow.modelData.id, event.x / Math.max(1, width));
                            }
                        }

                    }

                }

            }

        }

    }

    component MediaPanel: Column {
        id: root

        required property QtObject theme
        required property QtObject mediaService
        property var state: mediaService ? Util.parseJson(mediaService.stateJson(), {
            "activePlayer": {
            },
            "players": [],
            "mediaPanelContract": {
            }
        }) : ({
            "activePlayer": {
            },
            "players": [],
            "mediaPanelContract": {
            }
        })
        readonly property var player: state.activePlayer || ({
        })
        readonly property var players: state.players || []
        readonly property bool hasMedia: players.length > 0
        readonly property var panel: state.mediaPanelContract || ({
        })
        readonly property var transportActions: ["shuffle", "previous", "playPause", "next", "repeat"]


        function mmss(seconds) {
            const total = Math.max(0, Math.round(Number(seconds || 0)));
            const minutes = Math.floor(total / 60);
            const rest = String(total % 60).padStart(2, "0");
            return `${minutes}:${rest}`;
        }

        function refreshFrom(text) {
            state = Util.parseJson(text, state);
        }

        function runAction(kind) {
            if (mediaService)
                refreshFrom(mediaService.action(kind));

        }

        function seekByRatio(ratio) {
            const length = Math.max(0, Number(player.length || 0));
            if (mediaService && length > 0)
                refreshFrom(mediaService.seek(Math.round(Math.max(0, Math.min(1, ratio)) * length)));

        }

        function selectPlayer(id) {
            if (mediaService)
                refreshFrom(mediaService.select(id));

        }

        spacing: 10
        width: parent ? parent.width : 0

        Row {
            width: parent.width
            spacing: 12
            visible: root.hasMedia

            Rectangle {
                id: coverCard

                objectName: "coverDetailsProgressTransport"
                width: 96
                height: 96
                radius: 18
                color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.24) : "transparent"
                border.width: 0
                border.color: root.theme ? root.theme.ui.accent : "transparent"
                clip: true

                NuguText {
                    anchors.centerIn: parent
                    theme: root.theme
                    variant: "title"
                    selected: true
                    text: root.player.playbackState === "playing" ? "▶" : "Ⅱ"
                }

                Rectangle {
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.bottom: parent.bottom
                    height: 5
                    color: root.theme ? root.theme.ui.accent : "transparent"
                    opacity: root.player.playbackState === "playing" ? 1 : 0.35
                }

            }

            Column {
                width: parent.width - coverCard.width - parent.spacing
                spacing: 7

                NuguText {
                    theme: root.theme
                    variant: "title"
                    text: root.player.title || root.player.identity || "Untitled"
                    width: parent.width
                    elide: Text.ElideRight
                }

                NuguText {
                    theme: root.theme
                    text: root.player.artist || ""
                    visible: text.length > 0
                    width: parent.width
                    elide: Text.ElideRight
                }

                NuguText {
                    theme: root.theme
                    variant: "meta"
                    text: root.player.album || ""
                    visible: text.length > 0
                    width: parent.width
                    elide: Text.ElideRight
                }

                Row {
                    width: parent.width
                    spacing: 6

                    NuguText {
                        theme: root.theme
                        variant: "meta"
                        text: root.mmss(root.player.position)
                        width: 34
                    }

                    Rectangle {
                        id: progressRail

                        objectName: "mpris-progress"
                        width: Math.max(1, parent.width - 76)
                        height: 10
                        radius: 5
                        color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.28) : "transparent"
                        border.width: 0
                        border.color: root.theme ? root.theme.ui.minor : "transparent"

                        Rectangle {
                            anchors.left: parent.left
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom
                            width: Math.round(parent.width * Math.max(0, Math.min(1, Number(root.player.progress || 0))))
                            radius: parent.radius
                            color: root.theme ? root.theme.ui.accent : "white"
                        }

                        MouseArea {
                            anchors.fill: parent
                            onClicked: (event) => {
                                return root.seekByRatio(event.x / Math.max(1, width));
                            }
                        }

                    }

                    NuguText {
                        theme: root.theme
                        variant: "meta"
                        text: root.mmss(root.player.length)
                        width: 34
                    }

                }

                Row {
                    objectName: "transportActions"
                    width: parent.width
                    spacing: 6

                    Repeater {
                        model: root.transportActions

                        delegate: Rectangle {
                            id: transportButton

                            required property string modelData

                            width: modelData === "playPause" ? 58 : 38
                            height: 28
                            radius: 10
                            color: root.theme ? root.theme.withAlpha(modelData === "playPause" ? root.theme.ui.focus : root.theme.ui.accent, 0.2) : "transparent"
                            border.width: 0
                            border.color: root.theme ? root.theme.ui.accent : "transparent"

                            NuguText {
                                anchors.centerIn: parent
                                theme: root.theme
                                variant: "meta"
                                selected: transportButton.modelData === "playPause"
                                text: transportButton.modelData === "playPause" ? (root.player.playbackState === "playing" ? "pause" : "play") : transportButton.modelData
                            }

                            MouseArea {
                                anchors.fill: parent
                                onClicked: root.runAction(transportButton.modelData)
                            }

                        }

                    }

                }

            }

        }

        Row {
            objectName: "playerSelectorRail"
            width: parent.width
            spacing: 6
            visible: root.players.length > 1

            Repeater {
                model: root.players

                delegate: Rectangle {
                    id: playerButton

                    required property var modelData
                    readonly property bool active: modelData.id === root.player.id

                    height: 26
                    width: Math.max(76, playerName.implicitWidth + 18)
                    radius: 10
                    color: root.theme ? root.theme.withAlpha(active ? root.theme.ui.focus : root.theme.ui.minor, active ? 0.3 : 0.14) : "transparent"
                    border.width: 0
                    border.color: root.theme ? (active ? root.theme.ui.focus : root.theme.ui.accent) : "transparent"

                    NuguText {
                        id: playerName

                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "meta"
                        selected: playerButton.active
                        text: playerButton.modelData.identity || playerButton.modelData.id
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: root.selectPlayer(playerButton.modelData.id)
                    }

                }

            }

        }

        Item {
            objectName: "mediaEmptyState"
            visible: !root.hasMedia
            width: parent.width
            height: 300

            Column {
                anchors.centerIn: parent
                spacing: 12

                Rectangle {
                    anchors.horizontalCenter: parent.horizontalCenter
                    width: 68
                    height: 68
                    radius: 34
                    color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.16) : "transparent"

                    NuguText {
                        anchors.centerIn: parent
                        theme: root.theme
                        variant: "title"
                        selected: true
                        text: "♪"
                    }

                }

                NuguText {
                    anchors.horizontalCenter: parent.horizontalCenter
                    theme: root.theme
                    variant: "title"
                    text: "Nothing playing"
                }

                NuguText {
                    anchors.horizontalCenter: parent.horizontalCenter
                    theme: root.theme
                    variant: "meta"
                    text: "Start a track — controls appear here"
                }

            }

        }

    }

}