// 编辑个人资料页面功能

// 检查BASE_URL是否正确设置，避免请求失败
const BASE_URL = window.HuSNS_EditProfile?.baseUrl || window.location.origin;
const MAX_AVATAR_SIZE = 500;
const MAX_BACKGROUND_WIDTH = 1280;
const MAX_BACKGROUND_HEIGHT = 600;
const COMPRESSION_QUALITY = 0.5;
let selectedAvatarFile = null;
let selectedBackgroundFile = null;

document.addEventListener('DOMContentLoaded', function() {
    loadUserProfile();
    initEventListeners();
});

async function compressImage(file, maxWidth, maxHeight, quality = 0.8) {
    return new Promise((resolve) => {
        const img = new Image();
        img.onload = function() {
            let width = img.width;
            let height = img.height;
            
            if (width > maxWidth || height > maxHeight) {
                const ratio = Math.min(maxWidth / width, maxHeight / height);
                width = Math.round(width * ratio);
                height = Math.round(height * ratio);
            }
            
            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);
            
            canvas.toBlob(blob => {
                if (blob) {
                    const ext = file.name.split('.').pop() || 'jpg';
                    const compressedFile = new File([blob], file.name, {
                        type: blob.type || 'image/jpeg',
                        lastModified: Date.now()
                    });
                    console.log(`压缩: ${file.name} (${(file.size/1024).toFixed(1)}KB) -> ${(compressedFile.size/1024).toFixed(1)}KB, ${width}x${height}`);
                    resolve(compressedFile);
                } else {
                    resolve(file);
                }
            }, 'image/jpeg', quality);
        };
        img.onerror = function() { resolve(file); };
        img.src = URL.createObjectURL(file);
    });
}

// 加载用户信息
async function loadUserProfile() {
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/userInfo');
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.user) {
            const user = result.data.user;
            document.getElementById('usernameInput').value = user.username || '';
            document.getElementById('bioInput').value = user.bio || '';
            updateBioCount();
            
            if (user.avatar) {
                document.getElementById('avatarImg').src = user.avatar;
            }
            
            if (user.background) {
                const backgroundPreview = document.getElementById('backgroundPreview');
                backgroundPreview.innerHTML = `<img src="${user.background}" alt="背景图片">`;
            }
        }
    } catch (error) {
        console.error('加载失败:', error);
        showToast('加载失败，请刷新重试');
    }
}

// 初始化事件
function initEventListeners() {
    document.getElementById('avatarWrap').addEventListener('click', function() {
        document.getElementById('avatarInput').click();
    });
    
    document.getElementById('avatarInput').addEventListener('change', handleAvatarChange);
    
    document.getElementById('backgroundWrap').addEventListener('click', function() {
        document.getElementById('backgroundInput').click();
    });
    
    document.getElementById('backgroundInput').addEventListener('change', handleBackgroundChange);
    
    document.getElementById('bioInput').addEventListener('input', updateBioCount);
    
    document.getElementById('saveBtn').addEventListener('click', saveProfile);
}

// 处理头像选择
async function handleAvatarChange(e) {
    const file = e.target.files[0];
    if (!file) return;
    
    if (!file.type.startsWith('image/')) {
        showToast('请选择图片文件');
        return;
    }
    
    if (file.size > 5 * 1024 * 1024) {
        showToast('图片大小不能超过5MB');
        return;
    }
    
    selectedAvatarFile = await compressImage(file, MAX_AVATAR_SIZE, MAX_AVATAR_SIZE, COMPRESSION_QUALITY);
    
    const reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('avatarImg').src = e.target.result;
    };
    reader.readAsDataURL(selectedAvatarFile);
}

// 处理背景图片选择
async function handleBackgroundChange(e) {
    const file = e.target.files[0];
    if (!file) return;
    
    if (!file.type.startsWith('image/')) {
        showToast('请选择图片文件');
        return;
    }
    
    if (file.size > 5 * 1024 * 1024) {
        showToast('图片大小不能超过5MB');
        return;
    }
    
    selectedBackgroundFile = await compressImage(file, MAX_BACKGROUND_WIDTH, MAX_BACKGROUND_HEIGHT, COMPRESSION_QUALITY);
    
    const reader = new FileReader();
    reader.onload = function(e) {
        const backgroundPreview = document.getElementById('backgroundPreview');
        backgroundPreview.innerHTML = `<img src="${e.target.result}" alt="背景图片">`;
    };
    reader.readAsDataURL(selectedBackgroundFile);
}

// 更新字数统计
function updateBioCount() {
    const bio = document.getElementById('bioInput').value;
    document.getElementById('bioCount').textContent = bio.length;
}

// 保存资料
async function saveProfile() {
    const username = document.getElementById('usernameInput').value.trim();
    const bio = document.getElementById('bioInput').value.trim();
    
    if (!username) {
        showToast('用户名不能为空');
        return;
    }
    
    if (username.length < 2 || username.length > 20) {
        showToast('用户名长度需在2-20个字符之间');
        return;
    }
    
    if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(username)) {
        showToast('用户名只能包含字母、数字、下划线和中文');
        return;
    }
    
    const saveBtn = document.getElementById('saveBtn');
    const loadingMask = document.getElementById('loadingMask');
    
    saveBtn.disabled = true;
    loadingMask.classList.add('active');
    
    try {
        const formData = new FormData();
        formData.append('username', username);
        formData.append('bio', bio);
        
        if (selectedAvatarFile) {
            formData.append('avatar', selectedAvatarFile);
        }
        
        if (selectedBackgroundFile) {
            formData.append('background', selectedBackgroundFile);
        }
        
        const response = await fetch(BASE_URL + '/?r=mobileApi/updateProfile', {
            method: 'POST',
            credentials: 'include',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            showToast('保存成功');
            setTimeout(function() {
                window.location.href = BASE_URL + '/?r=mobile/profile';
            }, 1500);
        } else {
            showToast(data.message || '保存失败');
        }
    } catch (error) {
        console.error('保存失败:', error);
        showToast('网络错误，请重试');
    } finally {
        saveBtn.disabled = false;
        loadingMask.classList.remove('active');
    }
}

// Toast提示
function showToast(msg) {
    const t = document.createElement('div');
    t.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.75);color:#fff;padding:12px 24px;border-radius:8px;font-size:14px;z-index:10000;';
    t.textContent = msg;
    document.body.appendChild(t);
    setTimeout(() => {
        t.style.opacity = '0';
        t.style.transition = 'opacity 0.3s';
        setTimeout(() => t.remove(), 300);
    }, 2000);
}