import { clpp } from "@castlabs/prestoplay";
import "@castlabs/prestoplay/cl.core";
import "@castlabs/prestoplay/cl.mse";
import "@castlabs/prestoplay/cl.dash";
import "@castlabs/prestoplay/cl.hls";
import "@castlabs/prestoplay/cl.smooth";
import "@castlabs/prestoplay/cl.vtt";
import "@castlabs/prestoplay/cl.ttml";
import "@castlabs/prestoplay/cl.htmlcue";
import "@castlabs/prestoplay/clpp.styles.css";
import "./styles/index.css";
import { ControlBarComponent } from "./components/control-bar/control-bar.js";
import { TopBarComponent } from "./components/top-bar/top-bar.js";
import { LoadingComponent } from "./components/loading/loading.js";

class PrestoPlayDRMPlayer {
  constructor(options = {}) {
    if (!options.containerId) {
      throw new Error("containerId is required");
    }
    if (!options.source) {
      throw new Error("source is required");
    }
    if (!options.prestoplayCred?.license || !options.prestoplayCred?.viewerId) {
      throw new Error(
        "license and viewerId is required to initilize a PRESTOplay player"
      );
    }
    if (
      options.isDRM &&
      (!options.drmConfig || !Object.keys(options.drmConfig).length)
    ) {
      throw new Error("drmConfig parameter is required if isDRM is true");
    }

    this.options = {
      isDRM: false,
      width: "100%",
      height: "auto",
      ...options,
    };

    this.init();
  }

  init() {
    this.container = document.getElementById(this.options.containerId);
    if (!this.container)
      throw new Error(
        `Container with id "${this.options.containerId}" not found`
      );

    this.container.innerHTML = "";
    this.container.className = "drm-clpp-container";
    this.container.style.width = this.options.width;
    this.container.style.height = this.options.height;

    this.video = document.createElement("video");

    // Ensure no controls attribute is set (prevents iOS Safari built-in controls)
    this.video.removeAttribute("controls");
    this.video.setAttribute("playsinline", "");
    this.video.setAttribute("webkit-playsinline", "");
    this.video.setAttribute("x-webkit-airplay", "allow");

    this.container.appendChild(this.video);

    clpp.install(clpp.dash.DashComponent);
    clpp.install(clpp.hls.HlsComponent);
    clpp.install(clpp.smooth.SmoothComponent);

    clpp.install(clpp.vtt.VttComponent);
    clpp.install(clpp.ttml.TtmlComponent);
    clpp.install(clpp.htmlcue.HtmlCueComponent);

    this.player = new clpp.Player(this.video, this.options.prestoplayCred);

    try {
      // Load video
      const options = this.getPrestoPlayOptions();
      this.player.load(options);

      // Check if content is audio-only and adjust UI accordingly
      this.player.on(clpp.events.LOADEDMETADATA, () => {
        const trackManager = this.player.getTrackManager();
        const videoTracks = trackManager.getVideoTracks();
        const audioTracks = trackManager.getAudioTracks();
        if (audioTracks.length > 0 && videoTracks.length === 0) {
          this.container.classList.add("audio-only");
        }
        // TODO: Update audio-only's 4 UI formats

        setTimeout(() => {
          // Loading component
          this.loadingComponent = new LoadingComponent(this.player);
          if (this.loadingComponent) {
            this.video.parentNode?.appendChild(this.loadingComponent.container);
          }

          // Create custom controls
          this.controlBarComponent = new ControlBarComponent(
            this.player,
            this.video,
            this.container
          );
          if (this.controlBarComponent) {
            this.container.appendChild(this.controlBarComponent.container);
          }

          // TODO: Add top bar component and its fullscreen behavior
          // // Setup title detection after subtitles
          // this.topBarComponent = new TopBarComponent(this.options.title);
          // if (this.topBarComponent) {
          //   this.container.appendChild(this.topBarComponent.container);
          // }
        }, 1000);
      });
    } catch (err) {
      console.error("PRESTOplay load error:", err);
    }
  }

  getPrestoPlayOptions() {
    const options = { ...this.options };
    delete options.containerId;
    delete options.isDRM;

    if (this.options.isDRM && this.options.drmConfig) {
      options.drm = options.drmConfig;
    }
    delete options.drmConfig;

    return options;
  }

  play() {
    this.player?.play();
  }

  pause() {
    this.player?.pause();
  }

  stop() {
    this.player?.pause();
    this.player?.seek(0);
  }

  dispose() {
    this.container.classList.remove("audio-only");

    this.loadingComponent?.cleanup();
    this.controlBarComponent?.cleanup();
    // this.topBarComponent?.cleanup();

    this.player?.destroy();
    this.player = null;

    if (this.container) {
      this.container.innerHTML = "";
    }
  }
}

export default PrestoPlayDRMPlayer;
