import { Component } from "peura-ui";

const answerTemplate = `<div class="ListPage_Answer"></div>`;

export default class AnswerUI extends Component {
	constructor(answerText: string, scrollCallback: () => void, answerReady: () => void) {
		super(answerTemplate);
		let rowIndex = 0;
		let wordIndex = 0;
		let answerRowText: string = "";
		const rows = answerText.split("\n");
		let words: string[] = [];
		let pElem: HTMLParagraphElement | null = null;
		let h1Elem: HTMLHeadingElement | null = null;
		let h2Elem: HTMLHeadingElement | null = null;
		let ulElem: HTMLUListElement | null = null;
		let liElem: HTMLLIElement | null = null;
		const nextWord = () => {
			if (wordIndex === 0) {
				words = rows[rowIndex]?.split(" ") || [];

				// Handle headings
				if (words[0] === "#") {
					h1Elem = document.createElement("h1");
					this.elements[0]?.appendChild(h1Elem);
					words.splice(0, 1);
					ulElem = null;
				}
				else if (words[0] === "##") {
					h2Elem = document.createElement("h2");
					this.elements[0]?.appendChild(h2Elem);
					words.splice(0, 1);
					ulElem = null;
				}

				// Handle lists
				else if (ulElem === null && words[0] === "-") {
					ulElem = document.createElement("ul")
					this.elements[0]?.appendChild(ulElem);
				}

				// Handle normal paragraphs
				else if (ulElem === null) {
					pElem = document.createElement("p");
					this.elements[0]?.appendChild(pElem);
					ulElem = null;
				}

				if (ulElem !== null && words[0] === "-") {
					liElem = document.createElement("li");
					ulElem.appendChild(liElem);
					words.splice(0, 1);
				}
			}
			if (wordIndex === 0) answerRowText = words[0] || "";
			else answerRowText += " " + words[wordIndex];

			if (h1Elem) {
				h1Elem.textContent = answerRowText;
			}
			else if (h2Elem) {
				h2Elem.textContent = answerRowText;
			}
			else if (liElem) {
				liElem.textContent = answerRowText;
			}
			else if (pElem) {
				pElem.textContent = answerRowText;
			}

			wordIndex++;
			if (wordIndex >= words.length) {
				wordIndex = 0;
				rowIndex++;
				answerRowText = "";
				pElem = null;
				h1Elem = null;
				h2Elem = null;
				liElem = null;
			}
			if (rowIndex < rows.length) {
				window.setTimeout(nextWord, 50);
			}
			else {
				answerReady();
			}
			scrollCallback();
		}
		window.setTimeout(nextWord, 50);
	}
}