<template>
  <iframe v-if="videoId && !loadError" width="100%" height="843.75px" :src="embedUrl" frameborder="0" referrerpolicy="strict-origin-when-cross-origin" sandbox="allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen @error="handleError"></iframe>
  <div v-else style="text-align: center;">
    <img src="client/resources/images/no_media.png" alt="미디어를 표시할 수 없습니다" style="width: auto; height: auto;" />
  </div>
</template>
<script>
export default {
  name: 'YoutubePlayer',

  props: {
    link: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      loadError: false
    }
  },

  computed: {
    videoId() {
      if (!this.link) {
        this.loadError = true;
        return null;
      }

      try {
        let id = null;

        // 일반 YouTube URL (youtube.com/watch?v=VIDEO_ID)
        if (this.link.includes('youtube.com/watch')) {
          const url = new URL(this.link);
          id = url.searchParams.get('v');
        }

        // 단축 URL (youtu.be/VIDEO_ID)
        else if (this.link.includes('youtu.be/')) {
          const parts = this.link.split('youtu.be/');
          if (parts.length > 1) {
            id = parts[1].split('?')[0].split('&')[0];
          }
        }

        // 임베드 URL (youtube.com/embed/VIDEO_ID)
        else if (this.link.includes('youtube.com/embed/')) {
          const parts = this.link.split('youtube.com/embed/');
          if (parts.length > 1) {
            id = parts[1].split('?')[0].split('&')[0];
          }
        }

        if (!id) {
          this.loadError = true;
          return null;
        }

        return id;
      } catch (e) {
        console.error('YouTube URL 파싱 오류:', e);
        this.loadError = true;
        return null;
      }
    },

    embedUrl() {
      if (!this.videoId) return '';
      return `https://www.youtube-nocookie.com/embed/${this.videoId}?rel=0&modestbranding=1&origin=${encodeURIComponent(window.location.origin)}`;
    }
  },

  methods: {
    handleError() {
      console.error('YouTube 비디오 로드 실패');
      this.loadError = true;
    }
  },

  mounted() {
    if (this.videoId) {
      const checkIframeLoaded = setTimeout(() => {
        const iframe = this.$el.querySelector('iframe');
        if (iframe) {
          const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
          if (!iframeDoc) {
            this.loadError = true;
          }
        }
        clearTimeout(checkIframeLoaded);
      }, 5000); // 5초 타임아웃
    }
  },

  watch: {
    link() {
      this.loadError = false;
    }
  }
}
</script>