<template>
	<div class="simplestats-settings-card">
		<header class="simplestats-settings-card-header">
			<h2>{{ text_heading }}</h2>
		</header>

		<div class="simplestats-settings-row">
			<span class="simplestats-settings-row-label">{{ text_status_label }}</span>

			<span class="simplestats-settings-row-value">
				<template v-if="status === 'checking' || status === 'idle'">
					<span class="simplestats-pill is-checking">
						<span class="simplestats-pill-dot"></span>
						{{ text_checking }}
					</span>
				</template>

				<template v-else-if="status === 'connected'">
					<span class="simplestats-pill is-connected">
						<span class="simplestats-pill-dot"></span>
						{{ text_connected }}
					</span>
				</template>

				<template v-else-if="status === 'error'">
					<span class="simplestats-pill is-error">
						<span class="simplestats-pill-dot"></span>
						{{ text_connection_error }}
					</span>
					<button
						type="button"
						class="simplestats-settings-secondary-button"
						@click="onRetry"
						:disabled="store.connection.isFetching"
					>{{ text_retry }}</button>
				</template>

				<template v-else-if="status === 'disconnected'">
					<a
						class="simplestats-settings-primary-button"
						:href="SimpleStats.authenticationUrl"
					>{{ text_connect }}</a>
				</template>
			</span>
		</div>

		<div
			v-if="store.connection.email"
			class="simplestats-settings-row simplestats-settings-row--account"
		>
			<span class="simplestats-settings-row-label">{{ text_account_label }}</span>
			<span class="simplestats-settings-row-value">{{ store.connection.email }}</span>
		</div>
	</div>
</template>

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

	const store = useStore();

	const text_heading          = wp.i18n.__( 'API Connection', 'simplestats-friendly-website-analytics' );
	const text_status_label     = wp.i18n.__( 'Connection status', 'simplestats-friendly-website-analytics' );
	const text_checking         = wp.i18n.__( 'Checking…', 'simplestats-friendly-website-analytics' );
	const text_connected        = wp.i18n.__( 'Connected', 'simplestats-friendly-website-analytics' );
	const text_connection_error = wp.i18n.__( 'Connection Error', 'simplestats-friendly-website-analytics' );
	const text_retry            = wp.i18n.__( 'Retry', 'simplestats-friendly-website-analytics' );
	const text_connect          = wp.i18n.__( 'Connect Your Site', 'simplestats-friendly-website-analytics' );
	const text_account_label    = wp.i18n.__( 'Connected account', 'simplestats-friendly-website-analytics' );

	const status = computed( () => store.connection.status );

	function onRetry() {
		store.fetchConnectionStatus();
	}
</script>
