<script setup>
import { computed, inject } from 'vue';
import { useImageUpload } from '../../composables/useImageUpload';
import { useIntersectionActivation } from '../../composables/useIntersectionActivation';
import { getBunnyEmbedUrl, getFrameIoEmbedUrl, getYouTubeEmbedUrl } from '../../schema/projectSchema';
const props = defineProps({
    slotData: {
        type: Object,
        required: true,
    },
    blockId: {
        type: String,
        required: true,
    },
    slotKey: {
        type: String,
        default: 'slot',
    },
    activeLang: {
        type: String,
        default: '',
    },
    column: {
        type: Boolean,
        default: false,
    },
});

const uploadUrl = inject('editorUploadUrl', null);
const updateBlockImage = inject('editorUpdateBlockImage', null);

// Image upload for image-type slot
const { isDragOver, isUploading, fileInputRef, onDragOver, onDragLeave, onDrop, openPicker, onFileSelected } = useImageUpload(
    () => uploadUrl?.value ?? null,
    (url) => updateBlockImage?.(props.blockId, props.slotKey, null, url),
);

const resolveAlt = (alt, fallback) => {
    if (!alt) return fallback;
    if (typeof alt === 'string') return alt || fallback;
    return alt[props.activeLang] || alt[Object.keys(alt)[0]] || fallback;
};

// Video activation
const { isActive, target } = useIntersectionActivation();
const youtubeUrl = computed(() => getYouTubeEmbedUrl(props.slotData?.media));
const frameIoUrl = computed(() => getFrameIoEmbedUrl(props.slotData?.media?.url));
const bunnyUrl = computed(() => getBunnyEmbedUrl(props.slotData?.media));

// Text display
const displayContent = computed(() => {
    const c = props.slotData?.content;
    if (typeof c === 'string') return c;
    if (c && typeof c === 'object') {
        return c[props.activeLang] || c[Object.keys(c)[0]] || '';
    }
    return '';
});
</script>

<template>
    <!-- TEXT -->
    <section v-if="slotData.type === 'text'" class="slot-text">
        <div v-if="displayContent" class="slot-text__body" v-html="displayContent"></div>
        <p v-else class="slot-text__placeholder">Add narrative copy for this text slot.</p>
    </section>

    <!-- IMAGE -->
    <figure
        v-else-if="slotData.type === 'image'"
        class="slot-image"
        :class="{
            'slot-image--column': column,
            'slot-image--over': isDragOver,
            'slot-image--uploading': isUploading,
            'slot-image--editable': !!uploadUrl?.value,
        }"
        @dragover="uploadUrl?.value ? onDragOver($event) : null"
        @dragleave="onDragLeave"
        @drop="uploadUrl?.value ? onDrop($event) : null"
        @click="uploadUrl?.value ? openPicker() : null"
    >
        <img v-if="slotData.image?.url" :src="slotData.image.url" :alt="resolveAlt(slotData.image.alt, 'Project image')" loading="lazy">
        <div v-else class="slot-image__placeholder">
            {{ isUploading ? 'Uploading…' : (uploadUrl?.value ? 'Drop or click to upload.' : 'Add image URL.') }}
        </div>
        <div v-if="isDragOver" class="slot-image__overlay"></div>
        <div v-if="isUploading && slotData.image?.url" class="slot-image__overlay slot-image__overlay--uploading"></div>
        <input ref="fileInputRef" type="file" accept="image/*" style="display:none" @change="onFileSelected">
    </figure>

    <!-- VIDEO -->
    <section
        v-else-if="slotData.type === 'video'"
        ref="target"
        class="slot-video"
        :class="{ 'slot-video--column': column }"
    >
        <iframe
            v-if="slotData.media?.type === 'youtube' && isActive && youtubeUrl"
            :src="youtubeUrl"
            title="Video slot"
            loading="lazy"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen
        />
        <iframe
            v-else-if="slotData.media?.type === 'frameio' && isActive && frameIoUrl"
            :src="frameIoUrl"
            title="Video slot"
            loading="lazy"
            allow="autoplay; fullscreen; picture-in-picture"
            allowfullscreen
        />
        <div
            v-else-if="slotData.media?.type === 'bunny' && isActive && bunnyUrl"
            class="slot-video__bunny"
        >
            <iframe
                :src="bunnyUrl"
                loading="lazy"
                style="border:0;position:absolute;top:0;height:100%;width:100%;"
                allow="accelerometer;gyroscope;autoplay;encrypted-media;picture-in-picture;"
                allowfullscreen
            />
        </div>
        <video
            v-else-if="slotData.media?.type === 'video' && isActive && slotData.media?.url"
            :autoplay="slotData.media?.autoplay === true"
            :muted="slotData.media?.muted === true"
            :loop="slotData.media?.loop === true"
            controls
            playsinline
            preload="metadata"
        >
            <source :src="slotData.media.url">
        </video>
        <div v-else class="slot-video__placeholder">Add a video URL to render this slot.</div>
    </section>
</template>

<style scoped>
/* ---- Text ---- */
.slot-text {
    align-items: center;
    display: flex;
    justify-content: center;
    min-height: 8rem;
    padding: 2rem;
    text-align: center;
}

.slot-text__placeholder {
    color: var(--project-muted, #6b7280);
    font-size: clamp(1.05rem, 1.8vw, 1.4rem);
    line-height: 1.75;
    margin: 0;
}

:deep(.slot-text__body p),
:deep(.slot-text__body h2),
:deep(.slot-text__body h3),
:deep(.slot-text__body ul),
:deep(.slot-text__body ol) {
    color: var(--project-ink, #111827);
    font-size: clamp(1.05rem, 1.8vw, 1.4rem);
    line-height: 1.75;
    margin: 0 0 0.75em;
}

:deep(.slot-text__body p:last-child),
:deep(.slot-text__body h2:last-child),
:deep(.slot-text__body ul:last-child) {
    margin-bottom: 0;
}

:deep(.slot-text__body h2) {
    font-size: clamp(1.3rem, 2.2vw, 1.8rem);
    font-weight: 700;
}

:deep(.slot-text__body h3) {
    font-size: clamp(1.1rem, 1.9vw, 1.5rem);
    font-weight: 700;
}

/* ---- Image ---- */
.slot-image {
    aspect-ratio: 16 / 9;
    background: linear-gradient(135deg, rgba(15, 23, 42, 0.08), rgba(148, 163, 184, 0.15));
    border-radius: 1.65rem;
    margin: 0;
    overflow: hidden;
    position: relative;
    transition: outline-color 0.15s;
}

.slot-image--column {
    aspect-ratio: 4 / 4;
    border-radius: 1.5rem;
}

.slot-image--editable {
    cursor: pointer;
}

.slot-image--over {
    outline: 2px dashed rgba(14, 116, 144, 0.7);
    outline-offset: -2px;
}

.slot-image img {
    display: block;
    height: 100%;
    object-fit: cover;
    width: 100%;
}

.slot-image--uploading img {
    opacity: 0.5;
}

.slot-image__placeholder {
    align-items: center;
    color: var(--project-muted, #6b7280);
    display: flex;
    height: 100%;
    justify-content: center;
    padding: 2rem;
    text-align: center;
}

.slot-image__overlay {
    background: rgba(14, 116, 144, 0.15);
    bottom: 0;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
}

.slot-image__overlay--uploading {
    background: rgba(15, 23, 42, 0.3);
}

/* ---- Video ---- */
.slot-video {
    aspect-ratio: 16 / 9;
    background: linear-gradient(135deg, rgba(15, 23, 42, 0.08), rgba(148, 163, 184, 0.15));
    border-radius: 1.65rem;
    overflow: hidden;
}

.slot-video--column {
    aspect-ratio: 1 / 1;
    border-radius: 1.5rem;
}

.slot-video iframe,
.slot-video video {
    border: 0;
    display: block;
    height: 100%;
    width: 100%;
}

.slot-video__bunny {
    padding-top: 56.25%;
    position: relative;
}

.slot-video__placeholder {
    align-items: center;
    color: var(--project-muted, #6b7280);
    display: flex;
    height: 100%;
    justify-content: center;
    padding: 2rem;
    text-align: center;
}
</style>
