let skinViewer = null;
const defaultSkin = '/static/icons/Steve.png';

function getCurrentUsername() {
    const usernameElement = document.querySelector('.profile-field .value');
    return usernameElement ? usernameElement.textContent : null;
}

function checkAndClearOldUserData() {
    const currentUser = getCurrentUsername();
    const lastUser = localStorage.getItem('lastUsername');
    
    if (currentUser) {
        localStorage.setItem('lastUsername', currentUser);
    }
}

const defaultSkins = [
    { name: 'Steve', path: '/static/icons/Steve.png' },
    { name: 'Sheep', path: '/static/icons/sheepskin.png' },
    { name: 'Joper', path: '/static/icons/Joper.png' },
];

let currentSkin = defaultSkin;

let skinHistoryData = [];

function getSkinHistory() {
    return skinHistoryData;
}

function addToSkinHistory(skinUrl, skinName = null) {
    if (!skinName) {
        const defaultSkin = defaultSkins.find(s => s.path === skinUrl);
        if (defaultSkin) {
            skinName = defaultSkin.name;
        } else {
            const date = new Date();
            skinName = `Custom Skin ${date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}`;
        }
    }
    
    fetch('/user/skin-history', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            url: skinUrl,
            name: skinName
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.skin_history) {
            skinHistoryData = data.skin_history;
            renderSkinHistory();
        }
    })
    .catch(error => {
        console.error('Error saving skin history:', error);
    });
}

function loadSkinInViewer(skinUrl, skinName = null) {
    if (skinViewer) {
        skinViewer.loadSkin(skinUrl);
        addToSkinHistory(skinUrl, skinName);
        updateActiveSkin(skinUrl);
        
        saveSkinToBackend(skinUrl);
    }
}

function saveSkinToBackend(skinUrl) {
    fetch('/user', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            current_skin: skinUrl
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('Skin saved to backend:', data.current_skin);
    })
    .catch(error => {
        console.error('Error saving skin:', error);
    });
}

function updateActiveSkin(skinUrl) {
    document.querySelectorAll('.skin-thumbnail').forEach(thumb => {
        if (thumb.dataset.skin === skinUrl) {
            thumb.classList.add('active');
        } else {
            thumb.classList.remove('active');
        }
    });
}

function handleLogout() {
    localStorage.removeItem('lastUsername');
    
    window.location.href = '/logout';
}

window.addEventListener('DOMContentLoaded', function() {
    checkAndClearOldUserData();
    
    const skinContainer = document.getElementById('skin_container');
    if (skinContainer && skinContainer.dataset.currentSkin) {
        currentSkin = skinContainer.dataset.currentSkin;
    }
    
    if (skinContainer && skinContainer.dataset.skinHistory) {
        try {
            skinHistoryData = JSON.parse(skinContainer.dataset.skinHistory);
        } catch (e) {
            console.error('Error parsing skin history:', e);
            skinHistoryData = [];
        }
    }
    
    try {
        skinViewer = new skinview3d.SkinViewer({
            canvas: document.getElementById('skin_container'),
            width: 260,
            height: 300,
            skin: currentSkin
        });
        
        skinViewer.autoRotate = true;
        skinViewer.autoRotateSpeed = 0.5;
        skinViewer.zoom = 0.7;
        skinViewer.background = 0x323232;
        
        skinViewer.animation = new skinview3d.IdleAnimation();
        skinViewer.animation.speed = 0.5;
        
        renderDefaultSkins();
        
        renderSkinHistory();
        
        updateActiveSkin(currentSkin);
    } catch (error) {
        console.error('Error initializing skin viewer:', error);
    }
});

function renderDefaultSkins() {
    const gallery = document.getElementById('skin-gallery');
    if (!gallery) return;
    
    gallery.innerHTML = '';
    defaultSkins.forEach(skin => {
        const thumb = document.createElement('div');
        thumb.className = 'skin-thumbnail';
        thumb.dataset.skin = skin.path;
        thumb.title = skin.name;
        thumb.innerHTML = `<img src="${skin.path}" alt="${skin.name}">`;
        thumb.onclick = () => loadSkinInViewer(skin.path);
        gallery.appendChild(thumb);
    });
}

function renderSkinHistory() {
    const historyContainer = document.getElementById('skin-history');
    if (!historyContainer) return;
    
    const history = getSkinHistory();
    
    if (history.length === 0) {
        historyContainer.innerHTML = '<p style="color: #999; font-size: 12px; text-align: center; margin: 0;">История пуста</p>';
        return;
    }
    
    historyContainer.innerHTML = '';
    history.forEach((item, index) => {
        const historyItem = document.createElement('div');
        historyItem.className = 'history-item';
        const skinName = item.name || `Скин ${index + 1}`;
        const timestamp = typeof item.timestamp === 'string' ? new Date(item.timestamp) : new Date(item.timestamp);
        const date = timestamp.toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
        const time = timestamp.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
        historyItem.innerHTML = `
            <img src="${item.url}" alt="${skinName}">
            <div class="history-item-info">
                ${skinName}<br>
                <span style="color: #666; font-size: 11px;">${date} ${time}</span>
            </div>
        `;
        historyItem.onclick = () => loadSkinInViewer(item.url, skinName);
        historyContainer.appendChild(historyItem);
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const skinUpload = document.getElementById('skin-upload');
    if (skinUpload) {
        skinUpload.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const skinUrl = event.target.result;
                    if (skinViewer) {
                        loadSkinInViewer(skinUrl);
                        showMessage('Скин успешно загружен!', 'success');
                    }
                };
                reader.readAsDataURL(file);
            }
        });
    }
});

function resetSkin() {
    if (skinViewer) {
        loadSkinInViewer(defaultSkin);
        showMessage('Скин сброшен на стандартный', 'success');
    }
}

function updateProfile() {
    const newNickname = document.getElementById('new-nickname').value;
    const newEmail = document.getElementById('new-email').value;
    
    if (!newEmail && !newNickname) {
        showMessage('Пожалуйста, введите хотя бы одно поле!', 'error');
        return;
    }
    
    const data = {};
    if (newNickname) data.username = newNickname;
    if (newEmail) data.email = newEmail;
    data.role = 'user'
    
    fetch('/user', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            showMessage('Профиль успешно обновлен!', 'success');
            
            if (data.username && newNickname) {
                document.querySelector('.profile-field .value').textContent = data.username;
            }
            
            if (data.email && newEmail) {
                document.getElementById('email-value').textContent = data.email;
            }

            setTimeout(() => {
                location.reload();
            }, 2000);
        } else {
            showMessage('Ошибка обновления профиля!', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showMessage('Ошибка соединения с сервером!', 'error');
    });
}

function showMessage(text, type) {
    const container = document.getElementById('message-container');
    const messageClass = type === 'success' ? 'success-message' : 'error-message';
    
    container.innerHTML = `<div class="${messageClass}">${text}</div>`;
    
    setTimeout(() => {
        container.innerHTML = '';
    }, 5000);
}
