---
const title = 'Поиск по статьям';
---

<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>
  (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');
    let postsCache = null;

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

    async function fetchPosts() {
      if (postsCache) return postsCache;
      try {
        const res = await fetch('/api/posts?per_page=100');
        const data = await res.json();
        postsCache = data.posts || [];
        return postsCache;
      } catch (e) {
        return [];
      }
    }

    function formatDate(dateStr) {
      const d = new Date(dateStr);
      return d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' });
    }

    function openModal() {
      modal.classList.add('active');
      modal.setAttribute('aria-hidden', 'false');
      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 = '';
    }

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

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

      const posts = await fetchPosts();

      const filtered = posts.filter(post =>
          post.title.toLowerCase().includes(trimmed) ||
          post.description.toLowerCase().includes(trimmed) ||
          post.category.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(post => `
        <a href="/blog/${post.slug}" class="search-result-item">
          <span class="result-date">${formatDate(post.date)}</span>
          <h4 class="result-title">${post.title}</h4>
          <p class="result-description">${post.description.substring(0, 120)}...</p>
          <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="M5 12h14M12 5l7 7-7 7"/>
            </svg>
          </span>
        </a>
      `).join('');
    }

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

    window.addEventListener('open-modal', (e) => {
      if (e.detail === 'search-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-date {
    font-size: 0.8rem;
    color: #94a3b8;
    font-weight: 600;
    letter-spacing: 0.02em;
  }

  .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-arrow {
    position: absolute;
    right: 20px;
    bottom: 20px;
    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; }
    .result-arrow { right: 16px; bottom: 16px; }
  }
</style>