let lastMsgTime = 0;
let lastMsgContent = '';
const MSG_COOLDOWN = 500;

function fadeOutDiv(div) {
    div.removeClass('show');
    setTimeout(() => div.remove(), 1500);
}

let $msgDiv = $('.msgDiv');

jQuery(document).ready(function ($) {

    if ($msgDiv.length > 1) {
        $msgDiv.not(':first').remove();
        $msgDiv = $msgDiv.first();
    }

    if ($msgDiv.length === 0) {
        $msgDiv = $('<div class="msgDiv"></div>');
        $('body').append($msgDiv);
    }

});

const colors = ["rgb(255, 0, 0)", "rgb(0, 255, 0)", "#ff9d00"];

function displayMsg(type, msg) {
    const now = Date.now();

    if ($msgDiv.length === 0) {
        $msgDiv = $('.msgDiv');
    }

    if (now - lastMsgTime < MSG_COOLDOWN && lastMsgContent === msg) {
        return; // ignore spam
    }

    lastMsgTime = now;
    lastMsgContent = msg;

    if (type !== 0 && type !== 1 && type !== 2) return;

    const d = new Date();

    console.group("MsgDivLog:");
    console.log("Type:", type);
    console.log("Nachricht:", msg);
    console.log("Timestamp:", d);
    console.groupEnd();

    const $div = $('<div class="msgBox"></div>')
        .css({ 'border-color': colors[type] })
        .text(msg);

    $msgDiv.append($div);

    setTimeout(() => $div.addClass('show'), 50);
    setTimeout(() => fadeOutDiv($div), 5000);
}

function displayInfo(title = '', msg = null) {

    // Created clean layout references
    const $heading   = $('<h3>', { class: 'confirmImportantHeading', text: title || 'Information' });
    const $text      = $('<p>',  { class: 'confirmImportantText', text: msg || 'Diese Aktion ist unumkehrbar.' });

    const $submitBtn = $('<button>', { class: 'confirmImportantConfrimBtn', text: "OK" });
    const $btnDiv    = $('<div>', { class: 'confirmImportantBtnDiv' }).append($submitBtn);

    const $textDiv   = $('<div>', { class: 'confirmImportantTextDiv' }).append($heading, $text);
    const $box       = $('<div>', { class: 'confirmImportantBox' }).append($textDiv, $btnDiv);
    const $displayBg = $('<div>', { class: 'confirmImportantBg' }).append($box);

    $('body').append($displayBg);

    const closeModal = () => {
        $(document).off('keydown', handleEscape); 
        $displayBg.remove();
    };

    const handleEscape = function (e) {
        if (e.key === 'Escape' || e.key === 'Esc') {
            closeModal(false);
        }
    };
    $(document).on('keydown', handleEscape);

    $submitBtn.on('click', function () {
        closeModal();
    });
}

function displayConfirm(msg = null) {
    return new Promise((resolve) => {

        // Created clean layout references
        const $heading   = $('<h3>', { class: 'confirmImportantHeading', text: 'Bitte bestätige diese Aktion' });
        const $text      = $('<p>',  { class: 'confirmImportantText', text: msg || 'Diese Aktion ist unumkehrbar.' });

        const $submitBtn = $('<button>', { class: 'confirmImportantConfrimBtn', text: "Bestätigen" });
        const $cancelBtn = $('<button>', { class: 'confirmImportantCancelBtn', text: "Abbrechen" });
        const $btnDiv    = $('<div>', { class: 'confirmImportantBtnDiv' }).append($cancelBtn, $submitBtn);

        const $textDiv   = $('<div>', { class: 'confirmImportantTextDiv' }).append($heading, $text);
        const $box       = $('<div>', { class: 'confirmImportantBox' }).append($textDiv, $btnDiv);
        const $displayBg = $('<div>', { class: 'confirmImportantBg' }).append($box);

        $('body').append($displayBg);

        const closeModal = (result) => {
            $(document).off('keydown', handleEscape); 
            $displayBg.remove();
            resolve(result);
        };

        const handleEscape = function (e) {
            if (e.key === 'Escape' || e.key === 'Esc') {
                closeModal(false);
            }
        };
        $(document).on('keydown', handleEscape);

        $submitBtn.on('click', function () {
            closeModal(true);
        });

        $cancelBtn.on('click', function () {
            closeModal(false);
        });
    });
}

function displayConfirmImportant(msg = null, deleteString = "LOESCHEN") {
    return new Promise((resolve) => {

        const trimmedString = deleteString.trim();

        // Created clean layout references
        const $heading   = $('<h3>', { class: 'confirmImportantHeading', text: 'Bitte bestätige diese Aktion' });
        const $text      = $('<p>',  { class: 'confirmImportantText', text: msg || 'Diese Aktion ist unumkehrbar.' });

        const $label     = $('<label>', { class: 'confirmImportantLabel', for: 'confirmImportantInput', text: `Bitte geben Sie im untenstehenden Feld "${deleteString}" ein, um fortzufahren` });
        const $input     = $('<input>', { class: 'confirmImportantInput', id: 'confirmImportantInput', type: "text", placeholder: `Hier "${deleteString}" eingeben` });
        const $inputDiv  = $('<div>', { class: 'confirmImportantInputDiv' }).append($label, $input);

        const $submitBtn = $('<button>', { class: 'confirmImportantConfrimBtn notValidBtn', text: "Bestätigen" });
        const $cancelBtn = $('<button>', { class: 'confirmImportantCancelBtn', text: "Abbrechen" });
        const $btnDiv    = $('<div>', { class: 'confirmImportantBtnDiv' }).append($cancelBtn, $submitBtn);

        const $textDiv   = $('<div>', { class: 'confirmImportantTextDiv' }).append($heading, $text);
        const $box       = $('<div>', { class: 'confirmImportantBox' }).append($textDiv, $inputDiv, $btnDiv);
        const $displayBg = $('<div>', { class: 'confirmImportantBg' }).append($box);

        $('body').append($displayBg);

        const closeModal = (result) => {
            $(document).off('keydown', handleEscape); 
            $displayBg.remove();
            resolve(result);
        };

        const handleEscape = function (e) {
            if (e.key === 'Escape' || e.key === 'Esc') {
                closeModal(false);
            }
        };
        $(document).on('keydown', handleEscape);

        $input.on('input', function () {
            const matches = $(this).val().trim() === trimmedString;
            $submitBtn.toggleClass('notValidBtn', !matches);
            $(this).toggleClass('ok', matches).toggleClass('notOk', !matches);
        });

        $submitBtn.on('click', function () {
            if ($input.val().trim() !== trimmedString || $submitBtn.hasClass('notValidBtn')) return;
            closeModal(true);
        });

        $cancelBtn.on('click', function () {
            closeModal(false);
        });
    });
}