---
import { getCollection } from 'astro:content';
import BaseLayout from '../layouts/BaseLayout.astro';

// Get all posts for client-side search
const allPosts = await getCollection('blog');

// Prepare post data for search
const searchData = allPosts.map(post => ({
  title: post.data.title,
  description: post.data.description || '',
  slug: post.slug,
  tags: post.data.tags || [],
  category: post.data.category || '',
  heroImage: post.data.heroImage || '/blog/images/placeholders/default.jpg',
  pubDate: post.data.pubDate ? new Date(post.data.pubDate).toLocaleDateString('en-us', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  }) : '',
  draft: post.data.draft || false
}));
---

<BaseLayout title="Search | LaForce IT Blog" description="Search through all articles and guides on LaForce IT Blog">
  <main class="container">
    <section class="search-header">
      <h1 class="search-title">Search the <span>Blog</span></h1>
      <div class="search-box">
        <input 
          type="text" 
          id="search-input" 
          class="search-input" 
          placeholder="Search for articles, topics, or technologies..."
          aria-label="Search blog posts"
        />
        <button class="search-button" id="search-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
          </svg>
        </button>
      </div>
    </section>

    <div id="search-results" class="search-results">
      <p class="search-info">Type in the search box above to find articles</p>
      <!-- Results will be populated via JavaScript -->
    </div>
  </main>
</BaseLayout>

<script define:vars={{ searchData }}>
  document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');
    const searchResults = document.getElementById('search-results');
    
    // Function to perform search
    function performSearch() {
      const query = searchInput.value.toLowerCase().trim();
      
      // Clear previous results
      searchResults.innerHTML = '';
      
      if (!query) {
        searchResults.innerHTML = '<p class="search-info">Type in the search box above to find articles</p>';
        return;
      }
      
      // Filter posts based on query
      const results = searchData.filter(post => 
        post.title.toLowerCase().includes(query) || 
        post.description.toLowerCase().includes(query) ||
        post.category.toLowerCase().includes(query) ||
        post.tags.some(tag => tag.toLowerCase().includes(query))
      );
      
      // Display results
      if (results.length === 0) {
        searchResults.innerHTML = `<p class="search-info">No results found for "${query}"</p>`;
      } else {
        searchResults.innerHTML = `
          <p class="results-count">Found ${results.length} result${results.length === 1 ? '' : 's'} for "${query}"</p>
          <div class="blog-grid">
            ${results.map(post => `
              <article class="post-card">
                <img
                  width="720"
                  height="360"
                  src="${post.heroImage}"
                  alt=""
                  class="post-image"
                />
                <div class="post-content">
                  <div class="post-meta">
                    <time datetime="${post.pubDate}">${post.pubDate}</time>
                    ${post.category ? `<span class="post-category">${post.category}</span>` : ''}
                  </div>
                  <h3 class="post-title">
                    <a href="/blog/${post.slug}/">${post.title}</a>
                    ${post.draft ? '<span class="draft-badge">Draft</span>' : ''}
                  </h3>
                  <p class="post-excerpt">${post.description}</p>
                  <div class="post-footer">
                    <div class="post-tags">
                      ${post.tags.map(tag => `<a href="/tag/${tag}" class="post-tag">#${tag}</a>`).join('')}
                    </div>
                    <a href="/blog/${post.slug}/" class="read-more">Read More</a>
                  </div>
                </div>
              </article>
            `).join('')}
          </div>
        `;
      }
    }
    
    // Search on button click
    if (searchButton) {
      searchButton.addEventListener('click', performSearch);
    }
    
    // Search on enter key press
    if (searchInput) {
      searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          performSearch();
        }
      });
      
      // Initialize search if URL has query parameter
      const urlParams = new URLSearchParams(window.location.search);
      const queryParam = urlParams.get('q');
      if (queryParam) {
        searchInput.value = queryParam;
        performSearch();
      }
    }
  });
</script>

<style>
.search-header {
  margin: 3rem 0;
  text-align: center;
}

.search-title {
  font-size: clamp(2rem, 5vw, 3.5rem);
  margin-bottom: 2rem;
}

.search-title span {
  background: linear-gradient(90deg, var(--accent-primary), var(--accent-tertiary));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.search-box {
  display: flex;
  max-width: 600px;
  margin: 0 auto;
  border-radius: 0.75rem;
  border: 1px solid var(--card-border);
  background: var(--card-bg);
  overflow: hidden;
  transition: all 0.3s ease;
}

.search-box:focus-within {
  border-color: var(--accent-primary);
  box-shadow: 0 0 20px rgba(6, 182, 212, 0.1);
}

.search-input {
  flex: 1;
  padding: 1rem 1.5rem;
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-size: 1rem;
  font-family: 'Space Grotesk', sans-serif;
}

.search-input:focus {
  outline: none;
}

.search-button {
  background: transparent;
  border: none;
  color: var(--text-secondary);
  padding: 0 1.5rem;
  cursor: pointer;
  transition: color 0.3s ease;
}

.search-button:hover {
  color: var(--accent-primary);
}

.search-results {
  margin: 2rem 0 4rem;
}

.search-info {
  text-align: center;
  color: var(--text-secondary);
  font-size: 1.1rem;
  margin: 3rem 0;
}

.results-count {
  margin-bottom: 2rem;
  font-family: 'JetBrains Mono', monospace;
  color: var(--text-secondary);
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 1rem;
}

.post-tag {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 2rem;
  background: rgba(139, 92, 246, 0.1);
  color: var(--text-secondary);
  text-decoration: none;
  transition: all 0.3s ease;
  font-family: 'JetBrains Mono', monospace;
}

.post-tag:hover {
  background: rgba(139, 92, 246, 0.2);
}

.draft-badge {
  display: inline-block;
  margin-left: 0.5rem;
  padding: 0.25rem 0.5rem;
  background-color: rgba(226, 232, 240, 0.2);
  color: #94a3b8;
  font-size: 0.75rem;
  border-radius: 0.25rem;
  vertical-align: middle;
}

@media (max-width: 768px) {
  .search-box {
    width: 90%;
  }
}
</style> 