// 营养分析功能脚本

let currentUserId = null;

// DOM元素
const loginSection = document.getElementById('loginSection');
const requestSection = document.getElementById('requestSection');
const analysisSection = document.getElementById('analysisSection');
const messageArea = document.getElementById('messageArea');

const loginBtn = document.getElementById('loginBtn');
const userIdInput = document.getElementById('userId');
const analyzeBtn = document.getElementById('analyzeBtn');
const mealDataTextarea = document.getElementById('mealData');
const analysisResult = document.getElementById('analysisResult');

// 显示消息
function showMessage(message, type = 'info') {
    messageArea.textContent = message;
    messageArea.className = `message-area ${type}`;
    messageArea.style.display = 'block';
    setTimeout(() => {
        messageArea.className = 'message-area';
        messageArea.style.display = 'none';
    }, 3000);
}

// 用户登录
loginBtn.addEventListener('click', async () => {
    const userId = userIdInput.value.trim();
    
    if (!userId) {
        showMessage('请输入用户ID', 'error');
        return;
    }
    
    loginBtn.disabled = true;
    loginBtn.textContent = '登录中...';
    
    try {
        const response = await fetch('/api/user/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                user_id: userId
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentUserId = userId;
            loginSection.style.display = 'none';
            requestSection.style.display = 'block';
            showMessage(`欢迎，${data.name || userId}！`, 'success');
        } else {
            showMessage(data.message || '登录失败', 'error');
        }
    } catch (error) {
        console.error('登录失败:', error);
        showMessage('登录失败，请检查网络连接', 'error');
    } finally {
        loginBtn.disabled = false;
        loginBtn.textContent = '登录';
    }
});

// 开始分析
analyzeBtn.addEventListener('click', async () => {
    const mealDataText = mealDataTextarea.value.trim();
    
    if (!mealDataText) {
        showMessage('请输入餐食信息', 'error');
        return;
    }
    
    analyzeBtn.disabled = true;
    analyzeBtn.textContent = '分析中...';
    
    try {
        const response = await fetch('/api/analysis/nutrition', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                user_id: currentUserId,
                meal_data: {
                    text: mealDataText
                }
            })
        });
        
        const data = await response.json();
        
        if (data.success && data.analysis) {
            displayAnalysis(data.analysis);
            analysisSection.style.display = 'block';
            showMessage('分析完成！', 'success');
        } else {
            showMessage(data.message || '分析失败', 'error');
        }
    } catch (error) {
        console.error('分析失败:', error);
        showMessage('分析失败，请检查网络连接', 'error');
    } finally {
        analyzeBtn.disabled = false;
        analyzeBtn.textContent = '开始分析';
    }
});

// 显示分析结果
function displayAnalysis(analysis) {
    analysisResult.innerHTML = '';
    
    if (typeof analysis === 'string') {
        // 如果是字符串，直接显示
        analysisResult.innerHTML = `<div class="analysis-section"><p>${escapeHtml(analysis).replace(/\n/g, '<br>')}</p></div>`;
    } else if (analysis.analysis) {
        // 如果有analysis字段
        analysisResult.innerHTML = `<div class="analysis-section"><h4>营养分析</h4><p>${escapeHtml(analysis.analysis).replace(/\n/g, '<br>')}</p></div>`;
    } else {
        // 如果是对象，格式化显示
        for (const [key, value] of Object.entries(analysis)) {
            const section = document.createElement('div');
            section.className = 'analysis-section';
            const displayKey = escapeHtml(key);
            const displayValue = typeof value === 'string' 
                ? escapeHtml(value).replace(/\n/g, '<br>') 
                : escapeHtml(JSON.stringify(value, null, 2));
            section.innerHTML = `<h4>${displayKey}</h4><p>${displayValue}</p>`;
            analysisResult.appendChild(section);
        }
    }
}

// HTML转义函数，防止XSS攻击
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
