import app from "ags/gtk3/app"
import { Astal, Gtk, Gdk } from "ags/gtk3"
import Clock from "./modules/Clock"
import Battery from "./modules/Battery"
import Volume from "./modules/Volume"
import Network from "./modules/Network"
import SystemStats from "./modules/SystemStats"
import Media from "./modules/Media"
import SysTray from "./modules/SysTray"
import Prompt from "./modules/Prompt"

export default function Bar(gdkmonitor: Gdk.Monitor) {
  const { TOP, LEFT, RIGHT } = Astal.WindowAnchor

  let hideTimeout: number | null = null

  function scheduleHide(win: Astal.Window) {
    if (hideTimeout) clearTimeout(hideTimeout)
    hideTimeout = setTimeout(() => {
      win.visible = false
      hideTimeout = null
    }, 800)
  }

  function cancelHide() {
    if (hideTimeout) {
      clearTimeout(hideTimeout)
      hideTimeout = null
    }
  }

  return (
    <window
      class="Bar"
      name="bar"
      visible={false}
      gdkmonitor={gdkmonitor}
      exclusivity={Astal.Exclusivity.EXCLUSIVE}
      anchor={TOP | LEFT | RIGHT}
      application={app}
      layer={Astal.Layer.TOP}
    >
      <eventbox
        onHover={() => cancelHide()}
        onHoverLost={(self) => {
          const win = self.get_toplevel() as Astal.Window
          scheduleHide(win)
        }}
      >
        <centerbox>
          <box $type="start" class="modules-left" halign={Gtk.Align.START}>
            <Prompt />
            <label class="separator" label="│" />
            <SystemStats />
            <label class="separator" label="│" />
            <Media />
          </box>
          <box $type="center" class="modules-center">
            <Clock />
          </box>
          <box $type="end" class="modules-right" halign={Gtk.Align.END}>
            <SysTray />
            <label class="separator" label="│" />
            <Network />
            <label class="separator" label="│" />
            <Volume />
            <label class="separator" label="│" />
            <Battery />
          </box>
        </centerbox>
      </eventbox>
    </window>
  )
}
