(function () {
    let orderDirty = false;
    let beforeUnloadBound = false;

    function notify(message, type) {
        if (window.showToast) window.showToast(message, type || 'info');
        else alert(message);
    }

    function initPlaylistPage() {
        const list = document.getElementById('playlist-song-list');
        const saveButton = document.querySelector('.playlist-save-order-btn');
        const page = document.querySelector('.playlist-detail-page[data-playlist-id]');

        if (!list || !page || list.dataset.playlistBound === '1') return;
        list.dataset.playlistBound = '1';

        const playlistId = page.getAttribute('data-playlist-id');

        function rows() {
            return Array.from(list.querySelectorAll('.playlist-song-item'));
        }

        function renumber() {
            rows().forEach(function (row, index) {
                const number = row.querySelector('.playlist-order-number');
                if (number) number.textContent = String(index + 1);
            });
        }

        function markDirty() {
            orderDirty = true;
            if (saveButton) {
                saveButton.classList.add('is-dirty');
                saveButton.disabled = false;
            }
        }

        function moveRow(row, direction) {
            if (!row) return;
            if (direction === 'up') {
                const previous = row.previousElementSibling;
                if (previous) {
                    list.insertBefore(row, previous);
                    markDirty();
                }
            } else if (direction === 'down') {
                const next = row.nextElementSibling;
                if (next) {
                    list.insertBefore(next, row);
                    markDirty();
                }
            }
            renumber();
        }

        list.addEventListener('click', function (event) {
            const button = event.target.closest('.playlist-move-btn');
            if (button) {
                event.preventDefault();
                event.stopPropagation();
                moveRow(button.closest('.playlist-song-item'), button.getAttribute('data-direction'));
                return;
            }

            const removeButton = event.target.closest('.remove-playlist-song-btn');
            if (!removeButton) return;

            event.preventDefault();
            event.stopPropagation();
            if (!confirm('이 곡을 플레이리스트에서 제거할까요?')) return;

            const row = removeButton.closest('.playlist-song-item');
            const songId = row ? row.getAttribute('data-id') : '';
            const formData = new FormData();
            formData.append('playlist_id', playlistId);
            formData.append('song_id', songId);
            if (window.APP_CSRF_TOKEN) formData.append('csrf_token', window.APP_CSRF_TOKEN);

            removeButton.disabled = true;
            fetch(`${window.APP_BASE_PATH || './'}api/remove_from_playlist.php`, {
                method: 'POST',
                body: formData,
                headers: window.APP_CSRF_TOKEN ? { 'X-CSRF-Token': window.APP_CSRF_TOKEN } : {}
            })
                .then(function (res) { return res.json(); })
                .then(function (data) {
                    if (!data.success) throw new Error(data.message || '삭제 실패');
                    if (row) row.remove();
                    renumber();
                })
                .catch(function (error) {
                    console.error('Playlist remove failed:', error);
                    notify(error.message || '곡을 제거하지 못했습니다.', 'error');
                    removeButton.disabled = false;
                });
        });

        if (saveButton && saveButton.dataset.playlistBound !== '1') {
            saveButton.dataset.playlistBound = '1';
            saveButton.addEventListener('click', function () {
                const order = rows()
                    .map(function (row) { return parseInt(row.getAttribute('data-playlist-song-id'), 10); })
                    .filter(function (id) { return Number.isFinite(id) && id > 0; });

                if (order.length === 0) {
                    notify('저장할 곡이 없습니다.', 'info');
                    return;
                }

                const formData = new FormData();
                formData.append('playlist_id', playlistId);
                formData.append('order', JSON.stringify(order));
                if (window.APP_CSRF_TOKEN) formData.append('csrf_token', window.APP_CSRF_TOKEN);

                saveButton.disabled = true;
                fetch(`${window.APP_BASE_PATH || './'}api/update_playlist_order.php`, {
                    method: 'POST',
                    body: formData,
                    headers: window.APP_CSRF_TOKEN ? { 'X-CSRF-Token': window.APP_CSRF_TOKEN } : {}
                })
                    .then(function (res) { return res.json(); })
                    .then(function (data) {
                        if (!data.success) throw new Error(data.message || '저장 실패');
                        orderDirty = false;
                        saveButton.classList.remove('is-dirty');
                        notify(data.message || '순서를 저장했습니다.', 'success');
                    })
                    .catch(function (error) {
                        console.error('Playlist order save failed:', error);
                        notify(error.message || '순서를 저장하지 못했습니다.', 'error');
                    })
                    .finally(function () {
                        saveButton.disabled = false;
                    });
            });
        }

        if (!beforeUnloadBound) {
            beforeUnloadBound = true;
            window.addEventListener('beforeunload', function (event) {
                if (!orderDirty) return;
                event.preventDefault();
                event.returnValue = '';
            });
        }

        orderDirty = false;
        renumber();
    }

    window.MelonLiteInitPlaylistPage = initPlaylistPage;
    document.addEventListener('DOMContentLoaded', initPlaylistPage);
})();
