Skip to content
import QtQuick
import Quickshell
import Quickshell.Io
import qs.Commons
import qs.Ui

BarWidget {
  id: root

  moduleName: "notify.desktop"

  readonly property int flashMillis: root.setting("flashSeconds", 6) * 1000
  readonly property string statePath: Quickshell.env("HOME") + "/.local/state/omarchy/notify-desktop/latest.json"

  property var latest: null
  property bool flashing: false

  readonly property bool emergency: latest && latest.kind === "emergency"

  // ---- Panel contract (shape expected by bar.summon/hide/toggle routing)
  readonly property bool opened: panelLoader.item ? panelLoader.item.opened === true : false

  function open() {
    if (panelLoader.item) panelLoader.item.open()
  }

  function close() {
    if (panelLoader.item) panelLoader.item.close()
  }

  function togglePanel() {
    if (panelLoader.item) panelLoader.item.toggle()
  }

  function injectPanel() {
    var target = panelLoader.item
    if (!target) return
    if ("bar" in target) target.bar = root.bar
    if ("settings" in target) target.settings = root.settings
    if ("anchorItem" in target) target.anchorItem = button
    if ("hostWidget" in target) target.hostWidget = root
  }

  implicitWidth: button.implicitWidth
  implicitHeight: button.implicitHeight

  onBarChanged: injectPanel()
  onSettingsChanged: injectPanel()

  FileView {
    id: latestFile
    path: root.statePath
    watchChanges: true
    printErrors: false
    onFileChanged: reload()
    onLoaded: root.parseLatest(text())
  }

  function parseLatest(content) {
    try {
      var parsed = JSON.parse(String(content || ""))
      root.latest = parsed && typeof parsed === "object" ? parsed : null
    } catch (e) {
      root.latest = null
    }
    if (root.latest) {
      root.flashing = true
      flashTimer.restart()
    }
  }

  Timer {
    id: flashTimer
    interval: root.flashMillis > 0 ? root.flashMillis : 6000
    onTriggered: root.flashing = false
  }

  Loader {
    id: panelLoader
    active: true
    source: Qt.resolvedUrl("Panel.qml")
    visible: false
    onLoaded: {
      root.injectPanel()
      Qt.callLater(root.injectPanel)
    }
  }

  IpcHandler {
    target: "notify.desktop"

    function open(): void { root.open() }
    function close(): void { root.close() }
    function show(): void { root.open() }
    function hide(): void { root.close() }
    function toggle(): void { root.togglePanel() }
  }

  BarIconButton {
    id: button
    anchors.fill: parent
    bar: root.bar
    text: root.emergency ? "\uF06A" : "\uF004"
    active: root.flashing
    activeColor: root.emergency ? (root.bar ? root.bar.urgent : Color.urgent) : Color.accent
    tooltipText: root.latest && root.latest.message ? root.latest.message : "Notify"
    onPressed: function() {
      root.togglePanel()
    }
  }
}