<script setup lang="ts">
// V1.3-E : PreviewArticle gere 2 modes :
//   - 'article' (V1.2-P existant) : teaser + embed Substack / Instagram / CTA propagation
//   - 'manifeste' (V1.3-E)        : affiche <ManifesteContent /> dans la preview centrale
// Events ecoutes :
//   - 'journal-item-click'   -> mode 'article' (legacy V1.2-P, conserve tel quel)
//   - 'preview-open'         -> nouvel event unifie, payload { type: 'article' | 'manifeste', data?: ... }
//   - 'preview-close-request'-> close externe
// Event emis : 'preview-close' (utilise par ColCentre pour restaurer la mise en page).
import { ref, computed, onMounted, onUnmounted } from 'vue'
import ManifesteContent from './ManifesteContent.vue'

interface JournalItem {
  id: string
  platform: 'substack' | 'gitea' | 'github' | 'instagram' | 'castopod' | 'blog' | 'linkedin'
  hashtag: string
  date: string
  titre: string
  extrait: string
  url: string
  thumbnail: string | null
}

type PreviewMode = 'article' | 'manifeste' | null

const mode = ref<PreviewMode>(null)
const selectedItem = ref<JournalItem | null>(null)

const onJournalItemClick = (e: Event) => {
  const ce = e as CustomEvent
  if (ce.detail?.item) {
    selectedItem.value = ce.detail.item
    mode.value = 'article'
  }
}

const onPreviewOpen = (e: Event) => {
  const ce = e as CustomEvent
  const type = ce.detail?.type
  if (type === 'manifeste') {
    mode.value = 'manifeste'
    selectedItem.value = null
  } else if (type === 'article' && ce.detail?.item) {
    selectedItem.value = ce.detail.item
    mode.value = 'article'
  }
}

const onPreviewCloseExternal = () => {
  selectedItem.value = null
  mode.value = null
}

onMounted(() => {
  window.addEventListener('journal-item-click', onJournalItemClick as EventListener)
  window.addEventListener('preview-open', onPreviewOpen as EventListener)
  window.addEventListener('preview-close-request', onPreviewCloseExternal as EventListener)
})
onUnmounted(() => {
  window.removeEventListener('journal-item-click', onJournalItemClick as EventListener)
  window.removeEventListener('preview-open', onPreviewOpen as EventListener)
  window.removeEventListener('preview-close-request', onPreviewCloseExternal as EventListener)
})

const close = () => {
  selectedItem.value = null
  mode.value = null
  window.dispatchEvent(new CustomEvent('preview-close'))
}

const extractInstaShortcode = (url: string): string | null => {
  const m = url.match(/\/(p|reel)\/([^\/\?#]+)/)
  return m ? m[2] : null
}

const embedUrl = computed(() => {
  if (!selectedItem.value) return null
  const item = selectedItem.value
  if (item.platform === 'substack') {
    return item.url.includes('?') ? item.url + '&embed=1' : item.url + '?embed=1'
  }
  if (item.platform === 'instagram') {
    const sc = extractInstaShortcode(item.url)
    return sc ? `https://www.instagram.com/p/${sc}/embed/` : null
  }
  return null
})

const platformLabel = (p: string) => {
  const labels: Record<string, string> = {
    substack: 'Substack',
    instagram: 'Instagram',
    gitea: 'Gitea',
    github: 'GitHub',
    castopod: 'Podcast',
    blog: 'Blog',
    linkedin: 'LinkedIn',
  }
  return labels[p] || p
}

const formatDate = (iso: string) => {
  try {
    const d = new Date(iso)
    return isNaN(d.getTime())
      ? ''
      : `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}`
  } catch {
    return ''
  }
}
</script>

<template>
  <Transition name="preview-fade">
  <div v-if="mode" class="preview-article border border-neutral-200 rounded overflow-hidden bg-white flex flex-col">

    <!-- Header : reset + label (hashtag article OU "Manifeste") -->
    <div class="flex items-center justify-between px-4 py-2 border-b border-neutral-200 bg-white">
      <button
        class="text-xs text-neutral-500 hover:text-neutral-900 flex items-center gap-1"
        @click="close"
        type="button"
      >
        - Retour a la carte
      </button>
      <span
        v-if="mode === 'article' && selectedItem"
        class="text-xs text-neutral-400"
        style="font-family: 'Courier New', Courier, monospace;"
      >
        {{ selectedItem.hashtag }}
      </span>
      <span
        v-else-if="mode === 'manifeste'"
        class="text-xs text-neutral-400"
        style="font-family: 'Courier New', Courier, monospace;"
      >
        #manifeste
      </span>
    </div>

    <!-- Mode 'manifeste' : contenu manifeste -->
    <div v-if="mode === 'manifeste'" class="bg-white">
      <ManifesteContent />
    </div>

    <!-- Mode 'article' : V1.2-P legacy -->
    <template v-else-if="mode === 'article' && selectedItem">
      <!-- Teaser -->
      <div class="px-4 py-3 border-b border-neutral-100 bg-neutral-50">
        <p class="text-[11px] text-neutral-500 mb-1">{{ formatDate(selectedItem.date) }} - {{ selectedItem.platform }}</p>
        <h3 class="text-sm font-semibold text-neutral-900 leading-snug mb-1">{{ selectedItem.titre }}</h3>
        <p v-if="selectedItem.extrait" class="text-xs text-neutral-600 leading-relaxed line-clamp-3">
          {{ selectedItem.extrait }}
        </p>
        <img
          v-if="selectedItem.thumbnail"
          :src="selectedItem.thumbnail"
          :alt="selectedItem.titre"
          class="mt-2 w-full max-h-28 object-cover rounded"
          loading="lazy"
        />
      </div>

      <!-- Embed live (Substack ou Instagram) -->
      <div v-if="embedUrl" class="bg-white" style="height: 60vh; min-height: 400px;">
        <iframe
          :src="embedUrl"
          class="w-full h-full border-0"
          :title="selectedItem.titre"
          loading="lazy"
          sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation"
        ></iframe>
      </div>

      <!-- Carte incitative (autres plateformes) -->
      <div v-else class="flex flex-col items-start justify-center px-4 py-6">
        <p class="text-xs text-neutral-500 mb-3 italic">Embed non disponible pour cette plateforme.</p>
        <a
          :href="selectedItem.url"
          target="_blank"
          rel="noopener noreferrer"
          class="inline-block px-4 py-2 bg-neutral-900 text-white text-sm rounded-lg hover:bg-neutral-700 transition-colors"
        >
          Voir sur {{ platformLabel(selectedItem.platform) }} ->
        </a>
      </div>

      <!-- CTA propagation universel -->
      <div class="px-4 py-3 border-t border-neutral-100">
        <a
          :href="selectedItem.url"
          target="_blank"
          rel="noopener noreferrer"
          class="text-xs text-neutral-500 hover:text-neutral-900 underline"
        >
          Continuer sur {{ platformLabel(selectedItem.platform) }} - commenter, partager
        </a>
      </div>
    </template>
  </div>
  </Transition>
</template>

<style scoped>
/* V1.4-E2 : animation legere ouverture/fermeture preview (fade + slide-up subtil) */
.preview-fade-enter-active,
.preview-fade-leave-active {
  transition: opacity 0.25s ease, transform 0.25s ease;
}
.preview-fade-enter-from {
  opacity: 0;
  transform: translateY(8px);
}
.preview-fade-leave-to {
  opacity: 0;
  transform: translateY(4px);
}
</style>
