import QtQuick
import Quickshell
import Quickshell.Wayland
import "../config" as Cfg

PanelWindow {
    id: popup

    property string ns: ""
    property var    chipRoot: null
    property int    cardWidth: 260
    property bool   hasKeyboardFocus: false

    property alias clipItem: popupClip
    default property alias content: popupClip.data

    screen:  chipRoot ? chipRoot.targetScreen : null
    visible: false
    color:   "transparent"

    property bool popupOpen: false
    property real popupCenterX: -1

    function _doOpen() { hideTimer.stop(); visible = true; popupOpen = true }
    function open()   {
        if (popupCenterX < 0 && chipRoot)
            popupCenterX = chipRoot.mapToItem(null, 0, 0).x + chipRoot.width / 2
        _doOpen()
    }
    function close()  { popupOpen = false; hideTimer.restart() }
    function toggle() { popupOpen ? close() : open() }

    PopupHideTimer {
        id: hideTimer
        onTriggered: popup.visible = false
    }

    anchors { top: true; bottom: true; left: true; right: true }
    WlrLayershell.layer:         WlrLayer.Top
    WlrLayershell.namespace:     "main-shell-" + ns
    WlrLayershell.exclusiveZone: -1
    WlrLayershell.keyboardFocus: hasKeyboardFocus ? WlrKeyboardFocus.OnDemand : WlrKeyboardFocus.None
    mask: popupOpen ? null : _noInput
    Region { id: _noInput }

    MouseArea { anchors.fill: parent; onClicked: popup.close() }

    Item {
        id: popupClip
        property int screenPad: chipRoot ? chipRoot.barMargin + 10 : 30

        x: {
            if (!chipRoot && popupCenterX < 0) return 0
            let cx = popupCenterX >= 0 ? popupCenterX : chipRoot.mapToItem(null, 0, 0).x + chipRoot.width / 2
            return Math.max(screenPad, Math.min(cx - cardWidth / 2, parent.width - cardWidth - screenPad))
        }
        width: cardWidth

        anchors.top:          chipRoot && chipRoot.isTop ? parent.top    : undefined
        anchors.bottom:       chipRoot && chipRoot.isTop ? undefined     : parent.bottom
        anchors.topMargin:    chipRoot && chipRoot.isTop ? (chipRoot.barHeight + 10) : 0
        anchors.bottomMargin: chipRoot && chipRoot.isTop ? 0 : (chipRoot.barHeight + 10)
        height: chipRoot ? parent.height - chipRoot.barHeight - 10 : parent.height

        clip: true
    }
}
