import videojs from "video.js";
import { DISPLAY_FORMAT } from "../constants/displayFormat.js";
import "../styles/replay-overlay.css";

const Component = videojs.getComponent("Component");

/**
 * Centered replay control shown after playback ends.
 * Uses the Video.js icon font `vjs-icon-replay`
 * (https://videojs.github.io/font/).
 */
class ReplayOverlay extends Component {
  constructor(player, options) {
    super(player, options);

    // this.on(...) auto-unbinds on dispose.
    this.on(player, "ended", this.handleEnded);
    this.on(player, "play", this.hide);
    this.on(player, "loadstart", this.hide);
    this.on(player, "error", this.hide);
    this.on(player, "seeking", this.handleSeeking);
    this.on("click", this.handleClick);
  }

  createEl() {
    const el = super.createEl("button", {
      className: "videojs-drm-replay-overlay",
      type: "button",
    });
    el.setAttribute("aria-label", this.localize("replay"));
    el.style.display = "none";
    // Icon from Video.js font: https://videojs.github.io/font/
    el.innerHTML = `<span class="vjs-icon-replay" aria-hidden="true"></span>`;
    return el;
  }

  /**
   * Normal video always qualifies. Audio-only only when there is a black
   * content band (displayFormat VIDEO_AREA / 2).
   */
  canShow() {
    const player = this.player();
    if (!player || (typeof player.error === "function" && player.error())) {
      return false;
    }
    if (player.options_?.audioOnlyMode) {
      return player.options_?.displayFormat === DISPLAY_FORMAT.VIDEO_AREA;
    }
    return true;
  }

  handleEnded() {
    this.show();
  }

  handleSeeking() {
    if (!this.player().ended()) {
      this.hide();
    }
  }

  show() {
    if (!this.canShow() || !this.el()) {
      return;
    }
    this.el().style.display = "flex";
    this.player().addClass("vjs-has-replay-overlay");
  }

  hide() {
    if (!this.el()) {
      return;
    }
    this.el().style.display = "none";
    this.player().removeClass("vjs-has-replay-overlay");
  }

  handleClick(event) {
    event.preventDefault();
    event.stopPropagation();

    const player = this.player();
    this.hide();
    player.currentTime(0);
    const playPromise = player.play();
    if (playPromise && typeof playPromise.catch === "function") {
      playPromise.catch(() => {
        // Autoplay / gesture restrictions; user can retry via control bar.
      });
    }
  }
}

videojs.registerComponent("ReplayOverlay", ReplayOverlay);

export default ReplayOverlay;
