// Subtitle Toggle Component Class
import { clpp } from "@castlabs/prestoplay";
import { createButton } from "../../../utils/buttonFactory.js";

export class SubtitleToggleComponent {
  constructor(player) {
    this.player = player;

    this.container = null;
    this.subtitleToggleBtn = null;
    this.subtitleIndicator = null;

    this.init();
  }

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

  createElements() {
    // Create subtitle toggle wrapper
    this.container = document.createElement("div");
    this.container.className = "pp-subtitle-toggle-container";

    // Create subtitle toggle button
    this.subtitleToggleBtn = createButton(
      "subtitle-toggle",
      "Subtitles/CC",
      () => this.toggleSubtitle()
    );

    // Add red line indicator for active subtitle
    this.subtitleIndicator = document.createElement("div");
    this.subtitleIndicator.className = "pp-subtitle-indicator";

    this.container.appendChild(this.subtitleToggleBtn);
    this.subtitleToggleBtn.appendChild(this.subtitleIndicator);

    // Hide subtitle toggle button by default (will be shown if tracks are available)
    this.container.style.display =
      this.player.getTrackManager()?.getTextTracks()?.length > 0
        ? "block"
        : "none";
  }

  updateSubtitleToggleState() {
    try {
      this.subtitleIndicator.style.opacity = this.player
        .getTrackManager()
        ?.getTextTrack()
        ? "1"
        : "0";
    } catch (e) {
      console.error("Failed to get subtitle state:", e);
    }
  }

  toggleSubtitle() {
    try {
      const trackManager = this.player.getTrackManager();
      if (trackManager.getTextTracks().length > 0) {
        const textTrack = trackManager.getTextTrack()
          ? null
          : trackManager.getTextTracks()[0];
        trackManager.setTextTrack(textTrack);
      }
    } catch (err) {
      console.error("Failed to toggle subtitle:", err);
    }

    this.subtitleTimeout = setTimeout(
      this.updateSubtitleToggleState.bind(this),
      100
    );
  }

  setupEventListeners() {
    this.player.on(
      clpp.events.TEXT_TRACK_CHANGED,
      this.updateSubtitleToggleState.bind(this)
    );
  }

  cleanup() {
    if (this.subtitleTimeout) {
      clearTimeout(this.subtitleTimeout);
    }
    this.player.off(
      clpp.events.TEXT_TRACK_CHANGED,
      this.updateSubtitleToggleState.bind(this)
    );
  }
}
