<script>
	import GuessGrid from '../components/GuessGrid.vue'
	import Keyboard from '../components/Keyboard.vue';
	import Overlay from '../components/Overlay.vue';

	export default {
		data() {
			return {
				// Constants
				LETTER_ANIMATION_DURATION: 0.3,
				SHAKE_ANIMATION_DURATION: 0.3,

				// Variables
				words: [],
				pairs: [],

				listen: true,

				gridState: null,
				rowsAnimations: null,
				keyboardMask: null,

				currentAttempt: 0,
				currentIndex: 0,

				secretWords: null,

				gameOver: false,
				won: false,
				overlayVisible: false,

				popups: {}
			}
		},

		async created() {
			window.addEventListener('keyup', (e) => {
				if (e.key === 'Backspace') {
					this.keyPress('Delete');
				} else if (e.key === 'Delete' || e.key === 'Enter') {
					this.keyPress(e.key);
				} else if (e.key.match(/^[a-zA-Z]$/)) {
					this.keyPress(e.key.toUpperCase())
				}
			});

			let req = await fetch('./math-words.json');
			this.words = await req.json();
			req = await fetch('./math-pairs.json');
			this.pairs = await req.json();

			this.setupGame();
		},
		components: {
			GuessGrid,
			Keyboard,
			Overlay,
		},
		methods: {
			setupGame() {
				this.gridState = Array.from({length: 6}, () => {
					return Array.from({length: 5}, () => {
						return {
							letter: '',
							state: 'unset'
						};
					});
				});
				this.rowsAnimations = new Array(6).fill(false);

				this.keyboardMask = Object.fromEntries(
					Array.from({length: 26}, (v, i) => [
						String.fromCharCode(i + 65), 'unused'
					])
				);
				this.keyboardMask['Enter'] = 'unused';
				this.keyboardMask['Delete'] = 'unused';
				console.log(this.keyboardMask);

				this.currentAttempt = 0;
				this.currentIndex = 0;

				let gameId = 0;
				for(let i = 0; i < this.$route.params.id.length; i++) {
					let mod = this.$route.params.id.charCodeAt(i);
					gameId += mod * mod * mod * mod;
				}
				this.secretWords = this.pairs[gameId % this.pairs.length];
				console.log(this.secretWords);
				console.log(this.secretWords[0]);
				console.log(this.secretWords[1]);

				this.gameOver = false;
				this.won = false;
				this.overlayVisible = false;
			},
			async newGame() {
				let newId = this.randomId(8);
				await this.$router.replace({params: {id: newId}});
				this.setupGame();
			},
			randomId(length) {
				let result = '';
				let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				let charactersLength = characters.length;
				for ( let i = 0; i < length; i++ ) {
					result += characters.charAt(Math.floor(Math.random() * 
						charactersLength));
				}
				return result;
			},
			addPopUp(message) {
				let id = this.randomId(16);
				this.popups[id] = message;
				setTimeout(() => delete this.popups[id], 10*1000);
			},
			checkWin(matches, oneWordMatch) {
				if (!oneWordMatch) {
					return false;
				}
				for(let i = 0; i < 5; i++) {
					if (matches[i][0] === -1 || !matches[i][1]) {
						return false;
					}
				}

				return true;
			},
			resolveGame(won) {
				this.won = won;
				this.gameOver = true;
				this.overlayVisible = true;
			},
			keyPress(event) {
				if (!this.listen) {
					return;
				}
				if (event === "Delete") {
					if(this.currentIndex > 0) {
						this.currentIndex -= 1;
						this.gridState[this.currentAttempt][this.currentIndex].letter = '';
						this.gridState[this.currentAttempt][this.currentIndex].state = 'unset';
					}
				} else if (event == "Enter") {
					if(this.currentIndex === 5) {

						// Validate Word
						let currentWord = "";
						for(let i = 0; i < 5; i++) {
							currentWord += this.gridState[this.currentAttempt][i].letter;
						}
						if(!this.words.includes(currentWord)) {
							// Invalid attempt, signal error
							this.listen = false;
							this.rowsAnimations[this.currentAttempt] = true;
							
							setTimeout(() => {
								this.listen = true;
								this.rowsAnimations[this.currentAttempt] = false;
							}, this.SHAKE_ANIMATION_DURATION * 1000);

							return;
						}

						// Calculate result
						let wordsFlags = [ this.secretWords[0].split(''), this.secretWords[1].split('') ];
						let matches = [ [-1,false], [-1,false], [-1,false], [-1,false], [-1,false] ];

						for(let i = 0; i < 5; i++) {
							let letter = this.gridState[this.currentAttempt][i].letter;
							for(let j = 0; j < 2; j++) {
								if (wordsFlags[j][i] === letter) {
									wordsFlags[j][i] = null;
									matches[i] = [j, true];
								}
							}
						}
						for(let i = 0; i < 5; i++) {
							let letter = this.gridState[this.currentAttempt][i].letter;
							for(let j = 0; j < 2; j++) {
								for(let k = 0; k < 5; k++) {
									if(wordsFlags[j][k] === letter) {
										wordsFlags[j][k] = null;
										matches[i] = [j, false];
									}
								}
							}
						}
						let oneWordMatch = true;
						for(let i = 0; i < 5; i++) {
							for(let j = 0; j < 5; j++) {
								if (matches[i][0] == 0 && matches[j][0] == 1) {
									oneWordMatch = false;
								}
							}
						}

						// Update grid to tease result
						for(let i = 0; i < 5; i++) {
							if (matches[i][0] !== -1 && matches[i][1]) {
								this.gridState[this.currentAttempt][i].state = `correct-${oneWordMatch ? 'full' : 'half'}`;
							} else if (matches[i][0] !== -1 && !matches[i][1]) {
								this.gridState[this.currentAttempt][i].state = `misplaced-${oneWordMatch ? 'full' : 'half'}`;
							} else {
								this.gridState[this.currentAttempt][i].state = 'wrong';
							}
						}
						this.listen = false;

						// Resolve
						setTimeout(() => {
							for(let i = 0; i < 5; i++) {
								if (matches[i][0] !== -1 && matches[i][1]) {
									if(this.keyboardMask[this.gridState[this.currentAttempt][i].letter] === 'unused' ||
										this.keyboardMask[this.gridState[this.currentAttempt][i].letter] === 'misplaced') {
										this.keyboardMask[this.gridState[this.currentAttempt][i].letter] = 'correct';
									}
								} else if (matches[i][0] !== -1 && !matches[i][1]) {
									if(this.keyboardMask[this.gridState[this.currentAttempt][i].letter] === 'unused') {
										this.keyboardMask[this.gridState[this.currentAttempt][i].letter] = 'misplaced';
									}
								} else {
									if(this.keyboardMask[this.gridState[this.currentAttempt][i].letter] === 'unused') {
										this.keyboardMask[this.gridState[this.currentAttempt][i].letter] = 'wrong';
									}
								}
							}

							this.currentAttempt += 1;
							this.currentIndex = 0;


							if (this.checkWin(matches, oneWordMatch)) {
								this.resolveGame(true);
							} else if (this.currentAttempt === 6) {
								this.resolveGame(false);
							}

							this.listen = true;
						}, this.LETTER_ANIMATION_DURATION * 1000 * 5);
					}
				} else {
					if (this.currentIndex < 5) {
						this.gridState[this.currentAttempt][this.currentIndex].letter = event;
						this.gridState[this.currentAttempt][this.currentIndex].state = 'set';
						this.currentIndex += 1;
					}
				}
			}
		}
	};
</script>

<template>
	<div class="page" 
		:style="`--letter-animation-duration: ${LETTER_ANIMATION_DURATION}s; --shake-animation-duration: ${SHAKE_ANIMATION_DURATION}s`"
	>
		<div class="toolbar">
			<div class="logo">
				<img src="logo-circuit-board.svg" alt="logo" />
				/
				Math qwordle
			</div>
		</div>
		<div v-if="this.gridState !== null" class="interface">
			<div class="header">
				<div>Math qwordle</div>
				<div class="end">
					<div class="material-icons-outlined">info</div>
					<div v-if="gameOver" class="material-icons-outlined" @click="overlayVisible = true">military_tech</div>
				</div>
			</div>
			<GuessGrid :state="gridState" :rows-animations="rowsAnimations"/>
			<Keyboard :mask="keyboardMask" @add="keyPress($event)" :listen="true"/>
		</div>
		<Overlay v-if="overlayVisible"
			:secret-words="secretWords"
			:state="gridState"
			:won="won"
			:last-attempt="currentAttempt"
			@close="overlayVisible = false"
			@reset="newGame()"
			@share="addPopUp('copied to clipboard!')"
		/>
		<div v-for="popup in popups" class="popup">
			{{popup}}
		</div>
	</div>
</template>

<style lang="scss">
	.page {
		position: relative;

		.toolbar {
			padding: 1rem .75rem 1rem 1rem;

			display: flex;
			align-items: center;

			border-bottom: 2px solid var(--border-color);

			.logo {
				display: flex;
				align-items: center;
				img {
					max-height: 2.5rem;
				}
			}
		}

		.interface {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 2rem;

			padding: 4rem;

			.header {
				width: 18rem;
				display: flex;
				justify-content: space-between;

				font-size: 1.5rem;
				font-weight: 600;

				.end {
					display: flex;
					gap: 0.5rem;
				}
			}
		}
	}

	.material-icons, .material-icons-outlined, .button {
		cursor: pointer;
	}


	@keyframes appear {
		0% {
			transform: translate(-50%, 0);
			opacity: 0;
		}
		20% {
			transform: translate(-50%, -3rem);
			opacity: 1;
		}
		80% {
			transform: translate(-50%, -3rem);
			opacity: 1;
		}
		100% {
			transform: translate(-50%, 0);
			opacity: 0;
		}
	}

	.popup {
		position: absolute;
		bottom: 0%;
		left: 50%;
		transform: translateX(-50%);
		opacity: 0;

		animation: ease-in-out appear 5s;

		background-color: var(--popup-color);
		border-radius: 20px;
		padding: 1rem 3rem;

		font-weight: 600;
	}

</style>
