document.addEventListener("DOMContentLoaded", function() {
    const progressData = document.getElementById("progress_data");
    const progressBar = document.getElementById("progress_bar");
    const progressText = document.getElementById("progress_text");
    const resubmitForm = document.getElementById("resubmit_form");

    if (progressData && progressBar && resubmitForm) {
        const nextIndex = parseInt(progressData.getAttribute("data-next")) || 0;
        const totalProducts = parseInt(progressData.getAttribute("data-total")) || 0;
        const percentage = totalProducts > 0 ? (nextIndex / totalProducts) * 100 : 0;

        progressBar.style.width = percentage + "%";

        if (progressText) {
            progressText.innerHTML = `<p>Processed ${Math.min(nextIndex, totalProducts)} of ${totalProducts} products...</p>`;
        }

        if (nextIndex < totalProducts) {
            setTimeout(() => {
                resubmitForm.submit();
            }, 500);
        }
    }

    // image display checkbox
    const checkbox = document.getElementById('brandabeanimageCheckbox');
    const image = document.getElementById('brandabeanpricing');

    if (checkbox && image) {
        checkbox.addEventListener('change', function() {
            image.style.display = this.checked ? 'block' : 'none';
        });
    }
});

// products character countdown text field
const productPrefix = document.getElementById('product_prefix');
const charCount = document.getElementById('char_count');

if (productPrefix && charCount) { // Only run if both elements exist
    productPrefix.addEventListener('input', function() {
        var maxLength = this.getAttribute('maxlength');
        var currentLength = this.value.length;
        var remaining = maxLength - currentLength;
        charCount.textContent = remaining + ' characters remaining';
    });
}