(function () {
    const EMAIL_JS_PUBLIC_KEY = 'd7I4hw_UMkVTo2UXy';
    const EMAIL_JS_SERVICE_ID = 'service_jfxkmcd';
    const EMAIL_JS_TEMPLATE_ID = 'template_vu49z25';

    let emailJsInitialized = false;

    function getCsrfHeader() {
        const token = document.querySelector('meta[name="_csrf"]');
        const header = document.querySelector('meta[name="_csrf_header"]');

        return {
            token: token ? token.getAttribute('content') : '',
            header: header ? header.getAttribute('content') : ''
        };
    }

    function isValidEmail(email) {
        return /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test((email || '').trim());
    }

    function isValidMobile(phone) {
        return /^01[016789]-?\d{3,4}-?\d{4}$/.test((phone || '').trim());
    }

    function onlyNumber(value) {
        return value.replace(/[^0-9]/g, '');
    }

    function formatMobile(phone) {
        const numbers = onlyNumber(phone);

        if (numbers.length <= 3) {
            return numbers;
        }
        if (numbers.length <= 7) {
            return numbers.replace(/(\d{3})(\d{1,4})/, '$1-$2');
        }
        if (numbers.length <= 11) {
            return numbers.replace(/(\d{3})(\d{3,4})(\d{1,4})/, '$1-$2-$3');
        }

        return numbers.substring(0, 11).replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
    }

    function setErrorVisible(id, visible) {
        const element = document.getElementById(id);
        if (!element) {
            return;
        }
        element.style.display = visible ? 'block' : 'none';
    }

    function spinner(on) {
        const spinnerElement = $('#spinner');
        if (!spinnerElement.length) {
            return;
        }
        spinnerElement.toggleClass('show', on);
    }

    function buildPayload() {
        return {
            name: document.getElementById('name').value.trim(),
            email: document.getElementById('email').value.trim(),
            phone: document.getElementById('phone').value.trim(),
            subject: document.getElementById('subject').value.trim(),
            message: document.getElementById('message').value.trim()
        };
    }

    function validatePayload(payload) {
        if (!payload.name || !payload.email || !payload.phone || !payload.subject || !payload.message) {
            alert('필수 항목은 모두 입력해주세요.');
            return false;
        }
        if (!isValidEmail(payload.email)) {
            alert('올바른 이메일 형식이 아닙니다.');
            document.getElementById('email').focus();
            return false;
        }
        if (!isValidMobile(payload.phone)) {
            alert('올바른 휴대폰번호 형식이 아닙니다.');
            document.getElementById('phone').focus();
            return false;
        }
        return true;
    }

    function resetForm() {
        ['name', 'email', 'phone', 'subject', 'message'].forEach(function (id) {
            const element = document.getElementById(id);
            if (element) {
                element.value = '';
            }
        });
        setErrorVisible('emailError', false);
        setErrorVisible('phoneError', false);
    }

    function initEmailJs() {
        if (emailJsInitialized) {
            return true;
        }
        if (!window.emailjs || typeof window.emailjs.init !== 'function') {
            console.warn('EmailJS SDK could not be loaded.');
            return false;
        }

        window.emailjs.init({
            publicKey: EMAIL_JS_PUBLIC_KEY
        });
        emailJsInitialized = true;
        return true;
    }

    function sendContactToDatabase(payload) {
        const csrf = getCsrfHeader();

        return new Promise(function (resolve, reject) {
            $.ajax({
                url: '/api/contact',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(payload),
                beforeSend: function (xhr) {
                    if (csrf.header && csrf.token) {
                        xhr.setRequestHeader(csrf.header, csrf.token);
                    }
                }
            }).done(function (response) {
                resolve(response || {});
            }).fail(function (xhr) {
                reject(xhr);
            });
        });
    }

    function getEmailJsErrorMessage(error) {
        if (!error) {
            return 'Unknown EmailJS error';
        }
        if (typeof error === 'string') {
            return error;
        }
        if (error.text) {
            return error.text;
        }
        if (error.message) {
            return error.message;
        }
        try {
            return JSON.stringify(error);
        } catch (ignored) {
            return 'Unknown EmailJS error';
        }
    }

    function sendContactMail(form) {
        if (!initEmailJs() || !window.emailjs || typeof window.emailjs.sendForm !== 'function') {
            return Promise.reject(new Error('EmailJS SDK is not available.'));
        }

        return window.emailjs.sendForm(
            EMAIL_JS_SERVICE_ID,
            EMAIL_JS_TEMPLATE_ID,
            form,
            {
                publicKey: EMAIL_JS_PUBLIC_KEY
            }
        );
    }

    async function sendContact(event) {
        event.preventDefault();

        const form = event.currentTarget;
        const payload = buildPayload();
        if (!validatePayload(payload)) {
            return;
        }

        const btn = document.getElementById('btnSendMail');

        spinner(true);
        btn.disabled = true;

        try {
            const response = await sendContactToDatabase(payload);

            try {
                await sendContactMail(form);
                alert(response.message || '문의가 접수되었고 메일이 발송되었습니다.');
            } catch (error) {
                const errorMessage = getEmailJsErrorMessage(error);
                console.error('EmailJS send failed:', error);
                alert((response.message || '문의가 접수되었습니다.') + '\n메일 발송은 실패했습니다.\n사유: ' + errorMessage);
            }

            resetForm();
        } catch (xhr) {
            const response = xhr.responseJSON || {};
            alert(response.message || '문의 접수 중 오류가 발생했습니다.');
        } finally {
            spinner(false);
            btn.disabled = false;
        }
    }

    window.addEventListener('DOMContentLoaded', function () {
        const phoneInput = document.getElementById('phone');
        const emailInput = document.getElementById('email');
        const form = document.getElementById('contactForm');

        initEmailJs();

        if (phoneInput) {
            phoneInput.addEventListener('input', function (e) {
                e.target.value = formatMobile(e.target.value);
            });
            phoneInput.addEventListener('focusout', function () {
                setErrorVisible('phoneError', !!phoneInput.value && !isValidMobile(phoneInput.value));
            });
        }

        if (emailInput) {
            emailInput.addEventListener('focusout', function () {
                setErrorVisible('emailError', !!emailInput.value && !isValidEmail(emailInput.value));
            });
        }

        if (form) {
            form.addEventListener('submit', sendContact);
        }
    });
})();
