<template>
	<section class="simplestats-table-card">
		<header class="simplestats-table-card__header">
			<h3 class="simplestats-table-card__title">{{ text_title }}</h3>
		</header>
		<div class="simplestats-table-card__divider" />

		<div class="simplestats-table-card__th">
			<span class="simplestats-table-card__th-label">{{ text_col_country }}</span>
			<span class="simplestats-table-card__th-metrics">
				<span>{{ text_col_visitors }}</span>
				<span>{{ text_col_share }}</span>
			</span>
		</div>

		<ul v-if="rows.length" class="simplestats-table-card__list">
			<li v-for="( r, i ) in rows" :key="i" class="simplestats-table-card__row">
				<div class="simplestats-table-card__row-label">
					<span class="simplestats-table-card__row-icon">
						<CountryFlag :code="r.code" :name="countryName( r.code )" />
					</span>
					<span class="simplestats-table-card__row-text">{{ countryName( r.code ) }}</span>
				</div>
				<div class="simplestats-table-card__row-metrics">
					<span class="simplestats-table-card__row-metric">{{ formatNumber( r.visitors ) }}</span>
					<span class="simplestats-table-card__row-metric simplestats-table-card__row-metric--share">{{ r.pct }}%</span>
				</div>
			</li>
		</ul>
		<div v-else class="simplestats-table-card__empty">{{ text_empty }}</div>
	</section>
</template>

<script setup>
	import { computed } from 'vue';
	import CountryFlag from './atoms/CountryFlag.vue';
	import { useStore } from '@/dashboard/store.js';
	import { useReportHelper } from '@/dashboard/helper.js';

	defineOptions( { name: 'CountriesTable' } );

	const store            = useStore();
	const { formatNumber } = useReportHelper();
	const rows             = computed( () => store.report.data?.countries || [] );

	const text_title        = wp.i18n.__( 'Countries', 'simplestats-friendly-website-analytics' );
	const text_col_country  = wp.i18n.__( 'COUNTRY',   'simplestats-friendly-website-analytics' );
	const text_col_visitors = wp.i18n.__( 'VISITORS',  'simplestats-friendly-website-analytics' );
	const text_col_share    = wp.i18n.__( 'SHARE',     'simplestats-friendly-website-analytics' );
	const text_empty        = wp.i18n.__( 'No data for this range.', 'simplestats-friendly-website-analytics' );

	const regionDisplay = ( () => {
		try {
			return new Intl.DisplayNames( [ navigator.language || 'en' ], { type: 'region' } );
		} catch {
			return null;
		}
	} )();

	function countryName( code ) {
		if ( ! code ) return wp.i18n.__( 'Unknown', 'simplestats-friendly-website-analytics' );
		if ( regionDisplay ) {
			try { return regionDisplay.of( code ) || code; } catch { return code; }
		}
		return code;
	}
</script>
