<script lang="ts" setup>
import { Head, Link } from '@inertiajs/vue3'
import { ref } from 'vue'
import MarketingLayout from '@/Layouts/MarketingLayout.vue'
import type { KnowledgeBaseArticle } from '@/types'

interface Breadcrumb {
  name: string
  slug: string
}

interface RelatedArticle {
  id: number
  title: string
  slug: string
  excerpt: string | null
  view_count: number
  published_at: string | null
}

interface Props {
  article: KnowledgeBaseArticle
  htmlContent: string
  breadcrumbs: Breadcrumb[]
  relatedArticles: RelatedArticle[]
}

defineOptions({ layout: MarketingLayout })

const props = defineProps<Props>()

const voteSubmitted = ref<boolean>(false)
const helpfulCount = ref<number>(props.article.helpful_count)
const notHelpfulCount = ref<number>(props.article.not_helpful_count)

function formatDate(dateString: string | null): string {
  if (!dateString) {
    return ''
  }
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  })
}

async function vote(isHelpful: boolean): Promise<void> {
  if (voteSubmitted.value) {
    return
  }

  try {
    const response = await fetch(`/knowledge-base/articles/${props.article.id}/vote`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content ?? '',
      },
      body: JSON.stringify({ is_helpful: isHelpful }),
    })

    const data = await response.json()
    helpfulCount.value = data.helpful_count
    notHelpfulCount.value = data.not_helpful_count
    voteSubmitted.value = true
  } catch {
    // Silently fail
  }
}
</script>

<template>
  <Head :title="`${article.title} - Knowledge Base | EZSCALE`" />
  <div>
    <VContainer class="py-12">
      <!-- Breadcrumbs -->
      <VBreadcrumbs class="px-0 mb-6">
        <VBreadcrumbsItem>
          <Link href="/" class="text-decoration-none">
            Home
          </Link>
        </VBreadcrumbsItem>
        <VBreadcrumbsDivider />
        <VBreadcrumbsItem>
          <Link href="/knowledge-base" class="text-decoration-none">
            Knowledge Base
          </Link>
        </VBreadcrumbsItem>
        <template v-for="crumb in breadcrumbs" :key="crumb.slug">
          <VBreadcrumbsDivider />
          <VBreadcrumbsItem>
            <Link :href="`/knowledge-base/${crumb.slug}`" class="text-decoration-none">
              {{ crumb.name }}
            </Link>
          </VBreadcrumbsItem>
        </template>
        <VBreadcrumbsDivider />
        <VBreadcrumbsItem disabled>
          {{ article.title }}
        </VBreadcrumbsItem>
      </VBreadcrumbs>

      <VRow>
        <!-- Article Content -->
        <VCol cols="12" :md="relatedArticles.length > 0 ? 8 : 12">
          <!-- Article Header -->
          <div class="mb-8">
            <h1 class="text-h3 font-weight-bold mb-3">{{ article.title }}</h1>
            <div class="d-flex align-center gap-4 text-body-2 text-medium-emphasis">
              <span v-if="article.author">
                <VIcon icon="tabler-user" size="16" class="me-1" />
                {{ article.author.name }}
              </span>
              <span v-if="article.published_at">
                <VIcon icon="tabler-calendar" size="16" class="me-1" />
                {{ formatDate(article.published_at) }}
              </span>
              <span>
                <VIcon icon="tabler-eye" size="16" class="me-1" />
                {{ article.view_count.toLocaleString() }} views
              </span>
            </div>
          </div>

          <!-- Article Body -->
          <VCard variant="outlined" class="mb-8">
            <VCardText class="pa-6 pa-md-8">
              <!-- eslint-disable vue/no-v-html -->
              <div class="kb-article-content" v-html="htmlContent" />
              <!-- eslint-enable vue/no-v-html -->
            </VCardText>
          </VCard>

          <!-- Voting Widget -->
          <VCard variant="outlined" class="mb-8">
            <VCardText class="text-center pa-6">
              <h3 class="text-h6 font-weight-bold mb-2">Was this article helpful?</h3>
              <p class="text-body-2 text-medium-emphasis mb-4">
                Let us know if this article helped you find what you were looking for.
              </p>

              <div v-if="!voteSubmitted" class="d-flex justify-center gap-4">
                <VBtn
                  color="success"
                  variant="outlined"
                  prepend-icon="tabler-thumb-up"
                  @click="vote(true)"
                >
                  Yes ({{ helpfulCount }})
                </VBtn>
                <VBtn
                  color="error"
                  variant="outlined"
                  prepend-icon="tabler-thumb-down"
                  @click="vote(false)"
                >
                  No ({{ notHelpfulCount }})
                </VBtn>
              </div>

              <div v-else>
                <VIcon icon="tabler-check" color="success" size="24" class="me-2" />
                <span class="text-body-1 font-weight-medium">Thank you for your feedback!</span>
                <div class="d-flex justify-center gap-4 mt-3 text-body-2 text-medium-emphasis">
                  <span>{{ helpfulCount }} found helpful</span>
                  <span>{{ notHelpfulCount }} found not helpful</span>
                </div>
              </div>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar: Related Articles -->
        <VCol v-if="relatedArticles.length > 0" cols="12" md="4">
          <VCard variant="outlined" class="sticky" style="top: 80px;">
            <VCardTitle class="text-subtitle-1 font-weight-bold pa-4">
              Related Articles
            </VCardTitle>
            <VDivider />
            <VList density="compact">
              <VListItem
                v-for="related in relatedArticles"
                :key="related.id"
                :href="`/knowledge-base/${article.category?.slug}/${related.slug}`"
                class="text-decoration-none"
              >
                <VListItemTitle class="text-body-2 font-weight-medium" style="white-space: normal;">
                  {{ related.title }}
                </VListItemTitle>
                <VListItemSubtitle class="text-caption">
                  <VIcon icon="tabler-eye" size="12" class="me-1" />
                  {{ related.view_count }} views
                </VListItemSubtitle>
              </VListItem>
            </VList>
          </VCard>
        </VCol>
      </VRow>
    </VContainer>
  </div>
</template>

<style scoped>
.kb-article-content :deep(h1),
.kb-article-content :deep(h2),
.kb-article-content :deep(h3),
.kb-article-content :deep(h4) {
  margin-block-start: 1.5em;
  margin-block-end: 0.5em;
  font-weight: 700;
}

.kb-article-content :deep(h1) {
  font-size: 1.75rem;
}

.kb-article-content :deep(h2) {
  font-size: 1.5rem;
}

.kb-article-content :deep(h3) {
  font-size: 1.25rem;
}

.kb-article-content :deep(p) {
  margin-block-end: 1em;
  line-height: 1.7;
}

.kb-article-content :deep(code) {
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'JetBrains Mono', monospace;
  font-size: 0.875em;
  background: rgba(var(--v-theme-on-surface), 0.08);
}

.kb-article-content :deep(pre) {
  margin-block-end: 1em;
  padding: 1em;
  overflow-x: auto;
  border-radius: 8px;
  background: rgba(var(--v-theme-on-surface), 0.05);
}

.kb-article-content :deep(pre code) {
  padding: 0;
  background: none;
}

.kb-article-content :deep(ul),
.kb-article-content :deep(ol) {
  margin-block-end: 1em;
  padding-inline-start: 1.5em;
}

.kb-article-content :deep(li) {
  margin-block-end: 0.25em;
}

.kb-article-content :deep(blockquote) {
  margin-block-end: 1em;
  padding: 0.5em 1em;
  border-inline-start: 4px solid rgb(var(--v-theme-primary));
  font-style: italic;
  opacity: 0.85;
}

.kb-article-content :deep(img) {
  max-inline-size: 100%;
  border-radius: 8px;
}

.kb-article-content :deep(a) {
  color: rgb(var(--v-theme-primary));
  text-decoration: none;
}

.kb-article-content :deep(a:hover) {
  text-decoration: underline;
}

.kb-article-content :deep(table) {
  inline-size: 100%;
  margin-block-end: 1em;
  border-collapse: collapse;
}

.kb-article-content :deep(th),
.kb-article-content :deep(td) {
  padding: 0.5em 1em;
  border: 1px solid rgba(var(--v-theme-on-surface), 0.12);
  text-align: start;
}

.kb-article-content :deep(th) {
  font-weight: 700;
  background: rgba(var(--v-theme-on-surface), 0.04);
}
</style>
