---
import StarlightSearch from '@astrojs/starlight/components/Search.astro';
import { docsVersion } from '../docs-path';

const version = docsVersion(Astro.url.pathname);
---

<version-search data-version={version}>
  <StarlightSearch />
</version-search>

<script>
  class VersionSearch extends HTMLElement {
    observer?: MutationObserver;

    connectedCallback() {
      const version = this.dataset.version;
      if (!version) return;

      const selectVersion = () => {
        const checkbox = this.querySelector<HTMLInputElement>(
          `.pagefind-ui__filter-checkbox[name="version"][value="${version}"]`,
        );
        if (!checkbox) return false;
        if (!checkbox.checked) checkbox.click();
        this.observer?.disconnect();
        return true;
      };

      if (selectVersion()) return;
      // Starlight does not expose its PagefindUI instance, so wait for Pagefind's filter control.
      this.observer = new MutationObserver(selectVersion);
      this.observer.observe(this, { childList: true, subtree: true });
    }

    disconnectedCallback() {
      this.observer?.disconnect();
    }
  }

  customElements.define('version-search', VersionSearch);
</script>

<style>
  version-search {
    display: contents;
  }

  version-search :global(.pagefind-ui__filter-panel) {
    display: none;
  }
</style>
