import QtQuick
import QtQuick.Layouts
import Quickshell.Hyprland

import "../../config" as Cfg
import "../../components"

ModuleChip {
    id: root

    width:  workspaceLayout.implicitWidth + 24
    height: Cfg.Config.moduleHeight
    chipColor:       t.wsPanelBg
    chipBorderColor: t.wsPanelBorder

    property string activeSpecial: ""
    property string lastActiveName: ""

    Connections {
        target: Hyprland
        function onRawEvent(event) {
            if (event.name === "activespecial") {
                var name = event.data.split(",")[0]
                root.activeSpecial = name
            }
            if (event.name === "workspace") {
                root.lastActiveName = event.data
            }
        }
    }

    RowLayout {
        id: workspaceLayout
        anchors.centerIn: parent
        spacing: 6

        Repeater {
            model: Hyprland.workspaces

            Rectangle {
                id: wsPill

                visible: modelData.name !== "special:magic"

                property bool isSelected: modelData.active || (root.activeSpecial !== "" && modelData.name === root.lastActiveName)

                Layout.preferredWidth:  isSelected ? 34 : 28
                Layout.preferredHeight: 22
                radius: 11

                color: {
                    if (isSelected && root.activeSpecial !== "") {
                        return root.t.wsMagicActiveBg
                    }
                    if (modelData.active) {
                        return root.t.wsActiveBg
                    }
                    return wsHover.hovered ? root.t.wsHoverBg : root.t.wsInactiveBg
                }

                Behavior on color                 { ColorAnimation  { duration: 200 } }
                Behavior on Layout.preferredWidth { NumberAnimation { duration: 200 } }

                Text {
                    anchors.centerIn: parent
                    text: modelData.name
                    font.pixelSize: 11
                    font.bold: true
                    color: {
                        if (isSelected && root.activeSpecial !== "") {
                            return root.t.wsMagicActiveText
                        }
                        if (modelData.active) {
                            return root.t.wsActiveText
                        }
                        return wsHover.hovered ? root.t.wsHoverText : root.t.wsInactiveText
                    }
                }

                HoverHandler { id: wsHover; cursorShape: Qt.PointingHandCursor }
                TapHandler   { onTapped: modelData.activate() }
            }
        }
    }
}
