<template>
	<span class="simplestats-country-flag">
		<img :src="src" :alt="alt" @error="failed = true" />
	</span>
</template>

<script setup>
	import { computed, ref } from 'vue';
	import globeUrl from '@/images/icons/globe.svg?url';

	const flagModules = import.meta.glob( '@/images/flags/*.svg', { eager: true, query: '?url', import: 'default' } );

	const props = defineProps( {
		code: { type: String, default: '' },
		name: { type: String, default: '' },
	} );

	const failed = ref( false );

	const src = computed( () => {
		if ( failed.value || ! props.code ) return globeUrl;
		const lower = props.code.toLowerCase();
		const key = Object.keys( flagModules ).find( ( k ) => k.toLowerCase().endsWith( `/${ lower }.svg` ) );
		return key ? flagModules[ key ] : globeUrl;
	} );

	const alt = computed( () => props.name || props.code || '' );
</script>
