// CPU chart initialization and update functions
document.addEventListener('DOMContentLoaded', function() {
  // Background color for charts
  var chartBgColor = '#1e1e2f';
  
  // Initialize CPU chart
  var cpuChartDom = document.getElementById('cpu-chart');
  if (!cpuChartDom) return;
  
  var cpuChart = echarts.init(cpuChartDom, {renderer: 'canvas', useDirtyRect: false, backgroundColor: chartBgColor});
  var cpuOption = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        // Get the PID from the data
        var pid = params.data.pid || 'N/A';
        return params.seriesName + '<br/>' + 
               params.name + ' (PID: ' + pid + ')<br/>' + 
               'CPU: ' + Math.round(params.value) + '%';
      }
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      textStyle: {
        color: '#fff'
      },
      formatter: function(name) {
        // Display full process name without truncation
        return name;
      },
      itemGap: 8,
      itemWidth: 15,
      padding: 10
    },
    series: [
      {
        name: 'Process CPU Usage',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [{ name: 'Loading...', value: 100 }]
      }
    ]
  };
  cpuChart.setOption(cpuOption);
  
  // Function to update CPU chart
  window.updateCpuChart = function(processes) {
    // Calculate total CPU usage for top 5 processes
    var topProcesses = processes.slice(0, 5);
    var cpuUsageData = topProcesses.map(p => ({
      name: p.name, // Use full process name
      value: p.cpu_percent,
      pid: p.pid // Store PID for tooltip
    }));
    
    // Update chart option
    cpuOption.series[0].data = cpuUsageData;
    
    // Apply updated option
    cpuChart.setOption(cpuOption);
  };
  
  // Handle window resize
  window.addEventListener('resize', function() {
    cpuChart && cpuChart.resize();
  });
});
