<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_heading }}</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_label"
					:value="store.draft.email"
					autocomplete="email"
					required
					@input="onEmailInput"
				/>
				<p v-if="emailErrorMessage" class="simplestats-auth-card__error">{{ emailErrorMessage }}</p>
			</div>

			<div class="simplestats-auth-card__field" :class="{ 'has-error': store.fieldErrors.password }">
				<input
					type="password"
					class="simplestats-auth-card__input"
					:placeholder="text_password_label"
					:value="store.draft.password"
					autocomplete="current-password"
					required
					@input="onPasswordInput"
				/>
				<p v-if="passwordErrorMessage" class="simplestats-auth-card__error">{{ passwordErrorMessage }}</p>
				<p class="simplestats-auth-card__help">
					<router-link to="/forgot-password">{{ text_forgot }}</router-link>
				</p>
			</div>

			<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>

		<p class="simplestats-auth-card__alt">
			{{ text_no_account }}
			<router-link class="simplestats-auth-card__alt-link" to="/sign-up">{{ text_create }}</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();

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

	const text_heading        = wp.i18n.__( 'Welcome back — sign in to your SimpleStats account.', 'simplestats-friendly-website-analytics' );
	const text_email_label    = wp.i18n.__( 'Email address', 'simplestats-friendly-website-analytics' );
	const text_password_label = wp.i18n.__( 'Password', 'simplestats-friendly-website-analytics' );
	const text_forgot         = wp.i18n.__( 'I forgot my password', 'simplestats-friendly-website-analytics' );
	const text_cta            = wp.i18n.__( 'Sign In', 'simplestats-friendly-website-analytics' );
	const text_cta_loading    = wp.i18n.__( 'Signing in…', 'simplestats-friendly-website-analytics' );
	const text_no_account     = wp.i18n.__( 'New to SimpleStats?', 'simplestats-friendly-website-analytics' );
	const text_create         = wp.i18n.__( 'Create an account', 'simplestats-friendly-website-analytics' );

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

	const emailErrorMessage = computed( () => {
		const code = store.fieldErrors.email;
		if ( ! code ) return '';
		if ( 'credentials_invalid' === code ) return ''; // shown as global notice
		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' );
		if ( 'email_exists' === code )        return wp.i18n.__( 'An account with that email already exists.', 'simplestats-friendly-website-analytics' );
		return ( store.error && store.error.message ) || '';
	} );

	const passwordErrorMessage = computed( () => {
		const code = store.fieldErrors.password;
		if ( ! code ) return '';
		if ( 'credentials_invalid' === code ) return ''; // shown as global notice
		if ( 'password_required' === code )   return wp.i18n.__( 'Password is required.', 'simplestats-friendly-website-analytics' );
		if ( 'password_invalid' === code )    return wp.i18n.__( 'Incorrect password.', 'simplestats-friendly-website-analytics' );
		return ( store.error && store.error.message ) || '';
	} );

	const globalMessage = computed( () => {
		const code = store.fieldErrors._global ||
			( store.fieldErrors.email === 'credentials_invalid' ? 'credentials_invalid' : null );

		if ( ! code ) return '';
		if ( 'rate_limited' === code )         return wp.i18n.__( 'Too many attempts. Please wait before trying again.', 'simplestats-friendly-website-analytics' );
		if ( 'credentials_invalid' === code )  return wp.i18n.__( 'Incorrect email or password.', '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 onEmailInput( event ) {
		store.setDraft( { email: event.target.value } );
		store.clearFieldError( 'email' );
		store.clearFieldError( '_global' );
	}

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

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