<script lang="ts" module>
declare global {
    interface Window {
        dataLayer: any[];
        gtag: (...args: any[]) => void;
    }
}
</script>

<script lang="ts">
import { browser } from '$app/environment';

interface Props {
    log_lvl?: number;
    site_google_tracking_id?: string;
}

let { log_lvl = 0, site_google_tracking_id = $bindable('') }: Props = $props();

$effect(() => {
    if (browser && site_google_tracking_id) {
        if (log_lvl) {
            console.log(
                `AE Analytics: site_google_tracking_id = `,
                site_google_tracking_id
            );
        }

        window.dataLayer = window.dataLayer || [];
        window.gtag =
            window.gtag ||
            function gtag() {
                window.dataLayer.push(arguments);
            };
        window.gtag('js', new Date());
        window.gtag('config', site_google_tracking_id);

        if (log_lvl) {
            console.log(
                `AE Analytics: Google Analytics Tracking ID = `,
                site_google_tracking_id
            );
        }
    }
});
</script>

<svelte:head>
    {#if site_google_tracking_id}
        <script
            async
            src="https://www.googletagmanager.com/gtag/js?id={site_google_tracking_id}"></script>
    {/if}
</svelte:head>
