/* Exportación Interesados — Excel y PDF con comparativa por mes */

const LEAD_EXPORT_STATUS_LABELS = {
  nuevo: 'Nuevo',
  contactado: 'Contactado',
  inscrito: 'Inscrito',
  descartado: 'Descartado',
};

const LEAD_EXPORT_STATUS_COLORS = {
  nuevo: '#3b82f6',
  contactado: '#eab308',
  inscrito: '#22c55e',
  descartado: '#94a3b8',
};

const LEAD_ORIGIN_LABELS = {
  landing: 'Contacto web',
  anuncio: 'Avisos',
  evento: 'Eventos',
};

const LEAD_ORIGIN_COLORS = {
  landing: '#2563eb',
  anuncio: '#8b5cf6',
  evento: '#14b8a6',
};

const MONTH_SHORT = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];

function leadMonthKey (createdAt) {
  if (!createdAt) return 'sin-fecha';
  const d = new Date(createdAt);
  if (Number.isNaN(d.getTime())) return 'sin-fecha';
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}

function leadMonthLabel (key) {
  if (key === 'sin-fecha') return 'Sin fecha';
  const [y, m] = key.split('-');
  const mi = Number(m) - 1;
  if (mi < 0 || mi > 11) return key;
  return `${MONTH_SHORT[mi]} ${y}`;
}

function buildInterestedLeadsExportSummary (leads) {
  const rows = leads || [];
  const byMonth = {};
  const byEstado = {};
  const byOrigin = {};
  const byContext = {};
  rows.forEach((l) => {
    const mk = leadMonthKey(l.created_at);
    if (!byMonth[mk]) byMonth[mk] = { count: 0, label: leadMonthLabel(mk) };
    byMonth[mk].count += 1;

    const st = l.status || 'nuevo';
    byEstado[st] = (byEstado[st] || 0) + 1;

    const ok = l.contextKind || 'landing';
    byOrigin[ok] = (byOrigin[ok] || 0) + 1;

    const ctx = l.contextLabel || 'Contacto web';
    byContext[ctx] = (byContext[ctx] || 0) + 1;
  });
  return {
    total: rows.length,
    byMonth,
    byEstado,
    byOrigin,
    byContext,
  };
}

function interestedLeadsExportFilename (ext, filterLabel) {
  const safe = String(filterLabel || 'todos').replace(/\s+/g, '-').toLowerCase();
  const date = new Date().toISOString().slice(0, 10);
  return `tecos-interesados-${safe}-${date}.${ext}`;
}

function interestedLeadsDetailRows (leads) {
  return (leads || []).map(l => [
    l.createdLabel,
    LEAD_EXPORT_STATUS_LABELS[l.status] || l.status,
    l.contextLabel,
    l.announcementTitle || l.eventTitle || '—',
    l.name,
    l.phone,
    l.email,
    l.studentName,
    l.studentAge,
    (l.message || '').replace(/\s+/g, ' ').slice(0, 500),
    l.source,
  ]);
}

async function exportInterestedLeadsExcel (leads, filterLabel = 'todos') {
  if (typeof tecosEnsureExportLibs === 'function') await tecosEnsureExportLibs();
  if (typeof XLSX === 'undefined') {
    exportInterestedLeadsCsv(leads);
    alert('Librería Excel no cargada; se descargó CSV.');
    return;
  }
  const summary = buildInterestedLeadsExportSummary(leads);
  const wb = XLSX.utils.book_new();

  const detailHeader = [
    'Fecha', 'Estado', 'Origen', 'Aviso / evento', 'Nombre', 'Teléfono', 'Correo',
    'Alumno', 'Edad', 'Mensaje', 'Source',
  ];
  XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([detailHeader, ...interestedLeadsDetailRows(leads)]), 'Interesados');

  const resumenRows = [
    ['TECOS ELITE — Reporte de interesados'],
    ['Filtro', filterLabel],
    ['Generado', new Date().toLocaleString('es-MX')],
    ['Total registros', summary.total],
    [],
    ['Estado', 'Cantidad', '%'],
  ];
  Object.keys(LEAD_EXPORT_STATUS_LABELS).forEach((k) => {
    const n = summary.byEstado[k] || 0;
    const pct = summary.total ? ((n / summary.total) * 100).toFixed(1) : '0';
    resumenRows.push([LEAD_EXPORT_STATUS_LABELS[k], n, pct]);
  });
  resumenRows.push([]);
  resumenRows.push(['Origen', 'Cantidad', '%']);
  Object.keys(LEAD_ORIGIN_LABELS).forEach((k) => {
    const n = summary.byOrigin[k] || 0;
    const pct = summary.total ? ((n / summary.total) * 100).toFixed(1) : '0';
    resumenRows.push([LEAD_ORIGIN_LABELS[k], n, pct]);
  });
  XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(resumenRows), 'Resumen');

  const monthEntries = Object.entries(summary.byMonth).sort((a, b) => a[0].localeCompare(b[0]));
  const porMesRows = [
    ['Comparativa por mes — solicitudes desde la página'],
    ['Mes', 'Cantidad', '% del total'],
    ...monthEntries.map(([key, v]) => {
      const pct = summary.total ? ((v.count / summary.total) * 100).toFixed(1) : '0';
      return [v.label, v.count, pct];
    }),
  ];
  XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(porMesRows), 'Por mes');

  const chartEstadoLabels = Object.keys(LEAD_EXPORT_STATUS_LABELS).map(k => LEAD_EXPORT_STATUS_LABELS[k]);
  const chartEstadoCounts = Object.keys(LEAD_EXPORT_STATUS_LABELS).map(k => summary.byEstado[k] || 0);
  const wsGrafica = XLSX.utils.aoa_to_sheet([
    ['Datos para gráfica — interesados por mes'],
    ['Mes', 'Cantidad'],
    ...monthEntries.map(([, v]) => [v.label, v.count]),
    [],
    ['Datos para gráfica — por estado'],
    ['Estado', 'Cantidad'],
    ...chartEstadoLabels.map((l, i) => [l, chartEstadoCounts[i]]),
    [],
    ['Datos para gráfica — por origen'],
    ['Origen', 'Cantidad'],
    ...Object.keys(LEAD_ORIGIN_LABELS).map(k => [LEAD_ORIGIN_LABELS[k], summary.byOrigin[k] || 0]),
  ]);
  XLSX.utils.book_append_sheet(wb, wsGrafica, 'Gráficas');

  XLSX.writeFile(wb, interestedLeadsExportFilename('xlsx', filterLabel));
}

async function exportInterestedLeadsPdf (leads, filterLabel = 'todos', theme = {}) {
  if (typeof tecosEnsureExportLibs === 'function') await tecosEnsureExportLibs();
  const t = theme || (typeof THEMES !== 'undefined' ? THEMES.light : {});
  const primary = t.primary || '#2563eb';
  const summary = buildInterestedLeadsExportSummary(leads);
  const { jsPDF } = window.jspdf || {};
  if (!jsPDF) {
    exportInterestedLeadsCsv(leads);
    alert('Librería PDF no cargada; se descargó CSV.');
    return;
  }

  const renderChart = typeof renderChartPng === 'function' ? renderChartPng : null;
  const doc = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });
  const pageW = doc.internal.pageSize.getWidth();
  const dateStr = new Date().toLocaleString('es-MX', { dateStyle: 'long', timeStyle: 'short' });
  const logoDataUrl = typeof loadTecosLogoDataUrl === 'function'
    ? await loadTecosLogoDataUrl()
    : (typeof loadReceiptImage === 'function'
      ? await loadReceiptImage(window.TECOS_LOGO_PATH || window.RECEIPT_LOGO_PATH)
      : null);

  if (typeof drawTecosPdfReportHeader === 'function') {
    drawTecosPdfReportHeader(doc, {
      pageW,
      subtitle: 'Reporte de interesados — contacto, avisos y eventos',
      meta: `Filtro: ${filterLabel}  ·  ${dateStr}`,
      headerH: 34,
      logoDataUrl,
    });
  } else {
    doc.setFillColor(15, 23, 42);
    doc.rect(0, 0, pageW, 38, 'F');
    doc.setTextColor(255, 255, 255);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(22);
    doc.text('TECOS ELITE VOLLEYBALL', 14, 16);
    doc.setFontSize(11);
    doc.setFont('helvetica', 'normal');
    doc.text('Reporte de interesados — contacto, avisos y eventos', 14, 24);
    doc.text(`Filtro: ${filterLabel}  ·  ${dateStr}`, 14, 31);
  }

  doc.setTextColor(30, 41, 59);
  const kpis = [
    ['Total', String(summary.total)],
    ['Contacto web', String(summary.byOrigin.landing || 0)],
    ['Avisos', String(summary.byOrigin.anuncio || 0)],
    ['Eventos', String(summary.byOrigin.evento || 0)],
  ];
  const kpiY = 44;
  kpis.forEach((k, i) => {
    const x = 14 + i * 68;
    doc.setDrawColor(226, 232, 240);
    doc.roundedRect(x, kpiY, 62, 18, 2, 2);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(100, 116, 139);
    doc.setFontSize(9);
    doc.text(k[0], x + 4, kpiY + 7);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(12);
    doc.setTextColor(15, 23, 42);
    doc.text(k[1], x + 4, kpiY + 14);
  });

  const monthEntries = Object.entries(summary.byMonth).sort((a, b) => a[0].localeCompare(b[0]));
  const barLabels = monthEntries.map(([, v]) => v.label);
  const barValues = monthEntries.map(([, v]) => v.count);

  const originKeys = Object.keys(LEAD_ORIGIN_LABELS).filter(k => (summary.byOrigin[k] || 0) > 0);
  const pieLabels = originKeys.map(k => LEAD_ORIGIN_LABELS[k]);
  const pieValues = originKeys.map(k => summary.byOrigin[k]);
  const pieColors = originKeys.map(k => LEAD_ORIGIN_COLORS[k]);

  const estadoKeys = Object.keys(LEAD_EXPORT_STATUS_LABELS).filter(k => (summary.byEstado[k] || 0) > 0);
  const estadoLabels = estadoKeys.map(k => LEAD_EXPORT_STATUS_LABELS[k]);
  const estadoValues = estadoKeys.map(k => summary.byEstado[k]);
  const estadoColors = estadoKeys.map(k => LEAD_EXPORT_STATUS_COLORS[k]);

  let chartY = 68;
  if (renderChart) {
    try {
      const charts = await Promise.all([
        barLabels.length ? renderChart({
          type: 'bar',
          labels: barLabels,
          values: barValues,
          colors: barLabels.map(() => primary + '99'),
          width: 560,
          height: 280,
        }) : null,
        pieLabels.length ? renderChart({
          type: 'doughnut',
          labels: pieLabels,
          values: pieValues,
          colors: pieColors,
        }) : null,
        estadoLabels.length ? renderChart({
          type: 'doughnut',
          labels: estadoLabels,
          values: estadoValues,
          colors: estadoColors,
          width: 400,
          height: 280,
        }) : null,
      ]);
      const [barUrl, originUrl, estadoUrl] = charts;
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(11);
      doc.setTextColor(15, 23, 42);
      if (barUrl) {
        doc.text('Interesados por mes (desde la página)', 14, chartY);
        doc.addImage(barUrl, 'PNG', 14, chartY + 4, pageW - 28, 52);
        chartY += 60;
      }
      if (originUrl) {
        doc.text('Por origen', 14, chartY);
        doc.addImage(originUrl, 'PNG', 14, chartY + 4, 88, 48);
      }
      if (estadoUrl) {
        doc.text('Por estado de seguimiento', 108, chartY);
        doc.addImage(estadoUrl, 'PNG', 108, chartY + 4, 88, 48);
      }
      if (originUrl || estadoUrl) chartY += 56;
    } catch (e) {
      console.warn('[Tecos] PDF interesados charts', e);
    }
  }

  doc.autoTable({
    startY: chartY,
    head: [['Fecha', 'Nombre', 'Teléfono', 'Origen', 'Estado', 'Mensaje (extracto)']],
    body: (leads || []).slice(0, 400).map(l => [
      l.createdLabel,
      l.name,
      l.phone,
      l.contextLabel,
      LEAD_EXPORT_STATUS_LABELS[l.status] || l.status,
      (l.message || '').replace(/\s+/g, ' ').slice(0, 80),
    ]),
    styles: { fontSize: 8, cellPadding: 2 },
    headStyles: { fillColor: [37, 99, 235], textColor: 255 },
    alternateRowStyles: { fillColor: [248, 250, 252] },
    margin: { left: 14, right: 14 },
  });

  if ((leads || []).length > 400) {
    const finalY = doc.lastAutoTable.finalY || chartY;
    doc.setFontSize(8);
    doc.setTextColor(100, 116, 139);
    doc.text(`Mostrando 400 de ${leads.length} registros. Usa Excel para el listado completo.`, 14, finalY + 8);
  }

  doc.save(interestedLeadsExportFilename('pdf', filterLabel));
}

Object.assign(window, {
  buildInterestedLeadsExportSummary,
  exportInterestedLeadsExcel,
  exportInterestedLeadsPdf,
});
