<template>
    <div class="page-container" :style="{ transform: `scale(${zoom})` }">
        <div v-if="!pageData" class="error">Aucune donnée d'image disponible</div>
        <div v-else-if="!pageData.base64Content" class="error">Contenu de l'image manquant</div>
        <img
            v-else
            :src="imageSource"
            :alt="`Page ${pageNumber}`"
            class="page-image"
            :style="imageStyle"
            @load="handleImageLoad"
            ref="imageRef" />
    </div>
</template>

<script setup>
    import { computed, ref, onMounted } from 'vue';

    const props = defineProps({
        pageData: {
            type: Object,
            required: true
        },
        pageNumber: {
            type: Number,
            required: true
        },
        zoom: {
            type: Number,
            required: true
        }
    });

    const imageRef = ref(null);
    const naturalWidth = ref(0);
    const naturalHeight = ref(0);

    const imageSource = computed(() => {
        if (!props.pageData?.base64Content || !props.pageData?.mimeType) {
            return '';
        }
        return `data:${props.pageData.mimeType};base64,${props.pageData.base64Content}`;
    });

    const handleImageLoad = () => {
        if (imageRef.value) {
            naturalWidth.value = imageRef.value.naturalWidth;
            naturalHeight.value = imageRef.value.naturalHeight;
        }
    };

    // Calculer la largeur maximale en fonction de la hauteur de la fenêtre
    const maxWidth = computed(() => {
        if (!naturalWidth.value || !naturalHeight.value) return null;

        // On prend 70% de la largeur de la fenêtre comme largeur maximale
        const maxWidthPx = window.innerWidth * 0.7;

        // Si l'image est plus petite que la largeur maximale, on garde sa taille naturelle
        if (naturalWidth.value <= maxWidthPx) {
            return naturalWidth.value;
        }

        return maxWidthPx;
    });

    const imageStyle = computed(() => {
        if (!maxWidth.value) return {};

        return {
            width: `${maxWidth.value}px`,
            height: 'auto',
            maxWidth: '100%'
        };
    });

    onMounted(() => {
        if (imageRef.value && imageRef.value.complete) {
            handleImageLoad();
        }
    });
</script>

<style lang="postcss" scoped>
    .page-container {
        @apply flex-1 flex items-center justify-center overflow-hidden;
        transform-origin: center;
    }

    .page-image {
        @apply max-w-full max-h-full object-contain;
    }

    .error {
        @apply text-red-500 text-xl;
    }
</style>
