import React, { useEffect } from 'react';
import { useRouter } from 'next/router';

import { getPlayerEndpoint } from '@/modules/@common/PlayerWidget/helpers';

import styles from './Preview.module.scss';

const playerContainerId = 'player-container';

function Preview() {
  const router = useRouter();

  const options = router.query;

  useEffect(() => {
    document.body.style.overflow = 'hidden';
    const playerContainer = document.getElementById(playerContainerId);

    const script = document.createElement('script');

    script.setAttribute('pubname', options.publisher);
    script.setAttribute('widgetname', options.widget);
    script.setAttribute('data-tm-leid', options.id);
    script.setAttribute('ac-embed-mode', 'in-iframe');

    script.src = getPlayerEndpoint();

    playerContainer.appendChild(script);

    const messageSubscribeFn = (event) => {
      if (event.origin === window.location.origin) {
        const reg = /lre:playerReady:\/\//;

        if (reg.test(event.data)) {
          const { sessionId } = JSON.parse(event.data.replace(reg, ''));
          const playerWidget = window.anyclip.getWidget(null, sessionId);

          window.dispatchEvent(new CustomEvent('PlayerLiveReady', { detail: playerWidget }));
        }
      }
    };

    window.addEventListener('message', messageSubscribeFn);

    return () => {
      window.removeEventListener('message', messageSubscribeFn);
      playerContainer.innerHTML = '';
    };
  }, []);

  return <div id={playerContainerId} className={styles.Wrapper} />;
}

export default Preview;
