<template>
    <Teleport to="body">
        <Transition name="fade" appear>
            <div
                v-if="entry"
                class="fixed inset-0 z-[60] flex items-center justify-center bg-black/80"
                @click.self="$emit('close')"
                @keydown.escape="$emit('close')"
                @keydown.left="$emit('prev')"
                @keydown.right="$emit('next')"
                tabindex="0"
                ref="overlayRef"
            >
                <!-- Close button -->
                <MalioButtonIcon
                    icon="heroicons:x-mark"
                    aria-label="Fermer"
                    variant="ghost"
                    icon-size="24"
                    button-class="absolute right-4 top-4 rounded-full bg-black/50 text-white hover:bg-black/70"
                    @click="$emit('close')"
                />

                <!-- Navigation arrows -->
                <MalioButtonIcon
                    v-if="hasPrev"
                    icon="heroicons:chevron-left"
                    aria-label="Précédent"
                    variant="ghost"
                    icon-size="24"
                    button-class="absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 text-white hover:bg-black/70"
                    @click="$emit('prev')"
                />
                <MalioButtonIcon
                    v-if="hasNext"
                    icon="heroicons:chevron-right"
                    aria-label="Suivant"
                    variant="ghost"
                    icon-size="24"
                    button-class="absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 text-white hover:bg-black/70"
                    @click="$emit('next')"
                />

                <!-- Content -->
                <div class="flex max-h-[90vh] max-w-[90vw] flex-col items-center">
                    <!-- Image preview -->
                    <img
                        v-if="isImage"
                        :src="inlineUrl"
                        :alt="entry.name"
                        class="max-h-[85vh] max-w-[90vw] object-contain"
                    />

                    <!-- PDF preview — iframe pattern, même approche que TaskDocumentPreview -->
                    <iframe
                        v-else-if="isPdf"
                        :src="inlineUrl"
                        class="h-[85vh] w-[80vw] rounded-lg bg-white"
                    />

                    <!-- Text / Markdown / JSON / XML / CSV / Log preview -->
                    <div
                        v-else-if="isText"
                        class="flex max-h-[85vh] w-[85vw] max-w-3xl flex-col overflow-hidden rounded-xl bg-white"
                    >
                        <div class="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-3">
                            <p class="truncate text-sm font-medium text-neutral-700">{{ entry.name }}</p>
                            <a
                                :href="downloadUrl"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
                            >
                                {{ $t('sharedFiles.download') }}
                            </a>
                        </div>
                        <div class="overflow-auto p-4">
                            <div v-if="loadingText" class="flex justify-center py-10">
                                <Icon name="heroicons:arrow-path" class="h-6 w-6 animate-spin text-neutral-400" />
                            </div>
                            <pre
                                v-else
                                class="whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-neutral-800"
                            >{{ textContent }}</pre>
                        </div>
                    </div>

                    <!-- Generic file — download fallback -->
                    <div v-else class="flex flex-col items-center gap-4 rounded-xl bg-white p-10">
                        <Icon name="heroicons:document" class="h-16 w-16 text-neutral-400" />
                        <p class="max-w-xs truncate text-lg font-medium text-neutral-700">{{ entry.name }}</p>
                        <p class="text-sm text-neutral-400">{{ formatFileSize(entry.size) }}</p>
                        <a
                            :href="downloadUrl"
                            class="mt-2 rounded-lg bg-blue-600 px-6 py-2 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
                        >
                            {{ $t('sharedFiles.download') }}
                        </a>
                    </div>

                    <!-- File name footer (hors bloc texte car il a déjà le nom dans l'en-tête) -->
                    <p v-if="!isText" class="mt-3 text-sm text-white/70">{{ entry.name }}</p>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<script setup lang="ts">
import type { FileEntry } from '~/services/dto/share'
import { useShareService } from '~/services/share'
import { formatFileSize } from '~/utils/format'

const props = defineProps<{
    entry: FileEntry | null
    hasPrev: boolean
    hasNext: boolean
}>()

defineEmits<{
    close: []
    prev: []
    next: []
}>()

const overlayRef = ref<HTMLElement | null>(null)
const textContent = ref('')
const loadingText = ref(false)

const { getDownloadUrl } = useShareService()

const TEXT_RE = /\.(md|markdown|txt|csv|json|xml|log)$/i

const inlineUrl = computed(() => props.entry ? getDownloadUrl(props.entry.path, 'inline') : '')
const downloadUrl = computed(() => props.entry ? getDownloadUrl(props.entry.path, 'attachment') : '')
const isImage = computed(() => props.entry?.mimeType.startsWith('image/') ?? false)
const isPdf = computed(() => props.entry?.mimeType === 'application/pdf')
const isText = computed(() =>
    props.entry
        ? (props.entry.mimeType.startsWith('text/') || TEXT_RE.test(props.entry.name))
        : false
)

watch(() => props.entry, async (entry) => {
    textContent.value = ''
    if (!entry) return

    nextTick(() => overlayRef.value?.focus())

    if (isText.value) {
        loadingText.value = true
        try {
            textContent.value = await $fetch<string>(inlineUrl.value, {
                credentials: 'include',
                responseType: 'text' as never,
            })
        } catch {
            textContent.value = ''
        } finally {
            loadingText.value = false
        }
    }
}, { immediate: true })
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>
