<!-- src/components/web/NewsSection.vue -->
<template>
  <section class="news-section">
    <div class="container">
      <!-- Header centrado -->
      <div class="header">
        <div class="header-left">
          <a-typography-title :level="2" class="title">
            Noticias y Comunicados
          </a-typography-title>

          <a-typography-paragraph class="subtitle">
            Entérate de los anuncios, resultados y novedades institucionales
          </a-typography-paragraph>
        </div>
      </div>

      <a-divider class="divider" />

      <!-- Grid -->
      <div v-if="mappedNoticias.length">
        <a-row :gutter="[24, 24]">
          <a-col
            v-for="noticia in mappedNoticias"
            :key="noticia.id"
            :xs="24"
            :sm="12"
            :lg="8"
          >
            <a-badge-ribbon
              :text="noticia.categoria || 'Noticia'"
              :color="noticia.tagColor"
            >
   
              <a-card
                hoverable
                class="card"
                :bodyStyle="{ padding: '16px' }"
                @click="openModal(noticia)"
              >
    
                <template v-if="noticia.imagen" #cover>
                  <div
                    class="cover"
                    :style="{ backgroundImage: `url(${noticia.imagen})` }"
                  >
                    <div class="cover-overlay" />
                    <div class="date-pill">
                      <CalendarOutlined />
                      <span>{{ noticia.fecha }}</span>
                    </div>
                  </div>
                </template>

                <a-space direction="vertical" size="small" class="content">
                  <div v-if="!noticia.imagen" class="date-inline">
                    <CalendarOutlined />
                    <span>{{ noticia.fecha }}</span>
                  </div>

                  <a-typography-title
                    :level="4"
                    class="card-title"
                    :content="noticia.titulo"
                    :ellipsis="{ rows: 2, tooltip: noticia.titulo }"
                  />

                  <a-typography-paragraph
                    class="desc"
                    :content="noticia.descripcion"
                    :ellipsis="{ rows: 3, tooltip: noticia.descripcion }"
                  />

                  <div class="actions">
          
                    <a-button
                      type="link"
                      class="read-more"
                      @click.stop="openModal(noticia)"
                    >
                      Leer más
                      <ArrowRightOutlined />
                    </a-button>

                    <a-tag v-if="noticia.destacado" color="gold" class="tag-soft">
                      Destacado
                    </a-tag>
                  </div>
                </a-space>
              </a-card>
            </a-badge-ribbon>
          </a-col>
        </a-row>
      </div>

  
      <a-modal
        v-model:open="modalOpen"
        :title="modalTitle"
        :footer="null"
        :width="860"
        destroyOnClose
        @afterClose="onAfterClose"
      >
        <div v-if="noticiasStore.loadingOne" style="padding: 8px 0">
          <a-skeleton active :paragraph="{ rows: 6 }" />
        </div>

        <a-alert
          v-else-if="noticiasStore.error"
          type="error"
          show-icon
          :message="noticiasStore.error"
        />

        <div v-else>
          <div v-if="modalImage" class="modal-cover">
            <img :src="modalImage" alt="Imagen de noticia" />
          </div>

          <div class="modal-meta">
            <a-tag :color="modalTagColor">{{ modalCategoria }}</a-tag>
            <span class="modal-date">
              <CalendarOutlined />
              {{ modalFecha }}
            </span>
          </div>

          <a-typography-paragraph v-if="modalDescripcion" class="modal-desc">
            {{ modalDescripcion }}
          </a-typography-paragraph>

          <div v-if="modalContenido" class="modal-content" v-html="modalContenido" />

          <a-empty v-else description="No hay contenido disponible para esta noticia." />
          <div v-if="modalLinkUrl" class="modal-link">
            <a-button
              type="primary"
              :href="modalLinkUrl"
              target="_blank"
              rel="noopener"
            >
              {{ modalLinkTexto }}
            </a-button>
          </div>
        </div>
      </a-modal>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from "vue"
import { CalendarOutlined, ArrowRightOutlined } from "@ant-design/icons-vue"
import { useNoticiasPublicasStore } from "../../store/noticiasPublicas.store"

const noticiasStore = useNoticiasPublicasStore()

onMounted(() => {
  if (!noticiasStore.noticias.length) noticiasStore.fetchNoticias()
})

const mappedNoticias = computed(() => {
  return (noticiasStore.noticias ?? []).map((n) => {
    const titulo = n.titulo ?? "Sin título"
    const descripcion = n.descripcion_corta ?? n.descripcion ?? "Sin descripción"

    const imagen = n.imagen_url ?? null

    return {
      id: n.id,
      slug: n.slug,
      titulo,
      descripcion,
      imagen,
      fecha: formatFecha(n.fecha_publicacion),
      categoria: n.categoria,
      tagColor: normalizeTagColor(n.tag_color),
      destacado: !!n.destacado,
      raw: n,
    }
  })
})

const modalOpen = ref(false)
const selectedNoticia = ref(null)

const modalTitle = computed(() => selectedNoticia.value?.titulo ?? "Detalle de noticia")
const detail = computed(() => noticiasStore.noticiaActual)

const modalImage = computed(() => {
  const d = detail.value
  return d?.imagen_url ?? selectedNoticia.value?.imagen ?? null
})

const modalFecha = computed(() => {
  const d = detail.value
  return formatFecha(d?.fecha_publicacion ?? selectedNoticia.value?.raw?.fecha_publicacion)
})

const modalCategoria = computed(() => {
  return detail.value?.categoria ?? selectedNoticia.value?.categoria ?? "General"
})

const modalTagColor = computed(() => {
  return normalizeTagColor(detail.value?.tag_color ?? selectedNoticia.value?.raw?.tag_color)
})

const modalDescripcion = computed(() => {
  const d = detail.value
  return d?.descripcion_corta ?? selectedNoticia.value?.descripcion ?? ""
})

const modalContenido = computed(() => {
  return detail.value?.contenido ?? ""
})

const modalLinkUrl = computed(() => detail.value?.link_url ?? null)
const modalLinkTexto = computed(() => detail.value?.link_texto ?? "Leer más")

const openModal = async (noticia) => {
  selectedNoticia.value = noticia
  modalOpen.value = true

  noticiasStore.clearNoticiaActual()

  const identifier = noticia.slug || noticia.id
  await noticiasStore.fetchNoticia(identifier)
}

const onAfterClose = () => {
  noticiasStore.clearNoticiaActual()
  selectedNoticia.value = null
}

const formatFecha = (iso) => {
  if (!iso) return "Sin fecha"
  const d = new Date(iso)
  if (isNaN(d.getTime())) return "Sin fecha"
  return d.toLocaleDateString("es-PE", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  })
}

const normalizeTagColor = (c) => {
  const val = String(c || "").trim().toLowerCase()
  const allowed = new Set([
    "blue",
    "red",
    "green",
    "orange",
    "purple",
    "cyan",
    "gold",
    "geekblue",
    "magenta",
    "lime",
    "volcano",
    "default",
  ])
  return allowed.has(val) ? val : "blue"
}
</script>


<style scoped>
.news-section {
  position: relative;
  padding: 88px 0;
  background: radial-gradient(1200px 400px at 20% 0%, #eef4ff 0%, transparent 55%),
              radial-gradient(1000px 420px at 95% 10%, #f3f0ff 0%, transparent 55%),
              #fbfcff;
  overflow: hidden;
  font-family: "Times New Roman", Times, serif;
}

.news-section::before {
  content: "";
  position: absolute;
  inset: 0;
  opacity: 0.40;
  pointer-events: none;
  background-image:
    repeating-linear-gradient(to right,
      rgba(13, 27, 82, 0.06) 0,
      rgba(13, 27, 82, 0.06) 1px,
      transparent 1px,
      transparent 28px
    ),
    repeating-linear-gradient(to bottom,
      rgba(13, 27, 82, 0.06) 0,
      rgba(13, 27, 82, 0.06) 1px,
      transparent 1px,
      transparent 28px
    );
}

.container {
  position: relative;
  z-index: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 18px;
}

.header-left {
  width: 100%;
  max-width: 820px;
  text-align: center;
}

.title {
  margin: 0 !important;
  text-align: center;
  font-family: "Times New Roman", Times, serif !important;
  font-weight: 900;
  color: #111a56;
  letter-spacing: -0.4px;
}

.subtitle {
  margin: 8px 0 0 !important;
  text-align: center;
  font-family: "Times New Roman", Times, serif;
  font-weight: 300;
  color: rgba(0, 0, 0, 0.58);
  line-height: 1.6;
  font-size: 1.02rem;
}

.divider {
  margin: 18px 0 28px !important;
  opacity: 0.6;
}

.card {
  border: 0;
  border-radius: 18px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.86);
  backdrop-filter: blur(8px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  transition: transform 0.18s ease, box-shadow 0.18s ease;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 18px 44px rgba(0, 0, 0, 0.12);
}

.cover {
  position: relative;
  height: 200px;

  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;

  background-color: rgba(17, 26, 86, 0.06);
}

.cover-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.06),
    rgba(0, 0, 0, 0.45)
  );
}

.date-pill {
  position: absolute;
  left: 14px;
  bottom: 14px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 999px;
  color: rgba(255, 255, 255, 0.92);
  background: rgba(17, 26, 86, 0.40);
  border: 1px solid rgba(255, 255, 255, 0.22);
  backdrop-filter: blur(8px);
  font-size: 0.92rem;
  font-weight: 700;
}

.date-inline {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 6px 10px;
  border-radius: 999px;
  width: fit-content;
  background: rgba(17, 26, 86, 0.06);
  border: 1px solid rgba(17, 26, 86, 0.12);
  color: #111a56;
  font-weight: 700;
  font-size: 0.9rem;
}

.card-title {
  margin: 0 0 8px;
  font-size: 1.2rem;
  font-weight: 700;
  color: rgba(0, 0, 0, 0.88);
}

.desc {
  margin: 0 !important;
  color: rgba(0, 0, 0, 0.62);
  line-height: 1.6;
  font-size: 0.98rem;
}

.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.read-more {
  padding: 0;
  font-weight: 900;
}

.tag-soft {
  border-radius: 999px;
  font-weight: 700;
}

.modal-cover {
  width: 100%;
  height: 360px;             
  overflow: hidden;
  border-radius: 14px;
  margin-bottom: 14px;
  border: 1px solid rgba(17, 26, 86, 0.10);
  background: rgba(17, 26, 86, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
}

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


.modal-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 8px 0 10px;
}

.modal-date {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: rgba(0, 0, 0, 0.55);
  font-weight: 700;
}

.modal-desc {
  color: rgba(0, 0, 0, 0.70);
  line-height: 1.7;
  margin-bottom: 12px !important;
}

.modal-content {
  line-height: 1.8;
  color: rgba(0, 0, 0, 0.80);
}
.modal-content :deep(img) {
  max-width: 100%;
  height: auto;
  display: block;
}
.modal-content :deep(p) {
  margin: 0 0 12px;
}

.modal-content :deep(img) {
  max-width: 100%;
  border-radius: 12px;
}

.modal-link {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .news-section {
    padding: 64px 0;
  }
}
</style>
