import Quickshell
import Quickshell.Services.UPower
import QtQuick
import QtQuick.Layouts
import "../shared" as Shared

// Bar pill for the battery popout. Shows the composite battery icon + charge
// percentage, tinted by level and charging state. Only mounted when
// Config.hasBattery (laptop-only).
BarPill {
    id: root
    groupName: "battery"

    readonly property var bat: UPower.displayDevice
    readonly property bool charging: bat
        && (bat.state === UPowerDeviceState.Charging
            || bat.state === UPowerDeviceState.FullyCharged
            || bat.state === UPowerDeviceState.PendingCharge)
    readonly property int pct: bat ? Math.round(bat.percentage * 100) : 0

    // nf-md battery glyphs. Discharge buckets (full + 10..90) are contiguous;
    // charging uses the single generic charging glyph for reliability.
    function iconFor(p, chg) {
        if (chg) return "\u{f0084}";              // nf-md-battery_charging
        if (p <= 5) return "\u{f0083}";           // nf-md-battery_alert
        if (p >= 95) return "\u{f0079}";          // nf-md-battery (full)
        // 10..90 → f007a..f0082
        const bucket = Math.max(1, Math.min(9, Math.round(p / 10)));
        return String.fromCodePoint(0xf007a + (bucket - 1));
    }

    accentColor: charging
        ? Shared.Theme.green
        : (pct <= 15 ? Shared.Theme.red
            : pct <= 30 ? Shared.Theme.yellow
            : Shared.Theme.blue)

    content: [
        Text {
            Layout.alignment: Qt.AlignHCenter
            text: root.iconFor(root.pct, root.charging)
            color: root.accentColor
            font.pixelSize: Shared.Theme.fontLarge
            font.family: Shared.Theme.iconFont
        },
        Text {
            Layout.alignment: Qt.AlignHCenter
            text: root.pct.toString()
            color: Shared.Theme.text
            font.pixelSize: Shared.Theme.fontSmall
            font.family: Shared.Theme.fontFamily
            font.bold: true
        }
    ]
}
