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

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

    function refreshTagBox(container, tags, songId) {
        if (!container) return;
        if (!Array.isArray(tags) || tags.length === 0) {
            container.innerHTML = '<span class="tag-empty">태그 없음</span>';
            return;
        }
        container.innerHTML = tags.map(function (tag) {
            const id = parseInt(tag.id, 10) || 0;
            const name = String(tag.name || '');
            const href = (window.APP_BASE_PATH || './') + 'tag.php?id=' + encodeURIComponent(id);
            return '<a class="tag-badge" href="' + href + '">' + escapeHtml(name) + '</a>' +
                '<button type="button" class="tag-remove-btn" data-song-id="' + songId + '" data-tag-id="' + id + '" title="태그 제거">x</button>';
        }).join('');
    }

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

    async function postTag(action, songId, payload) {
        const formData = new FormData();
        formData.append('action', action);
        formData.append('song_id', songId);
        formData.append('csrf_token', window.APP_CSRF_TOKEN || '');
        Object.keys(payload || {}).forEach(function (key) {
            formData.append(key, payload[key]);
        });
        const response = await fetch((window.APP_BASE_PATH || './') + 'api/tag_song.php', {
            method: 'POST',
            body: formData,
            credentials: 'same-origin',
            headers: { 'Accept': 'application/json' }
        });
        const data = await response.json();
        if (!response.ok || !data.success) throw new Error(data.message || '태그 작업에 실패했습니다.');
        return data;
    }

    function initTagsPage() {
        document.querySelectorAll('.song-tag-form').forEach(function (form) {
            form.dataset.tagsReady = '1';
        });
    }

    document.addEventListener('submit', async function (event) {
        const form = event.target.closest('.song-tag-form');
        if (!form) return;
        event.preventDefault();
        const songId = parseInt(form.getAttribute('data-song-id'), 10) || 0;
        const input = form.querySelector('input[name="tag_name"]');
        const tagName = input ? input.value.trim() : '';
        if (!songId || !tagName) {
            if (input) input.focus();
            return;
        }
        const button = form.querySelector('button[type="submit"]');
        if (button) button.disabled = true;
        try {
            const data = await postTag('add', songId, { tag_name: tagName });
            refreshTagBox(document.querySelector('.song-tags-box[data-song-id="' + songId + '"]'), data.tags, songId);
            if (input) input.value = '';
            notify('태그를 추가했습니다.');
        } catch (err) {
            notify(err.message || '태그 추가에 실패했습니다.', true);
        } finally {
            if (button) button.disabled = false;
        }
    });

    document.addEventListener('click', async function (event) {
        const suggestion = event.target.closest('.tag-suggestion-btn');
        if (suggestion) {
            const form = suggestion.closest('.tag-editor-card')?.querySelector('.song-tag-form');
            const input = form ? form.querySelector('input[name="tag_name"]') : null;
            if (input) {
                input.value = suggestion.getAttribute('data-tag-name') || suggestion.textContent.trim();
                form.requestSubmit();
            }
            return;
        }

        const removeButton = event.target.closest('.tag-remove-btn');
        if (!removeButton) return;
        event.preventDefault();
        const songId = parseInt(removeButton.getAttribute('data-song-id'), 10) || 0;
        const tagId = parseInt(removeButton.getAttribute('data-tag-id'), 10) || 0;
        if (!songId || !tagId) return;
        removeButton.disabled = true;
        try {
            const data = await postTag('remove', songId, { tag_id: tagId });
            refreshTagBox(document.querySelector('.song-tags-box[data-song-id="' + songId + '"]'), data.tags, songId);
            notify('태그를 제거했습니다.');
        } catch (err) {
            notify(err.message || '태그 제거에 실패했습니다.', true);
            removeButton.disabled = false;
        }
    });

    window.MelonLiteInitTagsPage = initTagsPage;
    document.addEventListener('DOMContentLoaded', initTagsPage);
})();
