import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import LazyImage from 'gatsby-core-theme/src/hooks/lazy-image';
import { imagePrettyUrl } from 'gatsby-core-theme/src/helpers/getters';
import Iframe from 'gatsby-core-theme/src/components/atoms/iframe';
import Button from 'gatsby-core-theme/src/components/atoms/button/button';
import GatsbyImg from 'gatsby-core-theme/src/hooks/gatsby-img';
import useTranslate from '~hooks/useTranslate/useTranslate';
import styles from './game-iframe.module.scss';

const GameIframe = ({ page }) => {
  const [showIframe, setShowIframe] = useState(false);

  useEffect(() => {
    const playfreeLinks = document.querySelectorAll('button.playfree'); 

    const click = () => {
      if (!showIframe) {
        setShowIframe(true);
      }
    };

    playfreeLinks.forEach((item) => {
      item.addEventListener('click', click);
    });

    return () => {
      playfreeLinks.forEach((item) => {
        item.removeEventListener('click', click);
      });
    };
  }, [showIframe]);

  const clickHandler = () => {
    if (!showIframe) {
      setShowIframe(true);
    }
  };

  return (
    <>
      {page.relation && page.relation.iframe && page.relation.iframe !== '' && (
        <div>
          <div className={styles?.thumbnailContainer || ''}>
            <div className={`${styles?.thumbnail || ''} ${showIframe ? styles.hide || '' : ''}`}>
              {page.banner ? (
                <LazyImage
                  alt={page.title}
                  src={imagePrettyUrl(
                    page.banner,
                    page?.featured_image_object?.width,
                    page?.featured_image_object?.height
                  )}
                  width={page?.featured_image_object?.width}
                  height={page?.featured_image_object?.height}
                />
              ) : (
                <GatsbyImg alt={page.title} filename="default-slot.jpg" />
              )}

              <Button
                onClick={() => clickHandler()}
                isInternalLink={false}
                buttonType="primary"
                buttonSize="m"
                btnText={useTranslate('play_now_iframe', 'Play Now')}
              />
            </div>
            {showIframe && (
              <Iframe
                lazyLoad={false}
                src={page.relation.iframe}
                title={page.title}
                frameBorder={0}
              />
            )}
          </div>
        </div>
      )}
    </>
  );
};

GameIframe.propTypes = {
  page: PropTypes.shape({
    title: PropTypes.string,
    banner: PropTypes.string,
    featured_image_object: PropTypes.shape({
      width: PropTypes.string,
      height: PropTypes.string,
    }),
    relation: PropTypes.shape({
      iframe: PropTypes.string,
    }),
  }),
};

export default GameIframe;
