---
import { documents } from '@data/documents';

const searchData = documents.map(doc => ({
    title: doc.title,
    description: doc.description,
    downloadUrl: doc.downloadUrl,
    category: doc.category,
    fileType: doc.fileType,
    fileSize: doc.fileSize,
    tags: doc.tags?.join(', ') || ''
}));

const title = 'Поиск документов';
const postsJson = JSON.stringify(searchData);
---

<div id="search-modal" class="modal-overlay" aria-hidden="true">
    <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="search-modal-title">
        <button class="modal-close" aria-label="Закрыть" id="search-modal-close-btn">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
        </button>

        <div class="modal-content">
            <h2 id="search-modal-title" class="modal-title">{title}</h2>
            <p class="modal-description">
                Найдите нужный документ по названию, описанию или категории
            </p>

            <div class="search-form">
                <div class="search-input-wrapper">
                    <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"></circle>
                        <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                    </svg>
                    <input
                        type="text"
                        id="search-input"
                        class="search-input"
                        placeholder="Например: договор, доверенность, ДТП..."
                        autocomplete="off"
                    />
                </div>
            </div>

            <!-- Контейнер для динамических результатов -->
            <div class="search-results" id="search-results">
            </div>
        </div>
    </div>
</div>

<script define:vars={{ postsJson }}>
    (function() {
        const modal = document.getElementById('search-modal');
        const closeBtn = document.getElementById('search-modal-close-btn');
        const searchInput = document.getElementById('search-input');
        const resultsContainer = document.getElementById('search-results');
        const docs = JSON.parse(postsJson);

        if (!modal || !searchInput || !resultsContainer) return;

        function openModal() {
            modal.setAttribute('aria-hidden', 'false');
            modal.classList.add('active');
            document.body.style.overflow = 'hidden';
            setTimeout(() => searchInput.focus(), 200);
        }

        function closeModal() {
            modal.classList.remove('active');
            modal.setAttribute('aria-hidden', 'true');
            document.body.style.overflow = '';
            searchInput.value = '';
            resultsContainer.innerHTML = '';
        }

        function getFileTypeIcon(fileType) {
            const icons = {
                pdf: '📄',
                docx: '📝',
                xlsx: '📊',
                zip: '📦'
            };
            return icons[fileType] || '📄';
        }

        function handleSearch(query) {
            const trimmed = query.trim().toLowerCase();

            if (trimmed.length < 2) {
                resultsContainer.innerHTML = '';
                return;
            }

            const filtered = docs.filter(doc =>
                doc.title.toLowerCase().includes(trimmed) ||
                doc.description.toLowerCase().includes(trimmed) ||
                doc.category.toLowerCase().includes(trimmed) ||
                doc.tags.toLowerCase().includes(trimmed)
            );

            if (filtered.length === 0) {
                resultsContainer.innerHTML = `
                    <div class="no-results">
                        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" style="margin-bottom: 1rem; opacity: 0.5;">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                        </svg>
                        <p>По запросу <strong>"${query}"</strong> ничего не найдено</p>
                    </div>`;
                return;
            }

            resultsContainer.innerHTML = filtered.map(doc => `
                <a href="${doc.downloadUrl}" class="search-result-item" download target="_blank" rel="noopener noreferrer">
                    <div class="result-header">
                        <span class="result-icon">${getFileTypeIcon(doc.fileType)}</span>
                        <h4 class="result-title">${doc.title}</h4>
                    </div>
                    <p class="result-description">${doc.description}</p>
                    <div class="result-footer">
                        <span class="result-meta">
                            <span class="result-category">${doc.category}</span>
                            <span class="result-type">${doc.fileType.toUpperCase()}</span>
                            <span class="result-size">${doc.fileSize}</span>
                        </span>
                        <span class="result-arrow">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M12 4v12m0 0l-4-4m4 4l4-4M4 18h16"/>
                            </svg>
                        </span>
                    </div>
                </a>
            `).join('');
        }

        let timeout;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => handleSearch(e.target.value), 200);
        });

        window.addEventListener('open-modal', (e) => {
            console.log('open-modal event received:', e.detail);
            if (e.detail === 'search-modal') {
                console.log('Opening modal...');
                openModal();
            }
        });

        closeBtn.addEventListener('click', closeModal);
        modal.addEventListener('click', (e) => {
            if (e.target === modal) closeModal();
        });
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && modal.classList.contains('active')) closeModal();
        });
    })();
</script>

<style is:global>
    .modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(10, 25, 41, 0.85);
        backdrop-filter: blur(8px);
        display: flex;
        align-items: flex-start;
        justify-content: center;
        z-index: 9999;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        padding: 2rem 1rem;
    }

    .modal-overlay.active { opacity: 1; visibility: visible; }

    .modal-container {
        background: #ffffff;
        border-radius: 24px;
        width: 100%;
        max-width: 720px;
        max-height: 85vh;
        box-shadow: 0 30px 60px -12px rgba(0, 0, 0, 0.4);
        position: relative;
        transform: translateY(-20px);
        transition: transform 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .modal-overlay.active .modal-container { transform: translateY(0); }

    .modal-close {
        position: absolute;
        top: 1.25rem;
        right: 1.25rem;
        background: #f1f5f9;
        border: none;
        cursor: pointer;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #64748b;
        z-index: 10;
        transition: all 0.2s ease;
    }

    .modal-close:hover { background: #e2e8f0; color: #0f172a; transform: rotate(90deg); }

    .modal-content {
        padding: 3rem 2.5rem 2rem;
        display: flex;
        flex-direction: column;
        height: 100%;
        overflow: hidden;
    }

    .modal-title {
        font-size: 1.85rem;
        font-weight: 800;
        color: #0f172a;
        margin: 0 0 0.5rem;
        letter-spacing: -0.02em;
    }

    .modal-description { color: #64748b; margin-bottom: 2rem; font-size: 1.05rem; }

    .search-input-wrapper { position: relative; margin-bottom: 2rem; }

    .search-icon {
        position: absolute;
        left: 1.25rem;
        top: 50%;
        transform: translateY(-50%);
        color: #d4af37;
    }

    .search-input {
        width: 100%;
        padding: 1.1rem 1.1rem 1.1rem 3.75rem;
        border: 2px solid #e2e8f0;
        border-radius: 16px;
        font-size: 1.15rem;
        transition: all 0.3s ease;
        outline: none;
        background: #f8fafc;
    }

    .search-input:focus {
        border-color: #d4af37;
        background: #fff;
        box-shadow: 0 0 0 4px rgba(212, 175, 55, 0.1);
    }

    .search-results {
        overflow-y: auto;
        flex: 1;
        padding-right: 0.5rem;
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .search-result-item {
        display: flex;
        flex-direction: column;
        gap: 8px;
        padding: 20px;
        border-radius: 12px;
        text-decoration: none;
        background: #ffffff;
        border: 1px solid #eef2f6;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
    }

    .search-result-item::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background: linear-gradient(180deg, #d4af37 0%, #f4d03f 100%);
        opacity: 0;
        transition: opacity 0.3s ease;
        border-radius: 4px 0 0 4px;
    }

    .search-result-item:hover {
        border-color: #cbd5e1;
        transform: translateX(4px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    .search-result-item:hover::before {
        opacity: 1;
    }

    .result-header {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .result-icon {
        font-size: 1.5rem;
    }

    .result-title {
        font-size: 1.15rem;
        font-weight: 700;
        color: #0f172a;
        margin: 0;
        line-height: 1.4;
    }

    .result-description {
        font-size: 0.9rem;
        color: #64748b;
        margin: 0;
        line-height: 1.6;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        padding-right: 28px;
    }

    .result-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;
    }

    .result-meta {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .result-category {
        font-size: 0.75rem;
        color: #94a3b8;
        font-weight: 600;
        padding: 0.2rem 0.5rem;
        background: #f1f5f9;
        border-radius: 4px;
    }

    .result-type {
        font-size: 0.7rem;
        color: #d4af37;
        font-weight: 700;
        text-transform: uppercase;
        padding: 0.2rem 0.4rem;
        background: rgba(212, 175, 55, 0.1);
        border-radius: 4px;
    }

    .result-size {
        font-size: 0.8rem;
        color: #94a3b8;
    }

    .result-arrow {
        color: #cbd5e1;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .search-result-item:hover .result-arrow {
        color: #d4af37;
        transform: translateX(4px);
    }

    .no-results {
        padding: 4rem 1rem;
        text-align: center;
        color: #64748b;
        background: #f8fafc;
        border-radius: 20px;
        border: 2px dashed #e2e8f0;
    }

    .search-results::-webkit-scrollbar { width: 6px; }
    .search-results::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }

    @media (max-width: 640px) {
        .modal-content { padding: 2.5rem 1.5rem 1.5rem; }
        .modal-title { font-size: 1.5rem; }
        .search-result-item { padding: 16px; }
        .result-title { font-size: 1.05rem; }
        .result-description { padding-right: 0; -webkit-line-clamp: 1; }
    }
</style>
