<script>
// YouTube 링크 필터링 및 임베드 스크립트
const youtubeDomains = [
  'youtube\\.com',
  'youtu\\.be',
  'www\\.youtube\\.com'
];
// 복잡한 필터링을 위한 정규 표현식들
const EXCLUDE_CONTAINER_REGEX = /(<div[^>]*class="[^"]*(ke-component|ke-video-container|se-float-none)[^"]*"[^>]*>.*?<\/div>)/gis;
const YOUTUBE_LINK_REGEX = new RegExp(`(https?:\\/\\/)?(?:${youtubeDomains.join('|')})\\/(shorts\\/|watch\\?v=|embed\\/|)([\\w-]+)`, 'gi');

function createVideoEmbed(uniqueVideoId) {
  const supportsObject = (function () {
    try {
      return 'object' in document.createElement('object') && 
             'data' in document.createElement('object');
    } catch (e) {
      return false;
    }
  })();

  const containerStyle = `
    position: relative; 
    width: 100%; 
    max-width: 750px; /* 최대 가로길이 750px */
    margin: 0 auto;
  `;
  const ratioContainerStyle = `
    position: relative; 
    width: 100%; 
    padding-top: 56.25%; /* 16:9 비율 */
    margin: 0 auto;
  `;
  const embedStyle = `
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    border: 0;
  `;

  if (supportsObject) {
    return `
      <div class="video-container" style="${containerStyle}">
        <div style="${ratioContainerStyle}">
          <object data="https://www.youtube.com/embed/${uniqueVideoId}" style="${embedStyle}" type="text/html" allowfullscreen>
            <iframe 
              src="https://www.youtube.com/embed/${uniqueVideoId}" 
              style="${embedStyle}" 
              allowfullscreen>
            </iframe>
          </object>
        </div>
      </div>
    `;
  } else {
    return `
      <div class="video-container" style="${containerStyle}">
        <div style="${ratioContainerStyle}">
          <iframe 
            src="https://www.youtube.com/embed/${uniqueVideoId}" 
            style="${embedStyle}" 
            allowfullscreen>
          </iframe>
        </div>
      </div>
    `;
  }
}

function processContent(content) {
  // 제외할 컨테이너 내부의 모든 YouTube 링크 처리 방지
  const filteredContent = content.replace(EXCLUDE_CONTAINER_REGEX, (match) => {
    return match.replace(YOUTUBE_LINK_REGEX, (link) => link);
  });

  // 필터링된 컨테이너 외부의 YouTube 링크만 처리
  return filteredContent.replace(/<a[^>]*href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gi, (match, href, text) => {
    const youtubeMatch = href.match(YOUTUBE_LINK_REGEX);
    if (youtubeMatch) {
      const uniqueVideoId = youtubeMatch[3] || 
        (href.includes('youtu.be/') ? href.split('/').pop() : 
        (href.includes('v=') ? href.split('v=')[1].split('&')[0] : ''));
      return createVideoEmbed(uniqueVideoId);
    }
    // 유튜브 링크가 아닌 경우 원본 링크 유지
    return match;
  });
}

// 본문 처리
const boVCon = document.getElementById('bo_v_con');
if (boVCon) {
  boVCon.innerHTML = processContent(boVCon.innerHTML);
}

// 댓글 처리
const cmtContents = document.querySelectorAll('.cmt_contents');
cmtContents.forEach(cmt => {
  cmt.innerHTML = processContent(cmt.innerHTML);
});
</script>
