// Loading Component Class
import { loadingIcon } from "../../assets/icons/index.js";

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

    this.init();
  }

  init() {
    this.createElements();
    this.setupEventListeners();
  }

  createElements() {
    // Create loading overlay
    this.container = document.createElement("div");
    this.container.className = "pp-loading";

    // Create loading spinner
    this.spinner = document.createElement("div");
    this.spinner.className = "pp-loading-spinner";
    this.spinner.innerHTML = loadingIcon;

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

  setupEventListeners() {
    // Event listeners for loading states
    this.player.on("loadstart", () => this.showLoading());
    this.player.on("canplay", () => this.hideLoading());
    this.player.on("seeking", () => this.showLoading());
    this.player.on("seeked", () => this.hideLoading());
    this.player.on("waiting", () => this.showLoading());
    // this.player.on("stalled", () => this.showLoading());
    this.player.on("play", () => this.hideLoading());
    this.player.on("playing", () => this.hideLoading());
    this.player.on("pause", () => this.hideLoading());
    this.player.on("ended", () => this.hideLoading());
    this.player.on("error", () => this.hideLoading());
  }

  preventPlayerClicks(e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }

  showLoading() {
    this.container.style.display = "flex";
    // Prevent player clicks when loading
    this.player.on("click", this.preventPlayerClicks.bind(this), true);
  }

  hideLoading() {
    this.container.style.display = "none";
    // Re-enable player clicks when not loading
    this.player.off("click", this.preventPlayerClicks.bind(this), true);
  }

  cleanup() {
    this.player.off("loadstart", () => this.showLoading());
    this.player.off("canplay", () => this.hideLoading());
    this.player.off("seeking", () => this.showLoading());
    this.player.off("seeked", () => this.hideLoading());
    this.player.off("waiting", () => this.showLoading());
    // this.player.off("stalled", () => this.showLoading());
    this.player.off("play", () => this.hideLoading());
    this.player.off("playing", () => this.hideLoading());
    this.player.off("pause", () => this.hideLoading());
    this.player.off("ended", () => this.hideLoading());
    this.player.off("error", () => this.hideLoading());

    // Remove click prevention listeners
    this.player.off("click", this.preventPlayerClicks.bind(this), true);
  }
}
