<template>
	<div
		v-if="filteredCountries.length > 0"
		class="countries-container"
	>
		<input
			v-if="!filters.country"
			v-model="countryQuery"
			type="search"
			placeholder="Filter countries"
			class="input input-inline countries-search"
		>

		<div class="countries-list">
			<Countries
				v-if="!countryQuery && !filters.country && topCountries.length < filteredCountries.length"
				:countries="topCountries"
				:selected-country="filters.country"
				@country="(alpha2) => emit('update', 'country', alpha2, true)"
			/>

			<Countries
				:countries="filteredCountries"
				:selected-country="filters.country"
				@country="(alpha2) => emit('update', 'country', alpha2, true)"
			/>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, inject } from 'vue';

import Countries from './countries.vue';

const props = defineProps({
	filters: {
		type: Object,
		default: null,
	},
	countries: {
		type: Array,
		default: null,
	},
});

const emit = defineEmits(['update']);

const pageContext = inject('pageContext');
const { pageProps } = pageContext;

const allCountries = computed(() => props.countries || pageProps.countries);
const countryQuery = ref('');

const topCountryAlpha2s = ['AU', 'BR', 'CZ', 'DE', 'JP', 'RU', 'GB', 'US'];
const topCountries = computed(() => topCountryAlpha2s.map((alpha2) => allCountries.value.find((country) => country.alpha2 === alpha2)).filter(Boolean));
const filteredCountries = computed(() => allCountries.value.filter((country) => new RegExp(countryQuery.value, 'i').test(country.name)));
</script>

<style scoped>
.countries-container {
	border-bottom: solid 1px var(--shadow-weak-30);
	padding: .25rem 0;
	margin-bottom: .5rem;
}

.countries-search {
	width: 100%;
	margin-bottom: .25rem;
	border-bottom: solid 1px var(--shadow-weak-40);
}

.countries-list {
	max-height: 13rem;
	overflow-y: auto;
}

:deep(.country.selected) .country-name {
	padding: .5rem;
}
</style>