// Shared app behavior: CSRF for same-origin writes + flash dismissal.
(function() {
    function csrfToken() {
        const meta = document.querySelector('meta[name="csrf-token"]');
        return meta ? meta.getAttribute('content') : '';
    }

    const originalFetch = window.fetch;
    window.fetch = function(input, init) {
        const opts = init ? Object.assign({}, init) : {};
        const method = (opts.method || (input && input.method) || 'GET').toUpperCase();
        if (!['GET', 'HEAD', 'OPTIONS', 'TRACE'].includes(method)) {
            const target = (input && input.url) ? input.url : String(input);
            const url = new URL(target, window.location.href);
            if (url.origin === window.location.origin) {
                const headers = new Headers(opts.headers || (input && input.headers) || {});
                if (!headers.has('X-CSRF-Token')) {
                    headers.set('X-CSRF-Token', csrfToken());
                }
                opts.headers = headers;
            }
        }
        return originalFetch(input, opts);
    };

    document.addEventListener('DOMContentLoaded', function() {
        const token = csrfToken();
        if (!token) return;
        document.querySelectorAll('form[method]').forEach(function(form) {
            if ((form.getAttribute('method') || '').toUpperCase() !== 'POST') return;
            if (form.querySelector('input[name="csrf_token"]')) return;
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'csrf_token';
            input.value = token;
            form.appendChild(input);
        });
    });
})();

// Auto-dismiss flash messages after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const flashes = document.querySelectorAll('.flash');
    flashes.forEach(function(el) {
        setTimeout(function() {
            el.style.transition = 'opacity 0.3s';
            el.style.opacity = '0';
            setTimeout(function() { el.remove(); }, 300);
        }, 5000);
    });
});
