<template>
    <div
        class="mosaic-viewport"
        v-intersect:once="{
            callback: onIntersect,
            rootMargin: '-25% 0px -25% 0px',
        }"
    >
        <div class="mosaic-container">
            <router-link
                v-for="cell in content.cells"
                :class="[
                    'mosaic-cell',
                    `layout-${cell.width >= cell.height ? 'landscape' : 'portrait'}`,
                ]"
                :style="{
                    left: cell.x * 100 + 'vw',
                    top: cell.y * 100 + 'vh',
                    width: cell.width * 100 + 'vw',
                    height: cell.height * 100 + 'vh',
                }"
                :to="{
                    name: 'mosaic-item',
                    params: { id: cell.content.slug },
                }"
                :key="`${viewport.index}-${cell.id}`"
                ref="cells"
            >
                <strapi-media
                    :image="cell.content.image"
                    :aspect="100"
                    fit="contain"
                />
            </router-link>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import gsap from 'gsap'

const props = defineProps({
    viewport: {
        type: Object,
        required: true,
    },
    content: {
        type: Object,
        required: true,
    },
})

const cells = ref([])

const onIntersect = (isIntersecting) => {
    if (isIntersecting) {
        if (!cells.value) return

        const cellGifs = cells.value
            .map((cell) => cell.$el?.children?.[0])
            .filter(Boolean)

        gsap.to(cellGifs, { opacity: 1, duration: 0, stagger: 0.1 })
    }
}
</script>

<style lang="scss">
.mosaic-viewport {
    height: calc(100 * var(--vh));
    display: flex;
    position: relative;
    overflow: hidden;

    .mosaic-container {
        flex: 1;
        position: relative;

        .mosaic-cell {
            position: absolute;
            overflow: hidden;
            border: 0.5px solid var(--theme-fg);
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            background: var(--theme-bg);

            &.layout-portrait {
                .strapi-media {
                    width: 40%;
                }
            }
            &.layout-landscape {
                .strapi-media {
                    height: 40%;
                    aspect-ratio: 1;
                }
            }
            .strapi-media {
                mix-blend-mode: darken;
                opacity: 0;
            }
        }
    }
}
</style>
