<script setup>
import { ArrowLeft, Facebook, Linkedin, Share2, Twitter } from 'lucide-vue-next'
import PublicArticleImage from '~/components/shared/PublicArticleImage.vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { resolveNewsArticleRoute, useNewsContent } from '~/content/news'
import { renderPublicRichText } from '~/utils/public-rich-text'
import { buildPublicSeoLinks } from '~/utils/public-seo'

const route = useRoute()
const requestUrl = useRequestURL()
const { locale } = usePublicLocale()
const ui = usePublicUi()
const { newsIndex, useResolvedNewsArticle, useResolvedNewsArticleBody } = await useNewsContent()

const article = useResolvedNewsArticle(computed(() => route.params.id))
const articleBody = useResolvedNewsArticleBody(computed(() => route.params.id))
const articleSeo = computed(() => article.value?.seo || null)
const canonicalArticlePath = computed(() => resolveNewsArticleRoute(article.value, locale.value))
const articleUrl = computed(() => new URL(route.path, requestUrl.origin).toString())
const shareTitle = computed(() => articleBody.value?.title || article.value?.title || ui.value.news.articleFallbackTitle)
const articleBodyHtml = computed(() => renderPublicRichText(articleBody.value?.bodyHtml || articleBody.value?.body || ''))
const bodyParagraphs = computed(() => Array.isArray(articleBody.value?.paragraphs) ? articleBody.value.paragraphs.filter(Boolean) : [])
const leadParagraph = computed(() => bodyParagraphs.value[0] || articleBody.value?.lead || articleBody.value?.summary || '')
const remainingParagraphs = computed(() => bodyParagraphs.value.slice(1))
const articleListItems = computed(() => Array.isArray(articleBody.value?.listItems) ? articleBody.value.listItems.filter((item) => item?.label) : [])
const articleQuote = computed(() => {
  const quote = String(articleBody.value?.quote || '').trim()
  const summary = String(articleBody.value?.summary || '').trim()

  if (!quote || quote === summary) {
    return ''
  }

  return quote
})
const articleQuoteAuthor = computed(() => String(articleBody.value?.quoteAuthor || '').trim())
const newsIndexRoute = computed(() => newsIndex.value?.path || '/news')
const copyLabel = ref(ui.value.news.copyLink)
const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(article.value, {
  sectionPath: newsIndexRoute.value,
}))

useRegisterPublicLocaleSwitchContext(localeSwitchContext)

if (article.value?.isFallback && locale.value !== article.value?.sourceLocale) {
  await navigateTo(newsIndexRoute.value, { redirectCode: 302 })
}

if (!article.value || !articleBody.value) {
  throw createError({
    statusCode: 404,
    statusMessage: ui.value.news.articleNotFound,
  })
}

useSeoMeta({
  title: () => articleSeo.value?.title || `${articleBody.value?.title || article.value?.title || 'News'} | bent.ge`,
  description: () => articleSeo.value?.description || articleBody.value?.summary || '',
  ogTitle: () => articleSeo.value?.ogTitle || articleSeo.value?.title || articleBody.value?.title || '',
  ogDescription: () => articleSeo.value?.ogDescription || articleSeo.value?.description || articleBody.value?.summary || '',
  ogImage: () => articleSeo.value?.ogImage || articleBody.value?.heroImage || '',
  robots: () => articleSeo.value?.robots || 'index,follow',
})

useHead(() => ({
  link: buildPublicSeoLinks(articleSeo.value),
}))

function openSharePopup(url) {
  if (!import.meta.client) {
    return
  }

  window.open(url, '_blank', 'noopener,noreferrer,width=640,height=720')
}

function shareOnTwitter() {
  openSharePopup(`https://twitter.com/intent/tweet?url=${encodeURIComponent(articleUrl.value)}&text=${encodeURIComponent(shareTitle.value)}`)
}

function shareOnFacebook() {
  openSharePopup(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(articleUrl.value)}`)
}

function shareOnLinkedin() {
  openSharePopup(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(articleUrl.value)}`)
}

async function copyArticleLink() {
  if (!import.meta.client) {
    return
  }

  try {
    if (navigator.share) {
      await navigator.share({
        title: shareTitle.value,
        url: articleUrl.value,
      })
      return
    }
  }
  catch (error) {
    if (error?.name === 'AbortError') {
      return
    }
  }

  try {
    await navigator.clipboard.writeText(articleUrl.value)
    copyLabel.value = ui.value.news.copied
    window.setTimeout(() => {
      copyLabel.value = ui.value.news.copyLink
    }, 1800)
  }
  catch {
    copyLabel.value = ui.value.news.shareUnavailable
    window.setTimeout(() => {
      copyLabel.value = ui.value.news.copyLink
    }, 1800)
  }
}
</script>

<template>
  <div class="bg-slate-50 min-h-screen">
    <div class="max-w-4xl mx-auto pt-32 pb-12 px-4 sm:px-6">
      <NuxtLink
        :to="newsIndexRoute"
        class="inline-flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-slate-500 hover:text-brand-orange transition-colors mb-12 group"
      >
        <ArrowLeft class="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
        {{ ui.news.backToAllNews }}
      </NuxtLink>

      <div class="flex flex-wrap items-center gap-4 mb-8">
        <span class="bg-slate-900 text-white text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full">
          {{ articleBody.badge }}
        </span>
        <span class="font-mono text-xs text-slate-500">{{ articleBody.date }}</span>
        <span class="font-mono text-xs text-slate-300">•</span>
        <span class="font-mono text-xs text-slate-500">{{ articleBody.readTime }}</span>
      </div>

      <h1 class="text-5xl md:text-7xl font-black text-slate-900 tracking-tighter leading-[1.05] mb-8">
        {{ articleBody.title }}
      </h1>

      <p class="text-xl md:text-2xl text-slate-500 font-medium leading-relaxed max-w-3xl">
        {{ articleBody.summary }}
      </p>
    </div>

    <div class="w-full max-w-[100rem] mx-auto px-4 sm:px-6 mb-16 md:mb-24">
      <div class="aspect-[4/3] md:aspect-[21/9] rounded-[2rem] overflow-hidden shadow-2xl">
        <PublicArticleImage
          :src="articleBody.heroImage"
          :alt="article.title"
          label="Story"
          img-class="w-full h-full object-cover"
          fallback-class="w-full h-full"
        />
      </div>
    </div>

    <div class="max-w-3xl mx-auto px-4 sm:px-6 pb-32">
      <div
        v-if="articleBodyHtml"
        class="article-rich-content text-lg md:text-xl text-slate-600 leading-relaxed"
        v-html="articleBodyHtml"
      />

      <div v-else class="space-y-8 text-lg md:text-xl text-slate-600 leading-relaxed">
        <p
          v-if="leadParagraph"
          class="first-letter:text-7xl md:first-letter:text-8xl first-letter:font-black first-letter:text-brand-orange first-letter:mr-4 first-letter:float-left first-letter:leading-[0.8]"
        >
          {{ leadParagraph }}
        </p>

        <p
          v-for="(paragraph, index) in remainingParagraphs"
          :key="`${articleBody.id}-paragraph-${index}`"
        >
          {{ paragraph }}
        </p>

        <ul v-if="articleListItems.length" class="list-none pl-0 my-10 space-y-4">
          <li
            v-for="item in articleListItems"
            :key="item.label"
            class="flex items-center gap-4 p-4 bg-white rounded-2xl border border-slate-100 shadow-sm"
          >
            <div class="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center font-black text-brand-orange">
              {{ item.count }}
            </div>
            <span class="font-bold text-slate-900">{{ item.label }}</span>
          </li>
        </ul>

        <blockquote
          v-if="articleQuote"
          class="border-l-4 border-brand-orange pl-6 py-2 my-12 italic text-2xl font-medium text-slate-700"
        >
          "{{ articleQuote }}"
          <footer
            v-if="articleQuoteAuthor"
            class="text-sm font-bold uppercase tracking-widest text-slate-400 mt-4 not-italic"
          >
            - {{ articleQuoteAuthor }}
          </footer>
        </blockquote>
      </div>

      <div class="mt-20 pt-10 border-t-2 border-slate-900 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6">
        <div>
          <span class="text-[10px] font-bold uppercase tracking-widest text-slate-400 block mb-2">{{ ui.common.shareStory }}</span>
          <div class="flex items-center gap-3">
            <button class="w-12 h-12 rounded-full border border-slate-200 flex items-center justify-center text-slate-600 hover:bg-brand-orange hover:border-brand-orange hover:text-white transition-all duration-300" type="button" :aria-label="ui.news.shareOnX" @click="shareOnTwitter">
              <Twitter class="w-5 h-5" />
            </button>
            <button class="w-12 h-12 rounded-full border border-slate-200 flex items-center justify-center text-slate-600 hover:bg-brand-orange hover:border-brand-orange hover:text-white transition-all duration-300" type="button" :aria-label="ui.news.shareOnFacebook" @click="shareOnFacebook">
              <Facebook class="w-5 h-5" />
            </button>
            <button class="w-12 h-12 rounded-full border border-slate-200 flex items-center justify-center text-slate-600 hover:bg-brand-orange hover:border-brand-orange hover:text-white transition-all duration-300" type="button" :aria-label="ui.news.shareOnLinkedIn" @click="shareOnLinkedin">
              <Linkedin class="w-5 h-5" />
            </button>
            <button class="w-12 h-12 rounded-full border border-slate-200 flex items-center justify-center text-slate-600 hover:bg-slate-900 hover:border-slate-900 hover:text-white transition-all duration-300" type="button" :aria-label="copyLabel" @click="copyArticleLink">
              <Share2 class="w-5 h-5" />
            </button>
          </div>
        </div>

        <NuxtLink
          :to="newsIndexRoute"
          class="bg-slate-900 text-white px-8 py-4 rounded-full font-bold uppercase tracking-widest text-xs hover:bg-brand-orange transition-colors"
        >
          {{ ui.news.backToNews }}
        </NuxtLink>
      </div>
    </div>
  </div>
</template>

<style scoped>
.article-rich-content :deep(p) {
  margin: 0 0 1.75rem;
}

.article-rich-content :deep(p:first-child)::first-letter {
  float: left;
  margin-right: 1rem;
  color: rgb(249 115 22);
  font-size: 4.5rem;
  font-weight: 900;
  line-height: 0.8;
}

.article-rich-content :deep(h2) {
  margin: 3rem 0 1.25rem;
  color: rgb(15 23 42);
  font-size: clamp(1.75rem, 3vw, 2.4rem);
  font-weight: 900;
  letter-spacing: -0.03em;
  line-height: 1.05;
}

.article-rich-content :deep(h3) {
  margin: 2rem 0 1rem;
  color: rgb(15 23 42);
  font-size: clamp(1.2rem, 2vw, 1.5rem);
  font-weight: 800;
  letter-spacing: -0.02em;
  line-height: 1.15;
}

.article-rich-content :deep(ul),
.article-rich-content :deep(ol) {
  margin: 1.75rem 0 2rem;
  padding-left: 1.5rem;
}

.article-rich-content :deep(li) {
  margin: 0.75rem 0;
  padding-left: 0.35rem;
}

.article-rich-content :deep(li::marker) {
  color: rgb(249 115 22);
  font-weight: 700;
}

.article-rich-content :deep(strong) {
  color: rgb(15 23 42);
  font-weight: 700;
}

.article-rich-content :deep(a) {
  color: rgb(249 115 22);
  font-weight: 600;
  text-decoration: underline;
  text-underline-offset: 0.18em;
}

.article-rich-content :deep(blockquote) {
  margin: 3rem 0;
  border-left: 4px solid rgb(249 115 22);
  padding: 0.5rem 0 0.5rem 1.5rem;
  color: rgb(51 65 85);
  font-size: clamp(1.4rem, 2.4vw, 1.9rem);
  font-style: italic;
  font-weight: 500;
}

.article-rich-content :deep(code) {
  border-radius: 0.5rem;
  background: rgb(241 245 249);
  padding: 0.15rem 0.45rem;
  color: rgb(15 23 42);
  font-size: 0.88em;
}
</style>
