(function () {
    if (window.__MELON_LITE_NOTES_INITED) return;
    window.__MELON_LITE_NOTES_INITED = true;

    function escapeHtml(value) {
        return String(value || '').replace(/[&<>"']/g, function (ch) {
            return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[ch];
        });
    }

    function notify(message, isError) {
        if (window.showToast) return window.showToast(message, isError ? 'error' : 'success');
        if (isError) console.warn(message);
    }

    async function post(url, payload) {
        const formData = new FormData();
        Object.keys(payload).forEach(function (key) { formData.append(key, payload[key]); });
        formData.append('csrf_token', window.APP_CSRF_TOKEN || '');
        const response = await fetch((window.APP_BASE_PATH || './') + url, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin',
            headers: { 'Accept': 'application/json' }
        });
        const data = window.MelonLiteApi ? await window.MelonLiteApi.parseResponse(response) : await response.json();
        if (!response.ok || !data.success) throw new Error(data.message || '처리하지 못했습니다.');
        return data;
    }

    function paintStars(root, rating) {
        if (!root) return;
        rating = Math.max(0, Math.min(5, parseInt(rating, 10) || 0));
        root.dataset.rating = String(rating);
        root.querySelectorAll('.rating-star').forEach(function (star) {
            const value = parseInt(star.dataset.rating || star.textContent, 10) || 0;
            star.classList.toggle('active', value <= rating);
            const icon = star.querySelector('i');
            if (icon) icon.className = (value <= rating ? 'fas' : 'far') + ' fa-star';
        });
    }

    document.addEventListener('click', async function (event) {
        const ratingButton = event.target.closest('.rating-stars-editable .rating-star, .rating-stars-editable .rating-clear-btn');
        if (ratingButton) {
            event.preventDefault();
            const root = ratingButton.closest('.rating-stars-editable');
            const songId = parseInt(root?.dataset.songId, 10) || 0;
            const rating = parseInt(ratingButton.dataset.rating, 10) || 0;
            if (!songId) return;
            try {
                ratingButton.disabled = true;
                const data = await post('api/save_rating.php', { song_id: songId, rating: rating });
                document.querySelectorAll('.rating-stars[data-song-id="' + songId + '"]').forEach(function (el) {
                    paintStars(el, data.rating);
                });
                notify('별점을 저장했습니다.');
            } catch (err) {
                notify(err.message || '별점 저장 실패', true);
            } finally {
                ratingButton.disabled = false;
            }
            return;
        }

        const deleteButton = event.target.closest('.note-delete-btn');
        if (deleteButton) {
            event.preventDefault();
            if (!confirm('메모를 삭제할까요?')) return;
            const songId = parseInt(deleteButton.dataset.songId, 10) || 0;
            try {
                await post('api/save_note.php', { song_id: songId, action: 'delete' });
                document.querySelectorAll('.note-view-text[data-song-id="' + songId + '"]').forEach(function (el) {
                    el.innerHTML = '<p class="empty-text">작성된 메모가 없습니다.</p>';
                });
                const textarea = document.querySelector('.song-note-form[data-song-id="' + songId + '"] textarea[name="note_text"]');
                if (textarea) textarea.value = '';
                notify('메모를 삭제했습니다.');
            } catch (err) {
                notify(err.message || '메모 삭제 실패', true);
            }
        }
    });

    document.addEventListener('submit', async function (event) {
        const form = event.target.closest('.song-note-form');
        if (!form) return;
        event.preventDefault();
        const songId = parseInt(form.dataset.songId, 10) || 0;
        const textarea = form.querySelector('textarea[name="note_text"]');
        const text = textarea ? textarea.value : '';
        const button = form.querySelector('button[type="submit"]');
        if (!songId) return;
        try {
            if (button) button.disabled = true;
            const data = await post('api/save_note.php', { song_id: songId, action: 'save', note_text: text });
            document.querySelectorAll('.note-view-text[data-song-id="' + songId + '"]').forEach(function (el) {
                const note = String(data.note || '').trim();
                el.innerHTML = note ? '<div class="note-text-block">' + escapeHtml(note).replace(/\r?\n/g, '<br>') + '</div>' : '<p class="empty-text">작성된 메모가 없습니다.</p>';
            });
            notify('메모를 저장했습니다.');
        } catch (err) {
            notify(err.message || '메모 저장 실패', true);
        } finally {
            if (button) button.disabled = false;
        }
    });

    window.MelonLiteInitNotesPage = function () {};
})();
