<script setup lang="ts">
/**
 * Thin Documents-side adapter that drops the media_viewer module's hover
 * popover onto a file item. Resolves the popover from the integration store
 * and builds a generic MediaItem from the entity; the popover anchors to its
 * parent element via `activator="parent"`.
 */
import { computed, defineAsyncComponent } from 'vue'
import { useIntegrationStore } from '@KTXC'
import { EntityObject } from '@DocumentsManager/models/entity'

const props = defineProps<{
  entity: EntityObject
  /** Same resolver the fullscreen dialog uses (returns a GET URL string). */
  source: (item: { id: string; meta?: Record<string, unknown> }) => string | Blob | Promise<string | Blob>
}>()

const emit = defineEmits<{
  expand: [entity: EntityObject]
}>()

const integrationStore = useIntegrationStore()

const popoverComponent = computed(() => {
  // Integration ids are prefixed with the module handle (e.g. 'media_viewer.popover').
  const entry = integrationStore.getItems('media_viewer').find(i => i.id.endsWith('.popover'))
  return entry?.component
    ? defineAsyncComponent(entry.component as () => Promise<unknown>)
    : null
})

const item = computed(() => ({
  id: String(props.entity.identifier ?? ''),
  title: props.entity.properties.label ?? String(props.entity.identifier ?? ''),
  mime: props.entity.properties.mime ?? '',
  meta: { collection: props.entity.collection ? String(props.entity.collection) : null },
}))
</script>

<template>
  <component
    :is="popoverComponent"
    v-if="popoverComponent"
    :item="item"
    :source="source"
    @expand="emit('expand', entity)"
  />
</template>
