import * as state from "../state/state.js";

const parser = new DOMParser();
const translationsContainer = document.querySelector(".chart-translations");
const languageDropdown = document.querySelector(".language-dropdown");
const translationFiles = {
    "English": "MessageBundle_en.txt",
    "English-US": "MessageBundle_en_us.txt",
    "Spanish": "MessageBundle_es.txt",
    "German": "MessageBundle_de.txt",
    "French": "MessageBundle_fr.txt",
    "Korean": "MessageBundle_ko.txt"
};

const translationSelectorSrc = `
    <div class="table-field">
        <label>Select Text:</label>
        <select class="select-translation"></select>
    </div>
`;

const translationEditorSrc = `
    <div class="table-field">
        <label class="original-text">Translation:</label>
        <input type="text" class="translated-text">
    </div>
`;

function createTranslationsUI(language) {
    fetch(`CustomEditor/backend.jsp?file=custom/${translationFiles[language]}&type=translation&ts=${new Date().getTime()}`)
    .then((response) => response.json()).then(({data}) => {
        if (!data) {
            if (document.querySelector(".translation-fields")) {
                document.querySelector(".translation-fields").remove();
            }
            throw new Error("Translation file not found or cannot be read");
        }

        const translationLines = data.split("\n");
        const translations = {};

        translationLines.sort((a, b) => {
            return a.localeCompare(b);
        }).forEach(line => {
            const [key, value] = line.split('=');
            if (key && value) {
                translations[key.trim()] = value.trim();
            }
        });
        state.refreshTranslationsData(translations);
        
        const wrapper = document.createElement("section");
        wrapper.className = "translation-fields";

        const translationSelectorNode = parser.parseFromString(translationSelectorSrc, "text/html").body.firstChild;
        const translationEditorNode = parser.parseFromString(translationEditorSrc, "text/html").body.firstChild;
        const translationSelect = translationSelectorNode.querySelector(".select-translation");
        const translationInput = translationEditorNode.querySelector(".translated-text");
        translationInput.value = Object.values(state.getTranslationsData())[0];
        translationInput.setAttribute("data-translation-key", Object.keys(state.getTranslationsData())[0]);

        translationInput.addEventListener("change", (e) => {
            if (e.target.value.trim() !== "") {
                state.setUnsavedChanges(true);
                state.updateTranslationsData(e.target.getAttribute("data-translation-key"), e.target.value);
            }
        });

        translationSelect.addEventListener("change", (e) => {
            translationInput.value = state.getTranslationsData()[e.target.value];
            translationInput.setAttribute("data-translation-key", e.target.value);
            if (e.target.value.length > 40) {
                translationInput.classList.add("fullwidth");
            } else {
                translationInput.classList.remove("fullwidth");
            }
        });

        Object.entries(state.getTranslationsData()).forEach(([original, translated]) => {
            const translationSelectOption = document.createElement("option");
            translationSelectOption.value = original;
            translationSelectOption.title = original;

            if (original.length > 20) {
                translationSelectOption.textContent = original.slice(0, 19) + "...";
            } else {
                translationSelectOption.textContent = original;
            }

            translationSelect.appendChild(translationSelectOption);
        });

        wrapper.appendChild(translationSelectorNode);
        wrapper.appendChild(translationEditorNode);

        // When re-rendering during language change, clear previous fields
        if (document.querySelector(".translation-fields")) {
            document.querySelector(".translation-fields").remove();
        }

        translationsContainer.appendChild(wrapper);
        state.removeBlockedPage("translations");
    }).catch((error) => {
        state.addBlockedPage("translations", `An error occurred while loading ${translationFiles[language]} file`);
        console.error("Error loading translations:", error);
        alert(`An error occurred while loading ${translationFiles[language]} file. Please check if the file exists and try again.`);
    });
}

languageDropdown.addEventListener("change", (e) => {
    let allowSwitch = true;
    const currentLanguage = document.querySelector(".translation-language");
    if (state.hasUnsavedChanges()) {
        allowSwitch = confirm("You have unsaved changes. Proceed?");
    }
    if (allowSwitch) {
        state.setUnsavedChanges(false);
        currentLanguage.textContent = e.target.value;
        createTranslationsUI(e.target.value);
    } else {
        languageDropdown.value = currentLanguage.textContent; // Reset to previous language
    }
});

export {
    languageDropdown,
    translationFiles,
    createTranslationsUI
};
