// Play/Pause Button Component Class
import {
  replayIcon,
  pauseIcon,
  playIcon,
} from "../../../assets/icons/index.js";
import { createButton } from "../../../utils/buttonFactory.js";

export class PlayPauseComponent {
  constructor(player) {
    this.player = player;
    this.container = null;
    this.playPauseBtn = null;

    this.init();
  }

  init() {
    this.createButton();
    this.setupEventListeners();
    this.updateButton();
  }

  createButton() {
    this.container = document.createElement("div");
    this.container.className = "pp-play-container";

    this.playPauseBtn = createButton("play", "Play / Pause", () => {
      if (this.player.isPaused() || this.player.isEnded()) {
        this.player.play();
      } else {
        this.player.pause();
      }
    });

    this.container.appendChild(this.playPauseBtn);
  }

  updateButton() {
    this.playPauseBtn.innerHTML = this.player.isEnded()
      ? replayIcon
      : this.player.isPaused()
      ? playIcon
      : pauseIcon;
    this.playPauseBtn.title = this.player.isEnded()
      ? "Replay"
      : this.player.isPaused()
      ? "Play"
      : "Pause";
  }

  setupEventListeners() {
    this.handleUpdateButton = this.updateButton.bind(this);

    this.player.on("play", this.handleUpdateButton);
    this.player.on("pause", this.handleUpdateButton);
    this.player.on("ended", this.handleUpdateButton);
  }

  cleanup() {
    if (this.handleUpdateButton) {
      this.player.off("play", this.handleUpdateButton);
      this.player.off("pause", this.handleUpdateButton);
      this.player.off("ended", this.handleUpdateButton);
      this.handleUpdateButton = null;
    }
  }
}
