<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" :class="{ 'has-error': store.fieldErrors.email }">
				<input
					type="email"
					class="simplestats-auth-card__input"
					:placeholder="text_email_placeholder"
					:value="store.draft.email"
					autocomplete="email"
					required
					@input="onEmailInput"
				/>
				<p v-if="emailExists" class="simplestats-auth-card__error">
					{{ text_email_exists_prefix }}
					<router-link class="simplestats-auth-card__error-link" to="/sign-in">{{ text_sign_in }}</router-link>
					{{ text_email_exists_suffix }}
				</p>
				<p v-else-if="emailErrorMessage" class="simplestats-auth-card__error">{{ emailErrorMessage }}</p>
			</div>

			<label class="simplestats-auth-card__optin">
				<input
					type="checkbox"
					class="simplestats-auth-card__optin-input"
					v-model="optIn"
				/>
				<span class="simplestats-auth-card__optin-box" aria-hidden="true">
					<svg
						width="10"
						height="10"
						viewBox="0 0 12 12"
						fill="none"
						xmlns="http://www.w3.org/2000/svg"
					>
						<path d="M10 3L4.5 8.5L2 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
					</svg>
				</span>
				<span class="simplestats-auth-card__optin-label">{{ text_optin }}</span>
			</label>

			<button
				type="submit"
				class="simplestats-auth-card__submit"
				:class="{ 'is-loading': isSubmitting }"
				:disabled="!canSubmit"
			>
				<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>

		<ul class="simplestats-auth-card__features">
			<li
				v-for="feature in features"
				:key="feature"
				class="simplestats-auth-card__feature"
			>
				<span class="simplestats-auth-card__feature-icon" aria-hidden="true">
					<svg
						width="12"
						height="12"
						viewBox="0 0 12 12"
						fill="none"
						xmlns="http://www.w3.org/2000/svg"
					>
						<path d="M10 3L4.5 8.5L2 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
					</svg>
				</span>
				<span class="simplestats-auth-card__feature-text">{{ feature }}</span>
			</li>
		</ul>

		<p class="simplestats-auth-card__alt">
			{{ text_have_account }}
			<router-link class="simplestats-auth-card__alt-link" to="/sign-in">{{ text_sign_in }}</router-link>
		</p>
	</section>
</template>

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

	const router = useRouter();
	const store = useAuthStore();

	const optIn = ref( true );

	// Clear errors only when arriving from a different flow (sign-in / forgot-password).
	// Errors set by a failed sign-up submission must survive the redirect back here.
	onMounted( () => {
		if ( store.flow && store.flow !== 'sign-up' ) {
			store.resetRequest();
		}
	} );

	const text_tagline           = wp.i18n.__( 'You’re only a few minutes away from free, private, website analytics.', 'simplestats-friendly-website-analytics' );
	const text_email_placeholder = wp.i18n.__( 'Email address', 'simplestats-friendly-website-analytics' );
	const text_optin             = wp.i18n.__( 'Send me tips on getting more traffic and growing my site', 'simplestats-friendly-website-analytics' );
	const text_cta               = wp.i18n.__( 'Get Started For Free', 'simplestats-friendly-website-analytics' );
	const text_cta_loading       = wp.i18n.__( 'Setting things up…', 'simplestats-friendly-website-analytics' );
	const text_have_account      = wp.i18n.__( 'Already have an account?', 'simplestats-friendly-website-analytics' );
	const text_sign_in           = wp.i18n.__( 'Sign in', 'simplestats-friendly-website-analytics' );

	// Split so "Sign in" can render as a router-link inside the email-exists error.
	const text_email_exists_prefix = wp.i18n.__( 'An account with that email already exists.', 'simplestats-friendly-website-analytics' );
	const text_email_exists_suffix = wp.i18n.__( 'instead.', 'simplestats-friendly-website-analytics' );

	const features = [
		wp.i18n.__( 'Real-time activity feed', 'simplestats-friendly-website-analytics' ),
		wp.i18n.__( 'Easy to Use', 'simplestats-friendly-website-analytics' ),
		wp.i18n.__( 'Marketing Campaigns', 'simplestats-friendly-website-analytics' ),
		wp.i18n.__( 'GDPR compliant', 'simplestats-friendly-website-analytics' ),
	];

	const isSubmitting = computed( () => store.status === 'submitting' );
	const canSubmit    = computed( () => store.draft.email.length > 0 && ! isSubmitting.value );

	const emailExists = computed( () => 'email_exists' === store.fieldErrors.email );

	const emailErrorMessage = computed( () => {
		const code = store.fieldErrors.email;
		if ( ! code ) return '';
		if ( 'email_required' === code ) return wp.i18n.__( 'Email is required.', 'simplestats-friendly-website-analytics' );
		if ( 'email_invalid' === code )  return wp.i18n.__( 'Please enter a valid email address.', 'simplestats-friendly-website-analytics' );
		return ( store.error && store.error.message ) || '';
	} );

	const globalMessage = computed( () => {
		const code = store.fieldErrors._global;
		if ( ! code ) return '';
		if ( 'rate_limited' === code )      return wp.i18n.__( 'Too many attempts. Please try again in a moment.', '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 ) || wp.i18n.__( 'Something went wrong.', 'simplestats-friendly-website-analytics' );
	} );

	function onEmailInput( event ) {
		store.setDraft( { email: event.target.value } );
		store.clearFieldError( 'email' );
		store.clearFieldError( '_global' );
	}

	function onSubmit() {
		store.submitSignUp( router, optIn.value );
	}
</script>
