<script lang="ts">
    // @ts-nocheck
    import { page } from '$app/stores'
    import { sendPage } from '$utils/analytics'

    export let appKey: any
    export let url: any
    export let enabled: boolean = process.env.NODE_ENV !== 'development'

    let loaded = false

    const handleLoad = () => {
        // Init Countly
        if (Countly) {
            Countly.init({
                app_key: appKey,
                url,
            })
            Countly.track_sessions()
            Countly.track_pageview()
        }
        loaded = true
    }

    // Send page to Analytics when changing path
    $: enabled && $page.url.pathname && loaded && sendPage()
</script>

<svelte:head>
    {#if enabled}
        <script defer src="https://cdn.jsdelivr.net/npm/countly-sdk-web@latest/lib/countly.min.js" on:load={handleLoad} />
    {/if}
</svelte:head>

<noscript>
    <img src="{url}/pixel.png?app_key={appKey}&begin_session=1" alt="countly" width="0" height="0" />
</noscript>