<template>
    <div class="mosaic-viewport" :class="{ active: isActive }">
        <div class="mosaic-container">
            <div
                v-for="cell in content.cells"
                :class="[
                    'mosaic-cell',
                    `layout-${cell.width >= cell.height ? 'landscape' : 'portrait'}`,
                ]"
                :style="{
                    left: cell.x + 'px',
                    top: cell.y + 'px',
                    width: cell.width + 'px',
                    height: cell.height + 'px',
                }"
                :key="`${viewport.index}-${cell.id}`"
                @click="openModal(cell.content)"
            >
                <strapi-media
                    :field="cell.content.image"
                    :aspect="100"
                    fit="contain"
                />
            </div>
        </div>
    </div>

    <!-- Content modal -->
    <teleport to="#container">
        <mosaic-modal
            v-if="selectedItem"
            :item="selectedItem"
            @close="closeModal"
        />
    </teleport>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useEventListener } from '@vueuse/core'
import useLenis from '@/composables/useLenis'

const props = defineProps({
    viewport: {
        type: Object,
        required: true,
    },
    index: {
        type: Number,
        required: true,
    },
    content: {
        type: Object,
        required: true,
    },
    isActive: {
        type: Boolean,
        default: false,
    },
})

const selectedItem = ref(null)

const openModal = (cell) => {
    selectedItem.value = cell
}

const closeModal = () => {
    selectedItem.value = null
}

// Close note on Escape key
const handleKeydown = (event) => {
    if (event.key === 'Escape' && selectedItem.value) {
        closeModal()
    }
}
useEventListener('keydown', handleKeydown)

// Pause scroll when modal is open
const lenis = useLenis()
watch(selectedItem, (newItem, oldItem) => {
    if (newItem && !oldItem) {
        lenis.value.stop()
    } else if (oldItem && !newItem) {
        lenis.value.start()
    }
})
</script>

<style lang="scss" scoped>
.mosaic-viewport {
    height: 100vh;
    display: flex;
    position: relative;
    overflow: hidden;

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

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

            &.layout-portrait {
                .strapi-media {
                    width: 50%;
                }
            }
            &.layout-landscape {
                .strapi-media {
                    height: 50%;
                    aspect-ratio: 1;
                }
            }
        }
    }
}
</style>
