// Title Handler for PRESTOplay
import { shareIcon, checkIcon } from "../../assets/icons/index.js";

export class TopBarComponent {
  constructor(title) {
    this.title = title ?? "";

    this.init();
  }

  init() {
    this.createElements();
  }

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

    // Create title text
    this.titleText = document.createElement("div");
    this.titleText.textContent = this.title;
    this.titleText.className = "pp-title";

    // Create share button
    this.shareButton = document.createElement("button");
    this.shareButton.className = "pp-share-button";
    this.shareButton.title = "Share";
    this.shareButton.innerHTML = `
      ${shareIcon}
      <span>Share</span>
    `;

    this.shareButtonClickHandler = async (e) => {
      e.stopPropagation();

      try {
        // Get current video URL
        const videoUrl = window.location.href;

        // Copy to clipboard
        await navigator.clipboard.writeText(videoUrl);

        // Show success feedback
        const originalHTML = this.shareButton.innerHTML;
        this.shareButton.innerHTML = `
          ${checkIcon}
          <span>Copied!</span>
        `;

        // Reset after 2 seconds
        this.shareTimeout = setTimeout(() => {
          this.shareButton.innerHTML = originalHTML;
          this.shareButton.title = "Share";
        }, 2000);
      } catch (error) {
        console.error("Failed to copy link:", error);
      }
    };

    this.container.appendChild(this.titleText);
    this.container.appendChild(this.shareButton);

    this.shareButton.addEventListener("click", this.shareButtonClickHandler);
  }

  showTitle() {
    this.container.style.opacity = "1";
  }

  hideTitle() {
    this.container.style.opacity = "0";
  }

  cleanup() {
    if (this.shareTimeout) {
      clearTimeout(this.shareTimeout);
    }
    this.shareButton.removeEventListener("click", this.shareButtonClickHandler);
  }
}
