---
import { Icon } from 'astro-icon/components';
import { pb } from '@lib/pocketbase';
import type { Post } from '@globalInterfaces';

interface Props {
  currentTags: string[];
  currentSlug: string;
}

const { currentTags, currentSlug }: Props = Astro.props;

// Находим 5 похожих постов из PocketBase
let relatedPosts: Post[] = [];
if (currentTags && currentTags.length > 0) {
  try {
    // Формируем фильтр для поиска постов с похожими тегами
    const tagFilters = currentTags.map((tag: string) => `tags ~ "${tag}"`).join(' || ');
    const filter = `${tagFilters} && isActive = true && id != "${currentSlug}"`;

    const result = await pb.collection('posts').getList(1, 5, {
      filter: filter,
      sort: '-publishDate',
      requestKey: `related_posts_${currentSlug}`
    });

    relatedPosts = result.items.map(item => ({
      id: item.id,
      title: item.title,
      description: item.description,
      publishDate: item.publishDate,
      slug: item.slug,
      tags: item.tags || [],
      content: item.content,
      image: item.image,
      isFeatured: item.isFeatured,
      isActive: item.isActive
    }));
  } catch (error) {
    console.error('Ошибка при получении похожих статей:', error);
    relatedPosts = [];
  }
}
---

{relatedPosts.length > 0 && (
  <div class="mt-16 mb-20">
    <div class="border-t border-dashed border-neutral-300 dark:border-neutral-700"></div>
    <div class="mt-8">
      <h2 class="text-2xl font-bold mb-6 text-neutral-800 dark:text-neutral-200">Похожие статьи</h2>
      <ul class="flex flex-col gap-3">
        {relatedPosts.map(post => {
          const title = post.title.replace('{year}', new Date().getFullYear().toString());
          return (
            <li>
              <a
                href={`/blog/${post.slug}`}
                class="group flex items-center justify-between rounded-lg p-4 bg-neutral-50 dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800/60 border border-neutral-200/80 dark:border-neutral-800 transition-all duration-200 shadow-sm hover:shadow-md"
              >
                <span class="font-bold text-neutral-800 dark:text-neutral-200 group-hover:text-sky-600 dark:group-hover:text-sky-400 transition-colors duration-200">
                  {title}
                </span>
                <Icon name="chevron-left" class="h-5 w-5 text-neutral-400 dark:text-neutral-500 transform -rotate-180 transition-transform duration-200 group-hover:translate-x-1" />
              </a>
            </li>
          );
        })}
      </ul>
    </div>
  </div>
)}