// admin-feeds.js – Drag & Drop + edição fácil
document.addEventListener('DOMContentLoaded', function () {
    const container = document.getElementById('rsp-feeds-sortable');
    if (!container) return;

    // Reordena os índices dos inputs
    function updateIndices() {
        const items = container.querySelectorAll('.rsp-feed-item');
        items.forEach((item, index) => {
            item.querySelectorAll('input').forEach(input => {
                if (input.name) {
                    input.name = input.name.replace(/\[\d+\]/, '[' + index + ']');
                }
            });
        });
    }

    // Drag & Drop
    let dragged = null;
    container.addEventListener('dragstart', e => {
        dragged = e.target.closest('.rsp-feed-item');
        setTimeout(() => dragged.style.opacity = '0.5', 0);
    });

    container.addEventListener('dragend', () => {
        setTimeout(() => {
            dragged.style.opacity = '1';
            updateIndices(); // ← garante índices corretos
        }, 0);
        dragged = null;
    });

    container.addEventListener('dragover', e => {
        e.preventDefault();
        const afterElement = getDragAfterElement(container, e.clientY);
        if (afterElement == null) {
            container.appendChild(dragged);
        } else {
            container.insertBefore(dragged, afterElement);
        }
    });

    function getDragAfterElement(container, y) {
        const items = [...container.querySelectorAll('.rsp-feed-item:not(.dragging)')];
        return items.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            }
            return closest;
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    // Add new feed
    document.getElementById('rsp-add-feed')?.addEventListener('click', () => {
        const index = container.children.length;
        const div = document.createElement('div');
        div.className = 'rsp-feed-item';
        div.draggable = true;
        div.style = 'display:flex; align-items:center; gap:12px; padding:14px; margin:8px 0; background:#fff; border:1px solid #ddd; border-radius:8px; box-shadow:0 2px 5px rgba(0,0,0,0.05); cursor:move;';
        div.innerHTML = `
            <span class="dashicons dashicons-menu" style="font-size:20px; color:#999;"></span>
            <input type="url" name="feed_url[${index}]" placeholder="https://example.com/rss" style="flex:2;" required>
            <input type="text" name="feed_category[${index}]" placeholder="Category" style="flex:1;" required>
            <button type="button" class="button rsp-remove-feed" style="color:#a00; border-color:#a00;">Remove</button>
        `;
        container.appendChild(div);
        updateIndices();
    });

    // Remove + reindex
    container.addEventListener('click', e => {
        if (e.target.classList.contains('rsp-remove-feed')) {
            e.target.closest('.rsp-feed-item').remove();
            updateIndices();
        }
    });

    // ← A CHAVE: reindex ANTES do submit!
    const form = document.getElementById('rsp-feeds-form');
    if (form) {
        form.addEventListener('submit', function () {
            updateIndices();
        });
    }

    // Melhora edição
    container.addEventListener('focusin', e => {
        if (e.target.tagName === 'INPUT') {
            e.target.closest('.rsp-feed-item').draggable = false;
        }
    });
    container.addEventListener('focusout', e => {
        if (e.target.tagName === 'INPUT') {
            e.target.closest('.rsp-feed-item').draggable = true;
        }
    });
});