document.addEventListener("DOMContentLoaded", () => {

    // Проверка авторизации через cookie
    fetch('/api/verify', { credentials: 'include' })
        .then(r => { if (!r.ok) window.location.href = '/'; })
        .catch(() => { window.location.href = '/'; });

    // Logout — удаляем cookie на бэкенде
    document.getElementById('logoutForm').addEventListener('click', async function(e) {
        e.preventDefault();
        await fetch('/api/logout', {
            method: 'POST',
            credentials: 'include'
        });
        window.location.href = '/';
    });

    document.querySelector(".form-info").addEventListener("submit", async (e) => {
        e.preventDefault();

        const guestData = {
            name:          document.getElementById('ffname').value || "",
            middlename:    document.getElementById('fmname').value || "",
            surname:       document.getElementById('flname').value || "",
            text_field:    document.getElementById('text_field')?.value || "",
            activated:     true,
            types_of_food: document.querySelector('input[name="food"]:checked')?.value || "",
            types_of_alco: Array.from(document.querySelectorAll('input[name="drink"]:checked'))
                               .map(el => el.value)
                               .join(', ')
        };

        try {
            const response = await fetch('/api/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',  // ← токен идёт через cookie
                body: JSON.stringify(guestData)
            });

            if (!response.ok) {
                const err = await response.json();
                throw new Error(JSON.stringify(err.detail || 'Ошибка при отправке'));
            }

            const data = await response.json();
            console.log('Успешно:', data);
            alert('Данные сохранены!');

        } catch (err) {
            console.error(err);
            alert('Ошибка: ' + err.message);
        }
    });
});