// Memory chart initialization and update functions
document.addEventListener('DOMContentLoaded', function() {
  // Background color for charts
  var chartBgColor = '#1e1e2f';
  
  // Initialize Memory chart
  var memoryChartDom = document.getElementById('memory-chart');
  if (!memoryChartDom) return;
  
  var memoryChart = echarts.init(memoryChartDom, {renderer: 'canvas', useDirtyRect: false, backgroundColor: chartBgColor});
  var memoryOption = {
    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/>' + 
               'Memory: ' + Math.round(params.value) + ' MB';
      },
      textStyle: {
        fontSize: 14
      }
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      textStyle: {
        color: '#fff'
      },
      formatter: function(name) {
        // Display full process name without truncation
        return name;
      },
      itemGap: 12, // Increased gap for better readability
      itemWidth: 15,
      padding: 10
    },
    series: [
      {
        name: 'Process Memory 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 }]
      }
    ]
  };
  memoryChart.setOption(memoryOption);
  
  // Function to update Memory chart
  window.updateMemoryChart = function(processes) {
    // Sort processes by memory usage (descending)
    var topProcesses = processes
      .slice()
      .sort((a, b) => b.memory_mb - a.memory_mb)
      .slice(0, 5);
    
    var memoryUsageData = topProcesses.map(p => ({
      name: p.name, // Use full process name
      value: p.memory_mb,
      pid: p.pid // Store PID for tooltip
    }));
    
    // Update chart option
    memoryOption.series[0].data = memoryUsageData;
    
    // Apply updated option
    memoryChart.setOption(memoryOption);
  };
  
  // Handle window resize
  window.addEventListener('resize', function() {
    memoryChart && memoryChart.resize();
  });
});
