---
import context from 'virtual:starlight/project-context';
import config from 'virtual:starlight/user-config';
import { localizedUrl } from '../utils/localizedUrl';
import Select from './Select.astro';

/**
 * Get the equivalent of the current page path for the passed locale.
 */
function localizedPathname(locale: string | undefined): string {
	return localizedUrl(Astro.url, locale, context.trailingSlash).pathname;
}
---

{
	config.isMultilingual && (
		<starlight-lang-select>
			<Select
				icon="translate"
				label={Astro.locals.t('languageSelect.accessibleLabel')}
				options={Object.entries(config.locales).map(([code, locale]) => ({
					value: localizedPathname(code),
					selected: code === Astro.locals.starlightRoute.locale,
					label: locale!.label,
				}))}
				width="7em"
			/>
		</starlight-lang-select>
	)
}

<script>
	class StarlightLanguageSelect extends HTMLElement {
		constructor() {
			super();
			const select = this.querySelector('select');
			if (select) {
				select.addEventListener('change', (e) => {
					if (e.currentTarget instanceof HTMLSelectElement) {
						window.location.pathname = e.currentTarget.value;
					}
				});
				window.addEventListener('pageshow', (event) => {
					if (!event.persisted) return;
					// If the page was loaded from a cache, the language select selected index might not be
					// in sync with the current page.
					const markupSelectedIndex =
						select.querySelector<HTMLOptionElement>('option[selected]')?.index;
					if (markupSelectedIndex !== select.selectedIndex) {
						select.selectedIndex = markupSelectedIndex ?? 0;
					}
				});
			}
		}
	}
	customElements.define('starlight-lang-select', StarlightLanguageSelect);
</script>
