import React, { useEffect } from 'react';

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

const playerContainerId = 'player-container';

function PlayerFormPreview() {
  useEffect(() => {
    const playerContainer = document.getElementById(playerContainerId);

    const script$ = document.createElement('script');
    script$.src = process.env.APP_PLAYER_FORM_BUILDER;

    script$.addEventListener('load', () => {
      const formBuilder = window.createLreFormBuilder();
      formBuilder.target = playerContainer;
      formBuilder.setTarget(playerContainer);
      formBuilder.showBackground(false);

      window.dispatchEvent(new CustomEvent('FormBuilderReady', { detail: formBuilder }));
    });

    playerContainer.appendChild(script$);

    return () => {
      playerContainer.innerHTML = '';
    };
  }, []);

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

export default PlayerFormPreview;
