document.addEventListener("DOMContentLoaded", function() {
    function updateLabelFields() {
        var checkboxes = document.querySelectorAll('input[name="boxyfy_produktlabels[]"]');
        var selectedCount = 0;
        checkboxes.forEach(function(checkbox) {
            if (checkbox.checked) {
                selectedCount++;
            }
        });

        var customField = document.querySelector('input[name="boxyfy_custom_label"]');
        var customLabelFilled = customField && customField.value.trim() !== "";
        var total = selectedCount + (customLabelFilled ? 1 : 0);

        if (total >= 2) {
            // Deaktiviere alle noch nicht ausgewählten Checkboxen
            checkboxes.forEach(function(checkbox) {
                if (!checkbox.checked) {
                    checkbox.disabled = true;
                }
            });
            // Falls das benutzerdefinierte Label nicht gefüllt ist, disable das Feld
            if (!customLabelFilled && customField) {
                customField.disabled = true;
            }
        } else {
            // Wieder alle aktivieren
            checkboxes.forEach(function(checkbox) {
                checkbox.disabled = false;
            });
            if (customField) {
                customField.disabled = false;
            }
        }
    }

    // Setup
    var checkboxes = document.querySelectorAll('input[name="boxyfy_produktlabels[]"]');
    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener("change", updateLabelFields);
    });
    var customField = document.querySelector('input[name="boxyfy_custom_label"]');
    if (customField) {
        customField.addEventListener("input", updateLabelFields);
    }
    updateLabelFields();

    // Vor dem Absenden: alle deaktivierten Felder wieder aktivieren
    var postForm = document.querySelector("form#post") || document.querySelector("form");
    if (postForm) {
        postForm.addEventListener("submit", function() {
            var disabledElements = document.querySelectorAll("#boxyfy_produktlabels_metabox [disabled]");
            disabledElements.forEach(function(el) {
                el.disabled = false;
            });
        });
    }
});