$(document).ready(function() {
    function hasAccessRights() {
        if (typeof userInfo === 'undefined') {
            return false;
        }
        return userInfo.isAdmin || userInfo.isManager || userInfo.isTeacher;
    }
    
    function addNoteIconsToAnswers() {
        if (!hasAccessRights()) {
            return;
        }

        if (!window.location.pathname.includes('/control/lesson') && 
            !window.location.pathname.includes('/answers/unanswered')) {
            return;
        }
        
        const $answersBlock = $('.answers-list');
        if ($answersBlock.length === 0) {
            return;
        }
        
        $('.answer_wrapper').each(function() {
            const $answerWrapper = $(this);
            
            if ($answerWrapper.find('.user-note-icon').length > 0) {
                return;
            }
            
            const $userProfileLink = $answerWrapper.find('.user-profile-link');
            if ($userProfileLink.length === 0) {
                return;
            }
            
            const userId = $userProfileLink.data('user-id');
            if (!userId) {
                return;
            }
            
            const $noteIcon = $('<span>', {
                'class': 'user-note-icon',
                'data-user-id': userId,
                'title': 'Заметки куратора',
                'css': {
                    'display': 'inline-block',
                    'margin-left': '10px',
                    'cursor': 'pointer',
                    'font-size': '18px',
                    'color': '#666',
                    'transition': 'color 0.2s'
                },
                'mouseenter': function() {
                    $(this).css('color', '#ff6b6b');
                },
                'mouseleave': function() {
                    $(this).css('color', '#666');
                }
            }).html('&#128221;');
            
            $noteIcon.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const targetUserId = $(this).data('user-id');
                readUserNotes(targetUserId);
            });
            
            $userProfileLink.append($noteIcon);
        });
    }
    
    addNoteIconsToAnswers();
    
    let loadMoreTimeout;
    $('#showMoreAnswers').on('click', function() {
        if (loadMoreTimeout) {
            clearTimeout(loadMoreTimeout);
        }
        
        loadMoreTimeout = setTimeout(function() {
            addNoteIconsToAnswers();
        }, 3000);
    });
    
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length > 0) {
                let hasNewAnswers = false;
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if ($(node).hasClass('answer_wrapper') || $(node).find('.answer_wrapper').length > 0) {
                            hasNewAnswers = true;
                        }
                    }
                });
                
                if (hasNewAnswers) {
                    addNoteIconsToAnswers();
                }
            }
        });
    });
    
    if ($('.other-answers.answers-list').length > 0 && hasAccessRights()) {
        observer.observe($('.other-answers.answers-list')[0], {
            childList: true,
            subtree: true
        });
    }
});

function readUserNotes(userId) {
    if ($('#userNotesModal').length > 0) {
        $('#userNotesModal').remove();
    }
    
    showLoading();
    
    $.ajax({
        url: '/chtm/userNotes/userNotes_heap~get-by-user',
        method: 'GET',
        data: {
            user_id: userId
        },
        success: function(response) {
            hideLoading();
            
            if (response && response.success === false) {
                renderNotesModal(userId, []);
            } else if (response && response.notes) {
                const notes = response.notes.sort(function(a, b) {
                    return new Date(a.createdAt) - new Date(b.createdAt);
                });
                renderNotesModal(userId, notes);
            } else {
                renderNotesModal(userId, []);
            }
        },
        error: function() {
            hideLoading();
            renderNotesModal(userId, []);
        }
    });
}

function renderNotesModal(userId, notes) {
    const curatorId = window.accountUserId || 0;
    const curatorName = window.accountSafeUserName || 'Куратор';
    
    const modalHtml = `
        <div id="userNotesModal" class="notes-modal">
            <div class="notes-modal-content">
                <div class="notes-modal-header">
                    <h2>Заметки кураторов об ученике</h2>
                    <span class="notes-modal-close">×</span>
                </div>
                
                <div class="notes-modal-body">
                    <div class="notes-list">
                        ${renderNotesList(notes)}
                    </div>
                    
                    <div class="notes-add-form">
                        <h3>Добавить заметку</h3>
                        <div class="notes-mood-selector">
                            <span class="mood-option" data-mood="&#128522;">&#128522;</span>
                            <span class="mood-option" data-mood="&#128528;">&#128528;</span>
                            <span class="mood-option" data-mood="&#128542;">&#128542;</span>
                            <span class="mood-option" data-mood="&#129300;">&#129300;</span>
                            <span class="mood-option" data-mood="&#128077;">&#128077;</span>
                            <span class="mood-option" data-mood="&#128078;">&#128078;</span>
                            <span class="mood-option" data-mood="&#11088;">&#11088;</span>
                            <span class="mood-option" data-mood="&#128221;">&#128221;</span>
                            <input type="hidden" id="selectedMood" value="&#128221;">
                        </div>
                        <textarea id="newNoteText" placeholder="Введите текст заметки..." rows="3"><\/textarea>
                        <button id="saveNoteBtn" class="notes-save-btn" 
                                data-user-id="${userId}"
                                data-curator-id="${curatorId}"
                                data-curator-name="${escapeHtml(curatorName)}">
                            Сохранить заметку
                        </button>
                    </div>
                </div>
            </div>
            
            <div id="editNoteModal" class="notes-submodal">
                <div class="notes-submodal-content">
                    <div class="notes-submodal-header">
                        <h3>Редактировать заметку</h3>
                        <span class="notes-submodal-close">×</span>
                    </div>
                    <div class="notes-submodal-body">
                        <div class="notes-mood-selector edit-mood-selector">
                            <span class="mood-option" data-mood="&#128522;">&#128522;</span>
                            <span class="mood-option" data-mood="&#128528;">&#128528;</span>
                            <span class="mood-option" data-mood="&#128542;">&#128542;</span>
                            <span class="mood-option" data-mood="&#129300;">&#129300;</span>
                            <span class="mood-option" data-mood="&#128077;">&#128077;</span>
                            <span class="mood-option" data-mood="&#128078;">&#128078;</span>
                            <span class="mood-option" data-mood="&#11088;">&#11088;</span>
                            <span class="mood-option" data-mood="&#128221;">&#128221;</span>
                            <input type="hidden" id="editSelectedMood" value="&#128221;">
                        </div>
                        <textarea id="editNoteText" placeholder="Введите текст заметки..." rows="4"><\/textarea>
                        <input type="hidden" id="editNoteId">
                        <div class="edit-note-actions">
                            <button id="cancelEditBtn" class="edit-cancel-btn">Отмена</button>
                            <button id="updateNoteBtn" class="edit-save-btn">Сохранить изменения</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('body').append(modalHtml);
    
    setTimeout(function() {
        $('#userNotesModal').addClass('show');
    }, 10);
    
    $('.notes-modal-close').on('click', function() {
        closeNotesModal();
    });
    
    $(window).on('click', function(e) {
        if ($(e.target).hasClass('notes-modal')) {
            closeNotesModal();
        }
    });
    
    $('.mood-option').on('click', function() {
        if (!$(this).closest('.edit-mood-selector').length) {
            $('.mood-option').not('.edit-mood-selector .mood-option').removeClass('selected');
            $(this).addClass('selected');
            $('#selectedMood').val($(this).data('mood'));
        }
    });
    
    if ($('.mood-option.selected').length === 0) {
        $('.mood-option[data-mood="&#128221;"]').not('.edit-mood-selector .mood-option').addClass('selected');
    }
    
    $('#saveNoteBtn').on('click', function() {
        saveNewNote($(this));
    });
    
    $('.edit-note-btn').on('click', function() {
        const noteId = $(this).data('note-id');
        const $noteItem = $(this).closest('.note-item');
        const currentText = $noteItem.data('note-text');
        const currentMood = $noteItem.data('note-mood');
        
        openEditModal(noteId, currentText, currentMood);
    });
    
    $('.notes-submodal-close').on('click', function() {
        closeEditModal();
    });
    
    $(document).on('click', function(e) {
        if ($(e.target).hasClass('notes-submodal')) {
            closeEditModal();
        }
    });
    
    $('.edit-mood-selector .mood-option').on('click', function() {
        $('.edit-mood-selector .mood-option').removeClass('selected');
        $(this).addClass('selected');
        $('#editSelectedMood').val($(this).data('mood'));
    });
    
    $('#cancelEditBtn').on('click', function() {
        closeEditModal();
    });
    
    $('#updateNoteBtn').on('click', function() {
        updateNote();
    });
}

function renderNotesList(notes) {
    if (!notes || !Array.isArray(notes) || notes.length === 0) {
        return '<div class="notes-empty">У ученика пока нет заметок. Создайте первую заметку!</div>';
    }
    
    const currentUserId = window.accountUserId || 0;
    const now = new Date();
    
    return notes.map(function(note) {
        let formattedDate = 'Дата неизвестна';
        let canEdit = false;
        let timeDiff = null;
        
        if (note.createdAt) {
            const date = new Date(note.createdAt);
            if (!isNaN(date.getTime())) {
                formattedDate = date.toLocaleString('ru-RU', {
                    day: '2-digit',
                    month: '2-digit',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                timeDiff = Math.floor((now - date) / (1000 * 60));
                canEdit = (note.curator_id === currentUserId) && timeDiff < 60;
            }
        }
        
        const curatorLink = `/user/control/user/update/id/${note.curator_id}`;
        
        if (canEdit) {
            return `
                <div class="note-item editable-note" data-note-id="${note.id}" data-note-text="${escapeHtml(note.curator_msg || '')}" data-note-mood="${note.mood_icon || '&#128221;'}">
                    <div class="note-header">
                        <span class="note-curator">
                            <span class="note-mood">${note.mood_icon || '&#128221;'}</span>
                            <a href="${curatorLink}" target="_blank" class="curator-link">${escapeHtml(note.curator_name || 'Куратор')}</a>
                            <span class="edit-badge" title="Можно редактировать (еще ${60 - timeDiff} мин)">&#9999;&#65039;</span>
                        </span>
                        <span class="note-date">${formattedDate}</span>
                    </div>
                    <div class="note-text">${escapeHtml(note.curator_msg || '')}</div>
                    <div class="note-edit-actions">
                        <button class="edit-note-btn" data-note-id="${note.id}">Редактировать</button>
                    </div>
                </div>
            `;
        } else {
            return `
                <div class="note-item" data-note-id="${note.id}">
                    <div class="note-header">
                        <span class="note-curator">
                            <span class="note-mood">${note.mood_icon || '&#128221;'}</span>
                            <a href="${curatorLink}" target="_blank" class="curator-link">${escapeHtml(note.curator_name || 'Куратор')}</a>
                            ${note.curator_id === currentUserId && timeDiff >= 60 ? '<span class="edit-locked" title="Прошло более 60 минут, редактирование недоступно">&#128274;</span>' : ''}
                        </span>
                        <span class="note-date">${formattedDate}</span>
                    </div>
                    <div class="note-text">${escapeHtml(note.curator_msg || '')}</div>
                </div>
            `;
        }
    }).join('');
}

function saveNewNote($btn) {
    const targetUserId = $btn.data('user-id');
    const curatorId = $btn.data('curator-id');
    const curatorName = $btn.data('curator-name');
    const noteText = $('#newNoteText').val().trim();
    const selectedMood = $('#selectedMood').val();
    
    if (!noteText) {
        alert('Введите текст заметки');
        return;
    }
    
    if (!curatorId) {
        alert('Ошибка: не удалось определить ID куратора');
        return;
    }
    
    const originalText = $btn.text();
    $btn.text('Сохранение...').prop('disabled', true);
    
    $.ajax({
        url: '/chtm/userNotes/userNotes_heap~create',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            user_id: targetUserId,
            curator_id: curatorId,
            curator_msg: noteText,
            curator_name: curatorName,
            mood_icon: selectedMood
        }),
        success: function(response) {
            if (response && response.success && response.note) {
                $('#newNoteText').val('');
                addNoteToList(response.note);
                showNotification('Заметка успешно сохранена', 'success');
            } else {
                alert('Ошибка при сохранении: ' + (response.error || 'Неизвестная ошибка'));
            }
        },
        error: function() {
            alert('Ошибка при сохранении заметки');
        },
        complete: function() {
            $btn.text(originalText).prop('disabled', false);
        }
    });
}

function addNoteToList(note) {
    const $notesList = $('.notes-list');
    const currentUserId = window.accountUserId || 0;
    
    if ($notesList.find('.notes-empty').length > 0) {
        $notesList.empty();
    }
    
    let formattedDate = 'Только что';
    if (note.createdAt) {
        const date = new Date(note.createdAt);
        if (!isNaN(date.getTime())) {
            formattedDate = date.toLocaleString('ru-RU', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }
    
    const curatorLink = `/user/control/user/update/id/${note.curator_id}`;
    const canEdit = note.curator_id === currentUserId;
    
    let newNoteHtml;
    if (canEdit) {
        newNoteHtml = `
            <div class="note-item new-note editable-note" data-note-id="${note.id}" data-note-text="${escapeHtml(note.curator_msg || '')}" data-note-mood="${note.mood_icon || '&#128221;'}">
                <div class="note-header">
                    <span class="note-curator">
                        <span class="note-mood">${note.mood_icon || '&#128221;'}</span>
                        <a href="${curatorLink}" target="_blank" class="curator-link">${escapeHtml(note.curator_name || 'Куратор')}</a>
                        <span class="edit-badge" title="Можно редактировать">&#9999;&#65039;</span>
                    </span>
                    <span class="note-date">${formattedDate}</span>
                </div>
                <div class="note-text">${escapeHtml(note.curator_msg || '')}</div>
                <div class="note-edit-actions">
                    <button class="edit-note-btn" data-note-id="${note.id}">Редактировать</button>
                </div>
            </div>
        `;
    } else {
        newNoteHtml = `
            <div class="note-item new-note" data-note-id="${note.id}">
                <div class="note-header">
                    <span class="note-curator">
                        <span class="note-mood">${note.mood_icon || '&#128221;'}</span>
                        <a href="${curatorLink}" target="_blank" class="curator-link">${escapeHtml(note.curator_name || 'Куратор')}</a>
                    </span>
                    <span class="note-date">${formattedDate}</span>
                </div>
                <div class="note-text">${escapeHtml(note.curator_msg || '')}</div>
            </div>
        `;
    }
    
    $notesList.append(newNoteHtml);
    
    if (canEdit) {
        $(`.note-item[data-note-id="${note.id}"] .edit-note-btn`).on('click', function() {
            const noteId = $(this).data('note-id');
            const $noteItem = $(this).closest('.note-item');
            const currentText = $noteItem.data('note-text');
            const currentMood = $noteItem.data('note-mood');
            
            openEditModal(noteId, currentText, currentMood);
        });
    }
    
    setTimeout(function() {
        $('.new-note').css({
            'background-color': '#e8f5e9',
            'transition': 'background-color 2s'
        });
        
        setTimeout(function() {
            $('.new-note').css('background-color', '');
            $('.new-note').removeClass('new-note');
        }, 2000);
    }, 100);
    
    $notesList.scrollTop($notesList[0].scrollHeight);
}

function openEditModal(noteId, currentText, currentMood) {
    $('#editNoteId').val(noteId);
    $('#editNoteText').val(currentText);
    
    $('.edit-mood-selector .mood-option').removeClass('selected');
    $(`.edit-mood-selector .mood-option[data-mood="${currentMood}"]`).addClass('selected');
    $('#editSelectedMood').val(currentMood);
    
    $('#editNoteModal').addClass('show');
}

function closeEditModal() {
    $('#editNoteModal').removeClass('show');
    setTimeout(function() {
        $('#editNoteText').val('');
        $('#editNoteId').val('');
    }, 300);
}

function updateNote() {
    const noteId = $('#editNoteId').val();
    const newText = $('#editNoteText').val().trim();
    const newMood = $('#editSelectedMood').val();
    
    if (!newText) {
        alert('Введите текст заметки');
        return;
    }
    
    const $updateBtn = $('#updateNoteBtn');
    const originalText = $updateBtn.text();
    $updateBtn.text('Сохранение...').prop('disabled', true);
    
    $.ajax({
        url: '/chtm/userNotes/userNotes_heap~update',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            id: noteId,
            curator_msg: newText,
            mood_icon: newMood
        }),
        success: function(response) {
            if (response && response.success && response.note) {
                updateNoteInList(response.note);
                closeEditModal();
                showNotification('Заметка успешно обновлена', 'success');
            } else {
                alert('Ошибка при обновлении: ' + (response.error || 'Неизвестная ошибка'));
            }
        },
        error: function() {
            alert('Ошибка при обновлении заметки');
        },
        complete: function() {
            $updateBtn.text(originalText).prop('disabled', false);
        }
    });
}

function updateNoteInList(updatedNote) {
    const $noteItem = $(`.note-item[data-note-id="${updatedNote.id}"]`);
    
    if ($noteItem.length) {
        let formattedDate = 'Только что';
        if (updatedNote.createdAt) {
            const date = new Date(updatedNote.createdAt);
            if (!isNaN(date.getTime())) {
                formattedDate = date.toLocaleString('ru-RU', {
                    day: '2-digit',
                    month: '2-digit',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }
        }
        
        $noteItem.find('.note-mood').text(updatedNote.mood_icon || '&#128221;');
        $noteItem.find('.note-text').text(updatedNote.curator_msg || '');
        $noteItem.data('note-text', updatedNote.curator_msg || '');
        $noteItem.data('note-mood', updatedNote.mood_icon || '&#128221;');
        
        $noteItem.css({
            'background-color': '#fff3e0',
            'transition': 'background-color 2s'
        });
        
        setTimeout(function() {
            $noteItem.css('background-color', '');
        }, 2000);
    }
}

function closeNotesModal() {
    $('#userNotesModal').removeClass('show');
    setTimeout(function() {
        $('#userNotesModal').remove();
    }, 300);
}

function showLoading() {
    if ($('#notesLoading').length === 0) {
        $('body').append('<div id="notesLoading" class="notes-loading">Загрузка...</div>');
    }
}

function hideLoading() {
    $('#notesLoading').remove();
}

function showNotification(message, type = 'info') {
    $('#notesNotification').remove();
    
    const notificationHtml = `
        <div id="notesNotification" class="notes-notification notes-notification-${type}">
            ${message}
        </div>
    `;
    
    $('body').append(notificationHtml);
    
    setTimeout(function() {
        $('#notesNotification').addClass('show');
    }, 10);
    
    setTimeout(function() {
        $('#notesNotification').removeClass('show');
        setTimeout(function() {
            $('#notesNotification').remove();
        }, 300);
    }, 3000);
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}