---
import Layout from "@layouts/Layout.astro";
import BlogPost from "@components/single-post/BlogPost.astro";
import Comments from "@components/single-post/Comments";
import RelatedPosts from "@components/single-post/RelatedPosts.astro";
import { ARTICLE_AUTHOR } from "@lib/constants";
import { MONTHS } from "@lib/constants";

const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";

interface PostRecord {
  id: string;
  title: string;
  slug: string;
  content: string;
  excerpt: string;
  image?: string;
  tableOfContents?: Array<{ id: string; title: string }>;
  tags?: string[];
  readTime?: number;
  likes?: number;
  dislikes?: number;
  created: string;
  updated: string;
}

interface PocketBaseResponse {
  items: PostRecord[];
}

// Отключаем пререндеринг для динамической генерации
export const prerender = false;

const { slug } = Astro.params;

// Получаем конкретный пост по slug
let post: PostRecord | null = null;

try {
  const response = await fetch(
    `${POCKETBASE_URL}/api/collections/posts/records?filter=slug%3D%22${slug}%22`
  );
  const data: PocketBaseResponse = await response.json();

  if (data.items && data.items.length > 0) {
    post = data.items[0];
  }
} catch (error) {
  console.error("[BlogPost] Error fetching post from PocketBase:", error);
}

if (!post) {
  throw new Error(`Blog post not found: ${slug}`);
}

// Формируем URL изображения из PocketBase
const imageUrl = post.image 
  ? `${POCKETBASE_URL}/api/files/posts/${post.id}/${post.image}`
  : undefined;

// Парсим tags из JSON строки если нужно
let tags: string[] = [];
if (post.tags) {
  try {
    tags = typeof post.tags === "string" ? JSON.parse(post.tags) : post.tags;
  } catch {
    tags = Array.isArray(post.tags) ? post.tags : [];
  }
}

// Парсим tableOfContents из JSON строки если нужно
let tableOfContents: Array<{ id: string; title: string }> = [];
if (post.tableOfContents) {
  try {
    tableOfContents = typeof post.tableOfContents === "string" 
      ? JSON.parse(post.tableOfContents) 
      : post.tableOfContents;
  } catch {
    tableOfContents = Array.isArray(post.tableOfContents) ? post.tableOfContents : [];
  }
}

// Форматируем дату из created
const createdDate = new Date(post.created);
const isValidDate = !isNaN(createdDate.getTime());
const formattedDate = isValidDate
  ? `${createdDate.getDate()} ${MONTHS[createdDate.getMonth()]} ${createdDate.getFullYear()} года`
  : "Дата не указана";

// Декодируем HTML сущности в контенте
function decodeHtmlEntities(html: string): string {
  return html
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&amp;/g, '&')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&nbsp;/g, ' ')
    .replace(/&ndash;/g, '–')
    .replace(/&mdash;/g, '—');
}

const decodedContent = decodeHtmlEntities(post.content);
---

<Layout
  title={post.title}
  description={post.excerpt}
  pagePath={`/blog/${slug}`}
  blogPostTitle={post.title}
  bodyClass="bg-[#F8F9FA] text-gray-900"
>
  <main class="min-h-screen bg-[#F8F9FA] -mx-4 md:mx-0 overflow-x-hidden">
    <!-- Декоративный фон -->
    <div class="fixed inset-0 pointer-events-none">
      <div
        class="absolute top-0 left-1/4 w-96 h-96 bg-[var(--color-blue-primary)] opacity-5 rounded-full blur-3xl"
      >
      </div>
      <div
        class="absolute bottom-0 right-1/4 w-96 h-96 bg-[var(--color-gold)] opacity-5 rounded-full blur-3xl"
      >
      </div>
    </div>

    <div class="relative z-10">
      <BlogPost
        title={post.title}
        excerpt={post.excerpt}
        author={{
          name: ARTICLE_AUTHOR.name,
          avatar: ARTICLE_AUTHOR.avatar,
          role: ARTICLE_AUTHOR.role,
        }}
        publishDate={formattedDate}
        readTime={post.readTime ? `${post.readTime} мин чтения` : "5 мин чтения"}
        tags={tags}
        featuredImage={imageUrl}
        tableOfContents={tableOfContents}
        postId={post.id}
        likes={post.likes || 0}
        dislikes={post.dislikes || 0}
      >
        <!-- ✅ HTML контент из PocketBase Rich Editor -->
        <div set:html={decodedContent} />
      </BlogPost>

      <div
        class="bg-white rounded-2xl shadow-sm border border-gray-200 p-8 md:p-10 mt-12"
      >
        <div id="comments-section">
          <Comments client:only="solid" postSlug={post.id} />
        </div>
      </div>

      <RelatedPosts currentPostId={post.id} currentPostSlug={slug} />
    </div>
  </main>
</Layout>
