<script>
	import { getLastMessages, MessagePicToUrl, getAllChats, getPinnedMsg, getMessageById, pinMessage, unpinMessage, uploadImages } from '$lib/chat';
	import { UserCheck } from '$lib/userFunction'
	import Header from '../Header.svelte';
	import createWebSocket from '$lib/websocket';
	import { onMount, tick } from 'svelte';
	import Time from 'svelte-time';
	import { dayjs } from 'svelte-time';
	import 'dayjs/locale/ru';
	import { fade } from 'svelte/transition';
	import {page} from '$app/stores';
	import { writable } from 'svelte/store';
	
	
	dayjs.locale('ru');
	console.clear();

	let userId; //пользователь, который залогинен
	let socket; //вебсокет

	let messages = [] //массив сообщений, которые отображаются на сайте
	let msgLoaded = 0
	let messageText = '' //сообщения для отправки
	let selectedFile // картинка для отправки
	let image_url = null
	let messagePic //картинка для отправки
	let flag = "send"
    let answer = null
	let chats = [] //массив чатов, доступных юзеру
	let pinnedMsg = []
	let chatId = null
	let scrollableDiv;
	let answerMessageTextShow = false
	let answerMessageImgShow = false
	
	let answerMessage = ""
	let answerMessageImg = ""
	
	onMount(async () => {


		const userData = await UserCheck();
		userId = userData.id;
		
		chats = await getAllChats()
		console.log(chats, " чаты")

		async function handleChatUrlChange() {
        // Проверяем, что текущий хэш соответствует шаблону для чата
        if (window.location.hash.startsWith('#id=')) {
            chatId = window.location.hash.slice(4);
			msgLoaded = 0
			console.log(chatId, " chatId", msgLoaded)

			messages     = await getLastMessages(chatId,msgLoaded)
			setTimeout(scrollDown,50)
			msgLoaded += 15
			pinnedMsg = await getPinnedMsg(chatId)

			console.log(pinnedMsg, " pinned")
			console.log(messages, " сообщения")

			let token = localStorage.getItem('BPChat')
			const websocketUrl = `wss://docs.black-phoenix.ru/api/chat/ws/${chatId}`
			
			// const socket = createWebSocket(websocketUrl, token, async (message) => {
    		// 	// Обработка сообщения
    		// 	console.log('Received message: ', message);
			// });
			
			socket = createWebSocket(websocketUrl, token, async (message) => {

					console.log(message, "сообщение!!!!!")
				if(message.flag === "pin" ){
					console.log("ЗАКРЕП!!!!!!!!!!!")
					pinnedMsg = [message, ...pinnedMsg]
				}
				else if(message.flag === "delete"){
					let messageToDelete = messages.findIndex(msg => msg.id === message.id)
					console.log(messageToDelete, "индекс сообщения, которое нужно делитнуть")
					messages.splice(messageToDelete,1)
					messages = messages
					console.log(messages," сообщения после удаления")
				} else {
				messages = [...messages, message]
				setTimeout(scrollDown,50)
				}
				messages = messages
			})
		}
		}
		handleChatUrlChange();
		window.addEventListener('hashchange', handleChatUrlChange);

	});

	async function sendMessage() {

		let image = null
		if(image_url != null)
			image = await uploadImages(image_url)
		
		if((messageText != "") || image != null){
		
		console.log(image, " картинка")
		
		socket.send(JSON.stringify({flag: flag,
									message: messageText,
									image_url: image,
									answer: answer }));
		messageText = ""
		imageFile = undefined
		imageShow = false
		image_url = null
		answer = null
		answerMessageTextShow = false
		answerMessageImgShow =  false
	    answerMessage    = ""
		answerMessageImg = ""
		}

	}

	function onEnterPress(event) {
		if (event.key === "Enter" && !event.shiftKey) {
			event.preventDefault();
			console.log("нажата ", messageText)
			sendMessage()
		}
    }
  
	let	  rows = 1
	const maxRows = 10

	function adjustTextareaHeight() {
  const textarea = document.getElementById("msg");
  if (textarea) {
    textarea.style.height = '1em'; //??
    textarea.style.height = (textarea.scrollHeight > maxRows * 18) ? `${maxRows * 18}px` : `${textarea.scrollHeight}px`; // Limit height based on maxRows and font size
	//console.log(textarea.scrollHeight)
  }

}

function onInput(event) {
  const lines = event.target.value.split("\n").length;
  if (lines > maxRows) {
    event.target.value = event.target.value.slice(0, event.target.value.lastIndexOf("\n")); // Prevent exceeding max lines
  }
  adjustTextareaHeight();
}

let x ;
let y ;
let showDiv = false;
let helperDiv
let pickedId
let	PickedText = ""
let	PickedImg  = ""
let PickedName = ""
$: console.log(pickedId)
$: console.log(answer)

function helperDivShow(event, id, text, img, username) {
	event.preventDefault();
	
	PickedText = text
	PickedImg = img
	PickedName = username
	pickedId = id
    //showDiv = !showDiv;
	helperDiv = document.getElementById("helperDiv");

    x = event.clientX;
    y = event.clientY;

	helperDiv.style.opacity = "1";
    helperDiv.style.left = `${x}px`;
    helperDiv.style.top =  `${y}px`;
	console.log(x,"  ", y)
    
  }

  function hideHelperDiv(event){
	
	if ((event.target !== helperDiv) && (helperDiv)) {
		helperDiv.style.opacity = "0";
	}
  }

  function ansFunc(){

	answerMessage = PickedText
	answerMessageImg = PickedImg

	console.log(answerMessage, answerMessageImg)
	answer = pickedId
	if(answerMessage != "")
		answerMessageTextShow = true
	if(answerMessageImg != null)
		answerMessageImgShow = true 
	console.log(answerMessageTextShow, answerMessageImgShow)
  }

  async function pinFunc(event){
	
	let alreadyPinned = false
	if(pinnedMsg != null){
		let findPinMsg = pinnedMsg.find(msg => msg.id === pickedId)
		if(findPinMsg != null)
			alreadyPinned = true
	} 
	if(alreadyPinned === false){
		socket.send(JSON.stringify({"flag": "pin",
								"user_id": userId,
  								"id": pickedId
								}));
	}
  }

  function delFunc(event){
	socket.send(JSON.stringify({"flag": "delete",
								"user_id": userId,
  								"id": pickedId
								}));
	
  } 

  let imageFile = undefined
  let imageShow = false;
  $: console.log(imageFile, "картинка")

  function triggerFileInput() {
    imageFile.click();
  }

  function handleFileChange(event) {
    const file = event.target.files[0];
	image_url = file
    if (file) {
      const reader = new FileReader();
      reader.onloadend = (e) => {

        imageFile = e.target.result;
		imageShow = true;
      };
      reader.readAsDataURL(file);
    }
  }

  //афк
  function handleFileChangeCopy(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = (e) => {
		
        imageFile = e.target.result;
		imageShow = true;
		image_url = imageFile
      };
      
    }
  }

  function deleteImage(){
	imageFile = undefined;
	imageShow = false;
	image_url = null
  }

  function deleteAnswer(){
	answerMessageTextShow = false
	answerMessageImgShow = false
	answerMessageImg  = ""
	answerMessage     = ""
  }

  async function handleScroll(event) {
    const { scrollTop, scrollHeight, clientHeight } = event.target
	console.log(scrollHeight, ";" )
    if (scrollTop === 0) { // если прокрутка достигла верхней части
        console.log("конец")
		
		const previousScrollHeight = scrollHeight
		

		let newMessages = await getLastMessages(chatId,msgLoaded)
		console.log(newMessages, "new msg")
		messages = [...newMessages, ...messages]
		msgLoaded += newMessages.length

		
		requestAnimationFrame(() => {
		const differentScrollHeight = scrollHeight - previousScrollHeight
		console.log(differentScrollHeight, "нынешняя", previousScrollHeight, "предыдущая", scrollHeight, "ныняшняя")
		scrollableDiv.scrollTop = differentScrollHeight
			console.log(differentScrollHeight)
		})
    }
  }

  function scrollDown(){
	scrollableDiv.scrollTop = scrollableDiv.scrollHeight;
  }

</script>

<svelte:window on:click={hideHelperDiv} />

<body>

	<div class="grid">
		
		<div class="headerDiv"><Header/></div>
		
		<div>
			<div class="gradient">
				<div class="chatsDiv">
					{#each chats as chat}
						<div class="chatDivLeft">
							<a class="aChatDivLeft" href={`/chat#id=${chat.chat_id}`}>
							<img class="chatImage" src="{chat.avatar_image}" alt="аватарка">
							<h2 class="chatName">{chat.chat_name}</h2>
							</a>
						</div>
					{/each}
				</div>
			</div>
			</div>
		<div>
			<div class="gradient">

				
				<div class="chatDiv">

					<!-- svelte-ignore a11y-no-static-element-interactions -->
					<div id="helperDiv" class="helperDiv" on:contextmenu={(event) => event.preventDefault()}>
						<button on:click={ansFunc} class="helpDiv"><img class="helpImg" src="./icon/answer.png" alt="ans"><p class="ans">Ответить</p></button>
						<button on:click={pinFunc} class="helpDiv"><img class="helpImg" src="./icon/pin.png"    alt="pin"><p class="pin">Закрепить</p></button>
						<button on:click={delFunc} class="helpDiv"><img class="helpImg" src="./icon/trash.png"  alt="del"><p class="del">Удалить</p></button>
					</div>

					{#if ((chatId != null) && (messages.length === 0))}
							<div class="noMsgDiv">
								<h2 class="noMsg1">В этом чате еще нет сообщений.</h2>
								<h3 class="noMsg2">Крыски, начните обсуждать  <br> прям за ее спиной</h3>
							</div>
					{/if}
					
					<div class="msgDiv" bind:this={scrollableDiv} on:scroll={handleScroll}>
						{#each messages as message}
							<div class="messageMain">
								<img class="messageAvatar" src="{message.avatar_image}" alt="ава">
								<!-- svelte-ignore a11y-click-events-have-key-events -->
								<!-- svelte-ignore a11y-no-static-element-interactions -->
								<div class="messageDiv" on:contextmenu={helperDivShow(event,message.id, message.message, message.image_url, message.username)}>
									
									<div class="nameAnswerDiv">
									<h3>{message.username}</h3>
									{#if message.answer_message != null}
										<img src="./icon/answerMsg.png" alt="">
										<p>{message.answer_message.substr(0, 20)}</p>
									{/if}
									</div>
									
									<div class="messageMessage">
										<p class="messageMsg">{message.message}</p>
										{#if message.image_url != null}
											<img src="{message.image_url}" alt="пикча" class="messageImage">
										{/if}
									</div>
									
								</div>
							</div>
						{/each}
					</div>
				  	
					{#if (chatId != null)}
					<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
					<div class="inputDiv">

						{#if (answerMessageTextShow == true) || (answerMessageImgShow == true)}
						<div class="answerMessageDiv">
								{#if answerMessageImgShow == true}
									<img class="answerMessageImg" src="{answerMessageImg}" alt="">
								{/if}
							<div class="answerTextDiv">
								{#if answerMessageTextShow == true}
									<div class="answerBlockDiv"><h4 class="answerMessage">{answerMessage}</h4></div>
								{/if}
								<div class="answerBlockDiv"><h4 class="answerMessageName">{PickedName}</h4></div>
							</div>
							<button on:click={deleteAnswer} class="deleteAnswer">x</button>
						</div>
						{/if}

						{#if imageShow == true}
							<div class="imageDiv">
								<img src="{imageFile}" alt="" class="imageFile">
								<button on:click={deleteImage} class="imageDelete">x</button>
							</div>
						{/if}
						
						<!-- svelte-ignore a11y-autofocus -->
						<div class="textMsg">
							<textarea on:keydown={onEnterPress}
						 			  autofocus placeholder="Введите сообщение" rows="{rows}" bind:value={messageText}
						 			  on:input={onInput} name="msg" id="msg"></textarea>
						
						 	<!-- svelte-ignore a11y-click-events-have-key-events -->
						 	<img class="logoForImage"  src="logoForImage.svg" alt=""
						      	 on:click={() => document.getElementById('fileInput').click()}>

						</div>

						 <input type="file" accept="image/*" id="fileInput" 
							    on:change={handleFileChange} style="display: none;">
						
					</div>
					{/if}
				</div>

			</div>
		</div>
		<div><div class="gradient">
			{#if pinnedMsg == null}
				<div class="noMsgDiv">
					<h2 class="noMsg1">Тут ничего нет</h2>
					<h3 class="noMsg2">Но если ты закрепишь сообщение, <br> тут что то изменится</h3>
				</div>
			{:else}
			
			<div class="pinnedMain">
				{#each pinnedMsg as msg}
					<div class="pinDiv">
						<div class="pinAvatar"><img class="pinnedImg" src="{msg.avatar_image}" alt=""></div>
						<div class="pinMsg">
							<h3  class="pinnedMsg">{msg.message}</h3>
							<img src="{msg.image_url}" class="pinImg" alt="">
						</div>	
					</div>
				{/each}
				</div>
			{/if}
			
		</div></div>


		<div><h1>7</h1></div>
		<div><h1>8</h1></div>
		<div><h1>9</h1></div>
	</div>
</body>

<style lang="scss">

::-webkit-scrollbar-thumb {
    background: linear-gradient(45deg, var(--blue), var(--purple));
	background-repeat: no-repeat;
		background-attachment: fixed;
    border-radius: 15px;
	
	
  }

::-webkit-scrollbar {
    width: 3px;
  }

.deleteAnswer{
	padding: 0 0 0 10px;
}

.answerBlockDiv{
	padding-left:5px;
	width: 80%;
	height: 50%;
	//outline: 1px solid white;
}

.answerTextDiv{
	display: flex;
	flex-direction: column-reverse;
	justify-content: center;
	align-items: center;
}

.answerMessageName{
	font-size: 1.5rem;
}

.answerMessageImg{
	height: 3rem;
	padding: 0px 0 5px 0;

	border-radius: 13px;
}

.answerMessageDiv{
	display: flex;
	padding: 3px 0 0 5px;
	//background: red;
	border-bottom: 1px solid rgba($color: #ffffff, $alpha: 0.10727) ;
	//background-color: red;
}

.imageDiv{
	position: relative;
	padding-top: 5px;
}

.imageDelete{
	position: absolute;
    cursor: pointer;
}

.textMsg{
	display: flex;
	flex-direction: row;
	justify-content: center;
}

.imageFile{
	border-radius: 15px;
	height: auto;
	width: 250px;
}

.pinMsg{
	width: 90%;
}

.pinAvatar{
	width: 10%;
	margin-right: 15px;
}

.pinImg{
	max-width: 90%;
	height: auto;
	border-radius: 15px;
}

.pinnedImg{
	width: 60px;
	height: auto;
	border-radius: 15px;
}

.pinnedMsg{
	display: flex;
	width: 90%;
}

.pinDiv{
	display: flex;
	width: 100%;
}

.pinnedMain{
	display: flex;
	flex-direction: column;
	margin: 10px;
	width: 100%;
	height: 100%;
	margin-bottom: 10px;
}

.nameAnswerDiv > p,img{
	//margin-left: 5px;
}

.nameAnswerDiv > p{
	opacity: 72.7%;
}

.ans{
	color: #8ed46e;
}
.pin{
	color: #ffffff;
}
.del{
	color: #D15555 ;
}

.helpDiv > p{
	font-weight: 500;
}

.helpDiv{
	height: 30px;
	
	display: flex;
	flex-direction: row;
	cursor: pointer;
}

.helpImg{
	max-width: 100%;
	width: 25px;
	height: 25px;
	margin-right: 5px;
	margin-left: -5px;
}

.helperDiv{
	
	position: fixed;
	width: 160px;
	height: 90px;
	padding: 5px;

	transition: opacity 0.3s;
	opacity: 0;
		border-bottom-left-radius: 15px;
		border-bottom-right-radius: 15px;
		border-top-right-radius: 15px;
		border-top-left-radius: 0;

	border: 1px solid white;
		background:
			linear-gradient(rgba($color: #3C53FF, $alpha: 0.25),rgba($color: #7734AA, $alpha: 0.25));
	backdrop-filter: blur(25px);
	
}

.nameAnswerDiv{
	display: flex;
	flex-direction: row;
	align-items: center;
}

.chatsDiv{
	display: flex;
	align-items: center;
	flex-direction: column;
	width: 100%;
	height: 100%;
	overflow: hidden;
}

.aChatDivLeft{
	display: flex;
	flex-direction: row;
	align-items: center;
	 /* Задаем блочный тип элемента */
        width: 100%;
		text-decoration: none;
}

.chatDivLeft{
	display: flex;
	flex-direction: row;
	align-items: center;
	
	width: 95%;
	height: 75px;
	margin-top: 10px;
	
	border-radius: 15px;
	border: 1px solid transparent;
	background:
		linear-gradient(#101010, #101010) padding-box,
		var(--gradient) border-box;
	transition: 0.5s;
	z-index: 1;

	&:hover{
		z-index: 0;
		box-shadow:
			4px 4px 15px rgba($color: #5e2a83, $alpha: 1.58),
			-4px -4px 15px rgba($color: #3d53fe, $alpha: 1.58);

		& + .chatName{
			//text-shadow: 0px 0px 115px white;
			//TODO: не работает, починить подсветку текста
		}
	}
}


.chatImage{
	height: 60px;
	width: 60px;
	border-radius: 15px;
	margin: 0 10px;
}

.logoForImage{
	display: flex;
	justify-self: center;
	align-self: flex-start;
	width:  2rem;
	height: 2rem;
	padding: 5px;
	//background-color: red;
}

.messageImage{
	padding-bottom: 0px;
	border-radius: 0 0 10px 10px;
	max-width: 500px;
	max-height: 500px;
}

.messageMessage{
	display: flex;
	flex-direction: column;
	max-width: 500px;
	justify-content: space-between;
	background-color: #7734AA;
	border-radius: 15px;
	//padding: 5px;
	word-break: break-word;
}

.messageMsg{
	padding: 5px; //паддинг, чтобы текст нормально выглдяил
}

.messageAvatar{
	
	width: 60px;
	height: 60px;
	border-radius: 15px;
	margin-right: 10px;
}

.messageMain{
display: flex;
flex-direction: row;
padding-bottom: 10px;
}

.msgDiv{
	display: flex;
	flex-direction: column;
	height: 100%;
	margin-bottom: 10px;
	overflow: auto;
	//background-color: red;
	scroll-behavior: smooth;
}

.inputDiv{
	display: flex;
	flex-direction: column;
	border-radius: 15px;
	border: 1px solid transparent;
		background:
			linear-gradient(#101010, #101010) padding-box,
			var(--gradient) border-box;
	//padding: 5px;
	//background-color: red;
}

#msg{
	width: 100%;
	background-color: transparent;
	border: 0;
	line-height: 1em;
	outline: none;
	resize: none;
	padding: 13px 0 0 5px;
	//background-color: red;
}

.chatDiv{
	//background-color: red;
	width: 98%;
	height: 98%;
	display: flex;
	flex-direction: column;
	align-self: center;
	align-content: center;
}

// .chatDiv::after{
// 	content: '';
// 	background-image: url('./BPytka.png');
// 	background-repeat:no-repeat;
// 	width: 1010px;
// 	height: 1010px;
// 	pointer-events: none;
// }
//TODO: сделать бекграунт картинку

.headerDiv{
	grid-column: span 3;
	z-index: 69;
}

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

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

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

body{
width: 100%;
height: 100%;
}
.grid{
	display: grid;
        grid-template-columns: 30% 40% 30%;
        grid-template-rows: 10% 90% 10%;
        width: 100%; 
        height: 100%; 
}
.grid > *{
	//outline: 1px solid white;
	display: flex;
    align-items: center;
    justify-content: center;
}

.noMsgDiv{
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	text-align: center;
	
	height: 100%;
	//background-color: red;
}
.noMsgDiv > h2{
	padding-bottom: 10px;
}

</style>
