<script>
	import { handleRegister, checkExsistingUser, VerificationEmail, resendVerification } from '$lib/register';
	import { fly } from 'svelte/transition';
	import { cubicOut } from 'svelte/easing';

	let days = [];
	for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day);
	}

	const now = new Date();
	const legalyear = now.getFullYear();
	let years = [];
	for (let i = legalyear - 16; i > legalyear - 100; i--) years.push(i);

	let name      = ''
	let mail      = ''
	let password  = '' 
	let password2 = '' 
	let dateDay   = '' 
	let dateMonth = '' 
	let dateYear  = ''

	let nameError      = ''
	let mailError      = ''
	let passwordError  = '' 
	let password2Error = ''
	let code           = '' 
	let codeError      = ''

	let token

	async function SendData() {
		if ((name === '' )|| (name === undefined))
			nameError = 'пустой ник';

		if ((mail === '') || (mail === undefined))
			mailError = 'введи почту';
		
		if ((password === '') || (password2 === '') 
        && (password === undefined) || (password2 === undefined))
			passwordError = 'акк без пароля?';
		
    	if ((password != "") && (password2 == ""))
      		password2Error = "забыл повторить"
      	if ((password2 != "") && (password == ""))
      		passwordError = "забыл повторить"

		console.log(nameError, mailError, passwordError, password2Error)

		let allError = [nameError, mailError, passwordError, password2Error].every(
			error => error === '' || error === undefined )
		console.log(allError)

		if ( allError ) {
			let date = `${dateYear}-${dateMonth}-${dateDay}`;

			await handleRegister(name, password, password2, mail, date);

			token = localStorage.getItem('BPChat')

			rotate();
     		console.log("отправлено")
		}
	}

	async function lisenerName() {
		
		if(name.length == 0){
			nameError = "";
		}
		else if (name.length < 2){
			nameError = "ник от двух символов";
		}
		else if (name.length != 0) {
			let error = await checkExsistingUser(name, null);
			console.log(error);
			nameError = error;
		}
	}

	async function lisenerEmail() {
		if (mail.length == 0) {
			mailError = '';
		} else {
			let error = await checkExsistingUser(null, mail);
			console.log(error);
			mailError = error;
		}
	}

	async function lisenerPassword() {
		if(password.length == 0)
      { passwordError = ""; password2Error = "" }

   	  	else if((password2 === "") && (password != ""))
      { passwordError = ""; password2Error = "" }
		
	  	else if (password != password2)
      { passwordError = 'пароли не совпадают';}

	    else if ((password.length < 8) || (passwordError === undefined))
	  { passwordError = 'минимум 8 символов'; }
	  
		else passwordError = '';
	}

	async function lisenerCode(event){
		
		code = event.target.value
		
		if(code.length == 6){
			let verfcode = await VerificationEmail(code, token)
			if(verfcode == false)
				codeError = "Неправильный код"
		}
		
	}

	let leapYear = true
	let nowMonth
	async function lisinerMonth(event){
		nowMonth = event.target.value
		//console.log(nowMonth)
		days = [];
		switch(nowMonth){
			case "01":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;

			case "02":
				console.log(leapYear, " проверка")
			if(leapYear == true){
		for (let i = 1; i <= 29; i++) {
			let day = i.toString().padStart(2, '0');
			days.push(day)}
			} else if(leapYear == false){
		for (let i = 1; i <= 28; i++) {
			let day = i.toString().padStart(2, '0');
			days.push(day)}
			}
			break;
		
			case "03":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "04":
		for (let i = 1; i <= 30; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "05":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "06":
		for (let i = 1; i <= 30; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "07":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "08":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "09":
		for (let i = 1; i <= 30; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "10":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "11":
		for (let i = 1; i <= 30; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
			case "12":
		for (let i = 1; i <= 31; i++) {
		let day = i.toString().padStart(2, '0');
		days.push(day)}
			break;
		}
	}

	function lisinerYear(event){
		let pickedYear = event.target.value
		let leapYearChecker = pickedYear % 4
		if(leapYearChecker != 0){
			leapYear = false
			if(nowMonth == "02"){
				days = [];
				for (let i = 1; i <= 28; i++) {
			let day = i.toString().padStart(2, '0');
			days.push(day)}
			}
		} else {
			leapYear = true
			if(nowMonth == "02"){
				days = [];
				for (let i = 1; i <= 29; i++) {
			let day = i.toString().padStart(2, '0');
			days.push(day)}
			}
		}

		
	}

	let rotated = false;
	function rotate() {
		rotated = !rotated;
	}

	async function sendCodeAgain(){
		await resendVerification(token)
	}
</script>

<body>
	<div class="mainDiv {rotated ? 'rotated' : ''}">
		<div class="mainDivInner">

	<div class="mainDivFront">
			<div class="marginDiv">
				<form on:submit|preventDefault={SendData}>
					<h1>Регистрация</h1>

					<div class="group">
						<div class="groupname">
							<h3>имя</h3>
							{#if nameError !== ''}
								<h3 id="name" transition:fly={{ y: -30, duration: 300, easing: cubicOut }}>
									{nameError}
								</h3>
							{/if}
						</div>
						<input on:blur={lisenerName} type="text" maxlength="30" bind:value={name} />
					</div>

					<div class="group">
						<div class="groupname">
							<h3>эл почта</h3>
							{#if mailError !== ''}
								<h3 id="mail" transition:fly={{ y: -30, duration: 300, easing: cubicOut }}>
									{mailError}
								</h3>
							{/if}
						</div>
						<input on:blur={lisenerEmail} type="email" maxlength="100" bind:value={mail} />
					</div>

					<div class="group">
						<div class="groupname">
							<h3>пароль</h3>
							{#if passwordError !== ''}
								<h3 id="password" transition:fly={{ y: -30, duration: 300, easing: cubicOut }}>
									{passwordError}
								</h3>
							{/if}
						</div>
						<input
							type="password"
							maxlength="100"
							bind:value={password}
							on:blur={lisenerPassword}
						/>
					</div>

					<div class="group">
						<div class="groupname">
							<h3>повтори пароль</h3>
							{#if password2Error && password2Error !== ''}
								<h3 id="password2">{password2Error}</h3>
							{/if}
						</div>
						<input
							type="password"
							maxlength="100"
							bind:value={password2}
							on:blur={lisenerPassword}
						/>
					</div>

					<div class="group">
						<h3>Дата рождения</h3>
						<div class="birthday">
							<select id="dayDropDown" bind:value={dateDay}>
								{#each days as day}
									<option value={day}>{day}</option>
								{/each}
							</select>

							<select id="monthDropDown" bind:value={dateMonth} on:change={lisinerMonth}>
								<option value="01">Январь</option>
								<option value="02">Февраль</option>
								<option value="03">Март</option>
								<option value="04">Апрель</option>
								<option value="05">Май</option>
								<option value="06">Июнь</option>
								<option value="07">Июль</option>
								<option value="08">Август</option>
								<option value="09">Сентябрь</option>
								<option value="10">Октябрь</option>
								<option value="11">Ноябрь</option>
								<option value="12">Декабрь</option>
							</select>

							<select id="yearDropDown" bind:value={dateYear} on:change={lisinerYear}>
								{#each years as year}
									<option value={year}>{year}</option>
								{/each}
							</select>
						</div>
					</div>

					<button class="submitReg" type="submit">Зарегаться</button>
				</form>
			</div>
	</div>

	<div class="mainDivBack">
		<div class="noise">
		<div class="marginDivBack">
			
				<h1>Подтверди</h1>
				<h1>почту</h1>

				<form class="codeForm" on:submit|preventDefault={VerificationEmail}>
					<h3 id="codeError">{codeError}</h3>
				<input maxlength="6" type="text" name="code" id="code" on:input={lisenerCode}>
				<button on:click={sendCodeAgain} id="resendButt" type="submit">отправить код еще раз</button>
				</form>
			</div>
		</div>
	</div>

		</div>
	</div>
	
</body>

<style lang="scss">

	#code{
		text-align: center;
	}

	#resendButt{
		font-size: 16px;
	}

	.codeForm{
		display: flex;
		justify-content:flex-end;
		height: 50%;
	}

	body{
		overflow-y: hidden;
	}

	.mainDiv{
		position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		aspect-ratio: 1 / 1.44;
		height: calc(100% - 100px);
		perspective: 1000px;

		display: flex;
		place-content: center center;
	}
	
	.mainDivInner{
		width: 100%;
    	height: 100%;
    	transition: transform 0.6s;
		transform-style: preserve-3d;
	}

	.mainDivFront,
	.mainDivBack {
		position: absolute;
		border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
		width: 100%;
		height: 100%;
		backface-visibility: hidden;

		display: flex;
		place-content: center center;

	}

	.mainDivFront::before,
	.mainDivBack::before{
	content: '';
	position: absolute;
	background-image: url('/image/noise.gif');
	background-repeat: repeat;
	width: 100%;
	height: 100%;
	border-radius: 15px;
	opacity: 0.01;
	pointer-events: none;
}

	.rotated
	.mainDivInner,
	.mainDivBack{
		transform: rotateX(180deg);
	}

	form {
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		height: 100%;
		width: 100%;
		justify-content: space-around;
	}

	#name,
	#mail,
	#password,
    #password2,
	#codeError {
		color: var(--disable);
		font-weight: 700;
		font-size: 20px;
	}

	.groupname {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}

	.marginDivBack{
		display: flex;
		flex-direction: column; 
		position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		width: 70%;
		height: 80%;
		margin: 15px 0 0 0;
	}

	.marginDiv {
		display: flex;
		flex-direction: column;
		width: 90%;
		height: 100%;
		//background-color: red;
	}
	.birthday {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	input,
	select {
		border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 10px;
		width: 100%;
		height: 2em;
		font-size: 24px;
		font-weight: 600;
		box-shadow:
			4px 4px 15px rgba($color: #5e2a83, $alpha: 0.38),
			-4px -4px 15px rgba($color: #3d53fe, $alpha: 0.38);
		outline: none;
		margin-top: 5px;
	}

	input{
	}

	input:focus,
	select:focus {
		transition: 0.5s ease-in;
		box-shadow: 0 0 transparent;
	}
	input:not(:focus),
	select:not(:focus) {
		transition: 0.5s ease-in-out;
		box-shadow:
			4px 4px 15px rgba($color: #5e2a83, $alpha: 0.38),
			-4px -4px 15px rgba($color: #3d53fe, $alpha: 0.38);
	}

	#dayDropDown {
		width: 2.5em;
	}
	#monthDropDown {
		width: 8em;
	}
	#yearDropDown {
		width: 4em;
	}

	
</style>
