---
import config from "virtual:starlight/user-config"
import StarlightLanguageSelect from "@astrojs/starlight/components/LanguageSelect.astro"

const locales = Object.keys(config.locales ?? {})
---

<opencode-language-select data-locales={JSON.stringify(locales)}>
  <StarlightLanguageSelect />
</opencode-language-select>

<script>
  document.addEventListener("change", (event) => {
    if (!(event.target instanceof HTMLSelectElement)) return
    const wrapper = event.target.closest("opencode-language-select")
    if (!(wrapper instanceof HTMLElement)) return

    const locales = JSON.parse(wrapper.dataset.locales ?? "[]") as string[]
    const locale = locales[event.target.selectedIndex]
    if (!locale) return
    document.cookie = `oc_locale=${encodeURIComponent(locale === "root" ? "en" : locale)}; Path=/; Max-Age=31536000; SameSite=Lax`
  })
</script>

<style>
  opencode-language-select {
    display: contents;
  }
</style>
