export const getIsWordpressMode = () =>
  typeof window !== 'undefined' &&
  window.self !== window.top &&
  new URLSearchParams(window.location.search).get('mode') === 'wp';

export const getIsWPVideoMode = () => {
  if (typeof window === 'undefined') {
    return false;
  }
  const modeFromParams = new URLSearchParams(window.location.search).get('mode');
  const mode =
    modeFromParams && modeFromParams.indexOf('?') > 0
      ? modeFromParams.slice(0, modeFromParams.indexOf('?'))
      : modeFromParams;
  return window.self !== window.top && mode === 'wp_video';
};

const mountedTagList = [];

export const createTag = (tagName, props = {}, attrs = {}) => {
  const tag = document.createElement(tagName);

  Object.entries(props).forEach(([key, value]) => {
    tag[key] = value;
  });

  Object.entries(attrs).forEach(([key, value]) => {
    tag.setAttribute(key, `${value}`);
  });

  return tag;
};

export const mountTag = (
  tagName,
  { props = {}, attrs = {}, appendContainer = document.head, withoutUnmount = false },
) => {
  const tag = createTag(tagName, props, attrs);

  if (!withoutUnmount) {
    mountedTagList.push(tag);
  }

  appendContainer.appendChild(tag);

  return tag;
};

const gaIteration = (...args) => {
  if (window.ga) {
    window.ga(...args);
  } else {
    setTimeout(() => gaIteration(...args), 500);
  }
};
export const ga = gaIteration;

export const unmountTag = (domElementReferrer) => domElementReferrer?.remove();

export const unmountAllTags = () => mountedTagList.forEach(unmountTag);
