import AstalMpris from "gi://AstalMpris"
import { createBinding, For } from "ags"

export default function Media() {
  const mpris = AstalMpris.get_default()
  const players = createBinding(mpris, "players")

  // Filter to only show non-playerctld players
  const filtered = players((list: AstalMpris.Player[]) =>
    list.filter((p) => p.busName && !p.busName.includes("playerctld")).slice(0, 1)
  )

  return (
    <box class="media-module">
      <For each={filtered}>
        {(player) => {
          const title = createBinding(player, "title")
          const status = createBinding(player, "playbackStatus")

          const icon = status((s: AstalMpris.PlaybackStatus) =>
            s === AstalMpris.PlaybackStatus.PLAYING ? "▶" : "⏸"
          )

          const label = title((t: string) => {
            const a = player.artist
            const display = a ? `${a} — ${t}` : t
            return display.length > 45
              ? display.substring(0, 42) + "..."
              : display
          })

          const cls = status((s: AstalMpris.PlaybackStatus) =>
            s === AstalMpris.PlaybackStatus.PLAYING ? "media" : "media paused"
          )

          return (
            <box class={cls}>
              <button class="media-prev" onClicked={() => player.previous()}>
                <label label="⏮" />
              </button>
              <button class="media-play" onClicked={() => player.play_pause()}>
                <label label={icon} />
              </button>
              <button class="media-next" onClicked={() => player.next()}>
                <label label="⏭" />
              </button>
              <label class="media-text" label={label} />
            </box>
          )
        }}
      </For>
    </box>
  )
}
