---
import ArticleLayout from '@layouts/ArticleLayout.astro';
import { SITE_URL } from '@constants';
import Comments from '@components/blog/comments/Comments.tsx';
import RelatedPosts from '@components/blog/RelatedPosts.astro';
import ArticleTableOfContents from '@components/blog/ArticleTableOfContents.astro';
import { getPostBySlug, getPosts, getPostImageUrl, getPostVotesStats, getPostViews } from '@lib/pb';
import { marked } from 'marked';

export const prerender = false;

const slug = Astro.params.slug;

if (!slug) {
  return Astro.redirect('/blog');
}

const post = await getPostBySlug(slug);

if (!post) {
  return Astro.redirect('/blog');
}

const { likes = 0, dislikes = 0 } = await getPostVotesStats(post.id).catch(() => ({ likes: 0, dislikes: 0 }));
const views = await getPostViews(post.id).catch(() => 0);

// Конвертируем markdown в HTML
const contentHtml = marked(post.content || '');

// Извлекаем заголовки для оглавления (поддержка HTML и Markdown)
const headingRegex = /<h([2-3])[^>]*>([^<]+)<\/?h[2-3]>/gi;
const tocItems: { id: string; text: string; level: number }[] = [];
const body = post.content || '';
let match;
let headingIndex = 0;
while ((match = headingRegex.exec(body)) !== null) {
  const level = parseInt(match[1]); // Теперь 2 или 3
  const text = match[2].trim();
  tocItems.push({ level, id: `heading-${headingIndex++}`, text });
}
const formatDate = (date: string) => {
  const d = new Date(date);
  const day = d.getDate().toString().padStart(2, '0');
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const year = new Date().getFullYear().toString().slice(-2);
  return `${day}/${month}/${year}`;
};

// Для related posts берем те же категории
const { posts: relatedPosts } = await getPosts({ perPage: 4, category: post.category });
const filteredRelated = relatedPosts.filter(p => p.slug !== slug).slice(0, 3);

const currentUrl = `${SITE_URL}/blog/${slug}`;
const heroImage = getPostImageUrl(post);
---

<ArticleLayout
  title={`${post.title} — автоюрист в Сургуте`}
  description={post.description}
  canonicalLink={`${SITE_URL}/blog/${slug}`}
  breadcrumbs={[
    { label: 'Главная', href: '/' },
    { label: 'Блог', href: '/blog' },
    { label: post.title }
  ]}
  heroImage={heroImage}
  heroAlt={post.title}
  category={post.category}
  categoryColor={post.categoryColor}
  postTitle={post.title}
  date={formatDate(post.date)}
  author={post.author}
  readTime={post.readTime}
  readmeTime={post.readmeTime}
  postId={post.id}
  postUrl={currentUrl}
  initialLikes={likes}
  initialDislikes={dislikes}
  initialViews={views}
>
  <!-- Содержимое статьи в article -->
  <article class="article-content-wrapper" id="post-content">
    <div class="post-content" set:html={contentHtml} />
  </article>

  <!-- Комментарии и похожие статьи -->
<div class="comments-wrapper">
  <Comments postSlug={post.slug} client:load />
</div>

<RelatedPosts posts={filteredRelated} currentSlug={slug} />

  <!-- Оглавление -->
  <div slot="sidebar">
    <ArticleTableOfContents items={tocItems} />
  </div>
</ArticleLayout>

<style>
  /* Post Content */
  .post-content {
    padding: 0;
    color: #334155;
    line-height: 1.85;
    font-family: 'Merriweather', Georgia, serif;
  }

  .post-content :global(h2) {
    color: #1e293b;
    font-size: 1.75rem;
    font-weight: 700;
    margin: 2rem 0 1rem;
    letter-spacing: -0.02em;
    font-family: 'Merriweather', Georgia, serif;
    display: flex;
    align-items: baseline;
    gap: 0.6rem;
  }

  .post-content :global(h3) {
    color: #1e293b;
    font-size: 1.375rem;
    font-weight: 700;
    margin: 1.75rem 0 1rem;
    font-family: 'Merriweather', Georgia, serif;
    display: flex;
    align-items: baseline;
    gap: 0.5rem;
  }

  .post-content :global(p) {
    margin: 0 0 1.25rem;
    font-size: 1.05rem;
  }

  .post-content :global(ul), .post-content :global(ol) {
    margin: 1rem 0;
    padding-left: 1.5rem;
  }

  .post-content :global(li) {
    margin: 0.5rem 0;
    font-size: 1.05rem;
  }

  .post-content :global(blockquote) {
    margin: 2rem 0;
    padding: 1.5rem 2rem;
    background: #f8fafc;
    border-left: 4px solid #d4af37;
    border-radius: 0 0.75rem 0.75rem 0;
    font-style: italic;
  }

  .post-content :global(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 2rem 0;
    font-size: 0.95rem;
    background: #fff;
    border-radius: 0.5rem;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  .post-content :global(th) {
    background: #1e3a5f;
    color: #fff;
    padding: 1rem;
    text-align: left;
    font-weight: 600;
  }

  .post-content :global(td) {
    padding: 0.875rem 1rem;
    border-bottom: 1px solid #e2e8f0;
  }

  .post-content :global(tr:last-child td) {
    border-bottom: none;
  }

  .post-content :global(tr:hover td) {
    background: #f8fafc;
  }

  /* Comparison Grid */
  .post-content :global(.comparison-grid) {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 0;
    margin: 2rem 0;
    border-radius: 0.5rem;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  .post-content :global(.grid-row) {
    display: contents;
  }

  .post-content :global(.grid-cell) {
    padding: 1rem;
    border-bottom: 1px solid #e2e8f0;
    background: #fff;
    font-size: 0.95rem;
  }

  .post-content :global(.grid-header .grid-cell) {
    background: #1e3a5f;
    color: #fff;
    font-weight: 700;
    text-align: center;
  }

  .post-content :global(.grid-row:last-child .grid-cell) {
    border-bottom: none;
  }

  .post-content :global(.grid-row:hover .grid-cell) {
    background: #f8fafc;
  }

  @media (max-width: 768px) {
    .post-content {
      max-width: 100% !important;
      overflow-x: hidden !important;
      box-sizing: border-box;
    }

    .post-content :global(*) {
      max-width: 100% !important;
      box-sizing: border-box;
    }

    .post-content :global(h2) {
      font-size: 1rem;
      text-align: center;
      justify-content: center;
      box-sizing: border-box;
    }

    .post-content :global(h3) {
      font-size: 0.9rem;
      text-align: center;
      justify-content: center;
      box-sizing: border-box;
    }

    .post-content :global(p) {
      font-size: 0.9rem;
      box-sizing: border-box;
    }

    .post-content :global(li) {
      font-size: 0.9rem;
      box-sizing: border-box;
    }

    .post-content :global(table) {
      display: block;
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      max-width: 100% !important;
      width: auto !important;
      box-sizing: border-box;
    }

    .post-content :global(blockquote) {
      padding: 1rem;
      box-sizing: border-box;
      max-width: 100%;
    }

    .post-content :global(ul),
    .post-content :global(ol) {
      padding-left: 1rem;
      box-sizing: border-box;
    }

    /* Comparison Grid - мобильная версия */
    .post-content :global(.comparison-grid) {
      display: flex;
      flex-direction: column;
      gap: 0.75rem;
    }

    .post-content :global(.grid-row) {
      display: flex;
      flex-direction: column;
      background: #fff;
      border-radius: 0.5rem;
      overflow: hidden;
      box-shadow: 0 1px 2px rgba(0,0,0,0.08);
    }

    .post-content :global(.grid-header) {
      display: none;
    }

    .post-content :global(.grid-cell) {
      padding: 0.75rem 1rem;
      border: none;
      border-bottom: 1px solid #f1f5f9;
    }

    .post-content :global(.grid-cell:last-child) {
      border-bottom: none;
    }

    .post-content :global(.cell-label) {
      background: #1e3a5f;
      color: #fff;
      font-weight: 600;
    }

    .post-content :global(.cell-label + .grid-cell) {
      color: #64748b;
      font-size: 0.85rem;
    }

    .post-content :global(.cell-label + .grid-cell + .grid-cell) {
      color: #64748b;
      font-size: 0.85rem;
    }
  }
</style>