document.addEventListener('DOMContentLoaded', function () {
    // Track deleted blocks per post ID
    const deletedMap = {};

    document.querySelectorAll('.freshenup-highlight').forEach(el => {
        const postWrapper = el.closest('.freshenup-post');
        const postId = postWrapper?.querySelector('input[name=\"post_id\"]')?.value;
        const approveBtn = postWrapper?.querySelector('.freshenup_approve');

        const id = el.getAttribute('data-freshenup-id');
        if (!id || !postId) return;

        const btn = document.createElement('span');
        btn.className = 'freshenup-delete';
        btn.innerText = 'X';
        btn.title = 'Delete section';

        btn.addEventListener('click', function (e) {
            e.preventDefault();

            // Initialize deleted array for this post
            if (!deletedMap[postId]) deletedMap[postId] = [];

            if (!deletedMap[postId].includes(id)) {
                deletedMap[postId].push(id);
            }

            // Fade out & remove block
            el.classList.add('freshenup-fadeout');
            setTimeout(() => el.remove(), 800);

            // Update approve button label
            if (approveBtn) {
                approveBtn.innerText = 'Approve with changes';
            }
        });

        el.appendChild(btn);
    });

    // Inject deleted ID list on submission
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function () {
            const postId = form.querySelector('input[name=\"post_id\"]')?.value;
            if (!postId || !deletedMap[postId]) return;

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'freshenup_deleted_ids';
            input.value = JSON.stringify(deletedMap[postId]);
            form.appendChild(input);
        });
    });
});
