import { React, constants } from '../common';

export interface IGoogleAnalyticsProps {
  trackingId: string;
  force?: boolean;
}

/**
 * Inserts the Google Analytics script.
 * https://analytics.google.com
 */
export function GoogleAnalytics({
  trackingId,
  force = false,
}: IGoogleAnalyticsProps) {
  if (constants.IS_DEV && !force) {
    return <script />; // No-op.
  } else {
    return (
      <React.Fragment>
        <script
          async={true}
          src={`https://www.googletagmanager.com/gtag/js?id=${trackingId}`}
        />
        <script
          dangerouslySetInnerHTML={{ __html: formatScript(trackingId) }}
        />
      </React.Fragment>
    );
  }
}

const formatScript = (trackingId: string) => {
  return `
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '${trackingId}');
  `;
};
