<template>
	<section class="simplestats-auth-card">
		<header class="simplestats-auth-card__brand">
			<div class="simplestats-auth-card__logo">
				<img
					class="simplestats-auth-card__logo-image"
					:src="getImageUrl('logo.svg')"
					alt="SimpleStats"
				/>
			</div>
			<p class="simplestats-auth-card__tagline">{{ text_tagline }}</p>
		</header>

		<form class="simplestats-auth-card__form" @submit.prevent="onSubmit" novalidate>
			<div
				v-if="globalMessage"
				class="simplestats-auth-card__notice"
				role="alert"
			>{{ globalMessage }}</div>

			<div class="simplestats-auth-card__field">
				<label class="simplestats-auth-card__field-label" :for="selectId">
					{{ text_field_label }}
				</label>
				<select
					:id="selectId"
					class="simplestats-auth-card__select"
					:value="store.draft.tracking_type"
					:disabled="isSubmitting"
					@change="onChange"
				>
					<option value="normal">{{ text_option_normal }}</option>
					<option value="lightweight">{{ text_option_lightweight }}</option>
				</select>
				<p class="simplestats-auth-card__help-text">{{ helpText }}</p>
			</div>

			<button
				type="submit"
				class="simplestats-auth-card__submit"
				:class="{ 'is-loading': isSubmitting }"
				:disabled="isSubmitting"
			>
				<span v-if="isSubmitting" class="simplestats-auth-card__submit-spinner" aria-hidden="true" />
				<span>{{ isSubmitting ? text_cta_loading : text_cta }}</span>
				<svg
					v-if="!isSubmitting"
					class="simplestats-auth-card__submit-arrow"
					width="16"
					height="16"
					viewBox="0 0 16 16"
					fill="none"
					xmlns="http://www.w3.org/2000/svg"
					aria-hidden="true"
				>
					<path d="M3 8H13M13 8L8 3M13 8L8 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
			</button>
		</form>

		<p class="simplestats-auth-card__alt">
			<router-link class="simplestats-auth-card__alt-link" :to="backRoute">{{ text_back }}</router-link>
		</p>
	</section>
</template>

<script setup>
	import { computed, onMounted } from 'vue';
	import { useRouter } from 'vue-router';
	import { useAuthStore } from '@/authentication/store.js';

	const router = useRouter();
	const store  = useAuthStore();
	const selectId = 'simplestats-auth-tracking-type';

	// Hard guard: if the user lands here directly (refresh, bookmark) without
	// going through the credentials form first, the store has no email or flow,
	// so there's nothing to submit. Bounce them back to start.
	onMounted( () => {
		if ( ! store.flow || ! store.draft.email ) {
			router.replace( { name: 'sign-up' } );
		}
	} );

	const text_tagline            = wp.i18n.__( 'How would you like to track visitors?', 'simplestats-friendly-website-analytics' );
	const text_field_label        = wp.i18n.__( 'Tracking mode', 'simplestats-friendly-website-analytics' );
	const text_option_normal      = wp.i18n.__( 'Advanced', 'simplestats-friendly-website-analytics' );
	const text_option_lightweight = wp.i18n.__( 'Simple', 'simplestats-friendly-website-analytics' );
	const text_help_normal        = wp.i18n.__( 'Heatmaps, session replays, and repeat-visitor insight. Uses a small cookie + local storage to recognize repeat visitors. You can change this later from the SimpleStats app.', 'simplestats-friendly-website-analytics' );
	const text_help_lightweight   = wp.i18n.__( 'Cookie-free and GDPR/CCPA-friendly — no consent banner needed. Counts pageviews and goals only, with no repeat-visitor identity, heatmaps, or session replays.', 'simplestats-friendly-website-analytics' );
	const text_cta                = wp.i18n.__( 'Continue', 'simplestats-friendly-website-analytics' );
	const text_cta_loading        = wp.i18n.__( 'Connecting…', 'simplestats-friendly-website-analytics' );
	const text_back               = wp.i18n.__( 'Back', 'simplestats-friendly-website-analytics' );

	const isSubmitting = computed( () => store.status === 'submitting' );

	const helpText = computed( () =>
		'lightweight' === store.draft.tracking_type ? text_help_lightweight : text_help_normal
	);

	// The "Back" link should return the user to the form that brought them here.
	const backRoute = computed( () => ( {
		name: 'sign-in' === store.flow ? 'sign-in' : 'sign-up',
	} ) );

	// Non-field errors only — anything that maps to email/password gets
	// surfaced on the credentials page after submitConnect bounces back.
	const globalMessage = computed( () => {
		const code = store.fieldErrors._global;
		if ( ! code )                          return '';
		if ( 'rate_limited' === code )         return wp.i18n.__( 'Too many attempts. Please wait before trying again.', 'simplestats-friendly-website-analytics' );
		if ( 'network' === code )              return wp.i18n.__( 'Couldn’t reach SimpleStats. Check your connection and try again.', 'simplestats-friendly-website-analytics' );
		if ( 'already_connected' === code )    return wp.i18n.__( 'This site is already connected.', 'simplestats-friendly-website-analytics' );
		return ( store.error && store.error.message ) || '';
	} );

	function onChange( event ) {
		store.setTrackingType( event.target.value );
	}

	function onSubmit() {
		store.submitConnect( router );
	}
</script>
