<script lang="ts">
    import { onMount } from "svelte"
    export let query: string

    let mql: MediaQueryList
    let mqlListener: {
        (v: any): any
        (this: MediaQueryList, ev: MediaQueryListEvent): any
        (this: MediaQueryList, ev: MediaQueryListEvent): any
    }
    let wasMounted = false
    let matches = false

    onMount(() => {
        wasMounted = true
        return () => {
            removeActiveListener()
        }
    })

    $: {
        if (wasMounted) {
            removeActiveListener()
            addNewListener(query)
        }
    }

    function addNewListener(query: string) {
        if (!query) {
            query = "(min-width:0px)"
            console.warn(
                "Missing view property 'meta.views.mediaQuery' in collection config. Query has been set to '(min-width:0px)'."
            )
        }
        if (typeof "window" == "undefined") return
        mql = window.matchMedia(query)
        mqlListener = (e: { matches: boolean }) => (matches = e.matches)
        //mql.addListener(mqlListener)
        mql.addEventListener("change", mqlListener)
        matches = mql.matches
    }

    function removeActiveListener() {
        if (mql && mqlListener) {
            // mql.removeListener(mqlListener)
            mql.removeEventListener("change", mqlListener)
        }
    }
</script>

{#if matches}
    <slot />
{/if}
