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-connect").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,
            type_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);
            window.location.href = '#answer';
            showErrors(JSON.parse(err.message));
        }
    });
});

const fieldMap = {
    'name': 'ffname',
    'middlename': 'fmname',
    'surname': 'flname'
  };
  
  function showErrors(errors) {
    let errorElements = document.querySelectorAll(".formError")
    if (errorElements.length === 0) {
      document.querySelectorAll('.label_style').forEach(el => {
        const errorElem = document.createElement('div');
        errorElem.className = 'formError';
        errorElem.style.cssText = `
          color: red;
          font-size: medium;
          line-height: 100%;
          transition: 3s;
          text-decoration: underline;
          font-weight: bold;
          font-family: Arial, sans-serif;
        `;
        el.after(errorElem);
      });
    }  
    errors.forEach(error => {
      const fieldName = error.loc[1]; // 'name', 'middlename', 'surname'
      const inputId = fieldMap[fieldName];
      if (!inputId) return;
  
      const input = document.getElementById(inputId);
      if (!input) return;
      const label = input.closest('.label_style');
      if (label && label.nextElementSibling?.classList.contains('formError')) {
        label.nextElementSibling.textContent = error.msg;
      }
    });
  }
  

