import React from 'react';
import PropTypes from 'prop-types';
import { imagePrettyUrl, removeDomain } from '~helpers/getters';
import LazyImage from '~hooks/lazy-image';
import PrettyLink from '~atoms/pretty-link';
import styles from './stickyOperatorBanner.module.scss';

const StickyOperatorBanner = ({ data, template }) => {
  const getRandomItem = (array) => {
    if (!array || array.length === 0) return null;
    const randomIndex = Math.floor(Math.random() * array.length);
    return array[randomIndex];
  };

  const toplist = data?.modules?.find((module) => module.name === 'top_list');
  const tracker = toplist?.items?.[0]?.tracker || 'main';
  const randomItem = getRandomItem(toplist?.items?.[0]?.items);
  const gifUrl = randomItem?.extra_fields?.gif?.url;
  if (!gifUrl || !randomItem) return null;

  const filename = removeDomain(gifUrl);
  return (
    <PrettyLink
      operator={randomItem}
      tracker={tracker}
      template={template}
      className={styles.container}
    >
      <LazyImage src={imagePrettyUrl(filename, 'auto', 'auto')} alt="Sticky Operator Banner" />
    </PrettyLink>
  );
};

StickyOperatorBanner.propTypes = {
  data: PropTypes.shape({
    extra_fields: PropTypes.shape({
      gif: PropTypes.string,
    }),
    modules: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string,
        items: PropTypes.arrayOf(
          PropTypes.shape({
            tracker: PropTypes.string,

            items: PropTypes.shape({}),
          })
        ),
      })
    ),
  }),
  template: PropTypes.string,
};

export default StickyOperatorBanner;
