// Chart instances
const charts = {};

// UNIR Colors
const BLUE = '#0098CD';
const BLUE_DARK = '#007AA3';
const LIGHT = '#E6F4F9';
const RED = '#E8654A';
const ORANGE = '#F0A030';
const GREEN = '#2EAD4B';
const GRAY = '#CCCCCC';

// Common chart options
const commonOptions = {
  responsive: true,
  maintainAspectRatio: true,
  animation: { duration: 1200, easing: 'easeOutQuart' },
  plugins: { legend: { display: false } }
};

function createBenchmarkChart() {
  const ctx = document.getElementById('chartBenchmark');
  if (!ctx || charts.benchmark) return;
  charts.benchmark = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['EasyOCR', 'PaddleOCR', 'DocTR'],
      datasets: [
        {
          label: 'CER (%)',
          data: [11.23, 7.76, 12.06],
          backgroundColor: [GRAY, BLUE, GRAY],
          borderColor: [GRAY, BLUE_DARK, GRAY],
          borderWidth: 2,
          borderRadius: 6,
          barPercentage: 0.6
        },
        {
          label: 'WER (%)',
          data: [36.36, 11.62, 42.01],
          backgroundColor: ['rgba(204,204,204,0.4)', 'rgba(0,152,205,0.4)', 'rgba(204,204,204,0.4)'],
          borderColor: [GRAY, BLUE, GRAY],
          borderWidth: 2,
          borderRadius: 6,
          barPercentage: 0.6
        }
      ]
    },
    options: {
      ...commonOptions,
      indexAxis: 'y',
      plugins: {
        legend: { display: true, position: 'top', labels: { font: { family: 'Calibri', size: 12 } } }
      },
      scales: {
        x: { title: { display: true, text: 'Error Rate (%)', font: { family: 'Calibri' } }, grid: { color: '#f0f0f0' } },
        y: { grid: { display: false }, ticks: { font: { family: 'Calibri', size: 14, weight: 'bold' } } }
      }
    }
  });
}

function createTrialsChart() {
  const ctx = document.getElementById('chartTrials');
  if (!ctx || charts.trials) return;
  charts.trials = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['CER < 1%', 'CER 1-2%', 'CER 2-5%', 'CER 5-10%'],
      datasets: [{
        data: [15, 28, 10, 11],
        backgroundColor: [BLUE_DARK, BLUE, '#7EC8E3', GRAY],
        borderColor: 'white',
        borderWidth: 3,
        hoverOffset: 8
      }]
    },
    options: {
      ...commonOptions,
      cutout: '55%',
      plugins: {
        legend: {
          display: true,
          position: 'bottom',
          labels: { font: { family: 'Calibri', size: 12 }, padding: 15, usePointStyle: true, pointStyle: 'rectRounded' }
        }
      }
    }
  });
}

function createImpactChart() {
  const ctx = document.getElementById('chartImpact');
  if (!ctx || charts.impact) return;
  const params = [
    'use_doc_unwarping',
    'textline_orientation',
    'use_doc_orient_classify',
    'text_det_thresh',
    'text_det_box_thresh',
    'text_rec_score_thresh'
  ];
  const correlations = [0.879, -0.535, -0.712, 0.428, 0.311, -0.268];
  const absValues = correlations.map(Math.abs);
  // Sort by absolute value descending
  const indices = absValues.map((_, i) => i).sort((a, b) => absValues[b] - absValues[a]);
  const sortedParams = indices.map(i => params[i]);
  const sortedCorr = indices.map(i => correlations[i]);
  const colors = sortedCorr.map(v => v > 0 ? RED : BLUE);
  const borderColors = sortedCorr.map(v => v > 0 ? '#C04030' : BLUE_DARK);

  charts.impact = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: sortedParams,
      datasets: [{
        data: sortedCorr,
        backgroundColor: colors,
        borderColor: borderColors,
        borderWidth: 1.5,
        borderRadius: 4,
        barPercentage: 0.65
      }]
    },
    options: {
      ...commonOptions,
      indexAxis: 'y',
      scales: {
        x: {
          min: -1, max: 1,
          title: { display: true, text: 'Correlación con CER (rojo = perjudica, azul = mejora)', font: { family: 'Calibri', size: 10 } },
          grid: { color: (ctx) => ctx.tick.value === 0 ? '#666' : '#f0f0f0' }
        },
        y: {
          grid: { display: false },
          ticks: { font: { family: 'Consolas, monospace', size: 11 } }
        }
      },
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: (ctx) => `Correlación: ${ctx.parsed.x > 0 ? '+' : ''}${ctx.parsed.x.toFixed(3)}`
          }
        }
      }
    }
  });
}

function createCorrelationChart() {
  const ctx = document.getElementById('chartCorrelation');
  if (!ctx || charts.correlation) return;
  const params = [
    'use_doc_unwarping',
    'text_det_thresh',
    'text_det_box_thresh',
    'text_rec_score_thresh',
    'textline_orientation',
    'use_doc_orient_classify'
  ];
  const values = [0.879, 0.428, 0.311, -0.268, -0.535, -0.712];
  const colors = values.map(v => v > 0 ? RED : BLUE);

  charts.correlation = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: params,
      datasets: [{
        data: values,
        backgroundColor: colors,
        borderColor: colors.map(c => c === RED ? '#C04030' : BLUE_DARK),
        borderWidth: 1.5,
        borderRadius: 4,
        barPercentage: 0.65
      }]
    },
    options: {
      ...commonOptions,
      indexAxis: 'y',
      scales: {
        x: {
          min: -1, max: 1,
          title: { display: true, text: 'Correlación Pearson', font: { family: 'Calibri', size: 11 } },
          grid: { color: (ctx) => ctx.tick.value === 0 ? '#666' : '#f0f0f0' }
        },
        y: {
          grid: { display: false },
          ticks: { font: { family: 'Consolas, monospace', size: 10 } }
        }
      }
    }
  });
}

function createImportanceChart() {
  const ctx = document.getElementById('chartImportance');
  if (!ctx || charts.importance) return;
  const params = [
    'use_doc_unwarping',
    'use_doc_orient_classify',
    'textline_orientation',
    'text_det_thresh',
    'text_det_box_thresh',
    'text_rec_score_thresh'
  ];
  const values = [0.879, 0.712, 0.535, 0.428, 0.311, 0.268];
  const colors = values.map((_, i) => {
    const alpha = 1 - (i * 0.12);
    return `rgba(0, 152, 205, ${alpha})`;
  });

  charts.importance = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: params,
      datasets: [{
        data: values,
        backgroundColor: colors,
        borderColor: BLUE_DARK,
        borderWidth: 1,
        borderRadius: 4,
        barPercentage: 0.65
      }]
    },
    options: {
      ...commonOptions,
      indexAxis: 'y',
      scales: {
        x: {
          beginAtZero: true, max: 1,
          title: { display: true, text: '|Correlación|', font: { family: 'Calibri', size: 11 } },
          grid: { color: '#f0f0f0' }
        },
        y: {
          grid: { display: false },
          ticks: { font: { family: 'Consolas, monospace', size: 10 } }
        }
      }
    }
  });
}

function createValidationChart() {
  const ctx = document.getElementById('chartValidation');
  if (!ctx || charts.validation) return;
  charts.validation = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['CER (45 pág)', 'WER (45 pág)', 'CER (mejor trial)'],
      datasets: [
        {
          label: 'Baseline',
          data: [8.85, 13.05, 7.76],
          backgroundColor: 'rgba(204,204,204,0.7)',
          borderColor: '#aaa',
          borderWidth: 2,
          borderRadius: 6,
          barPercentage: 0.7
        },
        {
          label: 'Optimizado',
          data: [7.72, 11.40, 0.79],
          backgroundColor: BLUE,
          borderColor: BLUE_DARK,
          borderWidth: 2,
          borderRadius: 6,
          barPercentage: 0.7
        }
      ]
    },
    options: {
      ...commonOptions,
      plugins: {
        legend: { display: true, position: 'top', labels: { font: { family: 'Calibri', size: 13 } } }
      },
      scales: {
        y: {
          beginAtZero: true,
          title: { display: true, text: 'Error Rate (%)', font: { family: 'Calibri' } },
          grid: { color: '#f0f0f0' }
        },
        x: {
          grid: { display: false },
          ticks: { font: { family: 'Calibri', size: 12 } }
        }
      }
    }
  });
}

function createGPUChart() {
  const ctx = document.getElementById('chartGPU');
  if (!ctx || charts.gpu) return;
  charts.gpu = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['CPU (Ryzen 7 5800H)', 'GPU (RTX 3060)'],
      datasets: [{
        label: 'Segundos por página',
        data: [69.4, 0.84],
        backgroundColor: [ORANGE, BLUE],
        borderColor: ['#CC8020', BLUE_DARK],
        borderWidth: 2,
        borderRadius: 8,
        barPercentage: 0.5
      }]
    },
    options: {
      ...commonOptions,
      indexAxis: 'y',
      scales: {
        x: {
          beginAtZero: true,
          title: { display: true, text: 'Segundos por página', font: { family: 'Calibri', size: 13 } },
          grid: { color: '#f0f0f0' }
        },
        y: {
          grid: { display: false },
          ticks: { font: { family: 'Calibri', size: 14, weight: 'bold' } }
        }
      },
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: (ctx) => `${ctx.parsed.x} s/página`
          }
        }
      }
    }
  });
}

// Chart creation map
const chartCreators = {
  benchmark: createBenchmarkChart,
  trials: createTrialsChart,
  impact: createImpactChart,
  correlations: () => { createCorrelationChart(); createImportanceChart(); },
  validation: createValidationChart,
  gpu: createGPUChart
};
