(function () {
    'use strict';

    if (window.__melonFeedbackInitialized) return;
    window.__melonFeedbackInitialized = 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 user/page data to the console.
    }

    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 fillContext() {
        const pageUrl = $('#feedback-page-url');
        const pageTitle = $('#feedback-page-title');
        const songId = $('#feedback-song-id');
        const contextText = $('#feedback-context-text');
        if (pageUrl) pageUrl.value = window.location.pathname + window.location.search;
        if (pageTitle) pageTitle.value = document.title || '';
        if (songId) songId.value = currentSongIdFromUrl();
        if (contextText) {
            const songText = songId && songId.value ? ` · 관련 곡 #${songId.value}` : '';
            contextText.textContent = `현재 페이지: ${document.title || window.location.pathname}${songText}`;
        }
    }

    function setStatus(message, isError) {
        const status = $('#feedback-status-text');
        if (!status) return;
        status.textContent = message || '';
        status.classList.toggle('error', !!isError);
    }

    function openModal() {
        const modal = $('#feedback-modal');
        if (!modal) return;
        fillContext();
        modal.hidden = false;
        modal.style.display = 'flex';
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('modal-open', 'feedback-modal-open');
        setStatus('');
        const title = $('#feedback-title');
        if (title) setTimeout(() => title.focus(), 40);
    }

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

    function resetForm() {
        const form = $('#feedback-form');
        if (form) form.reset();
        fillContext();
    }

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

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

        const title = ($('#feedback-title') || {}).value || '';
        const body = ($('#feedback-body') || {}).value || '';
        if (title.trim().length < 3) {
            setStatus('제목을 3자 이상 입력해 주세요.', true);
            return;
        }
        if (body.trim().length < 8) {
            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() + 'feedback_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('#feedback-open-btn, [data-feedback-open]');
        if (openBtn) {
            event.preventDefault();
            openModal();
            return;
        }

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

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

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

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

    document.addEventListener('melonlite:page-ready', fillContext);
    document.addEventListener('DOMContentLoaded', fillContext);
})();
