import { withQuery } from "ufo";
import { disableGtag, enableGtag, gtag, initGtag } from "../gtag.mjs";
import { resolveTags } from "../utils.mjs";
import { useHead, useRuntimeConfig } from "#imports";
export function useGtag() {
  const options = useRuntimeConfig().public.gtag;
  const tags = resolveTags(options);
  let _gtag;
  if (process.server)
    _gtag = () => {
    };
  else if (process.client)
    _gtag = gtag;
  const setConsent = ({
    id,
    hasConsent = true
  }) => {
    if (process.client) {
      const _tags = [...tags];
      let tag = _tags.find((tag2) => tag2.id === id);
      if (!tag) {
        if (id) {
          tag = { id };
          _tags.unshift(tag);
        } else {
          tag = _tags[0];
        }
      }
      if (!tag) {
        console.error("[nuxt-gtag] Missing Google tag ID");
        return;
      }
      if (!hasConsent) {
        disableGtag(tag.id);
        return;
      }
      if (!window.dataLayer)
        initGtag({ tags: _tags });
      if (window.dataLayer.length > 2) {
        enableGtag(tag.id);
        return;
      }
      useHead({
        script: [{ src: withQuery(options.url, { id: tag.id }) }]
      });
    }
  };
  const grantConsent = (id) => {
    setConsent({ id, hasConsent: true });
  };
  const revokeConsent = (id) => {
    setConsent({ id, hasConsent: false });
  };
  return {
    gtag: _gtag,
    setConsent,
    grantConsent,
    revokeConsent
  };
}
