<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_page }}</span>
			<span class="simplestats-table-card__th-metrics">
				<span>{{ text_col_views }}</span>
				<span>{{ text_col_change }}</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">
						<RefIcon :host="r.host" />
					</span>
					<span class="simplestats-table-card__row-text">{{ r.host }}</span>
				</div>
				<div class="simplestats-table-card__row-metrics">
					<span class="simplestats-table-card__row-metric">{{ formatNumber( r.views ) }}</span>
					<span :class="[ 'simplestats-table-card__row-metric', deltaClass( r.delta_pct ) ]">{{ deltaText( r.delta_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 RefIcon from './atoms/RefIcon.vue';
	import { useStore } from '@/dashboard/store.js';
	import { useReportHelper } from '@/dashboard/helper.js';

	defineOptions( { name: 'ReferrersTable' } );

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

	const text_title      = wp.i18n.__( 'Referrers', 'simplestats-friendly-website-analytics' );
	const text_col_page   = wp.i18n.__( 'PAGE',      'simplestats-friendly-website-analytics' );
	const text_col_views  = wp.i18n.__( 'VIEWS',     'simplestats-friendly-website-analytics' );
	const text_col_change = wp.i18n.__( 'CHANGE',    'simplestats-friendly-website-analytics' );
	const text_empty      = wp.i18n.__( 'No data for this range.', 'simplestats-friendly-website-analytics' );

	function deltaClass( v ) {
		const n = v === null ? 100 : Number( v ) || 0;
		if ( n > 0 ) return 'simplestats-table-card__row-metric--up';
		if ( n < 0 ) return 'simplestats-table-card__row-metric--down';
		return '';
	}

	function deltaText( v ) {
		const n   = v === null ? 100 : Number( v ) || 0;
		if ( n === 0 ) return '0%';
		const sign = n > 0 ? '+' : '-';
		const abs  = Math.abs( n );
		const num  = Number.isInteger( abs ) ? String( abs ) : abs.toFixed( 1 );
		return `${ sign }${ num }%`;
	}
</script>
