{#
  Search Component

  Full-featured client-side search powered by Lunr.js with filters and keyboard shortcuts.

  Variables:
    - site: Site object (for site title)

  Features:
    - Client-side full-text search with Lunr.js
    - Real-time search as you type (debounced)
    - Keyboard shortcuts (Cmd/Ctrl + K to focus, Escape to clear)
    - Advanced filtering (section, type, tags)
    - Result highlighting and grouping
    - Loading and error states
    - Accessible with ARIA attributes
    - Responsive design

  Dependencies:
    - JavaScript: /assets/js/lunr.min.js (loaded in base.html)
    - JavaScript: /assets/js/search.js (BengalSearch module, loaded in base.html)
    - Search Index: /index.json (generated during build)

  Note:
    This component includes inline <script> and <style> tags for component-specific
    initialization and styling. This is intentional to keep the component self-contained.
    Core search functionality is in search.js, but UI-specific code is inline.

  Usage:
    {% include 'partials/search.html' %}

  CSS: See inline <style> tag below (component-specific overrides)
  JS: See inline <script> tag below (UI initialization logic)
#}

<div class="search-container" id="search-container">
  {# Search Input #}
  <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>
      <path d="m21 21-4.35-4.35"></path>
    </svg>

    <input
      type="search"
      id="search-input"
      class="search-input"
      placeholder="Search documentation..."
      autocomplete="off"
      autocorrect="off"
      autocapitalize="off"
      spellcheck="false"
      aria-label="Search"
      aria-describedby="search-status"
      aria-controls="search-results"
      aria-autocomplete="list"
    >

    {# Keyboard shortcut hint #}
    <div class="search-shortcut" aria-hidden="true">
      <kbd>⌘</kbd><kbd>K</kbd>
    </div>

    {# Clear button #}
    <button
      type="button"
      class="search-clear"
      id="search-clear"
      aria-label="Clear search"
      style="display: none;">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <line x1="18" y1="6" x2="6" y2="18"></line>
        <line x1="6" y1="6" x2="18" y2="18"></line>
      </svg>
    </button>
  </div>

  {# Search Status (for screen readers and loading) #}
  <div
    id="search-status"
    class="search-status"
    role="status"
    aria-live="polite"
    aria-atomic="true">
  </div>

  {# Filters (collapsible) #}
  <div class="search-filters" id="search-filters" style="display: none;">
    <button type="button" class="search-filters-toggle" aria-expanded="false" aria-controls="search-filters-content">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon>
      </svg>
      <span>Filters</span>
    </button>

    <div class="search-filters-content" id="search-filters-content" style="display: none;">
      {# Section filter #}
      <div class="search-filter-group">
        <label for="filter-section">Section:</label>
        <select id="filter-section" class="search-filter-select">
          <option value="">All Sections</option>
          {# Options populated by JavaScript #}
        </select>
      </div>

      {# Type filter #}
      <div class="search-filter-group">
        <label for="filter-type">Type:</label>
        <select id="filter-type" class="search-filter-select">
          <option value="">All Types</option>
          {# Options populated by JavaScript #}
        </select>
      </div>

      {# Tag filter #}
      <div class="search-filter-group">
        <label for="filter-tags">Tags:</label>
        <select id="filter-tags" class="search-filter-select" multiple size="5">
          {# Options populated by JavaScript #}
        </select>
        <small class="filter-hint">Hold Ctrl/Cmd to select multiple</small>
      </div>

      {# Clear filters button #}
      <button type="button" class="btn btn-sm btn-outline" id="clear-filters">
        Clear Filters
      </button>
    </div>
  </div>

  {# Search Results #}
  <div
    id="search-results"
    class="search-results"
    role="region"
    aria-label="Search results"
    style="display: none;">

    {# Results header #}
    <div class="search-results-header">
      <span id="search-results-count" class="search-results-count"></span>
    </div>

    {# Results list #}
    <div id="search-results-list" class="search-results-list">
      {# Results populated by JavaScript #}
    </div>

    {# No results message #}
    <div id="search-no-results" class="search-no-results" style="display: none;">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="11" cy="11" r="8"></circle>
        <path d="m21 21-4.35-4.35"></path>
      </svg>
      <p>No results found for "<span id="search-no-results-query"></span>"</p>
      <p class="search-no-results-suggestion">Try different keywords or clear your filters.</p>
    </div>
  </div>

  {# Loading indicator #}
  <div id="search-loading" class="search-loading" style="display: none;">
    <div class="loading-spinner"></div>
    <p>Loading search index...</p>
  </div>

  {# Error message #}
  <div id="search-error" class="search-error" style="display: none;">
    <p>Failed to load search index. Please try refreshing the page.</p>
  </div>
</div>

<script>
(function() {
  'use strict';

  // Initialize search UI
  function initializeSearchUI() {
    // Check if BengalSearch is available
    if (typeof window.BengalSearch === 'undefined') {
      // Not loaded yet, wait for it
      console.log('Waiting for BengalSearch to load...');
      setTimeout(initializeSearchUI, 100);
      return;
    }

    console.log('Initializing search UI...');

  // Elements
  const container = document.getElementById('search-container');
  const input = document.getElementById('search-input');
  const clearBtn = document.getElementById('search-clear');
  const status = document.getElementById('search-status');
  const results = document.getElementById('search-results');
  const resultsList = document.getElementById('search-results-list');
  const resultsCount = document.getElementById('search-results-count');
  const noResults = document.getElementById('search-no-results');
  const noResultsQuery = document.getElementById('search-no-results-query');
  const loading = document.getElementById('search-loading');
  const error = document.getElementById('search-error');
  const filters = document.getElementById('search-filters');
  const filtersToggle = document.querySelector('.search-filters-toggle');
  const filtersContent = document.getElementById('search-filters-content');
  const clearFiltersBtn = document.getElementById('clear-filters');

  // Filter elements
  const filterSection = document.getElementById('filter-section');
  const filterType = document.getElementById('filter-type');
  const filterTags = document.getElementById('filter-tags');

  let debounceTimer = null;
  let currentQuery = '';
  let currentFilters = {};

  // Initialize
  function init() {
    // Show loading
    loading.style.display = 'block';

    // Wait for index to load
    if (BengalSearch.isLoaded()) {
      onIndexLoaded();
    } else {
      window.addEventListener('searchIndexLoaded', onIndexLoaded);
      window.addEventListener('searchIndexError', onIndexError);
    }

    // Input handlers
    input.addEventListener('input', onInput);
    input.addEventListener('focus', onFocus);
    clearBtn.addEventListener('click', clearSearch);

    // Keyboard shortcuts
    document.addEventListener('keydown', handleKeyboardShortcuts);

    // Filter handlers
    filtersToggle.addEventListener('click', toggleFilters);
    filterSection.addEventListener('change', onFilterChange);
    filterType.addEventListener('change', onFilterChange);
    filterTags.addEventListener('change', onFilterChange);
    clearFiltersBtn.addEventListener('click', clearFilters);
  }

  function onIndexLoaded() {
    loading.style.display = 'none';
    populateFilterOptions();
    console.log('Search ready');
  }

  function onIndexError(event) {
    loading.style.display = 'none';
    error.style.display = 'block';
    console.error('Search index error:', event.detail.error);
  }

  function populateFilterOptions() {
    // Sections
    const sections = BengalSearch.getAvailableSections();
    sections.forEach(section => {
      const option = document.createElement('option');
      option.value = section;
      option.textContent = section;
      filterSection.appendChild(option);
    });

    // Types
    const types = BengalSearch.getAvailableTypes();
    types.forEach(type => {
      const option = document.createElement('option');
      option.value = type;
      option.textContent = type;
      filterType.appendChild(option);
    });

    // Tags
    const tags = BengalSearch.getAvailableTags();
    tags.forEach(tag => {
      const option = document.createElement('option');
      option.value = tag;
      option.textContent = tag;
      filterTags.appendChild(option);
    });

    // Show filters if we have options
    if (sections.length > 0 || types.length > 0 || tags.length > 0) {
      filters.style.display = 'block';
    }
  }

  function onInput(e) {
    const query = e.target.value.trim();

    // Show/hide clear button
    clearBtn.style.display = query ? 'flex' : 'none';

    // Debounce search
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      performSearch(query);
    }, 200);
  }

  function onFocus() {
    if (currentQuery) {
      results.style.display = 'block';
    }
  }

  function performSearch(query) {
    currentQuery = query;

    if (!query || query.length < 2) {
      results.style.display = 'none';
      status.textContent = '';
      return;
    }

    // Get current filters
    currentFilters = {
      section: filterSection.value || null,
      type: filterType.value || null,
      tags: Array.from(filterTags.selectedOptions).map(opt => opt.value),
    };

    // Perform search
    const searchResults = BengalSearch.search(query, currentFilters);

    // Display results
    displayResults(searchResults, query);
  }

  function displayResults(searchResults, query) {
    // Clear previous results
    resultsList.innerHTML = '';

    if (searchResults.length === 0) {
      results.style.display = 'block';
      noResults.style.display = 'block';
      noResultsQuery.textContent = query;
      status.textContent = 'No results found';
      return;
    }

    // Show results
    results.style.display = 'block';
    noResults.style.display = 'none';

    // Update count
    const count = searchResults.length;
    resultsCount.textContent = `${count} result${count !== 1 ? 's' : ''}`;
    status.textContent = `Found ${count} result${count !== 1 ? 's' : ''}`;

    // Group results by type if > 10 results
    const shouldGroup = searchResults.length > 10;

    if (shouldGroup && window.BengalSearch && window.BengalSearch.groupResults) {
      const grouped = window.BengalSearch.groupResults(searchResults);

      // Display each group
      grouped.forEach(group => {
        // Group header
        const header = document.createElement('div');
        header.className = 'search-results-group-header';
        header.innerHTML = `<h3>${group.name} <span class="group-count">(${group.count})</span></h3>`;
        resultsList.appendChild(header);

        // Group items
        group.items.slice(0, 5).forEach((result, index) => {
          const item = createResultItem(result, index);
          resultsList.appendChild(item);
        });

        // Show more button if truncated
        if (group.items.length > 5) {
          const showMore = document.createElement('button');
          showMore.className = 'search-show-more';
          showMore.textContent = `Show ${group.items.length - 5} more in ${group.name}`;
          showMore.onclick = () => {
            showMore.style.display = 'none';
            group.items.slice(5).forEach((result, index) => {
              const item = createResultItem(result, index + 5);
              resultsList.insertBefore(item, showMore);
            });
          };
          resultsList.appendChild(showMore);
        }
      });
    } else {
      // Display ungrouped (standard list)
      searchResults.forEach((result, index) => {
        const item = createResultItem(result, index);
        resultsList.appendChild(item);
      });
    }

    // Add click handlers for tag buttons
    document.querySelectorAll('.tag-clickable').forEach(button => {
      button.addEventListener('click', (e) => {
        e.preventDefault();
        const tag = button.getAttribute('data-tag');

        // Set filter and re-search
        filterTags.value = tag;
        currentFilters.tags = [tag];

        // Trigger search
        performSearch();

        // Scroll to top
        input.scrollIntoView({ behavior: 'smooth', block: 'start' });
      });
    });
  }

  function createResultItem(result, index) {
    const item = document.createElement('article');
    item.className = 'search-result-item';

    // Build HTML
    let html = '';

    // Title (with highlights)
    html += `<h3 class="search-result-title">`;
    html += `<a href="${result.href || result.uri || result.url}">${result.highlightedTitle || result.title}</a>`;
    html += `</h3>`;

    // Meta info
    html += `<div class="search-result-meta">`;

    if (result.section) {
      html += `<span class="search-result-section">${result.section}</span>`;
    }

    if (result.type) {
      html += `<span class="badge badge-sm badge-${result.type}">${result.type}</span>`;
    }

    if (result.formattedDate) {
      html += `<span class="search-result-date">${result.formattedDate}</span>`;
    }

    if (result.reading_time) {
      html += `<span class="search-result-reading-time">${result.reading_time} min read</span>`;
    }

    html += `</div>`;

    // Excerpt (with highlights)
    if (result.highlightedExcerpt) {
      html += `<p class="search-result-excerpt">${result.highlightedExcerpt}</p>`;
    }

    // Tags (clickable)
    if (result.tags && result.tags.length > 0) {
      html += `<div class="search-result-tags">`;
      result.tags.slice(0, 5).forEach(tag => {
        html += `<button class="tag tag-sm tag-clickable" data-tag="${tag}" title="Filter by ${tag}">${tag}</button>`;
      });
      html += `</div>`;
    }

    item.innerHTML = html;

    return item;
  }

  function clearSearch() {
    input.value = '';
    currentQuery = '';
    clearBtn.style.display = 'none';
    results.style.display = 'none';
    status.textContent = '';
    input.focus();
  }

  function toggleFilters() {
    const isExpanded = filtersToggle.getAttribute('aria-expanded') === 'true';
    filtersToggle.setAttribute('aria-expanded', !isExpanded);
    filtersContent.style.display = isExpanded ? 'none' : 'block';
  }

  function onFilterChange() {
    if (currentQuery) {
      performSearch(currentQuery);
    }
  }

  function clearFilters() {
    filterSection.value = '';
    filterType.value = '';
    filterTags.selectedIndex = -1;

    if (currentQuery) {
      performSearch(currentQuery);
    }
  }

  function handleKeyboardShortcuts(e) {
    // Cmd/Ctrl + K to focus search
    if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
      e.preventDefault();
      input.focus();
      input.select();
    }

    // Escape to clear/close
    if (e.key === 'Escape') {
      if (document.activeElement === input) {
        if (currentQuery) {
          clearSearch();
        } else {
          input.blur();
        }
      }
    }
  }

  // Initialize on page load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
  }  // End of initializeSearchUI

  // Start initialization (will retry if BengalSearch not loaded yet)
  initializeSearchUI();
})();
</script>

<style>
/* Search Container */
.search-container {
  max-width: 800px;
  margin: 0 auto 2rem;
}

/* Search Input */
.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.search-icon {
  position: absolute;
  left: 1rem;
  color: var(--color-text-tertiary);
  pointer-events: none;
}

.search-input {
  width: 100%;
  padding: 0.875rem 8rem 0.875rem 3rem;
  font-size: var(--text-body);
  font-family: inherit;
  color: var(--color-text-primary);
  background-color: var(--color-bg-elevated);
  border: 2px solid var(--color-border);
  border-radius: var(--border-radius-large);
  box-shadow: var(--elevation-subtle);
  transition: all var(--transition-fast);
}

.search-input:hover {
  border-color: var(--color-border-dark);
}

.search-input:focus {
  outline: none;
  border-color: var(--color-border-focus);
  box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
}

/* Keyboard shortcut hint */
.search-shortcut {
  position: absolute;
  right: 4rem;
  display: flex;
  gap: 0.25rem;
  pointer-events: none;
}

.search-shortcut kbd {
  padding: 0.125rem 0.375rem;
  font-size: var(--text-xs);
  font-family: var(--font-family-code);
  background-color: var(--color-bg-tertiary);
  border: 1px solid var(--color-border);
  border-radius: 3px;
  box-shadow: 0 1px 0 var(--color-border-dark);
}

.search-input:focus ~ .search-shortcut {
  display: none;
}

/* Clear button */
.search-clear {
  position: absolute;
  right: 1rem;
  display: none;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  background: transparent;
  border: none;
  color: var(--color-text-tertiary);
  cursor: pointer;
  border-radius: var(--border-radius-small);
  transition: all var(--transition-fast);
}

.search-clear:hover {
  color: var(--color-text-primary);
  background: var(--color-bg-hover);
}

/* Status */
.search-status {
  margin-top: 0.5rem;
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
}

/* Filters */
.search-filters {
  margin-top: 1rem;
}

.search-filters-toggle {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-medium);
  font-size: var(--text-sm);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.search-filters-toggle:hover {
  background: var(--color-bg-hover);
}

.search-filters-content {
  margin-top: 1rem;
  padding: 1rem;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-medium);
  display: grid;
  gap: 1rem;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

.search-filter-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.search-filter-group label {
  font-size: var(--text-sm);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-secondary);
}

.search-filter-select {
  padding: 0.5rem;
  font-family: inherit;
  font-size: var(--text-body-small);
  background: var(--color-bg-primary);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-small);
  color: var(--color-text-primary);
}

.filter-hint {
  font-size: var(--text-xs);
  color: var(--color-text-tertiary);
  margin-top: 0.25rem;
}

/* Results */
.search-results {
  margin-top: 2rem;
}

.search-results-header {
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--color-border);
}

.search-results-count {
  font-size: var(--text-sm);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-secondary);
}

.search-results-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.search-result-item {
  padding: 1rem;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-medium);
  transition: all var(--transition-fast);
}

.search-result-item:hover {
  border-color: var(--color-primary);
  box-shadow: var(--elevation-card);
}

.search-result-title {
  margin: 0 0 0.5rem 0;
  font-size: var(--text-lg);
  font-weight: var(--font-weight-semibold);
}

.search-result-title a {
  color: var(--color-text-primary);
  text-decoration: none;
}

.search-result-title a:hover {
  color: var(--color-primary);
}

.search-result-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
  font-size: var(--text-xs);
  color: var(--color-text-tertiary);
}

.search-result-excerpt {
  margin: 0 0 0.75rem 0;
  line-height: var(--line-height-relaxed);
  color: var(--color-text-secondary);
}

.search-result-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

/* Clickable tags */
.tag-clickable {
  cursor: pointer;
  transition: all var(--transition-fast);
  border: none;
  font: inherit;
}

.tag-clickable:hover {
  background: var(--color-primary);
  color: var(--color-text-inverse);
  transform: translateY(-1px);
}

.tag-clickable:active {
  transform: translateY(0);
}

/* Grouped results */
.search-results-group-header {
  margin: 2rem 0 1rem 0;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid var(--color-border);
}

.search-results-group-header:first-child {
  margin-top: 0;
}

.search-results-group-header h3 {
  margin: 0;
  font-size: var(--text-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.group-count {
  font-size: var(--text-sm);
  font-weight: var(--font-weight-normal);
  color: var(--color-text-secondary);
}

/* Show more button */
.search-show-more {
  display: block;
  width: 100%;
  margin: 1rem 0;
  padding: 0.75rem 1rem;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-medium);
  color: var(--color-primary);
  font-size: var(--text-body-small);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.search-show-more:hover {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: var(--color-text-inverse);
}

/* Highlighting */
mark.search-highlight {
  background-color: rgba(255, 215, 0, 0.3);
  color: inherit;
  font-weight: var(--font-weight-semibold);
  padding: 0 0.125rem;
  border-radius: 2px;
}

[data-theme="dark"] mark.search-highlight {
  background-color: rgba(255, 215, 0, 0.2);
}

/* No results */
.search-no-results {
  text-align: center;
  padding: 3rem 1rem;
  color: var(--color-text-tertiary);
}

.search-no-results svg {
  margin-bottom: 1rem;
  opacity: 0.3;
}

.search-no-results p {
  margin: 0.5rem 0;
}

.search-no-results-suggestion {
  font-size: var(--text-sm);
}

/* Loading */
.search-loading {
  text-align: center;
  padding: 2rem;
  color: var(--color-text-secondary);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 1rem;
  border: 4px solid var(--color-border);
  border-top-color: var(--color-primary);
  border-radius: var(--border-radius-full);
  animation: spin 0.8s linear infinite;
}

/* Error */
.search-error {
  padding: 1rem;
  background: var(--color-error-bg);
  border: 1px solid var(--color-error-border);
  border-radius: var(--border-radius-medium);
  color: var(--color-error-text);
}

/* Responsive */
@media (max-width: 640px) {
  .search-shortcut {
    display: none;
  }

  .search-input {
    padding-right: 3rem;
  }

  .search-filters-content {
    grid-template-columns: 1fr;
  }
}
</style>
