// Device Doctor Dashboard - Professional Developer Experience

const API_URL = '/api/health';

// Chart instances
let cpuChart = null;
let memoryChart = null;
let diskChart = null;

// Chart.js default configuration
const chartDefaults = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
        legend: { display: false },
        tooltip: {
            backgroundColor: '#1f1f1f',
            titleColor: '#e8e8e8',
            bodyColor: '#9ca3af',
            borderColor: '#2a2a2a',
            borderWidth: 1,
            padding: 10,
            cornerRadius: 4,
            displayColors: false
        }
    }
};

// Scanning steps
const SCAN_STEPS = [
    'Scanning system configuration…',
    'Scanning CPU & memory health…',
    'Scanning disk usage & integrity…',
    'Scanning application stability…',
    'Scanning network connectivity…',
    'Scanning driver stability…',
    'Scanning hardware health…',
    'Analyzing patterns…',
    'Generating health score…',
    'Preparing diagnostic report…'
];

// Chat state
let chatState = {
    selectedIssue: null,
    dashboardState: null,
    conversationHistory: [] // Array of {question, answer, timestamp}
};

// AI Provider settings
let aiSettings = {
    provider: 'ollama',
    apiKey: '',
    model: ''
};

// Initialize dashboard
document.addEventListener('DOMContentLoaded', () => {
    loadAISettings();
    initializeSettingsModal();
    startScanning();
    initializeChat();
});

/**
 * Start scanning experience
 */
async function startScanning() {
    const scanningSection = document.getElementById('scanningSection');
    const timeline = document.getElementById('scanningTimeline');
    
    // Clear timeline
    timeline.innerHTML = '';
    
    // Show scanning section
    scanningSection.style.display = 'block';
    
    // Start API call
    const apiPromise = fetch(API_URL);
    
    // Simulate scanning steps
    for (let i = 0; i < SCAN_STEPS.length; i++) {
        const step = createScanStep(SCAN_STEPS[i], i === 0);
        timeline.appendChild(step);
        
        // Wait for step animation
        await sleep(300 + Math.random() * 200);
        
        // Mark previous step as completed
        if (i > 0) {
            const prevStep = timeline.children[i - 1];
            prevStep.classList.remove('active');
            prevStep.classList.add('completed');
            prevStep.querySelector('.step-status').textContent = '✓';
        }
        
        // Mark current step as active
        if (i < SCAN_STEPS.length - 1) {
            step.classList.add('active');
            step.querySelector('.step-status').textContent = '⏳';
        }
    }
    
    // Wait for API response
    try {
        const response = await apiPromise;
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        
        // Complete final step
        const lastStep = timeline.children[SCAN_STEPS.length - 1];
        lastStep.classList.remove('active');
        lastStep.classList.add('completed');
        lastStep.querySelector('.step-status').textContent = '✓';
        
        // Show completion message
        await sleep(500);
        showScanComplete();
        await sleep(800);
        
        // Render results
        renderSystemConfiguration(data.telemetry);
        renderDashboard(data);
        
    } catch (error) {
        console.error('Error loading dashboard:', error);
        showError('Failed to load diagnostic data. Please ensure the API server is running.');
    }
}

/**
 * Create a scan step element
 */
function createScanStep(text, isFirst = false) {
    const step = document.createElement('div');
    step.className = 'scan-step';
    if (isFirst) step.classList.add('active');
    step.innerHTML = `
        <span class="step-status">${isFirst ? '⏳' : '○'}</span>
        <span class="step-text">${text}</span>
    `;
    return step;
}

/**
 * Show scan complete message
 */
function showScanComplete() {
    const timeline = document.getElementById('scanningTimeline');
    const complete = document.createElement('div');
    complete.className = 'scan-complete';
    complete.textContent = 'Scan completed successfully';
    timeline.appendChild(complete);
}

/**
 * Sleep utility
 */
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * Render system configuration
 */
function renderSystemConfiguration(telemetry) {
    const section = document.getElementById('systemConfigSection');
    const grid = document.getElementById('configGrid');
    
    const os = telemetry.os || {};
    const cpu = telemetry.cpu || {};
    const memory = telemetry.memory || {};
    const disk = telemetry.disk || [];
    const battery = telemetry.battery || {};
    const uptime = telemetry.uptime || {};
    
    const configs = [
        { label: 'Operating System', value: `${os.name || 'Unknown'} ${os.release || ''}` },
        { label: 'Architecture', value: os.arch || 'Unknown' },
        { label: 'Platform', value: os.type || 'Unknown' },
        { label: 'CPU Cores', value: `${cpu.count || 'Unknown'} cores` },
        { label: 'Total RAM', value: `${memory.total_gb || 0} GB` },
        { label: 'Primary Disk', value: disk[0] ? `${disk[0].total_gb || 0} GB (${disk[0].fstype || 'Unknown'})` : 'Unknown' },
        { label: 'System Uptime', value: `${uptime.days || 0} days` },
    ];
    
    if (battery && battery.percent !== undefined) {
        configs.push({ 
            label: 'Battery', 
            value: `${Math.round(battery.percent)}% ${battery.plugged ? '(plugged)' : '(not plugged)'}` 
        });
    }
    
    grid.innerHTML = configs.map(config => `
        <div class="config-item">
            <div class="config-label">${config.label}</div>
            <div class="config-value">${config.value}</div>
        </div>
    `).join('');
    
    section.style.display = 'block';
}

/**
 * Load dashboard data from API
 */
async function loadDashboard() {
    try {
        const response = await fetch(API_URL);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        renderDashboard(data);
    } catch (error) {
        console.error('Error loading dashboard:', error);
        showError('Failed to load diagnostic data. Please ensure the API server is running.');
    }
}

/**
 * Render dashboard with data
 */
function renderDashboard(data) {
    // Hide scanning section
    document.getElementById('scanningSection').style.display = 'none';
    
    // Show results dashboard
    document.getElementById('resultsDashboard').style.display = 'block';
    
    // Store dashboard state for chat
    chatState.dashboardState = data;
    
    updateStatusIndicator(data.health_score);
    renderHealthScore(data.health_score, data.summary, data.symptoms);
    renderTelemetry(data.telemetry);
    renderIssues(data.issues, data.symptoms, data.telemetry, data.top_contributors);
    renderSuggestedFixes(data.issues, data.top_contributors);
    renderDiagnosticScope(data.not_checked);
    updateTimestamp(data.timestamp);
}

/**
 * Update status indicator
 */
function updateStatusIndicator(healthScore) {
    const indicator = document.getElementById('statusIndicator');
    const dot = indicator.querySelector('.status-dot');
    const text = indicator.querySelector('.status-text');
    
    const status = healthScore.status;
    const statusMap = {
        'excellent': { class: 'healthy', text: 'Healthy' },
        'good': { class: 'healthy', text: 'Healthy' },
        'fair': { class: 'attention', text: 'Attention' },
        'poor': { class: 'attention', text: 'Attention' },
        'critical': { class: 'critical', text: 'Critical' }
    };
    
    const statusInfo = statusMap[status] || { class: 'attention', text: 'Unknown' };
    
    dot.className = 'status-dot';
    dot.classList.add(statusInfo.class);
    text.textContent = statusInfo.text;
}

/**
 * Render health score section
 */
function renderHealthScore(healthScore, summary, symptoms) {
    const scoreNumber = document.getElementById('scoreNumber');
    const scoreGrade = document.getElementById('scoreGrade');
    const scoreStatus = document.getElementById('scoreStatus');
    const scoreExplanation = document.getElementById('scoreExplanation');
    const scoreCircle = document.querySelector('.score-circle');
    
    const score = Math.round(healthScore.score);
    const grade = healthScore.grade;
    const status = healthScore.status;
    
    scoreNumber.textContent = score;
    scoreGrade.textContent = grade;
    scoreStatus.textContent = status.charAt(0).toUpperCase() + status.slice(1);
    
    const explanations = {
        'excellent': 'System is operating within normal parameters.',
        'good': 'System health is good with minor observations.',
        'fair': 'System may benefit from attention to detected issues.',
        'poor': 'System health requires attention.',
        'critical': 'System health needs immediate review.'
    };
    scoreExplanation.textContent = summary || explanations[status] || 'System health assessment complete.';
    
    scoreCircle.className = 'score-circle';
    if (score >= 75) {
        scoreCircle.classList.add('healthy');
    } else if (score >= 40) {
        scoreCircle.classList.add('warning');
    } else {
        scoreCircle.classList.add('critical');
    }
    
    renderScoreBreakdown(healthScore, symptoms);
}

/**
 * Render health score breakdown
 */
function renderScoreBreakdown(healthScore, symptoms) {
    const breakdownContainer = document.getElementById('scoreBreakdown');
    const toggleButton = document.getElementById('scoreBreakdownToggle');
    
    if (!healthScore.breakdown || Object.keys(healthScore.breakdown).length === 0) {
        toggleButton.style.display = 'none';
        return;
    }
    
    toggleButton.addEventListener('click', () => {
        const isExpanded = breakdownContainer.style.display !== 'none';
        breakdownContainer.style.display = isExpanded ? 'none' : 'block';
        toggleButton.classList.toggle('expanded', !isExpanded);
        const toggleText = toggleButton.querySelector('.breakdown-toggle-text');
        toggleText.textContent = isExpanded ? 'Show breakdown' : 'Hide breakdown';
    });
    
    const breakdown = healthScore.breakdown;
    const totalPenalty = healthScore.total_penalty || 0;
    const baseScore = 100;
    
    let html = '';
    
    for (const [category, data] of Object.entries(breakdown)) {
        const penalty = data.penalty || 0;
        const count = data.count || 0;
        const severity = data.max_severity || 'low';
        
        const categoryName = category.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
        html += `
            <div class="score-breakdown-item">
                <span class="score-breakdown-label">${categoryName}:</span>
                <span class="score-breakdown-value">-${penalty} (${count} ${count === 1 ? 'symptom' : 'symptoms'}, ${severity})</span>
            </div>
        `;
    }
    
    html += `
        <div class="score-breakdown-item" style="margin-top: 0.5rem; padding-top: 0.5rem; border-top: 1px solid var(--border); font-weight: 500;">
            <span class="score-breakdown-label">Total penalty:</span>
            <span class="score-breakdown-value">-${totalPenalty}</span>
        </div>
        <div class="score-breakdown-item">
            <span class="score-breakdown-label">Final score:</span>
            <span class="score-breakdown-value">${baseScore} - ${totalPenalty} = ${Math.round(healthScore.score)}</span>
        </div>
    `;
    
    breakdownContainer.innerHTML = html;
}

/**
 * Render telemetry charts
 */
function renderTelemetry(telemetry) {
    const cpuValue = telemetry.cpu?.average || 0;
    document.getElementById('cpuValue').textContent = Math.round(cpuValue);
    renderCPUChart(telemetry.cpu);
    
    const memoryValue = telemetry.memory?.percent || 0;
    document.getElementById('memoryValue').textContent = Math.round(memoryValue);
    renderMemoryChart(telemetry.memory);
    
    const primaryDisk = telemetry.disk?.[0] || {};
    const diskValue = primaryDisk.percent || 0;
    document.getElementById('diskValue').textContent = Math.round(diskValue);
    renderDiskChart(telemetry.disk);
}

/**
 * Render CPU chart
 */
function renderCPUChart(cpuData) {
    const ctx = document.getElementById('cpuChart').getContext('2d');
    
    if (cpuChart) {
        cpuChart.destroy();
    }
    
    const samples = cpuData?.samples || [cpuData?.average || 0];
    const labels = samples.map((_, i) => i + 1);
    
    cpuChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'CPU %',
                data: samples,
                borderColor: '#14b8a6',
                backgroundColor: 'rgba(20, 184, 166, 0.08)',
                tension: 0.3,
                fill: true,
                borderWidth: 2,
                pointRadius: 0,
                pointHoverRadius: 4
            }]
        },
        options: {
            ...chartDefaults,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: { 
                        color: '#6b7280',
                        font: { size: 11 },
                        stepSize: 25
                    },
                    grid: { 
                        color: '#2a2a2a',
                        drawBorder: false
                    }
                },
                x: {
                    ticks: { 
                        color: '#6b7280',
                        font: { size: 11 }
                    },
                    grid: { 
                        display: false,
                        drawBorder: false
                    }
                }
            }
        }
    });
}

/**
 * Render Memory chart
 */
function renderMemoryChart(memoryData) {
    const ctx = document.getElementById('memoryChart').getContext('2d');
    
    if (memoryChart) {
        memoryChart.destroy();
    }
    
    const used = memoryData?.percent || 0;
    const free = 100 - used;
    
    let color = '#14b8a6';
    if (used > 90) {
        color = '#dc2626';
    } else if (used > 80) {
        color = '#f59e0b';
    }
    
    memoryChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Used', 'Free'],
            datasets: [{
                data: [used, free],
                backgroundColor: [color, '#2a2a2a'],
                borderWidth: 0,
                cutout: '70%'
            }]
        },
        options: {
            ...chartDefaults,
            cutoutPercentage: 70
        }
    });
}

/**
 * Render Disk chart
 */
function renderDiskChart(diskData) {
    const ctx = document.getElementById('diskChart').getContext('2d');
    
    if (diskChart) {
        diskChart.destroy();
    }
    
    if (!diskData || diskData.length === 0) {
        return;
    }
    
    const sortedDisks = [...diskData]
        .sort((a, b) => (b.percent || 0) - (a.percent || 0))
        .slice(0, 5);
    
    diskChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedDisks.map(d => {
                const mount = d.mountpoint || '';
                return mount.split('/').pop() || 'Root';
            }),
            datasets: [{
                label: 'Usage %',
                data: sortedDisks.map(d => d.percent || 0),
                backgroundColor: sortedDisks.map(d => {
                    const pct = d.percent || 0;
                    if (pct > 90) return '#dc2626';
                    if (pct > 80) return '#f59e0b';
                    return '#14b8a6';
                }),
                borderRadius: 2,
                maxBarThickness: 40
            }]
        },
        options: {
            ...chartDefaults,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: { 
                        color: '#6b7280',
                        font: { size: 11 },
                        stepSize: 25
                    },
                    grid: { 
                        color: '#2a2a2a',
                        drawBorder: false
                    }
                },
                x: {
                    ticks: { 
                        color: '#6b7280',
                        font: { size: 11 },
                        maxRotation: 45,
                        minRotation: 0
                    },
                    grid: { 
                        display: false,
                        drawBorder: false
                    }
                }
            }
        }
    });
}

/**
 * Generate evidence-based confidence line
 */
function generateEvidence(issue, symptoms, telemetry) {
    const confidence = issue.confidence || 0;
    let confidenceLevel = 'Low';
    if (confidence >= 0.8) confidenceLevel = 'High';
    else if (confidence >= 0.6) confidenceLevel = 'Medium';
    
    let evidence = '';
    
    for (const symptom of symptoms || []) {
        const symptomType = symptom.type.toLowerCase();
        const issueNameLower = issue.name.toLowerCase();
        
        if (issueNameLower.includes('memory') || symptomType.includes('memory')) {
            const memPercent = telemetry?.memory?.percent || 0;
            if (memPercent > 0) {
                evidence = `based on memory usage ${Math.round(memPercent)}%`;
                if (memPercent > 85) {
                    evidence += ' sustained above 85%';
                } else if (memPercent > 75) {
                    evidence += ' above 75%';
                }
                break;
            }
        } else if (issueNameLower.includes('cpu') || symptomType.includes('cpu')) {
            const cpuAvg = telemetry?.cpu?.average || 0;
            if (cpuAvg > 0) {
                evidence = `based on CPU usage ${Math.round(cpuAvg)}% average`;
                if (cpuAvg > 85) {
                    evidence += ' sustained above 85%';
                }
                break;
            }
        } else if (issueNameLower.includes('disk') || symptomType.includes('disk')) {
            const diskData = telemetry?.disk?.[0];
            if (diskData && diskData.percent) {
                evidence = `based on disk usage ${Math.round(diskData.percent)}% on ${diskData.mountpoint || 'primary partition'}`;
                break;
            }
        } else if (issueNameLower.includes('network')) {
            evidence = 'based on network connectivity checks';
            break;
        } else if (issueNameLower.includes('security')) {
            evidence = 'based on security posture observations';
            break;
        }
    }
    
    if (!evidence) {
        evidence = 'based on detected symptoms';
    }
    
    return `${confidenceLevel} (${evidence})`;
}

/**
 * Get top contributors for a specific issue
 */
function getTopContributorsForIssue(issue, topContributors) {
    if (!topContributors) {
        return { memory: [], cpu: [] };
    }
    
    const issueNameLower = issue.name.toLowerCase();
    const contributors = {
        memory: [],
        cpu: []
    };
    
    if (issueNameLower.includes('memory') || issueNameLower.includes('pressure')) {
        contributors.memory = (topContributors.top_memory_processes || []).slice(0, 5);
    }
    
    if (issueNameLower.includes('cpu') || issueNameLower.includes('pressure')) {
        contributors.cpu = (topContributors.top_cpu_processes || []).slice(0, 5);
    }
    
    // If issue mentions performance but not specific resource, show both
    if (issueNameLower.includes('performance') && !issueNameLower.includes('memory') && !issueNameLower.includes('cpu')) {
        contributors.memory = (topContributors.top_memory_processes || []).slice(0, 3);
        contributors.cpu = (topContributors.top_cpu_processes || []).slice(0, 3);
    }
    
    return contributors;
}

/**
 * Render top contributors section
 */
function renderTopContributors(contributors, issueName) {
    const issueNameLower = issueName.toLowerCase();
    const hasMemory = issueNameLower.includes('memory') || issueNameLower.includes('pressure');
    const hasCPU = issueNameLower.includes('cpu') || issueNameLower.includes('pressure');
    
    let html = '';
    
    if (hasMemory && contributors.memory.length > 0) {
        html += '<div class="contributors-group">';
        html += '<div class="contributors-label">Top Memory Contributors:</div>';
        html += '<ul class="contributors-list">';
        contributors.memory.forEach(proc => {
            const memDisplay = proc.memory_gb 
                ? `${proc.memory_gb} GB` 
                : `${proc.memory_mb} MB`;
            html += `<li><span class="contributor-name">${proc.name}</span> — <span class="contributor-value">${proc.percent}%</span> (${memDisplay})</li>`;
        });
        html += '</ul></div>';
    }
    
    if (hasCPU && contributors.cpu.length > 0) {
        html += '<div class="contributors-group">';
        html += '<div class="contributors-label">Top CPU Contributors:</div>';
        html += '<ul class="contributors-list">';
        contributors.cpu.forEach(proc => {
            html += `<li><span class="contributor-name">${proc.name}</span> — <span class="contributor-value">${proc.cpu_percent}%</span></li>`;
        });
        html += '</ul></div>';
    }
    
    return html;
}

/**
 * Render issues list
 */
function renderIssues(issues, symptoms, telemetry, topContributors) {
    const container = document.getElementById('issuesList');
    
    if (!issues || issues.length === 0) {
        container.innerHTML = '<p class="empty-state">No issues detected. System is operating normally.</p>';
        return;
    }
    
    container.innerHTML = issues.map(issue => {
        const urgency = issue.urgency || 'low';
        const confidence = Math.round((issue.confidence || 0) * 100);
        const evidence = generateEvidence(issue, symptoms, telemetry);
        const contributors = getTopContributorsForIssue(issue, topContributors);
        const topContributorsHtml = renderTopContributors(contributors, issue.name);
        
        let confidenceText = `${confidence}%`;
        if (confidence >= 80) {
            confidenceText += ' (High confidence)';
        } else if (confidence >= 60) {
            confidenceText += ' (Moderate confidence)';
        } else {
            confidenceText += ' (Low confidence)';
        }
        
        return `
            <div class="issue-item" data-issue-id="${issue.name}" style="cursor: pointer;" title="Click to ask about this issue">
                <div class="issue-header">
                    <div>
                        <div class="issue-name">${issue.name}</div>
                    </div>
                    <span class="issue-urgency ${urgency}">${urgency}</span>
                </div>
                <div class="issue-explanation">${issue.explanation}</div>
                
                ${topContributorsHtml ? `
                    <div class="issue-section">
                        <div class="issue-section-title">Top Contributors</div>
                        ${topContributorsHtml}
                    </div>
                ` : ''}
                
                ${issue.likely_causes && issue.likely_causes.length > 0 ? `
                    <div class="issue-section">
                        <div class="issue-section-title">Likely Causes</div>
                        <ul class="issue-list">
                            ${issue.likely_causes.map(cause => `<li>${cause}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
                
                <div class="issue-evidence">
                    <span class="issue-evidence-label">Confidence:</span>
                    <span class="issue-evidence-text">${evidence}</span>
                </div>
                <div class="issue-confidence">Confidence level: ${confidenceText}</div>
            </div>
        `;
    }).join('');
    
    // Add click handlers to issue items
    container.querySelectorAll('.issue-item').forEach(item => {
        item.addEventListener('click', () => {
            const issueName = item.getAttribute('data-issue-id');
            const issue = issues.find(i => i.name === issueName);
            if (issue) {
                selectIssueForChat(issue);
            }
        });
    });
}

/**
 * Generate contextual suggestions based on top contributors
 */
function generateContextualSuggestions(issue, topContributors) {
    if (!topContributors) {
        return [];
    }
    
    const issueNameLower = issue.name.toLowerCase();
    const suggestions = [];
    const contributors = getTopContributorsForIssue(issue, topContributors);
    
    // Memory-related suggestions
    if ((issueNameLower.includes('memory') || issueNameLower.includes('pressure')) && contributors.memory.length > 0) {
        contributors.memory.slice(0, 3).forEach(proc => {
            const procName = proc.name.toLowerCase();
            
            if (procName.includes('chrome') || procName.includes('firefox') || procName.includes('safari') || procName.includes('edge') || procName.includes('brave')) {
                if (!suggestions.some(s => s.includes('browser tabs'))) {
                    suggestions.push(`Close unused browser tabs in ${proc.name.split('(')[0].trim()}`);
                }
                if (!suggestions.some(s => s.includes('extensions'))) {
                    suggestions.push(`Disable heavy browser extensions`);
                }
            } else if (procName.includes('slack') || procName.includes('discord') || procName.includes('teams')) {
                suggestions.push(`Restart ${proc.name.split('(')[0].trim()} to free up memory`);
            } else if (procName.includes('docker') || procName.includes('kubectl')) {
                suggestions.push(`Stop unused containers or reduce workload in ${proc.name.split('(')[0].trim()}`);
            } else if (proc.type === 'development') {
                suggestions.push(`Review and optimize workload in ${proc.name.split('(')[0].trim()}`);
            } else if (proc.type === 'user' && proc.percent > 2) {
                suggestions.push(`Close ${proc.name.split('(')[0].trim()} if not needed, or restart it`);
            }
        });
    }
    
    // CPU-related suggestions
    if ((issueNameLower.includes('cpu') || issueNameLower.includes('pressure')) && contributors.cpu.length > 0) {
        contributors.cpu.slice(0, 3).forEach(proc => {
            const procName = proc.name.toLowerCase();
            
            if (procName.includes('docker') || procName.includes('kubectl')) {
                suggestions.push(`Reduce container workload or stop unused containers in ${proc.name.split('(')[0].trim()}`);
            } else if (procName.includes('code') || procName.includes('xcode') || procName.includes('android') || procName.includes('cursor')) {
                suggestions.push(`Close unused projects or reduce background indexing in ${proc.name.split('(')[0].trim()}`);
            } else if (proc.type === 'development' && proc.cpu_percent > 10) {
                suggestions.push(`Pause or reduce background tasks in ${proc.name.split('(')[0].trim()}`);
            } else if (proc.type === 'user' && proc.cpu_percent > 50) {
                suggestions.push(`Restart ${proc.name.split('(')[0].trim()} if it's been running for a long time`);
            }
        });
    }
    
    // Remove duplicates and limit
    return [...new Set(suggestions)].slice(0, 5);
}

/**
 * Get best practices for an issue
 */
function getBestPracticesForIssue(issue) {
    const issueNameLower = issue.name.toLowerCase();
    const practices = [];
    
    if (issueNameLower.includes('memory')) {
        practices.push('Keep at least 20–25% RAM free during normal operation');
        practices.push('Restart long-running applications periodically to clear memory leaks');
        practices.push('Avoid auto-starting heavy applications on system boot');
        practices.push('Monitor recurring high-memory applications and investigate root causes');
    }
    
    if (issueNameLower.includes('cpu')) {
        practices.push('Monitor CPU-intensive applications and optimize their workloads');
        practices.push('Avoid running multiple heavy development tools simultaneously');
        practices.push('Restart applications that show sustained high CPU usage');
        practices.push('Review background processes and disable unnecessary ones');
    }
    
    if (issueNameLower.includes('pressure') || issueNameLower.includes('performance')) {
        practices.push('Maintain system resources within recommended thresholds');
        practices.push('Restart the system periodically to clear accumulated resource pressure');
    }
    
    return practices;
}

/**
 * Render suggested fixes
 */
function renderSuggestedFixes(issues, topContributors) {
    const section = document.getElementById('fixesSection');
    const container = document.getElementById('fixesList');
    
    if (!issues || issues.length === 0) {
        section.style.display = 'none';
        return;
    }
    
    section.style.display = 'block';
    
    container.innerHTML = issues.map(issue => {
        const baseRecommendations = issue.recommendations || [];
        const contextualSuggestions = generateContextualSuggestions(issue, topContributors);
        const allRecommendations = [...baseRecommendations, ...contextualSuggestions];
        const bestPractices = getBestPracticesForIssue(issue);
        
        if (allRecommendations.length === 0 && bestPractices.length === 0) {
            return '';
        }
        
        let html = `
            <div class="fix-item">
                <div class="fix-item-title">${issue.name}</div>
        `;
        
        if (allRecommendations.length > 0) {
            html += `
                <ul class="fix-steps">
                    ${allRecommendations.map(rec => `<li>${rec}</li>`).join('')}
                </ul>
            `;
        }
        
        if (bestPractices.length > 0) {
            html += `
                <div class="fix-best-practices">
                    <div class="fix-best-practices-title">Best Practices:</div>
                    <ul class="fix-best-practices-list">
                        ${bestPractices.map(practice => `<li>${practice}</li>`).join('')}
                    </ul>
                </div>
            `;
        }
        
        html += '</div>';
        return html;
    }).filter(html => html).join('');
}

/**
 * Render diagnostic scope
 */
function renderDiagnosticScope(notChecked) {
    const list = document.getElementById('notCheckedList');
    
    if (!notChecked || notChecked.length === 0) {
        list.innerHTML = '<li>All available diagnostic areas were evaluated.</li>';
        return;
    }
    
    list.innerHTML = notChecked.map(item => `<li>${item}</li>`).join('');
}

/**
 * Update timestamp
 */
function updateTimestamp(timestamp) {
    const timeElement = document.getElementById('lastScanTime');
    if (timestamp) {
        const date = new Date(timestamp * 1000);
        const options = { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric', 
            hour: '2-digit', 
            minute: '2-digit' 
        };
        timeElement.textContent = date.toLocaleString('en-US', options);
    } else {
        timeElement.textContent = 'Just now';
    }
}

/**
 * Show error message
 */
function showError(message) {
    const mainContent = document.querySelector('.main-content');
    mainContent.innerHTML = `
        <div class="card" style="text-align: center; padding: 3rem;">
            <h2 style="color: #dc2626; margin-bottom: 1rem;">Connection Error</h2>
            <p style="color: #9ca3af; margin-bottom: 1rem;">${message}</p>
            <p style="color: #6b7280; margin-top: 1rem; font-size: 0.8125rem;">
                Ensure the API server is running:<br>
                <code style="background: #1a1a1a; padding: 0.375rem 0.75rem; border-radius: 0.25rem; font-family: monospace; display: inline-block; margin-top: 0.5rem;">python api_server.py</code>
            </p>
        </div>
    `;
}

/**
 * Initialize diagnostic panel
 */
function initializeChat() {
    const panel = document.getElementById('diagnosticPanel');
    const panelBar = document.getElementById('panelBar');
    const panelToggle = document.getElementById('panelToggle');
    const panelCloseBtn = document.getElementById('panelCloseBtn');
    const panelExpandBtn = document.getElementById('panelExpandBtn');
    const panelInput = document.getElementById('panelInput');
    const quickQuestionBtns = document.querySelectorAll('.quick-question-btn');
    
    if (!panel) {
        console.error('Diagnostic panel not found in DOM');
        return;
    }
    
    // Panel bar click to expand
    panelBar.addEventListener('click', (e) => {
        if (e.target === panelToggle || panelToggle.contains(e.target)) {
            return; // Let toggle button handle it
        }
        expandPanel();
    });
    
    // Toggle button
    panelToggle.addEventListener('click', (e) => {
        e.stopPropagation();
        if (panel.classList.contains('collapsed')) {
            expandPanel();
        } else {
            collapsePanel();
        }
    });
    
    // Close button
    panelCloseBtn.addEventListener('click', () => {
        collapsePanel();
    });
    
    // Expand to full height
    panelExpandBtn.addEventListener('click', () => {
        if (panel.classList.contains('full-height')) {
            panel.classList.remove('full-height');
            panel.classList.add('expanded');
            document.body.classList.remove('panel-full-height');
            document.body.classList.add('panel-expanded');
        } else {
            panel.classList.remove('expanded');
            panel.classList.add('full-height');
            document.body.classList.remove('panel-expanded');
            document.body.classList.add('panel-full-height');
        }
    });
    
    // ESC key to collapse
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !panel.classList.contains('collapsed')) {
            collapsePanel();
        }
    });
    
    // Send message on Enter key
    panelInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendPanelMessage();
        }
    });
    
    // Handle quick question buttons
    quickQuestionBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const question = btn.getAttribute('data-question');
            panelInput.value = question;
            sendPanelMessage();
        });
    });
}

function expandPanel() {
    const panel = document.getElementById('diagnosticPanel');
    panel.classList.remove('collapsed');
    panel.classList.add('expanded');
    document.body.classList.add('panel-expanded');
}

function collapsePanel() {
    const panel = document.getElementById('diagnosticPanel');
    panel.classList.remove('expanded', 'full-height');
    panel.classList.add('collapsed');
    document.body.classList.remove('panel-expanded', 'panel-full-height');
}

/**
 * Select issue for panel context
 */
function selectIssueForChat(issue) {
    // Only clear history if selecting a different issue
    if (chatState.selectedIssue && chatState.selectedIssue.name !== issue.name) {
        chatState.conversationHistory = [];
    }
    
    chatState.selectedIssue = issue;
    
    // Update context indicator
    const contextValue = document.getElementById('contextValue');
    const panelContext = document.getElementById('panelContext');
    if (contextValue) contextValue.textContent = issue.name;
    if (panelContext) panelContext.textContent = `Explaining: ${issue.name}`;
    
    // Expand panel if collapsed
    const panel = document.getElementById('diagnosticPanel');
    if (panel.classList.contains('collapsed')) {
        expandPanel();
    }
    
    // Load initial explanation only if history is empty
    if (chatState.conversationHistory.length === 0) {
        loadIssueExplanation(issue);
    } else {
        // Just render existing history
        renderConversationHistory();
        scrollPanelToBottom();
    }
}

/**
 * Load explanation for selected issue
 */
async function loadIssueExplanation(issue) {
    // Clear conversation history when selecting a new issue
    chatState.conversationHistory = [];
    
    const explanationContainer = document.getElementById('panelExplanation');
    
    // Show loading
    explanationContainer.innerHTML = '<div class="explanation-placeholder"><p>Loading explanation...</p></div>';
    
    try {
        const response = await callChatAPI(
            'What does this mean?',
            issue,
            chatState.dashboardState || {}
        );
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // Add to conversation history
        chatState.conversationHistory.push({
            question: 'What does this mean?',
            answer: data.answer,
            timestamp: Date.now()
        });
        
        renderConversationHistory();
        
    } catch (error) {
        console.error('Error loading explanation:', error);
        explanationContainer.innerHTML = '<div class="explanation-placeholder"><p>Sorry, I encountered an error. Please try again.</p></div>';
    }
}

/**
 * Send panel message
 */
async function sendPanelMessage() {
    const panelInput = document.getElementById('panelInput');
    const question = panelInput.value.trim();
    
    if (!question || !chatState.selectedIssue) {
        return;
    }
    
    // Clear input
    panelInput.value = '';
    
    const explanationContainer = document.getElementById('panelExplanation');
    
    // Add user question to history immediately
    chatState.conversationHistory.push({
        question: question,
        answer: null, // Will be filled when response arrives
        timestamp: Date.now()
    });
    
    // Render with loading state
    renderConversationHistory();
    
    // Scroll to bottom to show loading
    scrollPanelToBottom();
    
    try {
        const response = await callChatAPI(
            question,
            chatState.selectedIssue,
            chatState.dashboardState || {}
        );
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // Update the last entry with the answer
        const lastEntry = chatState.conversationHistory[chatState.conversationHistory.length - 1];
        if (lastEntry && !lastEntry.answer) {
            lastEntry.answer = data.answer;
        }
        
        renderConversationHistory();
        scrollPanelToBottom();
        
    } catch (error) {
        console.error('Error sending message:', error);
        // Update last entry with error
        const lastEntry = chatState.conversationHistory[chatState.conversationHistory.length - 1];
        if (lastEntry) {
            lastEntry.answer = 'Sorry, I encountered an error. Please try again.';
        }
        renderConversationHistory();
    }
}

/**
 * Render conversation history
 */
function renderConversationHistory() {
    const explanationContainer = document.getElementById('panelExplanation');
    
    if (chatState.conversationHistory.length === 0) {
        explanationContainer.innerHTML = `
            <div class="explanation-placeholder">
                <p>Select an issue from the dashboard to view a detailed explanation.</p>
                <p>Or use the quick questions below to explore diagnostic findings.</p>
            </div>
        `;
        return;
    }
    
    let html = '<div class="conversation-history">';
    
    chatState.conversationHistory.forEach((entry, index) => {
        // User question
        html += `
            <div class="conversation-entry">
                <div class="conversation-question">
                    <div class="conversation-label">Question:</div>
                    <div class="conversation-text">${escapeHtml(entry.question)}</div>
                </div>
        `;
        
        // Assistant answer
        if (entry.answer) {
            html += `
                <div class="conversation-answer">
                    <div class="conversation-label">Answer:</div>
                    <div class="conversation-text">${formatExplanation(entry.answer)}</div>
                </div>
            `;
        } else {
            // Loading state
            html += `
                <div class="conversation-answer">
                    <div class="conversation-label">Answer:</div>
                    <div class="conversation-text">
                        <div class="explanation-placeholder">
                            <p>Thinking...</p>
                        </div>
                    </div>
                </div>
            `;
        }
        
        html += '</div>';
        
        // Add separator between entries (except last)
        if (index < chatState.conversationHistory.length - 1) {
            html += '<div class="conversation-separator"></div>';
        }
    });
    
    html += '</div>';
    explanationContainer.innerHTML = html;
}

/**
 * Format explanation content (markdown to HTML)
 */
function formatExplanation(content) {
    // Convert markdown-like formatting to HTML
    let htmlContent = content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code>$1</code>');
    
    // Convert to structured HTML
    const paragraphs = htmlContent.split('\n\n');
    let html = '<div class="explanation-content">';
    
    paragraphs.forEach(p => {
        const trimmed = p.trim();
        if (!trimmed) return;
        
        if (trimmed.startsWith('## ')) {
            html += `<h2>${trimmed.substring(3)}</h2>`;
        } else if (trimmed.startsWith('### ')) {
            html += `<h3>${trimmed.substring(4)}</h3>`;
        } else if (trimmed.startsWith('- ') || trimmed.startsWith('* ')) {
            // List item - check if we need to start a new list
            if (!html.endsWith('<ul>')) {
                html += '<ul>';
            }
            html += `<li>${trimmed.substring(2).replace(/\n/g, ' ')}</li>`;
        } else {
            // Close list if open
            if (html.endsWith('</li>')) {
                html += '</ul>';
            }
            html += `<p>${trimmed.replace(/\n/g, '<br>')}</p>`;
        }
    });
    
    // Close any open list
    if (html.endsWith('</li>')) {
        html += '</ul>';
    }
    
    html += '</div>';
    return html;
}

/**
 * Escape HTML to prevent XSS
 */
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * Scroll panel to bottom
 */
function scrollPanelToBottom() {
    const panelBody = document.querySelector('.panel-body');
    if (panelBody) {
        // Small delay to ensure content is rendered
        setTimeout(() => {
            panelBody.scrollTop = panelBody.scrollHeight;
        }, 100);
    }
}

// Legacy functions removed - using panel-based UI now

/**
 * AI Provider Settings Management
 */

// Load AI settings from localStorage
function loadAISettings() {
    const saved = localStorage.getItem('aiSettings');
    if (saved) {
        try {
            aiSettings = JSON.parse(saved);
        } catch (e) {
            console.error('Failed to load AI settings:', e);
        }
    }
}

// Save AI settings to localStorage
function saveAISettings() {
    localStorage.setItem('aiSettings', JSON.stringify(aiSettings));
}

// Initialize settings modal
function initializeSettingsModal() {
    const settingsBtn = document.getElementById('settingsBtn');
    const settingsModal = document.getElementById('settingsModal');
    const closeModal = document.getElementById('closeSettingsModal');
    const cancelBtn = document.getElementById('cancelSettingsBtn');
    const saveBtn = document.getElementById('saveSettingsBtn');
    const providerSelect = document.getElementById('providerSelect');
    const apiKeyInput = document.getElementById('apiKeyInput');
    const modelInput = document.getElementById('modelInput');
    const apiKeySection = document.getElementById('apiKeySection');
    const modelSection = document.getElementById('modelSection');
    const ollamaInfo = document.getElementById('ollamaInfo');
    const providerHint = document.getElementById('providerHint');

    // Open modal
    settingsBtn?.addEventListener('click', () => {
        // Load current settings into form
        providerSelect.value = aiSettings.provider;
        apiKeyInput.value = aiSettings.apiKey || '';
        modelInput.value = aiSettings.model || '';
        updateProviderUI();
        settingsModal.style.display = 'flex';
    });

    // Close modal
    closeModal?.addEventListener('click', () => {
        settingsModal.style.display = 'none';
    });
    cancelBtn?.addEventListener('click', () => {
        settingsModal.style.display = 'none';
    });
    settingsModal?.addEventListener('click', (e) => {
        if (e.target === settingsModal) {
            settingsModal.style.display = 'none';
        }
    });

    // Provider selection change
    providerSelect?.addEventListener('change', updateProviderUI);

    function updateProviderUI() {
        const provider = providerSelect.value;
        const needsApiKey = provider !== 'ollama';
        
        apiKeySection.style.display = needsApiKey ? 'block' : 'none';
        modelSection.style.display = needsApiKey ? 'block' : 'none';
        ollamaInfo.style.display = provider === 'ollama' ? 'block' : 'none';

        // Update hints
        const hints = {
            ollama: 'Ollama is free and runs locally. Models download automatically on first use.',
            openai: 'Get your API key from https://platform.openai.com/api-keys',
            gemini: 'Get your API key from https://makersuite.google.com/app/apikey',
            claude: 'Get your API key from https://console.anthropic.com/'
        };
        providerHint.textContent = hints[provider] || '';
    }

    // Save settings
    saveBtn?.addEventListener('click', () => {
        aiSettings.provider = providerSelect.value;
        aiSettings.apiKey = apiKeyInput.value.trim();
        aiSettings.model = modelInput.value.trim();
        
        saveAISettings();
        settingsModal.style.display = 'none';
        
        // Show success message
        const statusText = document.querySelector('.status-text');
        if (statusText) {
            const originalText = statusText.textContent;
            statusText.textContent = `AI Provider: ${aiSettings.provider.toUpperCase()}`;
            setTimeout(() => {
                statusText.textContent = originalText;
            }, 3000);
        }
    });
}

// Update API calls to include provider settings
async function callChatAPI(question, selectedIssue, dashboardState) {
    const response = await fetch('/api/chat/explain', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: question,
            selected_issue: selectedIssue,
            dashboard_state: dashboardState,
            provider: aiSettings.provider,
            api_key: aiSettings.apiKey || undefined,
            model: aiSettings.model || undefined
        })
    });
    return response;
}
