<script lang="ts">
	import { createEventDispatcher } from 'svelte';

	interface FormValidations {
		email?: boolean;
		general?: boolean;
	}

	export const validations: FormValidations = {};

	let email: string = '';
	let password: string = '';
	let passwordConfirmation: string = '';

	const dispatch = createEventDispatcher();
	const execLogin = () =>
		dispatch('login', {
			email,
			password
		});

	const execRegister = () => {
		if (password !== passwordConfirmation) {
			console.log("password and confirm don't match");
			return;
		}

		dispatch('register', {
			email,
			password
		});
	};

	let showPassword = false;
	let showRegistration = false;

	const revealPass = () => (showPassword = !showPassword);
	const toggleFormType = () => (showRegistration = !showRegistration);

	$: ctaTxt = showRegistration ? 'Up' : 'In';
	$: toggleCtaTxt = !showRegistration ? 'Up' : 'In';
	$: ctaFunc = showRegistration ? execRegister : execLogin;
</script>

<form class="flex" style="max-width: 600px;" on:submit|preventDefault={ctaFunc}>
	<span class="flex flex-col justify-around w-20">
		<label for="email"> Email </label>
		<label for="password"> Password&nbsp;</label>
	</span>

	<span class="flex flex-col">
		<span class="flex">
			<input
				class="px-2 py-1 border-r-0 grow invalid:border-red-500 invalid:border-2"
				type="email"
				required
				bind:value={email}
			/>
			<button class="border-l-0 px-2 py-1 disabled:text-gray-500">
				Sign {ctaTxt}
			</button>
		</span>
		<span class="flex">
			<input
				class="px-2 py-1 w-full"
				name="password"
				type={showPassword ? 'text' : 'password'}
				required
				placeholder={showRegistration ? 'Password' : ''}
				on:blur={() => (showPassword = false)}
				on:change={(evt) => (password = evt?.target?.value)}
			/>
			{#if showRegistration}
				<input
					class="px-2 py-1 border-r-0 invalid:border-red-500 invalid:border-2"
					name="confirm_password"
					type={showPassword ? 'text' : 'password'}
					pattern={password}
					required
					placeholder="Confirm Password"
					on:blur={() => (showPassword = false)}
					on:change={(evt) => (passwordConfirmation = evt?.target?.value)}
				/>

				<button
					class="border-l-0 px-2 py-1 w-16"
					tabindex="-1"
					on:click|stopPropagation={revealPass}
				>
					{showPassword ? 'Hide' : 'Show'}
				</button>
			{/if}
		</span>
	</span>
	<button
		class="w-20 bg-bh-gold text-bh-black border-bh-black"
		on:click|stopPropagation={toggleFormType}
	>
		I Want to Sign {toggleCtaTxt}
	</button>
</form>
