<script setup>
import { computed, inject, ref } 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>

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

			<Icon icon="search" />
		</label>

		<div
			v-if="filteredCountries.length > 0"
			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
			v-else
			class="empty"
		>
			No matching countries
		</div>
	</div>
</template>

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

.filter-search {

	border-bottom: solid 1px var(--shadow-weak-40);
}

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

.empty {
	padding: .5rem;
	color: var(--glass);
	font-style: italic;
}

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