import videojs from 'video.js';
import {
  replayIcon,
  pauseIcon,
  playIcon,
} from "../../../assets/icons/index.js";
import '../../../styles/play-button.css';

const Button = videojs.getComponent('Button');

class PlayButton extends Button {
  constructor(player, options) {
    super(player, options);
    this.controlText(this.localize("playPause"));

    // this.on(...) auto-unbinds on dispose. seeking/seeked keep the icon in
    // sync when the user scrubs away from (or back to) the ended state —
    // play/pause/ended alone are not enough because seek does not always
    // emit those events.
    this.on(player, 'play', this.updatePlayButton);
    this.on(player, 'pause', this.updatePlayButton);
    this.on(player, 'ended', this.updatePlayButton);
    this.on(player, 'seeking', this.updatePlayButton);
    this.on(player, 'seeked', this.updatePlayButton);
    this.on(player, 'loadstart', this.updatePlayButton);

    this.updatePlayButton();
  }

  createEl() {
    const el = super.createEl('button', {
      className: 'videojs-drm-button videojs-drm-play-button'
    });
    
    el.innerHTML = playIcon;
    
    return el;
  }

  handleClick() {
    const player = this.player();

    // After ended, a plain play() is ambiguous across browsers; restart
    // explicitly so the control stays aligned with ReplayOverlay.
    if (player.ended()) {
      player.currentTime(0);
      player.play();
      return;
    }

    if (player.paused()) {
      player.play();
    } else {
      player.pause();
    }
  }

  updatePlayButton() {
    if (!this.el()) {
      return;
    }

    this.el().innerHTML = this.player().ended()
      ? replayIcon
      : this.player().paused()
      ? playIcon
      : pauseIcon;
  }
}

// Register the component
videojs.registerComponent('PlayButton', PlayButton);

export default PlayButton;
