import { useState, useEffect, useRef, useMemo } from 'react';
const TWITTER_SDK = 'https://platform.twitter.com/widgets.js';
const Tweet = function Tweet(props) {
  const {
    tweet,
    className
  } = props;
  const ref = useRef();
  const [sdkLoaded, setSdkLoaded] = useState(false);
  const tweetId = useMemo(() => {
    const match = /twitter.com\/.*\/status\/(.*)/.exec(tweet);
    if (match) {
      return match[1];
    }
    return null;
  }, [tweet]);
  useEffect(() => {
    if (!tweetId || sdkLoaded) return undefined;
    if (window.twttr) {
      setSdkLoaded(true);
      return undefined;
    }
    if (window.document.querySelector(`script[src="${TWITTER_SDK}"]`)) {
      return undefined;
    }
    const body = window.document.getElementsByTagName('body')[0];
    const scriptElement = window.document.createElement('script');
    scriptElement.setAttribute('src', TWITTER_SDK);
    scriptElement.setAttribute('async', '');
    body.appendChild(scriptElement);
    let timer;
    const checkTwitter = (retries = 10) => {
      if (window.twttr) {
        setSdkLoaded(true);
        return;
      }
      if (retries > 0 && !window.twttr) {
        timer = setTimeout(() => checkTwitter(retries - 1), 100);
      }
    };
    checkTwitter();
    return () => {
      clearTimeout(timer);
    };
  }, [tweetId]);
  useEffect(() => {
    if (tweetId && sdkLoaded && window.twttr) {
      window.twttr.ready().then(({
        widgets
      }) => {
        if (ref.current) {
          ref.current.innerHTML = '';
          widgets.createTweetEmbed(tweetId, ref.current, {
            conversation: 'none',
            align: 'center'
          });
        }
      });
    }
  }, [tweetId, sdkLoaded]);
  if (!tweetId) {
    return null;
  }
  return <div ref={ref} className={className} />;
};
Tweet.nodeToProps = node => ({
  tweet: node.data.url
});
export default Tweet;