<script>

    import { onMount } from 'svelte';
    import { fade, slide, fly, scale } from 'svelte/transition';

    import { getAvatarHistory, changeUserData, getConfirmationCode } from '$lib/settings'
    import { checkExsistingUser } from '$lib/register'
    import { UserCheck } from '$lib/userFunction';
    import { uploadImages } from '$lib/chat';
    import Header from '../Header.svelte';

    import Cropper from 'cropperjs';
    import 'cropperjs/dist/cropper.css';

    let urlChecker = "https://"
    let token
    let confCode
    let userData = []
    let oldName
    let oldEmail

    let afterChanging
    let newAvatarVisualize = ""
    let avatars = []

    let newName = ""
    let newEmail = ""
    let newPassword = ""
    let newAvatar = null
    let code = ""

    let showSubmitDiv = false

    let nameError = ""
    let emailError = ""
    let passwordError = ""

    let submitButton

    onMount(async () => {

        token = localStorage.getItem('BPChat')
        userData = await UserCheck()
        avatars = await getAvatarHistory(token)
        oldName = userData.username
        oldEmail = userData.email
        
    })

  async function changingData(){

    confCode = await getConfirmationCode(token, oldEmail)
    if(confCode == true)
        showSubmitDiv = true
    else
        console.log("ну ты лошара, земля тебе пухом")
  }

  async function submit(){
    if(pickedImg != ""){
        newAvatar = pickedImg
    } else {
        newAvatar = await uploadImages(newAvatar)
    }

    let nName     = "" 
    let nEmail    = "" 
    let nPassword = "" 

    if(newName != ""){
        nName = newName
    } else {
        nName = oldName
    }

    if(newEmail != ""){
        nEmail = newEmail
    } else {
        nEmail = oldEmail
    }

    if(newPassword != ""){
        nPassword = newPassword
    } else {
        nPassword = null
    }
    if(newAvatar == undefined){
        newAvatar = null
    }

    console.log(nName, nEmail,nPassword,newAvatar)
    let changing = afterChanging = await changeUserData(token, nName, nEmail, nPassword, newAvatar, code)

    if (changing == true){
        showSubmitDiv = false
        location.reload()
    } else {
        let changingError = "ник или почта уже занята"
    }
  }

  function cancelSubmitting(){
    showSubmitDiv = false
    code = ""
  }

  function cancel(){
    newName = ""
    newEmail = ""
    newPassword = ""
    newAvatar = null
    newAvatarVisualize = ""
  }

    let imageElement;
    let cropper;
    let croppedImage = "";
    let showCroppingImgDiv = false
    
    const handleFileChange = (event) => {
        showCroppingImgDiv = true
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          imageElement.src = e.target.result;
          if (cropper) {
            cropper.destroy();
          }
          cropper = new Cropper(imageElement, {
            aspectRatio: 1,
            viewMode: 1,
            autoCropArea: 0, // Начальное значение для автообрезки 0
            center: true,
            zoomOnTouch: false,
            zoomOnWheel: false,
            cropBoxMovable: true,
            cropBoxResizable: true,
            background: false, // Убирает сеточный фон
            autoCrop: false, // Изначально не показывать зону обрезки
            ready: function () {
              cropper.setCropBoxData({
                width: 200,
                height: 200,
                left: (cropper.getContainerData().width - 200) / 2,
                top: (cropper.getContainerData().height - 200) / 2,
              });
              cropper.crop(); // Включить зону обрезки
            },
          });
        };
        reader.readAsDataURL(file);
      }
    };
  
    const getCroppedImage = () => {
      if (cropper) {
        croppedImage = cropper.getCroppedCanvas().toDataURL();

        cropper.getCroppedCanvas().toBlob((blob) => {
        newAvatar = blob;
        }, 'image/jpeg');

      }
      showCroppingImgDiv = false
    };

    function cancelCroppedImage(){
        showCroppingImgDiv = false
    }

    let pickedImg = ""
    function PickOldAvatar(oldAvatarUrl){
        pickedImg = oldAvatarUrl
    }

    async function existingUser(){
        
        if((newName.length <= 2) && (newName != "")){
            nameError = "ник от 2 символов"
        } else{
            nameError = ""
        }
        
        if((newName != "") && (newName.length > 2)){
            nameError = await checkExsistingUser(newName, null)
        }

        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        let isValidEmail = emailPattern.test(newEmail)

        if((newEmail != "") && (isValidEmail == true)){
            emailError = await checkExsistingUser(null, newEmail)
        }

        if((newPassword.length < 8) && (newPassword != "")){
            passwordError = "пароль от 8 символов"
            submitButton.disabled = true
        } else {
            passwordError = ""
            submitButton.disabled = false
        }

        if((nameError || emailError || passwordError) != ""){
            submitButton.disabled = true
        } else {
            submitButton.disabled = false
        }
    }

    

</script>

<body>

{#if showCroppingImgDiv}
    <div class="backgroundBlur" transition:fade={{ duration: 500 }}></div>

    <div class="croppingDiv" transition:fly={{y: -800, duration: 500 }}>
        <!-- svelte-ignore a11y-img-redundant-alt -->
        <img class="cropAvatar" bind:this={imageElement} alt="Image to crop" />
        <div class="cropButtonsDiv">
            <button class="cropButton" on:click={getCroppedImage}>Подтвердить</button>
            <button class="cropButton" on:click={cancelCroppedImage}>Отменить</button>
        </div>
    </div>
{/if}

{#if showSubmitDiv}
<div class="backgroundBlur" transition:fade={{ duration: 500 }}></div>
    <div class="submitPassword" transition:fly={{y: -800, duration: 500 }}>
            <h2>Подтвердите кодом из почты</h2>
            <input bind:value={code} type="password" id="oldPassword" placeholder="Код">
            <div class="submitDiv">
                <button on:click={submit}>Отправить</button>
                <button on:click={cancelSubmitting}>Отменить</button>
            </div>
    </div>
{/if}


<div class="header"> <Header/> </div>

<div class="mainDiv">

    <div class="gradient">

        <div class="division">
            <div class="buttonDiv">
                <button class="button">Аккаунт</button>
            </div>
            <div class="changingData">
                <h1>Изменение данных</h1>
                <div class="divisionChangingData">
                    <div class="avatarDiv">
                        <h2>изменить аватарку</h2>
                        <button class="changeAvatar" on:click={() => document.getElementById('fileInput').click()}>
                            {#if croppedImage != ""}
                            <img class="newAvatar" src="{croppedImage}" alt="новая ава">
                            {:else}
                            +
                            {/if}
                        </button>
                        
                        <div class="avatarHistoryDiv">
                            <h3>старые фотки</h3>
                            <div class="avatarsHistory">
                                {#each avatars as avatar}
                                    <!-- svelte-ignore a11y-click-events-have-key-events -->
                                    <!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
                                    <img class="avatarHistory" class:avatarHistoryPicked={avatar.avatar_url == pickedImg} src="{avatar.avatar_url}" alt="ава"
                                    on:click={PickOldAvatar(avatar.avatar_url)}>
                                {/each}
                            </div>
                        </div>
                        <input type="file" accept="image/*" id="fileInput" 
							   on:change={handleFileChange} style="display: none;">
                    </div>

                    <div class="textDiv">
                        <div class="blockDiv">
                            <h3>ник</h3>
                            <input bind:value={newName} type="name" placeholder={oldName} on:input={existingUser} autocomplete="off">
                            {#if nameError != ""}
                                <h2 class="error">{nameError}</h2>
                            {/if}
                        </div>
                        <div class="blockDiv">
                            <h3>почта</h3>
                            <input bind:value={newEmail} type="name" placeholder={oldEmail} on:input={existingUser} autocomplete="off">
                            {#if emailError != ""}
                                <h2 class="error">{emailError}</h2>
                            {/if}
                        </div>
                        <div class="blockDiv">
                            <h2>новый пароль</h2>
                            <input on:blur={existingUser} bind:value={newPassword} type="password" placeholder="новый пароль" autocomplete="new-password">
                            {#if passwordError != ""}
                                <h2 class="error">Пароль от 8 символов</h2>
                            {/if}
                        </div>
                    </div>
                </div>
                <div class="finishButton">
                    <button on:click={changingData} bind:this={submitButton}>Подтвердить</button>
                    <button on:click={cancel}>Отменить</button>
                </div>
            </div>
        </div>

    </div>

</div>    
</body>

<style lang="scss">

.blockDiv{
    display: flex;
    flex-direction: column;
    height: 33%;
    //background-color: red;
}

.error{
    color:var(--disable);
    padding-top:0.25em;
}

.submitDiv{
    display: flex;
    flex-direction: row;
    height: 50px;
    align-items: center;

    button{
        height: 100%;
        &:nth-child(2){
            font-size: 24px;
        }
    }
}

.cropButtonsDiv{
    width: 100%;

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

.cropButton{
    padding-top: 15px;
}

.cropAvatar{
    border-radius: 15px;
    width: 500px;
    height: 500px;

}

.croppingDiv{
    z-index: 5;

    display: flex;
    flex-direction: column;
    align-items: center;


    position: absolute;
    left: 33.33%; top: 10%;

    padding: 20px;
    max-height: 90%;
    max-width: 90%;

    border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
}

.newAvatar{
    width: 75px;
    height: 75px;
    border-radius: 15px;
}

.avatarsHistory{
    display: flex;
    flex-direction: row;
    width: 50%;
    background-color: #FFFFFF0a;
    border-radius: 15px;
    overflow-y: hidden;
}

.avatarHistory{
    width: 75px;
    height: 75px;

    border-radius: 15px;
    padding: 3px;

    cursor: pointer;
}

.avatarHistoryPicked{
    width: 75px;
    height: 75px;

    border-radius: 15px;
    padding: 1px;

    border: 2px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
}

.avatarHistoryDiv{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    width: 100%;
}

.changeAvatar{
    width: 75px;
    height: 75px;
    border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
    background-repeat: no-repeat;
	background-attachment: fixed;

    display: flex;
    justify-content: center;
    align-items: center;
}

button{
    font-size: 32px;
}

#oldPassword{
    justify-content: center;
}

.submitPassword{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 69;

    display: flex;
    flex-direction: column;
    justify-content: space-around;
    text-align: center;
    align-items: center;
    padding: 20px;

    width: 400px;
    height: 600px;

    border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
    background-repeat: no-repeat;
	background-attachment: fixed;
}

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

.avatarDiv{
    height: 60%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    //background-color: red;
}

input {
		border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 10px;
		width: 80%;
		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);
        background-repeat: no-repeat;
		background-attachment: fixed;
		outline: none;
        margin-top: 5px;
	}

	input:focus {
		transition: 0.5s ease-in;
		box-shadow: 0 0 transparent;
	}
	input: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);
        //background-repeat: no-repeat;
        //background-attachment: fixed;
	}

.textDiv{
    height: 60%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    //background-color: blue;
}

.button{
    border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
        background-repeat: no-repeat;
		background-attachment: fixed;
        margin: 10px 0 0 10px;
        width: calc(100% - 10px);
}

.buttonDiv{
    width: 20%;
}
.changingData{
    display: flex;
    flex-direction: column;

    border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
        background-repeat: no-repeat;
		background-attachment: fixed;
        margin: 10px;
        width: 80%;
}

.divisionChangingData{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 80%;
}

.divisionChangingData > div{
    width: 50%;
    padding: 0 0 10% 0;
}

.division{
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
}

.finishButton{
   display: flex;
   justify-content: space-around; 
}

.header {
    height: 10%;
    width:  85%;
    z-index: 3;
}

.mainDiv{
    position: relative;
    height: 90%;
    padding-top: 15px;
}

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

.gradient{
	border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
		border-radius: 15px;
        background-repeat: no-repeat;
		background-attachment: fixed;
		width: 95%;
		height: 95%;

		display: flex; /* Добавляем для центрирования по вертикали и горизонтали */
    	align-self: center; /* Центрируем по вертикали */
    	justify-content: center; /* Центрируем по горизонтали */
    	margin: auto;
}



body{
    display: flex;
    flex-direction: column;
    
        width: 100%; 
        height: 100%;  
        overflow: hidden;
}

</style>