import { useEffect } from 'react';
import { useTracker } from "../index.js";
import initUtag from "../../../utils/tracking/initUtag.js";
import useUtagConfig from '../useUtagConfig';
export default function useUtagSetup({
  embed,
  utag = {}
} = {}) {
  const track = useTracker();
  const baseUtagConf = useUtagConfig();
  const {
    pageName
  } = utag;
  useEffect(() => {
    (async () => {
      if (embed) {
        return;
      }
      if (window.UTAG_SCRIPTS_LOADED) {
        if (pageName) {
          track.view(pageName);
        }
      } else if (baseUtagConf && !window.UTAG_SCRIPTS_LOADED && !window.UTAG_SCRIPTS_LOADING) {
        window.utag_cfg_ovrd = {
          noview: true
        };
        window.UTAG_SCRIPTS_LOADING = true;
        try {
          if (pageName) {
            await initUtag({
              ...baseUtagConf,
              page_name: pageName
            });
            window.UTAG_SCRIPTS_LOADED = true;
            track.view(pageName);
          } else {
            // eslint-disable-next-line no-console
            console.error('Utag: No page name provided to utag configuration');
          }
        } catch (error) {
          // eslint-disable-next-line no-console
          console.error(error);
        } finally {
          window.UTAG_SCRIPTS_LOADING = false;
        }
      }
    })();
  }, [pageName, baseUtagConf]);
}