(function () {
    'use strict';

    if (window.__melonMetadataRequestInitialized) return;
    window.__melonMetadataRequestInitialized = true;

    const state = { submitting: false };

    function basePath() {
        return window.APP_BASE_PATH || window.APP_ROOT_PATH || './';
    }

    function $(selector) {
        return document.querySelector(selector);
    }

    function showToast(message, type) {
        if (window.MelonToast && typeof window.MelonToast.show === 'function') {
            window.MelonToast.show(message, type || 'info');
            return;
        }
        if (typeof window.showToast === 'function') {
            window.showToast(message, type || 'info');
            return;
        }
        // Toast UI is optional; avoid leaking song metadata to the console.
    }

    function safeText(value) {
        return String(value || '').replace(/\s+/g, ' ').trim();
    }

    function currentSongIdFromUrl() {
        const url = new URL(window.location.href);
        if (!/song\.php$/i.test(url.pathname) && !/lyrics_edit\.php$/i.test(url.pathname)) return '';
        const id = parseInt(url.searchParams.get('id') || '', 10);
        return Number.isFinite(id) && id > 0 ? String(id) : '';
    }

    function readSongContext(trigger) {
        const item = trigger && trigger.closest ? trigger.closest('.song-item') : null;
        const fallbackId = currentSongIdFromUrl();
        return {
            id: safeText(trigger && (trigger.dataset.songId || trigger.dataset.id)) || safeText(item && item.dataset.id) || fallbackId,
            title: safeText(trigger && trigger.dataset.songTitle) || safeText(item && item.dataset.title),
            artist: safeText(trigger && trigger.dataset.songArtist) || safeText(item && item.dataset.artist),
            album: safeText(trigger && trigger.dataset.songAlbum) || safeText(item && item.dataset.album),
        };
    }

    function setStatus(message, isError) {
        const status = $('#metadata-request-status-text');
        if (!status) return;
        status.textContent = message || '';
        status.classList.toggle('error', !!isError);
        status.dataset.type = isError ? 'error' : '';
    }

    function fillContext(context) {
        const songId = $('#metadata-request-song-id');
        const pageUrl = $('#metadata-request-page-url');
        const current = $('#metadata-request-current');
        if (songId) songId.value = context.id || '';
        if (pageUrl) pageUrl.value = window.location.pathname + window.location.search;
        if (current) {
            const title = context.title || '선택한 곡';
            const artist = context.artist ? ` · ${context.artist}` : '';
            const album = context.album ? ` · ${context.album}` : '';
            current.textContent = `${title}${artist}${album}`;
        }
    }

    function openModal(trigger) {
        const modal = $('#metadata-request-modal');
        if (!modal) return;
        const context = readSongContext(trigger);
        if (!context.id) {
            showToast('곡 정보를 확인할 수 없습니다.', 'warning');
            return;
        }
        fillContext(context);
        setStatus('');
        modal.hidden = false;
        modal.style.display = 'flex';
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('modal-open', 'metadata-request-modal-open');
        const type = $('#metadata-request-type');
        if (type) setTimeout(() => type.focus(), 40);
    }

    function closeModal() {
        const modal = $('#metadata-request-modal');
        if (!modal) return;
        modal.hidden = true;
        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('modal-open', 'metadata-request-modal-open');
        setStatus('');
    }

    function resetForm() {
        const form = $('#metadata-request-form');
        const current = $('#metadata-request-current');
        if (form) form.reset();
        if (current) current.textContent = '';
    }

    async function submitRequest(event) {
        event.preventDefault();
        if (state.submitting) return;

        const form = $('#metadata-request-form');
        const submitBtn = $('#metadata-request-submit-btn');
        if (!form) return;

        const songId = ($('#metadata-request-song-id') || {}).value || '';
        const suggested = ($('#metadata-request-suggested') || {}).value || '';
        const reason = ($('#metadata-request-reason') || {}).value || '';
        if (!songId) {
            setStatus('곡 정보를 확인할 수 없습니다.', true);
            return;
        }
        if (suggested.trim().length < 2 && reason.trim().length < 4) {
            setStatus('수정 제안 내용이나 요청 사유를 조금 더 입력해 주세요.', true);
            return;
        }

        state.submitting = true;
        if (submitBtn) submitBtn.disabled = true;
        setStatus('수정 요청을 전송하는 중입니다...', false);

        try {
            const formData = new FormData(form);
            if (!formData.get('csrf_token') && window.APP_CSRF_TOKEN) {
                formData.set('csrf_token', window.APP_CSRF_TOKEN);
            }
            const response = await fetch(basePath() + 'metadata_request_submit.php', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin',
                cache: 'no-store',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                },
            });
            const payload = await response.json().catch(() => null);
            if (!response.ok || !payload || !payload.success) {
                throw new Error((payload && payload.message) || '수정 요청 전송에 실패했습니다.');
            }
            resetForm();
            closeModal();
            showToast(payload.message || '음악 정보 수정 요청이 접수되었습니다.', 'success');
        } catch (error) {
            setStatus(error.message || '수정 요청 전송 중 문제가 발생했습니다.', true);
        } finally {
            state.submitting = false;
            if (submitBtn) submitBtn.disabled = false;
        }
    }

    document.addEventListener('click', function (event) {
        const openBtn = event.target.closest('.metadata-request-btn');
        if (openBtn) {
            event.preventDefault();
            event.stopPropagation();
            openModal(openBtn);
            return;
        }

        if (event.target.closest('#metadata-request-modal-close') || event.target.closest('#metadata-request-cancel-btn')) {
            event.preventDefault();
            closeModal();
            return;
        }

        const modal = $('#metadata-request-modal');
        if (modal && event.target === modal) {
            closeModal();
        }
    });

    document.addEventListener('submit', function (event) {
        if (event.target && event.target.id === 'metadata-request-form') {
            submitRequest(event);
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && document.body.classList.contains('metadata-request-modal-open')) {
            closeModal();
        }
    });
})();
