---
export const prerender = false;

import Layout from '@layouts/Layout.astro';
import { authService } from '@/lib/authService';

import PartnersSponsors from '@components/blog/PartnersSponsors.astro';
import PostCard from '@components/blog/PostCard.astro';
import TagsCloud from '@components/blog/TagsCloud.astro';
import PopularPosts from '@components/blog/PopularPosts.astro';
import SocialFollow from '@components/blog/SocialFollow.astro';

// Подключаемся к PocketBase и получаем статьи
const pb = authService.createClientFromRequest(Astro.request);

// Получаем все опубликованные статьи
const allPostsResponse = await pb.collection('posts').getList(1, 100, {
  filter: 'isDraft = false',
  sort: '-date',
  expand: '',
});

const allPosts = allPostsResponse.items;
const totalPosts = allPostsResponse.totalItems;

// Получаем параметр страницы из URL
const { page } = Astro.url.searchParams;
const currentPage = parseInt(page) || 1;
const pageSize = 6;
const totalPages = Math.ceil(totalPosts / pageSize);

// Определяем статьи для текущей страницы
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pagePosts = allPosts.slice(startIndex, endIndex);

// Получаем глобальные настройки сайта из PocketBase
const siteSettings = await pb.collection('site_settings').getFirstListItem('');
const siteUrl = siteSettings.site_url;

// Получаем данные страницы из PocketBase
const pageData = await pb.collection('pages').getFirstListItem('slug = "blog"');
const baseTitle = pageData.title;
const description = pageData.meta_description;

// Подготовка данных для сайдбара
const popularPostsList = allPosts.slice(0, 3);

// Подсчет тегов
const tagCounts = allPosts.reduce((acc: Record<string, number>, post) => {
  if (post.tags && Array.isArray(post.tags)) {
    post.tags.forEach((tag: string) => {
      acc[tag] = (acc[tag] || 0) + 1;
    });
  } else if (post.tags && typeof post.tags === 'string') {
    // Если теги хранятся как строка (массив в виде строки), нужно обработать по-другому
    // В PocketBase тип text с maxSelect > 1 возвращает массив, но иногда может быть строка
    const tagsArray = JSON.parse(post.tags);
    if (Array.isArray(tagsArray)) {
      tagsArray.forEach((tag: string) => {
        acc[tag] = (acc[tag] || 0) + 1;
      });
    }
  }
  return acc;
}, {} as Record<string, number>);

let pageTitle = currentPage > 1 ? `${pageData.title} - Seite ${currentPage}` : pageData.title;

// Ensure title does not exceed 70 characters
if (pageTitle.length > 70) {
  // Truncate if too long
  pageTitle = pageTitle.substring(0, 67) + '...';
}
const canonicalLink = pageData.canonical_url ? 
  pageData.canonical_url : 
  (currentPage === 1 ? `${siteUrl}/blog` : `${siteUrl}/blog?page=${currentPage}`);
---

<Layout title={pageTitle} description={description} canonicalLink={canonicalLink} skipSiteName={true}>
    <!-- Фоновая декорация -->
    <div class="absolute inset-x-0 top-0 -z-10 transform-gpu overflow-hidden blur-3xl sm:-top-80" aria-hidden="true">
        <div class="relative left-[calc(50%-11rem)] aspect-1155/678 w-144.5 -translate-x-1/2 rotate-30 bg-gradient-to-tr from-blue-400 to-amber-400 opacity-20 sm:left-[calc(50%-30rem)] sm:w-[72.1875rem]"></div>
    </div>

    <div class="max-w-7xl mx-auto px-4 py-12 sm:px-6 lg:px-8">

        {/* HERO SECTION */}
        <div class="text-center py-16 mb-12 border-b border-gray-100">
            <h1 class="text-4xl font-extrabold tracking-tight text-gray-900 sm:text-5xl lg:text-6xl mb-6">
                {currentPage > 1 ? `Alle Artikel - Seite ${currentPage}` : 'Neueste Artikel und Blog'}
            </h1>
            <p class="max-w-2xl mx-auto text-xl text-gray-500">
                Einblicke, Tutorials und Neuigkeiten aus der Welt der Entwicklung.
            </p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-12 gap-10">

            {/* --- Основной контент --- */}
            <main class="lg:col-span-8">

                {/* Секция "Популярное" для первой страницы */}
                {currentPage === 1 && popularPostsList.length > 0 && (
                        <section class="mb-16">
                            <div class="flex items-center gap-2 mb-6">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-red-500" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M12.395 2.553a1 1 0 00-1.45-.385c-.345.23-.614.558-.822.88-.214.33-.403.713-.57 1.116-.334.804-.614 1.768-.84 2.734a31.365 31.365 0 00-.613 3.58 2.64 2.64 0 01-.945-1.067c-.328-.68-.398-1.45-.412-1.725a1 1 0 00-1.996.067c.01.265.034.793.18 1.488.134.636.353 1.25.65 1.776a3.79 3.79 0 00.744.975 6.002 6.002 0 00-2.316 2.053c-.34.52-.556 1.096-.615 1.67-.063.61.026 1.21.246 1.763.218.547.56 1.037.994 1.425.438.391.956.685 1.503.864.577.19 1.196.229 1.815.114.618-.115 1.226-.388 1.772-.782a6.035 6.035 0 001.373-1.417c.21.05.424.076.637.076.994 0 1.933-.563 2.531-1.396.656-.913.795-2.122.368-3.177a3.52 3.52 0 00-.818-1.192 10.428 10.428 0 00.932-1.944c.15-.436.26-.884.32-1.332.067-.5.06-1.025-.018-1.572a1 1 0 00-.776-.856z" clip-rule="evenodd" />
                                </svg>
                                <h2 class="text-2xl font-bold text-gray-800">Trending Now</h2>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                {/* Первую статью делаем большой, остальные обычной */}
                                {popularPostsList.slice(0, 1).map((post) => (
                                        <div class="md:col-span-2">
                                            <PostCard post={post} />
                                        </div>
                                ))}
                                {popularPostsList.slice(1, 3).map((post) => (
                                        <PostCard post={post} compact={true} />
                                ))}
                            </div>
                        </section>
                )}

                <div class="flex items-center justify-between mb-6 border-b border-gray-100 pb-4">
                    <h2 class="text-2xl font-bold text-gray-800">Neueste Artikel</h2>
                    <span class="text-sm text-gray-500">Seite {currentPage} von {totalPages}</span>
                </div>

                {pagePosts.length > 0 ? (
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-8 auto-rows-fr">
                            {currentPage === 1
                              ? pagePosts
                                  .filter(post => !popularPostsList.some(popularPost => popularPost.id === post.id))
                                  .slice(0, 4)
                                  .map((post) => (
                                    <PostCard post={post} />
                                ))
                              : pagePosts.map((post) => (
                                    <PostCard post={post} />
                                ))
                            }
                        </div>
                ) : (
                        <div class="flex flex-col items-center justify-center py-20 bg-white rounded-2xl border border-dashed border-gray-300">
                            <svg class="h-16 w-16 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z" />
                            </svg>
                            <h3 class="text-lg font-medium text-gray-900">Keine Beiträge gefunden</h3>
                            <p class="text-gray-500 mt-1">Versuchen Sie es später noch einmal.</p>
                        </div>
                )}

                <div class="mt-12">
                    {totalPages > 1 && (
                        <nav class="flex justify-center items-center gap-6 mt-12" aria-label="Pagination">
                            {currentPage > 1 ? (
                                <a
                                    href={`/blog?page=${currentPage - 1}`}
                                    class="inline-flex items-center justify-center w-12 h-12 bg-white rounded-full border border-gray-200 text-gray-600 hover:bg-gray-100 hover:text-gray-900 hover:shadow-md transition-all duration-300 group"
                                    aria-label="Vorherige Seite"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
                                    </svg>
                                </a>
                            ) : (
                                <span
                                    class="inline-flex items-center justify-center w-12 h-12 bg-white rounded-full border border-gray-200 text-gray-300 cursor-not-allowed"
                                    aria-label="Vorherige Seite"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
                                    </svg>
                                </span>
                            )}

                            <span class="text-sm text-gray-700">
                                Seite <span class="font-medium">{currentPage}</span> von <span class="font-medium">{totalPages}</span>
                            </span>

                            {currentPage < totalPages ? (
                                <a
                                    href={`/blog?page=${currentPage + 1}`}
                                    class="inline-flex items-center justify-center w-12 h-12 bg-white rounded-full border border-gray-200 text-gray-600 hover:bg-gray-100 hover:text-gray-900 hover:shadow-md transition-all duration-300 group"
                                    aria-label="Nächste Seite"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
                                    </svg>
                                </a>
                            ) : (
                                <span
                                    class="inline-flex items-center justify-center w-12 h-12 bg-white rounded-full border border-gray-200 text-gray-300 cursor-not-allowed"
                                    aria-label="Nächste Seite"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
                                    </svg>
                                </span>
                            )}
                        </nav>
                    )}
                </div>
            </main>

            {/* --- Сайдбар --- */}
            <aside class="lg:col-span-4 space-y-8">
                {/* Поиск (можно добавить позже) */}

                {/* Облако тегов */}
                {Object.keys(tagCounts).length > 0 && (
                        <TagsCloud tags={tagCounts} />
                )}

                {/* Популярные в сайдбаре (если не первая страница или просто дубль для навигации) */}
                <PopularPosts posts={popularPostsList} />

                {/* Партнеры */}
                <PartnersSponsors />

                {/* Side Projects */}
                <SocialFollow />
            </aside>

        </div>
    </div>
</Layout>