const inputTextArea = document.getElementById("maths-input");
const outputDiv = document.getElementById("maths-output");
const buttonDeck = document.getElementById("button-deck");

const buttons = {
    "Inline": ["$", "$"],
    "Block": ["$$", "$$"],
    "$\\mathbb N$": "\\natSet",
    "$\\mathbb Z$": "\\intSet",
    "$\\mathbb Q$": "\\rationalSet",
    "$\\mathbb R$": "\\realSet",
    "$( )$": ["\\left ( ", " \\right )"],
    "$\\{ \\}$": ["\\left \\{ ", " \\right \\}"],
    "Align": ["\\begin{align} ", " \\end{align}"],
}

const triggerTexRefresh = (inputText) => {
    outputDiv.innerHTML = inputText;
    MathJax.typeset([outputDiv]);
};

for (let button in buttons) {
    const elem = document.createElement("span");
    elem.addEventListener("click", () => {
        const cont = buttons[button];

        const start = inputTextArea.selectionStart;
        const end = inputTextArea.selectionEnd;
        const sel = inputTextArea.value.substring(start, end);

        let finText;
        let offset;

        if (typeof cont == "object") {
            finText = inputTextArea.value.substring(0, start) + cont[0] + sel + cont[1] + inputTextArea.value.substring(end);
            offset = cont[0].length;
        } else {
            finText = inputTextArea.value.substring(0, start) + cont + sel + inputTextArea.value.substring(end);
            offset = cont.length;
        }

        inputTextArea.value = finText;
        inputTextArea.focus();
        inputTextArea.selectionEnd = start + offset;
        triggerTexRefresh(inputTextArea.value)
    });
    elem.innerHTML = button
    elem.classList.add("tex-button");
    buttonDeck.appendChild(elem);
}

window.addEventListener("load", () => {
    console.log("load");
    const tex = "$x = \\frac{b \\pm \\sqrt{b^2 - 4ac}}{2a}$";
    inputTextArea.placeholder = tex;
    triggerTexRefresh(tex);
});

inputTextArea.addEventListener("input", () => {
    triggerTexRefresh(inputTextArea.value);
});