---
import Layout from '@layouts/Layout.astro';
import PostCard from '@components/blog/PostCard.astro';
import SidebarSearch from '@components/blog/SidebarSearch.astro';
import SidebarPopular from '@components/blog/SidebarPopular.astro';
import SidebarCategories from '@components/blog/SidebarCategories.astro';
import TagCloud from '@components/blog/TagCloud.astro';
import { MONTHS } from '@lib/constants';

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

interface PostRecord {
    id: string;
    title: string;
    slug: string;
    excerpt: string;
    image?: string;
    category?: string;
    created: string;
}

interface PocketBaseResponse {
    items: PostRecord[];
}

interface CategoryItem {
    name: string;
    count: number;
}

// Получаем поисковый запрос из URL
const searchQuery = Astro.url.searchParams.get('q') || '';

// Загружаем посты из PocketBase с поиском по заголовку и контенту
let posts: Array<{
    id: string;
    image: string;
    category: string;
    title: string;
    excerpt: string;
    date: string;
    slug: string;
}> = [];

let searchPerformed = false;

if (searchQuery) {
    searchPerformed = true;
    try {
        // Ищем по title и content с использованием full-text поиска PocketBase
        const encodedQuery = encodeURIComponent(`title ~ "${searchQuery}" || content ~ "${searchQuery}"`);
        const response = await fetch(`${POCKETBASE_URL}/api/collections/posts/records?filter=${encodedQuery}&perPage=20&sort=-created`);
        const data: PocketBaseResponse = await response.json();

        if (data.items) {
            posts = data.items.map((post) => {
                const date = new Date(post.created);
                const formattedDate = `${date.getDate()} ${MONTHS[date.getMonth()]} ${date.getFullYear()} года`;

                const imageUrl = post.image
                    ? `${POCKETBASE_URL}/api/files/posts/${post.id}/${post.image}`
                    : "https://images.unsplash.com/photo-1556761175-5973dc0f32e7?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80";

                const postCategory = post.category && post.category.trim() !== "" ? post.category : "НОВОСТИ";

                return {
                    id: post.id,
                    image: imageUrl,
                    category: postCategory,
                    title: post.title,
                    excerpt: post.excerpt,
                    date: formattedDate,
                    slug: `/blog/${post.slug}`
                };
            });
        }
    } catch (error) {
        console.error("Error searching posts from PocketBase:", error);
    }
}

const popularPosts = [
    {
        image: "https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=200&h=200&fit=crop&q=80",
        title: "Как обжаловать решение суда первой инстанции",
        views: "2.4K просмотров"
    },
    {
        image: "https://images.unsplash.com/photo-1589829085413-56de8ae18c73?w=200&h=200&fit=crop&q=80",
        title: "Снижение кадастровой стоимости в Сургуте",
        views: "1.8K просмотров"
    },
    {
        image: "https://images.unsplash.com/photo-1569336415962-a4bd9f69cd83?w=200&h=200&fit=crop&q=80",
        title: "Защита прав потребителей при покупке авто",
        views: "1.5K просмотров"
    }
];

// Загружаем категории для сайдбара
let categories: CategoryItem[] = [];

try {
    const allPostsResponse = await fetch(`${POCKETBASE_URL}/api/collections/posts/records?perPage=500`);
    const allPostsData: PocketBaseResponse = await allPostsResponse.json();

    if (allPostsData.items) {
        const categoryMap = new Map<string, number>();

        allPostsData.items.forEach((post) => {
            const cat = post.category && post.category.trim() !== "" ? post.category : "НОВОСТИ";
            const currentCount = categoryMap.get(cat) || 0;
            categoryMap.set(cat, currentCount + 1);
        });

        categories = Array.from(categoryMap.entries())
            .map(([name, count]) => ({ name, count }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 6);
    }
} catch (error) {
    console.error("Error fetching categories from PocketBase:", error);
    categories = [];
}

// SEO данные
const pageTitle = searchQuery ? `Поиск: ${searchQuery}` : 'Поиск по статьям';
const pageDescription = searchQuery ? `Результаты поиска по запросу "${searchQuery}"` : 'Поиск по всем статьям блога';
---

<Layout
    title={pageTitle}
    description={pageDescription}
    pagePath={`/blog/search${searchQuery ? `?q=${searchQuery}` : ''}`}
>
    <div class="relative min-h-screen py-16 mb-6 overflow-hidden">
        <!-- Декоративный фон -->
        <div class="absolute inset-0 bg-gradient-to-b from-gray-50 to-white pointer-events-none"></div>
        <div class="absolute top-0 left-1/4 w-96 h-96 bg-[var(--color-blue-primary)] opacity-5 rounded-full blur-3xl pointer-events-none"></div>
        <div class="absolute bottom-0 right-1/4 w-96 h-96 bg-[var(--color-gold)] opacity-5 rounded-full blur-3xl pointer-events-none"></div>

        <div class="relative z-10 w-full px-4 md:container md:mx-auto md:px-4 md:max-w-7xl">
            <!-- Заголовок секции -->
            <div class="flex items-center justify-between mb-12">
                <div>
                    <div class="flex items-center gap-3 mb-2">
                        <a href="/blog" class="text-sm font-semibold text-gray-500 hover:text-[var(--color-blue-primary)] transition-colors flex items-center gap-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                            </svg>
                            Все статьи
                        </a>
                        <span class="text-gray-300">/</span>
                        <span class="text-sm font-semibold text-[var(--color-blue-primary)]">Поиск</span>
                    </div>
                    {searchQuery && (
                        <Fragment>
                            <h1 class="text-3xl md:text-4xl font-bold text-gray-900 mb-2">
                                Результаты поиска
                            </h1>
                            <div class="flex items-center gap-3">
                                <div class="px-4 py-1.5 bg-[var(--color-blue-primary)]/10 rounded-full">
                                    <span class="text-sm font-bold text-[var(--color-blue-primary)]">"{searchQuery}"</span>
                                </div>
                                <div class="w-20 h-1 bg-gradient-to-r from-[var(--color-gold)] to-[var(--color-gold-hover)] rounded-full"></div>
                                <span class="text-sm text-gray-500 font-medium">
                                    {`${posts.length} ${posts.length === 1 ? 'статья' : posts.length >= 2 && posts.length <= 4 ? 'статьи' : 'статей'}`}
                                </span>
                            </div>
                        </Fragment>
                    )}
                    {!searchQuery && (
                        <Fragment>
                            <h1 class="text-3xl md:text-4xl font-bold text-gray-900 mb-2">
                                Поиск по статьям
                            </h1>
                            <div class="w-20 h-1 bg-gradient-to-r from-[var(--color-gold)] to-[var(--color-gold-hover)] rounded-full"></div>
                        </Fragment>
                    )}
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
                <!-- Основной контент -->
                <main class="lg:col-span-8">
                    {searchPerformed ? (
                        posts.length > 0 ? (
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-12">
                                {posts.map((post) => (
                                    <PostCard post={post} />
                                ))}
                            </div>
                        ) : (
                            <div class="bg-white/80 backdrop-blur-xl rounded-2xl p-12 text-center border border-white/50 shadow-lg">
                                <svg class="w-16 h-16 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                                </svg>
                                <h3 class="text-xl font-bold text-gray-900 mb-2">Ничего не найдено</h3>
                                <p class="text-gray-600 mb-6">
                                    По запросу <span class="font-semibold">"{searchQuery}"</span> не найдено статей.
                                </p>
                                <div class="flex flex-col gap-3">
                                    <p class="text-sm text-gray-500">Попробуйте:</p>
                                    <ul class="text-sm text-gray-600 space-y-1">
                                        <li>• Изменить поисковый запрос</li>
                                        <li>• Использовать более общие keywords</li>
                                        <li>• Проверить правильность написания</li>
                                    </ul>
                                </div>
                                <a 
                                    href="/blog" 
                                    class="mt-6 inline-flex items-center gap-2 px-6 py-3 bg-[var(--color-blue-primary)] text-white rounded-xl font-semibold hover:bg-[var(--color-gold)] transition-all duration-300 hover:shadow-lg hover:shadow-[var(--color-gold)]/30 hover:-translate-y-0.5"
                                >
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                                    </svg>
                                    Вернуться ко всем статьям
                                </a>
                            </div>
                        )
                    ) : (
                        <div class="bg-white/80 backdrop-blur-xl rounded-2xl p-12 text-center border border-white/50 shadow-lg">
                            <svg class="w-16 h-16 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                            </svg>
                            <h3 class="text-xl font-bold text-gray-900 mb-2">Введите поисковый запрос</h3>
                            <p class="text-gray-600 mb-6">
                                Используйте поле поиска выше для поиска статей по сайту.
                            </p>
                            <a 
                                href="/blog" 
                                class="inline-flex items-center gap-2 px-6 py-3 bg-[var(--color-blue-primary)] text-white rounded-xl font-semibold hover:bg-[var(--color-gold)] transition-all duration-300 hover:shadow-lg hover:shadow-[var(--color-gold)]/30 hover:-translate-y-0.5"
                            >
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                                </svg>
                                Вернуться ко всем статьям
                            </a>
                        </div>
                    )}
                </main>

                <!-- Сайдбар -->
                <aside class="lg:col-span-4 space-y-6">
                    <SidebarSearch />
                    <SidebarPopular posts={popularPosts} />
                    <SidebarCategories categories={categories} />
                    <TagCloud />
                </aside>
            </div>
        </div>
    </div>
</Layout>
