// 쿠키 값 설정
function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // 일(day) 단위로 유효 기간 설정
        expires = ("; expires=" + date.toUTCString());
    }
    document.cookie = (name + "=" + encodeURIComponent(value) + expires + "; path=/");
}

// 쿠키 값 조회
function getCookie(name) {
    const nameEQ = name + "=";
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i];
        while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1, cookie.length); // 공백 제거
        }
        if (cookie.indexOf(nameEQ) === 0) {
            return decodeURIComponent(cookie.substring(nameEQ.length, cookie.length));
        }
    }
    return null;
}

// 쿠키 삭제
function deleteCookie(name) {
    document.cookie = (name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;");
}

// 이미지 미리보기
function setupImagePreview(fileInputID, previewImageID) {
    const fileInput = document.getElementById(fileInputID);
    const previewImage = document.getElementById(previewImageID);

    if (!fileInput || !previewImage) {
        return;
    }

    fileInput.addEventListener("change", function (e) {
        const file = e.target.files[0];
        const image = previewImage.querySelector("img");

        if (file && file.type.startsWith("image/")) {
            const reader = new FileReader();

            reader.onload = function (e) {
                image.src = e.target.result;
                previewImage.removeAttribute("hidden");
            };

            reader.readAsDataURL(file);
        } else {
            image.src = "";
            previewImage.setAttribute("hidden", "hidden");
        }
    });

    // 미리보기 삭제
    const removeBtn = previewImage.querySelector(".btn-remove-preview");
    if (removeBtn) {
        removeBtn.addEventListener("click", function () {
            const image = previewImage.querySelector("img");
            if (image) {
                image.src = "";
            }
            previewImage.hidden = true;
            fileInput.value = "";
        });
    }
}

$.validator.setDefaults({ // Bootstrap Required.
    ignore: [], // hidden
    debug: false,
    invalidHandler: function (event, validator) {

    },
    submitHandler: function (form, event) {
        const submitter = event?.originalEvent?.submitter;
        if (submitter?.getAttribute('formaction')) {
            form.action = submitter.getAttribute('formaction');
        }
        form.submit();
    },
    showErrors: function (errorMap, errorList) {
        $.each(this.successList, function (index, value) {
            let field = $(value);
            if (field.is(':hidden')) {
                field = field.parent();
            }
            if (typeof field.tooltip !== "undefined") { // 3.3.7은 destroy 4.0 이후 dispose
                field.tooltip('dispose');
            }
        });
        if (errorList.length <= 0) {
            $(".tooltip").tooltip("dispose");
        }
        $.each(errorList, function (index, value) {
            let field = $(value.element);
            if (field.is(':hidden')) {
                field = field.parent();
            }
            field.tooltip('dispose').tooltip({
                placement: 'bottom',
                title: value.message,
                trigger: 'manual'
            }).tooltip('show');
        });
    }
});