document.addEventListener('DOMContentLoaded', () => {
    fetch('/api/verify', { credentials: 'include' })
        .then(r => { if (r.ok) window.location.href = '/main/'; })
        .catch(() => {});

    document.getElementById('loginForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const code = document.getElementById('password').value;

        try {
            const response = await fetch('/api/auth', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',   // ← чтобы браузер принял cookie
                body: JSON.stringify({ code })
            });

            const data = await response.json();

            if (response.ok) {
                window.location.href = '/main/';
            } else {
                if (Array.isArray(data.detail)) {
                    const messages = data.detail.map(e => {
                        const field = e.loc.filter(p => p !== 'body').join(' -> ');
                        return `${field}: ${e.msg}`;
                    });
                    showError(messages);
                } else if (typeof data.detail === 'string') {
                    showError([data.detail]);
                } else {
                    showError(['Unknown error']);
                }
            }
        } catch (err) {
            showError(['Connection error: ' + err.message]);
        }
    });
});

function showError(messages) {
    let errorElem = document.getElementById('formError');
    if (!errorElem) {
        errorElem = document.createElement('div');
        errorElem.id = 'formError';
        errorElem.style.cssText = `
            color: red;
            margin-top: 20px;
            margin-bottom: 20px;
            font-size: 14px;
            font-weight: 100;
            line-height: 120%;
            transition: 3s;
        `;
        document.getElementById('loginForm').insertAdjacentElement('afterend', errorElem);
    }
    errorElem.innerHTML = '';
    messages.forEach(msg => {
        const li = document.createElement('li');
        li.style.listStyleType = 'none';
        li.textContent = msg;
        errorElem.appendChild(li);
    });
}