document.addEventListener("DOMContentLoaded", function () {
    const tableBody = document.querySelector(".tabular");
    let draggedRow = null;

    tableBody.querySelectorAll("tr").forEach(row => {
        row.addEventListener("dragstart", e => {
            draggedRow = row;
            row.style.opacity = 0.5;
        });

        row.addEventListener("dragend", e => {
            row.style.opacity = "";
        });

        row.addEventListener("dragover", e => {
            e.preventDefault(); // Allow drop
            const bounding = row.getBoundingClientRect();
            const offset = bounding.y + bounding.height / 2;
            if (e.clientY - offset > 0) {
                row.style["border-bottom"] = "2px solid #ccc";
                row.style["border-top"] = "";
            } else {
                row.style["border-top"] = "2px solid #ccc";
                row.style["border-bottom"] = "";
            }
        });

        row.addEventListener("dragleave", e => {
            row.style["border-top"] = "";
            row.style["border-bottom"] = "";
        });

        row.addEventListener("drop", e => {
            e.preventDefault();
            row.style["border-top"] = "";
            row.style["border-bottom"] = "";

            if (draggedRow !== row) {
                const bounding = row.getBoundingClientRect();
                const offset = bounding.y + bounding.height / 2;

                if (e.clientY - offset > 0) {
                    row.after(draggedRow);
                } else {
                    row.before(draggedRow);
                }

                updateOrder();
            }
        });
    });

    function updateOrder() {
        const rows = tableBody.querySelectorAll("tr");
        const order = [];

        rows.forEach((row, index) => {
            const id = row.dataset.id;
            if (id) {
                order.push({ id: id, position: index + 1 });
            }
        });

        fetch("/site-menu/admin/reorder", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ order: order })
        })
            .then(res => res.json())
            .then(data => {
                console.log("Order updated:", data);
            })
            .catch(err => {
                console.error("Failed to update order", err);
            });
    }
});
