import Quickshell
import Quickshell.Io
import QtQuick

BarPill {
    id: root
    layer.enabled: true

    property int currentIdx: 0
    property var names: []

    readonly property string shortName: {
        if (names.length === 0) return "??"
        const n = names[currentIdx] ?? ""
        if (n.includes("Portuguese")) return "PT"
        if (n.includes("English"))    return "EN"
        // fallback: first two chars of first word
        return n.split(" ")[0].substring(0, 2).toUpperCase()
    }

    Process {
        command: ["niri", "msg", "--json", "event-stream"]
        running: true
        stdout: SplitParser {
            splitMarker: "\n"
            onRead: data => {
                try {
                    const ev = JSON.parse(data)
                    if (ev.KeyboardLayoutsChanged) {
                        const kl = ev.KeyboardLayoutsChanged.keyboard_layouts
                        root.currentIdx = kl.current_idx
                        root.names      = kl.names
                    } else if (ev.KeyboardLayoutSwitched) {
                        root.currentIdx = ev.KeyboardLayoutSwitched.idx
                    }
                } catch (e) {}
            }
        }
    }

    Text {
        text:           "󰌌"
        color:          Theme.purple
        font.pixelSize: Theme.fontSize
        font.family:    Theme.font
    }
    Text {
        id:             shortNameText
        text:           root.shortName
        color:          Theme.text
        font.pixelSize: Theme.fontSize
        font.family:    Theme.font

        Behavior on text {
            // Flash the label on layout change
            SequentialAnimation {
                PropertyAnimation { target: shortNameText; property: "opacity"; to: 0; duration: 80 }
                PropertyAction    { target: shortNameText; property: "text" }
                PropertyAnimation { target: shortNameText; property: "opacity"; to: 1; duration: 80 }
            }
        }
    }
}
