import {forwardRef, useEffect, useImperativeHandle, useRef, useState} from 'react';
import React from 'react';

const IS_SSR = typeof window !== 'object' || !window || typeof window.document !== 'object';
const GOOGLE_JS_URI = '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
const GOOGLE_JS = `https://${GOOGLE_JS_URI}`;
const ID = 'adsense-js-script';
const loaded = IS_SSR || (
    (document.querySelector(`script#${ID}`) as HTMLScriptElement)
        ?.getAttribute('src')
        ?.split('#')[0].split('?')[0]
        .endsWith(GOOGLE_JS)
    || false
);

const AdsenseJS = forwardRef((props, ref) => {
    const [mounted, setMounted] = useState(IS_SSR);
    const [scriptLoaded, setScriptLoaded] = useState(loaded);
    const scriptRef = useRef<null|HTMLScriptElement>(null);

    useEffect(() => {
        setMounted(true);
        return () => setMounted(false);
    }, []);

    useEffect(() => {
        if (mounted && !scriptLoaded) {
            if (!scriptRef.current) {
                const script = document.createElement('script');
                script.id = 'adsense-js-script';
                script.async = true;
                script.src = GOOGLE_JS;
                script.crossOrigin = 'anonymous';
                script.onload = () => {
                    setScriptLoaded(true);
                };
                scriptRef.current = script;
                document.head.appendChild(script);
            } else if (scriptRef.current.parentNode !== document.head) {
                document.head.appendChild(scriptRef.current);
                setScriptLoaded(true);
            } else {
                setScriptLoaded(true);
            }
        }
    }, [mounted, scriptLoaded]);

    useImperativeHandle(ref, () => ({
        isLoaded: scriptLoaded,
        reload: () => {},
    }));

    if (IS_SSR) {
        return <script id={ID} src={GOOGLE_JS} async crossOrigin="anonymous"/>;
    }
    return null;
});

export default AdsenseJS;
