// mobileAppAnaEstDesBieMot.js

async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP error ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error("Error fetching", url, error);
    return null;
  }
}

async function initCharts() {
  const rawData = await fetchData('get_lineCuestionariosSatisfaccionChartData.php');
  console.log("Datos recibidos:", rawData);
  if (!rawData) return;
  
  const modalities = [
    "baja intensidad y equilibrio",
    "resistencia moderada",
    "aerobicos adaptados",
    "ninguna"
  ];
  
  const dates = rawData.dates;
  
  const chartsContainer = document.getElementById('chartsContainer');
  if (!chartsContainer) {
    console.error("No se encontró el contenedor 'chartsContainer'.");
    return;
  }
  chartsContainer.innerHTML = "";
  
  // --- Grupo de gráficos para Bienestar ---
  modalities.forEach(mod => {
    const container = document.createElement('div');
    container.className = 'chart-container';
    const title = document.createElement('h3');
    title.textContent = mod.toUpperCase() + " - Bienestar";
    container.appendChild(title);
    
    const canvas = document.createElement('canvas');
    canvas.id = mod.replace(/\s/g, '') + '_bienestar';
    container.appendChild(canvas);
    chartsContainer.appendChild(container);
    
    const preData = (rawData.bienestar_pre && rawData.bienestar_pre[mod]) ? rawData.bienestar_pre[mod] : {};
    const postData = (rawData.bienestar_post && rawData.bienestar_post[mod]) ? rawData.bienestar_post[mod] : {};
    
    const prePoints = dates.map(month => preData[month] || 0);
    const postPoints = dates.map(month => postData[month] || 0);
    
    const ctx = canvas.getContext('2d');
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: dates,
        datasets: [
          { label: 'Bienestar Pre', data: prePoints, borderColor: 'rgba(255, 99, 132, 1)', fill: false, tension: 0.1 },
          { label: 'Bienestar Post', data: postPoints, borderColor: 'rgba(54, 162, 235, 1)', fill: false, tension: 0.1 }
        ]
      },
      options: {
        responsive: true,
        plugins: { title: { display: true, text: mod.toUpperCase() + " - Evolución Bienestar" } },
        scales: { x: { title: { display: true, text: 'Mes (YYYY-MM)' } }, y: { title: { display: true, text: 'Acumulado de Puntajes' } } }
      }
    });
  });
  
  // Gráfica de torta para Bienestar
  const totalsBienestar = modalities.map(mod => rawData.totals_bienestar[mod] || 0);
  const pieContainerBienestar = document.createElement('div');
  pieContainerBienestar.className = 'chart-container';
  const pieTitleBienestar = document.createElement('h3');
  pieTitleBienestar.textContent = "Acumulados Generales - Bienestar";
  pieContainerBienestar.appendChild(pieTitleBienestar);
  const pieCanvasBienestar = document.createElement('canvas');
  pieCanvasBienestar.id = 'globalPieChart_bienestar';
  pieContainerBienestar.appendChild(pieCanvasBienestar);
  chartsContainer.appendChild(pieContainerBienestar);
  
  new Chart(pieCanvasBienestar.getContext('2d'), {
    type: 'pie',
    data: {
      labels: modalities,
      datasets: [{ data: totalsBienestar, backgroundColor: ['rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)', 'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)'] }]
    },
    options: {
      responsive: true,
      plugins: {
        title: { display: true, text: 'Acumulados Generales - Bienestar' },
        legend: { position: 'top' },
        tooltip: { callbacks: { label: (context) => { const label = context.label || ''; const value = context.raw; const total = totalsBienestar.reduce((a,b)=>a+b,0); const pct = total > 0 ? ((value/total)*100).toFixed(2) : 0; return `${label}: ${pct}% (${value})`; } } } } 
    }
  });
  
  // --- Grupo de gráficos para Motivación ---
  modalities.forEach(mod => {
    const container = document.createElement('div');
    container.className = 'chart-container';
    const title = document.createElement('h3');
    title.textContent = mod.toUpperCase() + " - Motivación";
    container.appendChild(title);
    
    const canvas = document.createElement('canvas');
    canvas.id = mod.replace(/\s/g, '') + '_motivacion';
    container.appendChild(canvas);
    chartsContainer.appendChild(container);
    
    const preData = (rawData.motivacion_pre && rawData.motivacion_pre[mod]) ? rawData.motivacion_pre[mod] : {};
    const postData = (rawData.motivacion_post && rawData.motivacion_post[mod]) ? rawData.motivacion_post[mod] : {};
    
    const prePoints = dates.map(month => preData[month] || 0);
    const postPoints = dates.map(month => postData[month] || 0);
    
    const ctx = canvas.getContext('2d');
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: dates,
        datasets: [
          { label: 'Motivación Pre', data: prePoints, borderColor: 'rgba(255, 159, 64, 1)', fill: false, tension: 0.1 },
          { label: 'Motivación Post', data: postPoints, borderColor: 'rgba(75, 192, 192, 1)', fill: false, tension: 0.1 }
        ]
      },
      options: {
        responsive: true,
        plugins: { title: { display: true, text: mod.toUpperCase() + " - Evolución Motivación" } },
        scales: { x: { title: { display: true, text: 'Mes (YYYY-MM)' } }, y: { title: { display: true, text: 'Acumulado de Puntajes' } } }
      }
    });
  });
  
  // Gráfica de torta para Motivación
  const totalsMotivacion = modalities.map(mod => rawData.totals_motivacion[mod] || 0);
  const pieContainerMotivacion = document.createElement('div');
  pieContainerMotivacion.className = 'chart-container';
  const pieTitleMotivacion = document.createElement('h3');
  pieTitleMotivacion.textContent = "Acumulados Generales - Motivación";
  pieContainerMotivacion.appendChild(pieTitleMotivacion);
  const pieCanvasMotivacion = document.createElement('canvas');
  pieCanvasMotivacion.id = 'globalPieChart_motivacion';
  pieContainerMotivacion.appendChild(pieCanvasMotivacion);
  chartsContainer.appendChild(pieContainerMotivacion);
  
  new Chart(pieCanvasMotivacion.getContext('2d'), {
    type: 'pie',
    data: {
      labels: modalities,
      datasets: [{ data: totalsMotivacion, backgroundColor: ['rgba(255, 159, 64, 0.6)', 'rgba(75, 192, 192, 0.6)', 'rgba(153, 102, 255, 0.6)', 'rgba(201, 203, 207, 0.6)'] }]
    },
    options: {
      responsive: true,
      plugins: {
        title: { display: true, text: 'Acumulados Generales - Motivación' },
        legend: { position: 'top' },
        tooltip: { callbacks: { label: (context) => { const label = context.label || ''; const value = context.raw; const total = totalsMotivacion.reduce((a,b)=>a+b,0); const pct = total > 0 ? ((value/total)*100).toFixed(2) : 0; return `${label}: ${pct}% (${value})`; } } } } 
    }
  });
}

document.addEventListener('DOMContentLoaded', initCharts);
