---
const base = import.meta.env.BASE_URL;
---

<div class="relative" id="search-container">
  <button
    id="search-btn"
    class="flex items-center gap-2 px-2 sm:px-3 py-1.5 text-sm rounded-lg border border-surface-200 dark:border-surface-700 text-surface-500 dark:text-surface-400 hover:border-surface-300 dark:hover:border-surface-600 hover:text-surface-700 dark:hover:text-surface-300 bg-surface-50 dark:bg-surface-900 transition-colors sm:min-w-[180px]"
    aria-label="Search docs"
  >
    <svg class="w-4 h-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
      <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
    </svg>
    <span class="hidden sm:inline">Search docs...</span>
    <kbd class="hidden sm:inline-flex ml-auto text-xs border border-surface-300 dark:border-surface-600 rounded px-1.5 py-0.5 text-surface-400" id="search-shortcut-kbd">
      <span class="text-xs" id="search-modifier">Ctrl+</span>K
    </kbd>
  </button>
</div>

<!-- Search modal -->
<div id="search-modal" class="hidden fixed inset-0 z-[100]">
  <div id="search-backdrop" class="absolute inset-0 bg-black/60 backdrop-blur-sm"></div>
  <div class="relative flex justify-center pt-[10vh] px-4">
    <div class="w-full max-w-2xl bg-white dark:bg-surface-900 rounded-xl shadow-2xl border border-surface-200 dark:border-surface-700 overflow-hidden">
      <div class="flex items-center gap-3 px-4 border-b border-surface-200 dark:border-surface-700">
        <svg class="w-5 h-5 shrink-0 text-surface-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        <input
          id="search-input"
          type="text"
          placeholder="Search documentation..."
          class="flex-1 py-3 bg-transparent text-surface-900 dark:text-white placeholder-surface-400 outline-none text-base"
          autocomplete="off"
        />
        <kbd class="text-xs border border-surface-300 dark:border-surface-600 rounded px-1.5 py-0.5 text-surface-400 cursor-pointer" id="search-close-kbd">Esc</kbd>
      </div>
      <div id="search-status" class="hidden px-4 py-2 text-xs text-surface-500 dark:text-surface-400 border-b border-surface-100 dark:border-surface-800"></div>
      <div id="search-results" class="max-h-[60vh] overflow-y-auto p-2">
        <div class="p-8 text-center text-surface-400 text-sm" id="search-empty">
          Start typing to search...
        </div>
      </div>

    </div>
  </div>
</div>

<script define:vars={{ base }}>
  // Pagefind instance persists across View Transitions - no need to re-import
  let pagefind = null;

  async function loadPagefind() {
    if (pagefind) return pagefind;
    pagefind = await import(`${base}pagefind/pagefind.js`);
    await pagefind.init();
    return pagefind;
  }

  // Section badge color mapping (static, no DOM dependency)
  const SECTION_COLORS = {
    'Get Started': 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    'Guide': 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    'Features': 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
    'Reference': 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400',
    'Scenarios': 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-400',
    'Concepts': 'bg-rose-100 text-rose-800 dark:bg-rose-900/30 dark:text-rose-400',
    'Cookbook': 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400',
    'Blog': 'bg-pink-100 text-pink-800 dark:bg-pink-900/30 dark:text-pink-400',
  };

  function getSectionBadge(section) {
    if (!section) return '';
    const colors = SECTION_COLORS[section] || 'bg-surface-100 text-surface-700 dark:bg-surface-800 dark:text-surface-300';
    return `<span class="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${colors}">${section}</span>`;
  }

  // --- DOM-dependent state, refreshed on each navigation ---
  let searchBtn, searchModal, searchBackdrop, searchInput,
      searchResults, searchEmpty, searchCloseKbd, searchStatus;
  let debounceTimer;

  // Bound handler refs so we can removeEventListener cleanly
  let _onBtnClick, _onBackdropClick, _onCloseKbdClick, _onInput;

  function openSearch() {
    searchModal?.classList.remove('hidden');
    searchInput?.focus();
    document.body.style.overflow = 'hidden';
  }

  function closeSearch() {
    searchModal?.classList.add('hidden');
    if (searchInput) searchInput.value = '';
    if (searchResults) searchResults.innerHTML = '';
    if (searchEmpty) {
      searchResults?.appendChild(searchEmpty);
      searchEmpty.textContent = 'Start typing to search...';
    }
    searchStatus?.classList.add('hidden');
    document.body.style.overflow = '';
  }

  async function performSearch() {
    const query = searchInput?.value?.trim();
    if (!query) {
      if (searchResults && searchEmpty) {
        searchResults.innerHTML = '';
        searchEmpty.textContent = 'Start typing to search...';
        searchResults.appendChild(searchEmpty);
      }
      searchStatus?.classList.add('hidden');
      return;
    }

    try {
      const pf = await loadPagefind();
      const search = await pf.search(query);
      const results = await Promise.all(search.results.slice(0, 8).map(r => r.data()));

      if (!searchResults) return;
      searchResults.innerHTML = '';

      if (results.length === 0) {
        const noResults = document.createElement('div');
        noResults.className = 'p-8 text-center text-surface-400 text-sm';
        noResults.textContent = `No results for "${query}"`;
        searchResults.appendChild(noResults);
        searchStatus?.classList.add('hidden');
        return;
      }

      if (searchStatus) {
        searchStatus.textContent = `${search.results.length} result${search.results.length === 1 ? '' : 's'}`;
        searchStatus.classList.remove('hidden');
      }

      results.forEach((result) => {
        const section = result.meta?.section || '';
        const a = document.createElement('a');
        a.href = result.url;
        a.className = 'block px-3 py-2.5 rounded-lg hover:bg-surface-100 dark:hover:bg-surface-800 transition-colors group';
        a.innerHTML = `
          <div class="flex items-center gap-2">
            <span class="font-medium text-base text-surface-900 dark:text-white group-hover:text-squad-600 dark:group-hover:text-squad-400 transition-colors">${result.meta?.title || 'Untitled'}</span>
            ${getSectionBadge(section)}
          </div>
          <div class="text-sm text-surface-500 dark:text-surface-400 mt-0.5 line-clamp-2">${result.excerpt || ''}</div>
        `;
        // Close modal on click - navigation proceeds via View Transitions
        a.addEventListener('click', closeSearch);
        searchResults.appendChild(a);
      });
    } catch {
      if (searchResults) {
        searchResults.innerHTML = '<div class="p-8 text-center text-surface-400 text-sm">Search index loading...</div>';
      }
    }
  }

  // Global keydown - register exactly once, never duplicated
  let _globalKeydownRegistered = false;
  function handleGlobalKeydown(e) {
    if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
      e.preventDefault();
      if (searchModal?.classList.contains('hidden')) {
        openSearch();
      } else {
        closeSearch();
      }
    }
    if (e.key === 'Escape') closeSearch();
  }

  function initSearch() {
    // Cancel any in-flight debounce from the previous page
    clearTimeout(debounceTimer);

    // Tear down old element listeners (old refs may be detached)
    if (_onBtnClick && searchBtn) searchBtn.removeEventListener('click', _onBtnClick);
    if (_onBackdropClick && searchBackdrop) searchBackdrop.removeEventListener('click', _onBackdropClick);
    if (_onCloseKbdClick && searchCloseKbd) searchCloseKbd.removeEventListener('click', _onCloseKbdClick);
    if (_onInput && searchInput) searchInput.removeEventListener('input', _onInput);

    // Re-query all DOM elements (fresh references after View Transition swap)
    searchBtn = document.getElementById('search-btn');
    searchModal = document.getElementById('search-modal');
    searchBackdrop = document.getElementById('search-backdrop');
    searchInput = document.getElementById('search-input');
    searchResults = document.getElementById('search-results');
    searchEmpty = document.getElementById('search-empty');
    searchCloseKbd = document.getElementById('search-close-kbd');
    searchStatus = document.getElementById('search-status');

    // Detect OS and update shortcut badge
    const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform);
    const modifierEl = document.getElementById('search-modifier');
    if (modifierEl) {
      modifierEl.textContent = isMac ? 'Cmd+' : 'Ctrl+';
    }

    // Create fresh bound handlers
    _onBtnClick = () => openSearch();
    _onBackdropClick = () => closeSearch();
    _onCloseKbdClick = () => closeSearch();
    _onInput = () => {
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => performSearch(), 200);
    };

    searchBtn?.addEventListener('click', _onBtnClick);
    searchBackdrop?.addEventListener('click', _onBackdropClick);
    searchCloseKbd?.addEventListener('click', _onCloseKbdClick);
    searchInput?.addEventListener('input', _onInput);

    // Register global keydown exactly once
    if (!_globalKeydownRegistered) {
      document.addEventListener('keydown', handleGlobalKeydown);
      _globalKeydownRegistered = true;
    }
  }

  // astro:page-load fires on initial load AND after each View Transition
  document.addEventListener('astro:page-load', initSearch);
</script>
