document.addEventListener('DOMContentLoaded', () => {
    if (window.bootstrap) {
        document.querySelectorAll('.toast').forEach((toastEl) => {
            const toast = bootstrap.Toast.getOrCreateInstance(toastEl);
            toast.show();
        });
    }

    document.querySelectorAll('[data-countdown]').forEach((node) => {
        const unlockAt = Number.parseInt(node.getAttribute('data-countdown') || '0', 10);
        const targetSelector = node.getAttribute('data-countdown-target');
        const targetButton = targetSelector ? document.querySelector(targetSelector) : null;
        const card = node.closest('[data-countdown-card]') || node.closest('.countdown-card');

        const updateCountdown = () => {
            const remaining = Math.max(0, unlockAt - Math.floor(Date.now() / 1000));
            if (remaining > 0) {
                node.textContent = `${remaining} 秒`;
                node.classList.remove('ready');
                if (targetButton) {
                    targetButton.disabled = true;
                    targetButton.setAttribute('aria-disabled', 'true');
                }
                if (card) {
                    card.classList.remove('ready');
                }
                return false;
            }

            node.textContent = '可提交';
            node.classList.add('ready');
            if (targetButton) {
                targetButton.disabled = false;
                targetButton.removeAttribute('aria-disabled');
            }
            if (card) {
                card.classList.add('ready');
            }
            return true;
        };

        const done = updateCountdown();
        if (!done) {
            const interval = window.setInterval(() => {
                if (updateCountdown()) {
                    window.clearInterval(interval);
                }
            }, 1000);
        }
    });

    document.querySelectorAll('[data-confirm]').forEach((button) => {
        button.addEventListener('click', (event) => {
            const message = button.getAttribute('data-confirm');
            if (message && !window.confirm(message)) {
                event.preventDefault();
            }
        });
    });
});
