// A deliberately absent-until-needed health affordance. Healthy and merely
// unconfigured systems leave no ornament or layout residue in the bar.

import QtQuick
import QtQuick.Controls
import qs.config
import qs.services

Rectangle {
    id: root

    signal activated

    readonly property int issueCount: Health.summary.warnings + Health.summary.errors
    readonly property color tone: Health.status === "error"
        ? Theme.danger
        : (Health.status === "warning" ? Theme.warn : "transparent")
    readonly property string statusText: root.issueCount === 1
        ? "1 system health issue"
        : root.issueCount + " system health issues"
    readonly property string accessibleLabel: Health.status === "error"
        ? "System Health: " + root.issueCount + (root.issueCount === 1 ? " issue requires action" : " issues require action")
        : "System Health: " + root.issueCount + (root.issueCount === 1 ? " issue needs attention" : " issues need attention")
    readonly property string tooltipText: root.accessibleLabel

    visible: Health.actionable
    implicitWidth: visible ? content.implicitWidth + 16 : 0
    implicitHeight: visible ? 24 : 0
    width: implicitWidth
    height: implicitHeight
    radius: 9
    color: visible ? Theme.alpha(root.tone, 0.09) : "transparent"
    border.width: activeFocus ? 2 : 1
    border.color: visible ? Theme.alpha(root.tone, activeFocus ? 0.72 : 0.20) : "transparent"

    activeFocusOnTab: visible
    Accessible.role: Accessible.Button
    Accessible.name: root.accessibleLabel
    Accessible.description: "Open System Health"
    Accessible.onPressAction: root.activated()

    onActivated: {
        ShellState.openSettings("services");
        Health.refresh();
    }

    Keys.onReturnPressed: root.activated()
    Keys.onEnterPressed: root.activated()
    Keys.onSpacePressed: root.activated()

    Row {
        id: content

        anchors.centerIn: parent
        spacing: 6

        Text {
            anchors.verticalCenter: parent.verticalCenter
            text: "\u{F0ECD}" // md-shield-alert-outline
            color: root.tone
            font.family: Theme.fontMono
            font.pixelSize: 14
        }

        Text {
            anchors.verticalCenter: parent.verticalCenter
            text: String(root.issueCount)
            color: root.tone
            font.family: Theme.fontFamily
            font.features: Theme.tabularFigures
            font.pixelSize: Theme.fontSizeSmall
            font.weight: Font.DemiBold
        }
    }

    MouseArea {
        id: pointer

        anchors.fill: parent
        enabled: root.visible
        hoverEnabled: true
        cursorShape: Qt.PointingHandCursor
        onClicked: root.activated()
    }

    ToolTip.visible: pointer.containsMouse && root.visible
    ToolTip.delay: 500
    ToolTip.text: root.tooltipText
}
