/* ==========================================================================
   CHARTS MANAGER & CHART.JS HELPERS
   Theme-aware palette, neon gradients, interactive tooltips
   ========================================================================== */

const ChartManager = {
  instances: {},

  getThemeColors() {
    const isLight = document.body.classList.contains('light-theme');
    return {
      isLight,
      text: isLight ? '#475569' : '#94a3b8',
      textMain: isLight ? '#0f172a' : '#f8fafc',
      grid: isLight ? 'rgba(0, 0, 0, 0.06)' : 'rgba(255, 255, 255, 0.06)',
      primary: isLight ? '#059669' : '#00f59b',
      secondary: isLight ? '#0891b2' : '#06b6d4',
      purple: '#8b5cf6',
      amber: '#f59e0b',
      rose: '#f43f5e',
      blue: '#3b82f6',
      cardBg: isLight ? '#ffffff' : '#0f172a'
    };
  },

  destroy(canvasId) {
    if (this.instances[canvasId]) {
      this.instances[canvasId].destroy();
      delete this.instances[canvasId];
    }
  },

  destroyAll() {
    Object.keys(this.instances).forEach((id) => this.destroy(id));
  },

  // GRÁFICO DE PIZZA: ATENDIMENTOS POR MARCA (Toyota, Chery, Nissan, Omoda Jaecoo, GWM)
  renderBrandsPieChart(canvasId, brandsData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas || !brandsData || brandsData.length === 0) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    const labels = brandsData.map((b) => b.marca);
    const values = brandsData.map((b) => b.total);

    const palette = [
      '#06b6d4', // Toyota (Cyan)
      '#10b981', // GWM (Emerald)
      '#f59e0b', // CAOA Chery (Amber)
      '#8b5cf6', // Omoda Jaecoo (Purple)
      '#ec4899', // Nissan (Pink)
      '#64748b'  // Outras (Slate)
    ];

    this.instances[canvasId] = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: labels,
        datasets: [{
          data: values,
          backgroundColor: palette.slice(0, labels.length),
          borderWidth: 2,
          borderColor: colors.cardBg,
          hoverOffset: 6
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '62%',
        plugins: {
          legend: {
            position: 'right',
            labels: {
              color: colors.textMain,
              font: { family: 'Inter', size: 11, weight: '600' },
              padding: 12,
              usePointStyle: true,
              pointStyle: 'circle'
            }
          },
          tooltip: {
            callbacks: {
              label: (context) => {
                const val = context.raw || 0;
                const total = values.reduce((a, b) => a + b, 0);
                const pct = total > 0 ? ((val / total) * 100).toFixed(1) : 0;
                return ` ${context.label}: ${val} atendimentos (${pct}%)`;
              }
            }
          }
        }
      }
    });
  },

  // 1. TIMELINE DE ATENDIMENTOS & CONVERSÃO (ÁREA COM GRADIENTE)
  renderTimeline(canvasId, timelineData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    const labels = timelineData.map((d) => {
      const parts = d.data_dia.split('-');
      return `${parts[2]}/${parts[1]}`;
    });
    const dataTotal = timelineData.map((d) => d.total);
    const dataConv = timelineData.map((d) => d.convertidos);

    // Gradiente Neon Primário
    const gradPrimary = ctx.createLinearGradient(0, 0, 0, 260);
    gradPrimary.addColorStop(0, 'rgba(0, 245, 155, 0.45)');
    gradPrimary.addColorStop(1, 'rgba(0, 245, 155, 0.0)');

    // Gradiente Turquesa
    const gradSecondary = ctx.createLinearGradient(0, 0, 0, 260);
    gradSecondary.addColorStop(0, 'rgba(6, 182, 212, 0.40)');
    gradSecondary.addColorStop(1, 'rgba(6, 182, 212, 0.0)');

    this.instances[canvasId] = new Chart(ctx, {
      type: 'line',
      data: {
        labels,
        datasets: [
          {
            label: 'Total de Atendimentos',
            data: dataTotal,
            borderColor: colors.secondary,
            backgroundColor: gradSecondary,
            borderWidth: 2.5,
            tension: 0.35,
            fill: true,
            pointRadius: 3,
            pointHoverRadius: 6,
            pointBackgroundColor: colors.secondary
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top',
            labels: { color: colors.text, font: { family: 'Plus Jakarta Sans', size: 12, weight: 600 } }
          },
          tooltip: {
            backgroundColor: colors.cardBg,
            titleColor: colors.textMain,
            bodyColor: colors.text,
            borderColor: 'rgba(0, 245, 155, 0.3)',
            borderWidth: 1,
            padding: 10
          }
        },
        scales: {
          x: {
            grid: { color: colors.grid },
            ticks: { color: colors.text, font: { family: 'Plus Jakarta Sans', size: 11 } }
          },
          y: {
            grid: { color: colors.grid },
            ticks: { color: colors.text, font: { family: 'Plus Jakarta Sans', size: 11 } },
            beginAtZero: true
          }
        }
      }
    });
  },

  // 2. CANAIS (DONUT CHART)
  renderChannelsDonut(canvasId, canaisData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    const labels = canaisData.map((c) => c.canal);
    const data = canaisData.map((c) => c.total);

    const palette = ['#00f59b', '#06b6d4', '#e1306c', '#1877f2', '#0088cc', '#8b5cf6'];

    this.instances[canvasId] = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels,
        datasets: [
          {
            data,
            backgroundColor: palette,
            borderWidth: 2,
            borderColor: colors.cardBg,
            hoverOffset: 6
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '72%',
        plugins: {
          legend: {
            position: 'bottom',
            labels: { color: colors.text, font: { family: 'Plus Jakarta Sans', size: 11 }, padding: 12 }
          }
        }
      }
    });
  },

  // 3. PERFORMANCE POR OPERADOR (BAR MULTI-SERIES)
  renderOperatorsBar(canvasId, operatorsData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    const labels = operatorsData.map((o) => o.nome.split(' ')[0]);
    const dataTotal = operatorsData.map((o) => o.total_atendimentos);
    const dataConv = operatorsData.map((o) => o.convertidos);
    const dataRate = operatorsData.map((o) => o.taxa_conversao);

    this.instances[canvasId] = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [
          {
            label: 'Total Atendidos',
            data: dataTotal,
            backgroundColor: 'rgba(6, 182, 212, 0.45)',
            borderColor: colors.secondary,
            borderWidth: 1.5,
            borderRadius: 6
          },
          {
            label: 'Convertidos',
            data: dataConv,
            backgroundColor: 'rgba(0, 245, 155, 0.75)',
            borderColor: colors.primary,
            borderWidth: 1.5,
            borderRadius: 6
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top',
            labels: { color: colors.text, font: { family: 'Plus Jakarta Sans', size: 11, weight: 600 } }
          }
        },
        scales: {
          x: { grid: { color: colors.grid }, ticks: { color: colors.text } },
          y: { grid: { color: colors.grid }, ticks: { color: colors.text }, beginAtZero: true }
        }
      }
    });
  },

  // 4. MOTIVOS DE FECHAMENTO (HORIZONTAL BAR)
  renderMotivosBar(canvasId, motivosData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    const labels = motivosData.map((m) => m.motivo_fechamento);
    const data = motivosData.map((m) => m.total);

    const bgColors = labels.map((l) => {
      if (l.includes('Venda') || l.includes('Aceita')) return 'rgba(0, 245, 155, 0.75)';
      if (l.includes('Somente informações')) return 'rgba(239, 68, 68, 0.75)';
      if (l.includes('Sem retorno')) return 'rgba(245, 158, 11, 0.75)';
      return 'rgba(139, 92, 246, 0.65)';
    });

    this.instances[canvasId] = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [
          {
            label: 'Ocorrências',
            data,
            backgroundColor: bgColors,
            borderRadius: 6
          }
        ]
      },
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false }
        },
        scales: {
          x: { grid: { color: colors.grid }, ticks: { color: colors.text }, beginAtZero: true },
          y: { grid: { display: false }, ticks: { color: colors.text, font: { size: 11 } } }
        }
      }
    });
  },

  // 5. HEATMAP DE HORÁRIOS DE PICO
  renderHourlyChart(canvasId, horariosData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    // Normalizar 24 horas (00h a 23h)
    const fullHours = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0'));
    const mapCounts = {};
    horariosData.forEach((h) => {
      mapCounts[h.hora] = h.total;
    });

    const labels = fullHours.map((h) => `${h}h`);
    const data = fullHours.map((h) => mapCounts[h] || 0);

    this.instances[canvasId] = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [
          {
            label: 'Volume de Mensagens',
            data,
            backgroundColor: 'rgba(6, 182, 212, 0.65)',
            hoverBackgroundColor: '#00f59b',
            borderRadius: 4
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
          x: { grid: { display: false }, ticks: { color: colors.text, font: { size: 10 } } },
          y: { grid: { color: colors.grid }, ticks: { color: colors.text }, beginAtZero: true }
        }
      }
    });
  },

  // 6. MOTIVOS DE FECHAMENTO (BARRAS HORIZONTAIS)
  renderMotivosChart(canvasId, motivosData) {
    this.destroy(canvasId);
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const colors = this.getThemeColors();

    if (!motivosData || motivosData.length === 0) return;

    const labels = motivosData.map((m) => m.motivo);
    const data = motivosData.map((m) => m.total);

    const palette = [
      colors.primary,
      colors.secondary,
      colors.purple,
      colors.amber,
      colors.blue,
      colors.rose,
      '#10b981',
      '#0284c7'
    ];

    this.instances[canvasId] = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [
          {
            label: 'Total de Atendimentos',
            data,
            backgroundColor: palette.slice(0, data.length),
            borderRadius: 6
          }
        ]
      },
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false }
        },
        scales: {
          x: { grid: { color: colors.grid }, ticks: { color: colors.text }, beginAtZero: true },
          y: { grid: { display: false }, ticks: { color: colors.text, font: { size: 11 } } }
        }
      }
    });
  }
};
