<!--

    Use for global mobile / media query awareness in javascript. Provides values for isMobile and
    currentBreakpoint that can be used in any component.

    Use this in parent component or layout to provide the values to child components. Use
    PxBaseMobileAware in child components to inject the values.

    In many cases you can just add this as a mixin but if that component also has a resize method
    then be sure to call this.updateMediaQuery() from the resize method.

-->

<script>
import PxBaseResize from '../bases/PxBaseResize.vue';
export default {
    provide() {
        return {
            mediaQuery: this.mediaQuery,
        };
    },
    mixins: [PxBaseResize],
    data() {
        return { mediaQuery: { isMobile: null, currentBreakpoint: null, breakpoints: {} } };
    },
    mounted() {
        const breakpointNames = getComputedStyle(document.documentElement)
            .getPropertyValue('--breakpoint-names')
            .trim()
            .split(' ');

        const breakpointSizes = getComputedStyle(document.documentElement)
            .getPropertyValue('--breakpoint-sizes')
            .trim()
            .split(' ');

        if (breakpointNames.length !== breakpointSizes.length) {
            console.warn('Breakpoint names and sizes do not match');
            return;
        }

        try {
            this.mediaQuery.breakpoints = Object.fromEntries(
                breakpointNames
                    .map((name, index) => {
                        return [name, parseInt(breakpointSizes[index])];
                    })
                    .sort((a, b) => a[1] - b[1]),
            );
        } catch {
            console.warn(
                'Could not parse breakpoint sizes. Check the format of the breakpoint-sizes variable in the theme file.',
            );
        }
    },
    methods: {
        updateMediaQuery() {
            this.mediaQuery.isMobile =
                getComputedStyle(document.documentElement).getPropertyValue('--is-mobile').trim() ==
                'true';

            this.mediaQuery.currentBreakpoint = getComputedStyle(document.documentElement)
                .getPropertyValue('--breakpoint')
                .trim();
        },
        resize() {
            this.updateMediaQuery();
        },
    },
};
</script>

<style lang="scss">
@use '../styles/px.scss' as *;

@include media-breakpoint-vars;
</style>
