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

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

  return (
    <box class="media-module">
      <For each={players}>
        {(player) => {
          const title = createBinding(player, "title")
          const artist = createBinding(player, "artist")
          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
            // truncate long titles
            return display.length > 40
              ? display.substring(0, 37) + "..."
              : 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>
  )
}
