---
import Layout from '@layouts/Layout.astro';
import { SITE_URL } from '@constants';
import PageHero from '@components/base/PageHero.astro';
import DocCard from '@components/documents/DocCard.astro';
import DocCategories from '@components/documents/DocCategories.astro';
import Pagination from '@components/base/Pagination.astro';
import SearchDocumentsModal from '@components/documents/SearchDocumentsModal.astro';
import { documents, getCategories, filterByCategory, DOCUMENTS_PER_PAGE } from '@data/documents';

const url = new URL(Astro.request.url);
const categoryParam: string = url.searchParams.get('category') || 'Все';
const pageParam: string | null = url.searchParams.get('page');

const activeCategory = categoryParam;
const currentPage: number = pageParam ? parseInt(pageParam, 10) : 1;

const filteredDocs = filterByCategory(activeCategory);
const totalPages = Math.ceil(filteredDocs.length / DOCUMENTS_PER_PAGE);
const validPage = Math.max(1, Math.min(currentPage, totalPages));

const startIndex = (validPage - 1) * DOCUMENTS_PER_PAGE;
const endIndex = startIndex + DOCUMENTS_PER_PAGE;
const paginatedDocs = filteredDocs.slice(startIndex, endIndex);

const categories = getCategories();
---

<Layout
    title="Документы для скачивания"
    description="Скачайте необходимые документы: договоры, доверенности, памятки, шаблоны заявлений и другую полезную информацию"
    canonicalLink={`${SITE_URL}/documents`}
    breadcrumbs={[
        { label: 'Главная', href: '/' },
        { label: 'Документы' }
    ]}
>
    <PageHero
        badgeText="ДОКУМЕНТЫ"
        titleWhite="Документы для"
        titleGold="скачивания"
        description="Здесь вы можете скачать все необходимые документы, договоры, памятки и шаблоны в удобном формате"
        layout="with-image"
        sideImage="/images/documents/docImg.avif"
        sideImageAlt="Документы Автоюрист"
        experienceBadge={{
            number: "50+",
            text: "ДОКУМЕНТОВ"
        }}
        bgImage="/images/documents/docBg.avif"
        icon="file"
    />

    <section class="documents-section">
        <div class="site-container">
            <!-- Фильтры по категориям -->
            <DocCategories categories={categories} activeCategory={activeCategory} />

            <!-- Сетка документов -->
            <div class="documents-grid" id="documents-grid">
                {paginatedDocs.map((doc) => (
                    <DocCard
                        id={doc.id}
                        title={doc.title}
                        description={doc.description}
                        fileSize={doc.fileSize}
                        fileType={doc.fileType}
                        downloadUrl={doc.downloadUrl}
                        category={doc.category}
                    />
                ))}
            </div>

            <!-- Пагинация -->
            {totalPages > 1 && (
                <Pagination
                    currentPage={validPage}
                    totalPages={totalPages}
                    baseUrl="/documents"
                />
            )}
        </div>
    </section>

    <SearchDocumentsModal />
</Layout>

<style>
    :root {
        --color-primary-docs: #0f172a;
        --color-secondary-docs: #1e293b;
        --color-accent-docs: #eac26e;
        --color-accent-dark-docs: #ce9f40;
        --color-light-docs: #ffffff;
        --color-gray-docs: #94a3b8;
        --color-card-bg-docs: rgba(255, 255, 255, 0.04);
        --color-card-border-docs: rgba(255, 255, 255, 0.08);
        --gradient-docs-bg: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
    }

    .documents-section {
        padding: 2rem 1.5rem 4rem;
        background: var(--gradient-docs-bg);
        position: relative;
        overflow: hidden;
        font-family: 'Inter', system-ui, -apple-system, sans-serif;
    }

    .documents-section::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 1px;
        background: linear-gradient(90deg, transparent, var(--color-accent-docs), transparent);
        opacity: 0.3;
    }

    .site-container {
        max-width: var(--site-max-width, 1400px);
        margin: 0 auto;
        position: relative;
        z-index: 2;
    }

    /* Сетка документов */
    .documents-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 1.25rem;
        margin-bottom: 3rem;
    }

    /* Пагинация */
    :global(.pagination) {
        padding: 2rem 0 4rem;
    }

    /* Адаптивность */
    @media (max-width: 1024px) {
        .documents-grid {
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        }
    }

    @media (max-width: 768px) {
        .documents-section {
            padding: 2rem 1rem 3rem;
        }

        .documents-grid {
            grid-template-columns: 1fr;
        }
    }
</style>

<script>
    const setupFilter = () => {
        const buttons = document.querySelectorAll('.category-btn');
        const cards = document.querySelectorAll('.doc-card');

        buttons.forEach((btn) => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                const category = btn.getAttribute('data-category');
                if (!category) return;

                const url = new URL(window.location.href);

                if (category === 'Все') {
                    url.searchParams.delete('category');
                } else {
                    url.searchParams.set('category', category);
                }
                url.searchParams.set('page', '1');

                window.location.href = url.toString();
            });
        });
    };

    setupFilter();
</script>
