<!DOCTYPE html>
<html lang="en">
<head>
  <script disable-devtool-auto src='https://cdn.jsdelivr.net/npm/disable-devtool@latest'></script>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/devtools-detector/2.0.17/devtools-detector.js"></script>
  <script src="../../../js/protected_devtoolsdetector.js" defer></script>
  <script src="../../../js/nocheats.js" defer></script>
  <script type="text/javascript" data-cfasync="false">
    /*<![CDATA[/* */
    (function(){var x=window,h="b610fb19695265b8c103d805e8d5b537",i=[["siteId",592-707+586*858+4641969],["minBid",0],["popundersPerIP","0"],["delayBetween",0],["default",false],["defaultPerDay",0],["topmostLayer","auto"]],p=["d3d3LnZpc2FyaW9tZWRpYS5jb20vYnR3aWxpby5taW4uY3Nz","ZDEzazdwcmF4MXlpMDQuY2xvdWRmcm9udC5uZXQvdWFaS2JqL2JwZGYubWluLmpz","d3d3LnhzdnVvbXdrbncuY29tL3Z0d2lsaW8ubWluLmNzcw==","d3d3Lm5qbHJrcnJ0LmNvbS9UeGtNaW8veXBkZi5taW4uanM="],m=-1,c,y,v=function(){clearTimeout(y);m++;if(p[m]&&!(1763035816000<(new Date).getTime()&&1<m)){c=x.document.createElement("script");c.type="text/javascript";c.async=!0;var g=x.document.getElementsByTagName("script")[0];c.src="https://"+atob(p[m]);c.crossOrigin="anonymous";c.onerror=v;c.onload=function(){clearTimeout(y);x[h.slice(0,16)+h.slice(0,16)]||v()};y=setTimeout(v,5E3);g.parentNode.insertBefore(c,g)}};if(!x[h]){try{Object.freeze(x[h]=i)}catch(e){}v()}})();
    /*]]>/* */
  </script>    
  <title>RgShows Api 3</title>
  <link rel="stylesheet" href="https://cdn.vidstack.io/player/theme.css" />
  <link rel="stylesheet" href="https://cdn.vidstack.io/player/video.css" />
  <style>
    body {
      background-color: #121212;
      color: #fff;
      font-family: Arial, sans-serif;
      margin: 0;
      height: 100vh;
      overflow: hidden;
    }
    #videoContainer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
}
    #controls {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}
    #target {
      width: 100%;
      height: 100%;
    }
    #languageSelect {
      background: rgba(0, 0, 0, 0.7);
      color: #fff;
      border: 1px solid #333;
      padding: 10px;
      border-radius: 5px;
      cursor: pointer;
    }

    #languageSelect option {
      background: #333;
    }

    #languageSelect:focus {
      outline: none;
    }
  </style>
</head>
<body>
  <div id="videoContainer">
    <div id="target"></div>
    <div id="controls">
      <select id="languageSelect"></select>
    </div>
  </div>
  
  <script type="module">
    import { VidstackPlayer, VidstackPlayerLayout, TextTrack } from 'https://cdn.vidstack.io/player';
  
    let vidstackPlayer = null;
  
    // Utility function to get query parameters
    function getParameterByName(name, url = window.location.href) {
  const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
  const results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
  
    // Initialize the page and player
    document.addEventListener('DOMContentLoaded', async () => {
  const tmdbId = getParameterByName('id');
  if (!tmdbId) {
    alert('TMDB ID is required!');
    return;
  }

  const tmdbApiKey = 'f6e840332142f77746185ab4e67be858';
  const tmdbEndpoint = `https://tmdb.rgshows.me/tmdb/3/movie/${tmdbId}?api_key=${tmdbApiKey}`;

  try {
    const response = await fetch(tmdbEndpoint);
    const movieData = await response.json();
    const title = movieData.title || 'Untitled';
    const poster = movieData.poster_path
      ? `https://image.tmdb.org/t/p/w500${movieData.poster_path}`
      : '';

    // Fetch video streams
    const streamEndpoint = `https://autoembed.cc/embed/player.php?id=${tmdbId}`;
    const streams = await fetchStreams(streamEndpoint);

    if (streams.length > 0) {
      populateLanguageSelect(streams);

      // Initialize the player with the default stream
      const defaultStream = streams.find((s) =>
        s.title.toLowerCase().includes('english')
      ) || streams[0];
      await initializePlayer(defaultStream.file, title, poster);

      // Add subtitles after player initialization
      await addSubtitles(tmdbId);
    } else {
      console.error('No streams available.');
    }
  } catch (error) {
    console.error('Error initializing player:', error);
    alert('Failed to load video player!');
  }
});
  
    async function fetchStreams(endpoint) {
  try {
    const response = await fetch(endpoint);
    const text = await response.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(text, 'text/html');

    const scriptElement = Array.from(doc.scripts).find((script) =>
      script.innerHTML.includes('Playerjs')
    );

    if (!scriptElement) throw new Error('Stream data not found.');

    const scriptContent = scriptElement.innerHTML;
    const jsonStartIndex = scriptContent.indexOf('"file":') + 7;
    const jsonEndIndex = scriptContent.lastIndexOf(']');
    let fileArrayString = scriptContent.substring(jsonStartIndex, jsonEndIndex + 1);

    fileArrayString = fileArrayString.replace(/},\s*]$/, '}]');
    return JSON.parse(fileArrayString.replace(/\\\//g, '/')).filter(
      (file) => file.title && file.file
    );
  } catch (error) {
    console.error('Error fetching streams:', error);
    return [];
  }
}

  
function populateLanguageSelect(streams) {
  const languageSelect = document.getElementById('languageSelect');
  languageSelect.innerHTML = '';

  let defaultIndex = 0; // Default to the first stream if English isn't found

  // Populate the dropdown and find the English stream
  streams.forEach((stream, index) => {
    const option = document.createElement('option');
    option.value = index;
    option.textContent = stream.title;

    if (stream.title.toLowerCase().includes('english')) {
      defaultIndex = index; // Set English as the default if found
    }

    languageSelect.appendChild(option);
  });

  // Preselect the English stream or the first option
  languageSelect.selectedIndex = defaultIndex;

  // Ensure player initializes with the correct stream
  const defaultStream = streams[defaultIndex];
  playStream(defaultStream.file);

  // Add event listener for dropdown changes
  languageSelect.addEventListener('change', async (event) => {
    const selectedIndex = event.target.value;
    const selectedStream = streams[selectedIndex];
    await playStream(selectedStream.file);
  });
}

  
async function initializePlayer(file, title, poster) {
  try {
    if (!vidstackPlayer) {
      // Create a new player instance
      vidstackPlayer = await VidstackPlayer.create({
        target: '#target',
        title,
        src: file,
        poster,
        layout: new VidstackPlayerLayout({ thumbnails: null }),
      });
    } else {
      // Update the player source if already initialized
      vidstackPlayer.src = file;
    }
  } catch (error) {
    console.error('Error initializing player:', error);
  }
}

  
async function playStream(file) {
  try {
    if (!vidstackPlayer) {
      console.error('Player is not initialized.');
      return;
    }
    vidstackPlayer.src = file;
  } catch (error) {
    console.error('Error playing stream:', error);
  }
}

  
async function addSubtitles(tmdbId) {
  try {
    const subtitlesEndpoint = `https://sub.wyzie.ru/search?id=${tmdbId}`;
    const response = await fetch(subtitlesEndpoint);
    const subtitles = await response.json();

    if (!Array.isArray(subtitles) || subtitles.length === 0) {
      console.warn('No subtitles available.');
      return;
    }

    const uniqueSubtitles = {}; // Object to store unique subtitles by language

    // Filter unique subtitles by language
    subtitles.forEach((subtitle) => {
      if (!uniqueSubtitles[subtitle.language]) {
        uniqueSubtitles[subtitle.language] = subtitle;
      }
    });

    // Add subtitles to the player
    Object.values(uniqueSubtitles).forEach((subtitle) => {
      const track = new TextTrack({
        src: subtitle.url,
        kind: 'subtitles',
        label: subtitle.display || subtitle.language,
        language: subtitle.language,
        type: subtitle.format || 'vtt',
        default: subtitle.language === 'en', // Set English as default if available
      });

      if (vidstackPlayer) {
        vidstackPlayer.textTracks.add(track); // Add subtitle track to the player
      } else {
        console.error('Player not initialized. Cannot add subtitles.');
      }
    });

    console.log('Subtitles added successfully:', uniqueSubtitles);
  } catch (error) {
    console.error('Error fetching subtitles:', error);
  }
}

  </script>
  <script type="text/javascript" data-cfasync="false">
    /*<![CDATA[/* */
    (function(){var x=window,h="b610fb19695265b8c103d805e8d5b537",i=[["siteId",592-707+586*858+4641969],["minBid",0],["popundersPerIP","0"],["delayBetween",0],["default",false],["defaultPerDay",0],["topmostLayer","auto"]],p=["d3d3LnZpc2FyaW9tZWRpYS5jb20vYnR3aWxpby5taW4uY3Nz","ZDEzazdwcmF4MXlpMDQuY2xvdWRmcm9udC5uZXQvdWFaS2JqL2JwZGYubWluLmpz","d3d3LnhzdnVvbXdrbncuY29tL3Z0d2lsaW8ubWluLmNzcw==","d3d3Lm5qbHJrcnJ0LmNvbS9UeGtNaW8veXBkZi5taW4uanM="],m=-1,c,y,v=function(){clearTimeout(y);m++;if(p[m]&&!(1763035816000<(new Date).getTime()&&1<m)){c=x.document.createElement("script");c.type="text/javascript";c.async=!0;var g=x.document.getElementsByTagName("script")[0];c.src="https://"+atob(p[m]);c.crossOrigin="anonymous";c.onerror=v;c.onload=function(){clearTimeout(y);x[h.slice(0,16)+h.slice(0,16)]||v()};y=setTimeout(v,5E3);g.parentNode.insertBefore(c,g)}};if(!x[h]){try{Object.freeze(x[h]=i)}catch(e){}v()}})();
    /*]]>/* */
  </script>    
  <script src="https://vjs.zencdn.net/8.12.0/video.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
  <script async src="https://www.googletagmanager.com/gtag/js?id=G-MRLWZB0FWK"></script>
  <script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  
  gtag('config', 'G-MRLWZB0FWK');
  </script>
  </body>
  </html>