/* Exportación listado de alumnos — Excel y PDF con logo y fotos */

const STUDENTS_EXPORT_STATUS = {
  activo: 'Activo',
  inactivo: 'Inactivo',
};

const SCHOOL_NAME = 'TECOS ELITE VOLLEYBALL';
const LOGO_PATH = (typeof window !== 'undefined' && window.TECOS_LOGO_PATH) || 'assets/logo-tecos.png?v=no-bg-2';
const LOGO_PDF_ASPECT = (typeof LOGO_ASPECT !== 'undefined' && LOGO_ASPECT) || (918 / 887);

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

function studentsFilterLabel (statusFilter) {
  const map = { todos: 'Todos', activo: 'Activos', inactivo: 'Inactivos', adeudo: 'Con adeudo' };
  return map[statusFilter] || statusFilter || 'Todos';
}

function sortStudentsForExport (alumnos) {
  return [...(alumnos || [])].sort((a, b) =>
    String(a.name || '').localeCompare(String(b.name || ''), 'es', { sensitivity: 'base' }));
}

function buildStudentsExportSummary (alumnos) {
  const rows = alumnos || [];
  const byStatus = {};
  const byCategory = {};
  rows.forEach((a) => {
    const st = a.status || 'activo';
    byStatus[st] = (byStatus[st] || 0) + 1;
    const cat = a.cat && a.cat !== '—' ? a.cat : 'Sin categoría';
    byCategory[cat] = (byCategory[cat] || 0) + 1;
  });
  return {
    total: rows.length,
    activos: rows.filter(a => a.status === 'activo').length,
    inactivos: rows.filter(a => a.status !== 'activo').length,
    conAdeudo: rows.filter(a => Number(a.adeudo) > 0).length,
    adeudoTotal: rows.reduce((s, a) => s + (Number(a.adeudo) || 0), 0),
    byStatus,
    byCategory,
  };
}

function studentsDetailRows (alumnos) {
  return sortStudentsForExport(alumnos).map((a) => [
    a.id || '—',
    a.name || '—',
    a.age != null && a.age !== '' ? `${a.age}` : '—',
    a.cat || '—',
    a.tutor || '—',
    a.student_phone && a.student_phone !== '—' ? a.student_phone : '—',
    a.phone || '—',
    a.email || '—',
    STUDENTS_EXPORT_STATUS[a.status] || a.status || '—',
    Number(a.adeudo) > 0 ? Number(a.adeudo) : 'Al corriente',
    a.joined || '—',
    a.antiguedad || computeSeniorityLabel?.(a.joined_at) || '—',
  ]);
}

async function urlToDataUrl (url) {
  if (!url) return null;
  try {
    const res = await fetch(url, { mode: 'cors', cache: 'no-cache' });
    if (!res.ok) return null;
    const blob = await res.blob();
    return await new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  } catch {
    return null;
  }
}

function dataUrlFormat (dataUrl) {
  if (!dataUrl || typeof dataUrl !== 'string') return 'JPEG';
  if (dataUrl.includes('image/png')) return 'PNG';
  if (dataUrl.includes('image/webp')) return 'WEBP';
  return 'JPEG';
}

function dataUrlBase64 (dataUrl) {
  if (!dataUrl || typeof dataUrl !== 'string') return null;
  const i = dataUrl.indexOf(',');
  return i >= 0 ? dataUrl.slice(i + 1) : dataUrl;
}

async function loadSchoolLogo () {
  if (typeof loadTecosLogoDataUrl === 'function') return loadTecosLogoDataUrl();
  return urlToDataUrl(LOGO_PATH);
}

async function preloadStudentPhotos (alumnos) {
  const sorted = sortStudentsForExport(alumnos);
  const cache = {};
  await Promise.all(sorted.map(async (a) => {
    const key = a._uuid || a.id;
    if (!a.photoUrl) return;
    cache[key] = await urlToDataUrl(a.photoUrl);
  }));
  return cache;
}

function styleExcelHeaderRow (row) {
  row.font = { bold: true, color: { argb: 'FFFFFFFF' }, size: 11 };
  row.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF0F172A' } };
  row.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
  row.height = 22;
}

async function exportStudentsExcel (alumnos, filterLabel = 'Todos', theme = {}) {
  if (typeof tecosEnsureExportLibs === 'function') await tecosEnsureExportLibs();
  if (typeof ExcelJS === 'undefined') {
    exportStudentsCsv?.(alumnos);
    alert('ExcelJS no disponible; se descargó CSV.');
    return;
  }

  const summary = buildStudentsExportSummary(alumnos);
  const sorted = sortStudentsForExport(alumnos);
  const photoCache = await preloadStudentPhotos(sorted);
  const logoDataUrl = await loadSchoolLogo();

  const wb = new ExcelJS.Workbook();
  wb.creator = SCHOOL_NAME;
  wb.created = new Date();

  const wsResumen = wb.addWorksheet('Resumen', { views: [{ showGridLines: false }] });
  wsResumen.getColumn(1).width = 28;
  wsResumen.getColumn(2).width = 22;
  wsResumen.getColumn(3).width = 18;

  let row = 1;
  if (logoDataUrl) {
    const logoId = wb.addImage({
      base64: dataUrlBase64(logoDataUrl),
      extension: dataUrlFormat(logoDataUrl).toLowerCase() === 'png' ? 'png' : 'jpeg',
    });
    wsResumen.addImage(logoId, { tl: { col: 0, row: 0 }, ext: { width: 88, height: 44 } });
    row = 4;
  }

  const titleRow = wsResumen.getRow(row);
  titleRow.getCell(1).value = SCHOOL_NAME;
  titleRow.getCell(1).font = { bold: true, size: 18, color: { argb: 'FF0F172A' } };
  titleRow.height = 28;
  row += 1;
  wsResumen.getRow(row).getCell(1).value = 'Directorio de alumnos';
  wsResumen.getRow(row).getCell(1).font = { size: 12, color: { argb: 'FF64748B' } };
  row += 2;

  [
    ['Filtro', filterLabel],
    ['Generado', new Date().toLocaleString('es-MX')],
    ['Total alumnos', summary.total],
    ['Activos', summary.activos],
    ['Inactivos', summary.inactivos],
    ['Con adeudo', summary.conAdeudo],
    ['Adeudo total MXN', summary.adeudoTotal],
  ].forEach(([k, v]) => {
    const r = wsResumen.getRow(row);
    r.getCell(1).value = k;
    r.getCell(1).font = { bold: true, color: { argb: 'FF475569' } };
    r.getCell(2).value = v;
    row += 1;
  });

  row += 1;
  wsResumen.getRow(row).getCell(1).value = 'Por estado';
  wsResumen.getRow(row).getCell(1).font = { bold: true };
  row += 1;
  Object.keys(STUDENTS_EXPORT_STATUS).forEach((k) => {
    const n = summary.byStatus[k] || 0;
    const r = wsResumen.getRow(row);
    r.getCell(1).value = STUDENTS_EXPORT_STATUS[k];
    r.getCell(2).value = n;
    row += 1;
  });

  row += 1;
  wsResumen.getRow(row).getCell(1).value = 'Por categoría';
  wsResumen.getRow(row).getCell(1).font = { bold: true };
  row += 1;
  Object.entries(summary.byCategory).sort((a, b) => b[1] - a[1]).forEach(([cat, n]) => {
    const r = wsResumen.getRow(row);
    r.getCell(1).value = cat;
    r.getCell(2).value = n;
    row += 1;
  });

  const ws = wb.addWorksheet('Alumnos');
  const headers = [
    'Foto', 'ID', 'Nombre completo', 'Edad', 'Categoría', 'Tutor',
    'Tel. alumno', 'Tel. tutor', 'Correo', 'Estado', 'Adeudo MXN', 'Ingreso', 'Antigüedad',
  ];
  const colWidths = [14, 12, 32, 8, 14, 22, 14, 14, 28, 12, 14, 14, 14];
  headers.forEach((_, i) => { ws.getColumn(i + 1).width = colWidths[i]; });

  if (logoDataUrl) {
    const logoId2 = wb.addImage({
      base64: dataUrlBase64(logoDataUrl),
      extension: dataUrlFormat(logoDataUrl).toLowerCase() === 'png' ? 'png' : 'jpeg',
    });
    ws.addImage(logoId2, { tl: { col: 0, row: 0 }, ext: { width: 72, height: 36 } });
  }

  const headerRowNum = 4;
  const headerRow = ws.getRow(headerRowNum);
  headers.forEach((h, i) => { headerRow.getCell(i + 1).value = h; });
  styleExcelHeaderRow(headerRow);

  ws.mergeCells(1, 2, 2, 6);
  const banner = ws.getCell(1, 2);
  banner.value = `${SCHOOL_NAME} — Listado de alumnos`;
  banner.font = { bold: true, size: 16, color: { argb: 'FF0F172A' } };
  banner.alignment = { vertical: 'middle' };
  ws.getCell(2, 2).value = `Filtro: ${filterLabel}  ·  ${new Date().toLocaleString('es-MX')}`;
  ws.getCell(2, 2).font = { size: 10, color: { argb: 'FF64748B' } };

  let dataRow = headerRowNum + 1;
  for (const a of sorted) {
    const r = ws.getRow(dataRow);
    const cells = studentsDetailRows([a])[0];
    r.getCell(2).value = cells[0];
    r.getCell(3).value = cells[1];
    r.getCell(4).value = cells[2];
    r.getCell(5).value = cells[3];
    r.getCell(6).value = cells[4];
    r.getCell(7).value = cells[5];
    r.getCell(8).value = cells[6];
    r.getCell(9).value = cells[7];
    r.getCell(10).value = cells[8];
    r.getCell(11).value = cells[9];
    r.getCell(12).value = cells[10];
    r.getCell(13).value = cells[11];
    r.getCell(14).value = cells[12];

    r.height = 52;
    r.alignment = { vertical: 'middle', wrapText: true };
    if (dataRow % 2 === 0) {
      for (let c = 2; c <= 14; c++) {
        r.getCell(c).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF8FAFC' } };
      }
    }

    const key = a._uuid || a.id;
    const photo = photoCache[key];
    if (photo) {
      try {
        const ext = dataUrlFormat(photo) === 'PNG' ? 'png' : 'jpeg';
        const imgId = wb.addImage({ base64: dataUrlBase64(photo), extension: ext });
        ws.addImage(imgId, {
          tl: { col: 0, row: dataRow - 1, nativeCol: 0, nativeRow: 0 },
          ext: { width: 44, height: 44 },
        });
      } catch { /* sin foto embebida */ }
    }

    dataRow += 1;
  }

  ws.views = [{ state: 'frozen', ySplit: headerRowNum }];

  const buffer = await wb.xlsx.writeBuffer();
  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = studentsExportFilename('xlsx', filterLabel);
  a.click();
  URL.revokeObjectURL(a.href);
}

async function exportStudentsPdf (alumnos, filterLabel = 'Todos', theme = {}) {
  if (typeof tecosEnsureExportLibs === 'function') await tecosEnsureExportLibs();
  const t = theme || (typeof THEMES !== 'undefined' ? THEMES.light : {});
  const primary = t.primary || '#2563eb';
  const summary = buildStudentsExportSummary(alumnos);
  const sorted = sortStudentsForExport(alumnos);
  const { jsPDF } = window.jspdf || {};
  if (!jsPDF) {
    exportStudentsCsv?.(alumnos);
    alert('Librería PDF no cargada; se descargó CSV.');
    return;
  }

  const [logoDataUrl, photoCache] = await Promise.all([
    loadSchoolLogo(),
    preloadStudentPhotos(sorted),
  ]);

  const doc = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });
  const pageW = doc.internal.pageSize.getWidth();
  const pageH = doc.internal.pageSize.getHeight();
  const margin = 12;
  const dateStr = new Date().toLocaleString('es-MX', { dateStyle: 'long', timeStyle: 'short' });

  const drawPageHeader = (pageNum) => {
    doc.setFillColor(15, 23, 42);
    doc.rect(0, 0, pageW, 28, 'F');
    const logoH = 22;
    const logoW = Math.round(logoH * LOGO_PDF_ASPECT * 10) / 10;
    if (logoDataUrl) {
      try {
        doc.addImage(logoDataUrl, dataUrlFormat(logoDataUrl), margin, 3, logoW, logoH);
      } catch { /* skip */ }
    }
    const textX = logoDataUrl ? margin + logoW + 8 : margin;
    doc.setTextColor(255, 255, 255);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(16);
    doc.text(SCHOOL_NAME, textX, 11);
    doc.setFontSize(9);
    doc.setFont('helvetica', 'normal');
    doc.text('Directorio de alumnos', textX, 17);
    doc.text(`Filtro: ${filterLabel}`, textX, 22);
    doc.text(dateStr, pageW - margin, 11, { align: 'right' });
    if (pageNum != null) {
      doc.text(`Pág. ${pageNum}`, pageW - margin, 22, { align: 'right' });
    }
  };

  drawPageHeader(1);
  doc.setTextColor(30, 41, 59);

  const kpis = [
    ['Total', String(summary.total)],
    ['Activos', String(summary.activos)],
    ['Inactivos', String(summary.inactivos)],
    ['Con adeudo', String(summary.conAdeudo)],
    ['Adeudo total', `$${summary.adeudoTotal.toLocaleString('es-MX')}`],
  ];
  let kpiY = 34;
  kpis.forEach((k, i) => {
    const x = margin + i * 52;
    doc.setDrawColor(226, 232, 240);
    doc.setFillColor(248, 250, 252);
    doc.roundedRect(x, kpiY, 48, 14, 2, 2, 'FD');
    doc.setFontSize(7);
    doc.setTextColor(100, 116, 139);
    doc.setFont('helvetica', 'normal');
    doc.text(k[0], x + 3, kpiY + 5);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(10);
    doc.setTextColor(15, 23, 42);
    doc.text(k[1], x + 3, kpiY + 11);
  });

  const tableStartY = 52;
  const head = [['', 'ID', 'Nombre', 'Ed.', 'Categoría', 'Tutor', 'Teléfonos', 'Correo', 'Estado', 'Adeudo', 'Ingreso']];
  const body = sorted.map((a) => [
    '',
    a.id || '—',
    a.name || '—',
    a.age != null && a.age !== '' ? String(a.age) : '—',
    a.cat || '—',
    (a.tutor || '—').slice(0, 28),
    [a.student_phone, a.phone].filter(p => p && p !== '—').join(' / ') || '—',
    (a.email || '—').slice(0, 32),
    STUDENTS_EXPORT_STATUS[a.status] || a.status || '—',
    Number(a.adeudo) > 0 ? `$${Number(a.adeudo).toLocaleString('es-MX')}` : 'Al corriente',
    a.joined || '—',
  ]);

  doc.autoTable({
    startY: tableStartY,
    head,
    body,
    theme: 'grid',
    margin: { left: margin, right: margin },
    styles: {
      fontSize: 8,
      cellPadding: 2,
      valign: 'middle',
      overflow: 'linebreak',
    },
    headStyles: {
      fillColor: [37, 99, 235],
      textColor: 255,
      fontStyle: 'bold',
      fontSize: 8,
    },
    alternateRowStyles: { fillColor: [248, 250, 252] },
    columnStyles: {
      0: { cellWidth: 16 },
      1: { cellWidth: 16, fontStyle: 'bold' },
      2: { cellWidth: 38 },
      3: { cellWidth: 10, halign: 'center' },
      9: { halign: 'right' },
    },
    didDrawCell: (data) => {
      if (data.section !== 'body' || data.column.index !== 0) return;
      const idx = data.row.index;
      const alumno = sorted[idx];
      if (!alumno) return;
      const img = photoCache[alumno._uuid || alumno.id];
      if (!img) return;
      const pad = 1.5;
      const size = Math.min(data.cell.width - pad * 2, data.cell.height - pad * 2, 14);
      try {
        doc.addImage(
          img,
          dataUrlFormat(img),
          data.cell.x + (data.cell.width - size) / 2,
          data.cell.y + (data.cell.height - size) / 2,
          size,
          size,
        );
      } catch { /* skip */ }
    },
    didDrawPage: (data) => {
      if (data.pageNumber > 1) {
        drawPageHeader(data.pageNumber);
      }
      doc.setFontSize(7);
      doc.setTextColor(148, 163, 184);
      doc.text(
        `${SCHOOL_NAME} — ${filterLabel} — ${sorted.length} alumno(s)`,
        pageW / 2,
        pageH - 6,
        { align: 'center' },
      );
    },
    rowPageBreak: 'avoid',
    bodyStyles: { minCellHeight: 16 },
  });

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

Object.assign(window, {
  studentsFilterLabel,
  exportStudentsExcel,
  exportStudentsPdf,
});
