(function () {
    'use strict';

    function postGuestbook(form) {
        var data = { form_type: 'guestbook' };
        new FormData(form).forEach(function (value, key) { data[key] = value; });
        if (!data.name || !data.phone || !data.content) {
            alert('请填写姓名、电话和留言内容');
            return;
        }
        var button = form.querySelector('[type="submit"]');
        if (button) { button.disabled = true; button.dataset.text = button.textContent; button.textContent = '提交中...'; }
        fetch('/admin/main.php?act=builder_api&action=submit_form', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        }).then(function (response) { return response.json(); }).then(function (result) {
            if (Number(result.code) === 200) {
                alert('提交成功，我们会尽快与您联系');
                form.reset();
            } else {
                alert(result.msg || '提交失败，请稍后再试');
            }
        }).catch(function () {
            alert('提交失败，请检查网络后重试');
        }).finally(function () {
            if (button) { button.disabled = false; button.textContent = button.dataset.text || '提交留言'; }
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.tpl-guestbook-form').forEach(function (form) {
            form.addEventListener('submit', function (event) { event.preventDefault(); postGuestbook(form); });
        });
        document.querySelectorAll('.go-top').forEach(function (button) {
            button.addEventListener('click', function () { window.scrollTo({ top: 0, behavior: 'smooth' }); });
        });
        document.querySelectorAll('img').forEach(function (image) {
            image.addEventListener('error', function () {
                if (!image.dataset.fallback) {
                    image.dataset.fallback = '1';
                    image.src = document.body.dataset.fallbackImage || '/template/default/skin/images/inside-banner.jpg';
                }
            });
        });
    });
}());
