/* PDF comprobante — registro de interés (avisos / eventos) */

async function exportInterestRegistrationReceiptPdf ({
  kind = 'announcement',
  entity = {},
  registration = {},
  studentExtra = null,
  settings = {},
  theme = {},
}) {
  const { jsPDF } = window.jspdf || {};
  if (!jsPDF) throw new Error('Librería PDF no disponible');
  const drawBanner = window.drawReceiptPdfBanner;
  const drawStudent = window.drawReceiptStudentCard;
  const drawFooter = window.drawReceiptPdfFooter;
  const fmtDt = window.formatReceiptDateTime || ((iso) => (iso ? new Date(iso).toLocaleString('es-MX') : '—'));
  const loadImg = window.loadReceiptImage;
  const imgFmt = window.receiptImgFormat || (() => 'JPEG');
  if (!drawBanner || !drawStudent || !drawFooter) {
    throw new Error('Carga payment-receipt-export.jsx antes de generar PDF');
  }

  const schoolName = settings?.venue_name || window.RECEIPT_SCHOOL_NAME || 'TECOS ELITE VOLLEYBALL';
  const isEvent = kind === 'event';
  const titleLine = isEvent
    ? 'Comprobante de confirmación de asistencia'
    : 'Comprobante de registro de interés';
  const entityLabel = isEvent ? 'Evento' : 'Aviso';
  const regAt = registration.registered_at || registration.confirmed_at;
  const folio = String(registration.id || '').slice(0, 8).toUpperCase();
  const dark = [15, 23, 42];
  const margin = 16;

  const alumno = {
    id: registration.student_code || studentExtra?.code || '—',
    name: registration.student_name || studentExtra?.full_name || '—',
    cat: studentExtra?.category || '—',
    tutor: studentExtra?.tutor_name || '—',
    phone: studentExtra?.tutor_phone || '—',
    photoUrl: studentExtra?.photo_path && typeof getStoragePublicUrl === 'function'
      ? getStoragePublicUrl('gallery', studentExtra.photo_path)
      : null,
  };

  const [logoData, photoData] = await Promise.all([
    loadImg(window.RECEIPT_LOGO_PATH),
    loadImg(alumno.photoUrl),
  ]);

  const doc = new jsPDF({ unit: 'mm', format: 'a4' });
  const pageW = doc.internal.pageSize.getWidth();
  let y = drawBanner(doc, {
    schoolName,
    titleLine,
    rightTop: `Folio: ${folio}`,
    rightBottom: fmtDt(regAt),
    logoData,
    margin,
    pageW,
  });

  y = drawStudent(doc, alumno, photoData, y, margin, pageW);

  const starts = entity.starts_at ? new Date(entity.starts_at) : null;
  const dateLabel = starts && !Number.isNaN(starts.getTime())
    ? starts.toLocaleString('es-MX', {
      weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit',
    })
    : '—';

  doc.setFont('helvetica', 'bold');
  doc.setFontSize(12);
  doc.text(`Detalle del ${entityLabel.toLowerCase()}`, margin, y);
  y += 8;

  doc.autoTable({
    startY: y,
    head: [[entityLabel, 'Título', 'Fecha', 'Lugar', 'Estado']],
    body: [[
      entityLabel,
      entity.title || '—',
      dateLabel,
      entity.location || '—',
      'REGISTRADO',
    ]],
    theme: 'grid',
    headStyles: { fillColor: dark, textColor: 255, fontStyle: 'bold' },
    styles: { fontSize: 9, cellPadding: 3 },
    margin: { left: margin, right: margin },
  });
  y = doc.lastAutoTable.finalY + 10;

  doc.autoTable({
    startY: y,
    body: [
      ['Alumno', alumno.name],
      ['ID Tecos', alumno.id],
      ['Fecha y hora de registro', fmtDt(regAt)],
      ['Origen', 'Landing público — soy alumno'],
    ],
    theme: 'plain',
    styles: { fontSize: 10, cellPadding: 3 },
    columnStyles: { 0: { fontStyle: 'bold', cellWidth: 52 } },
    margin: { left: margin, right: margin },
  });
  y = doc.lastAutoTable.finalY + 10;

  doc.setFillColor(234, 179, 8);
  doc.roundedRect(margin, y, pageW - margin * 2, 14, 2, 2, 'F');
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(11);
  doc.setTextColor(15, 23, 42);
  doc.text(
    isEvent ? '✓ Asistencia registrada correctamente' : '✓ Interés registrado correctamente',
    pageW / 2,
    y + 9,
    { align: 'center' },
  );
  y += 22;

  drawFooter(doc, schoolName, y, margin, pageW);

  const safeTitle = String(entity.title || kind).replace(/[^\w\-]+/g, '-').slice(0, 40);
  doc.save(`comprobante-registro-${alumno.id}-${safeTitle}.pdf`);
}

async function exportInterestRegistrationsRosterPdf ({
  kind = 'announcement',
  entity = {},
  studentRegistrations = [],
  interestedLeads = [],
  settings = {},
}) {
  const { jsPDF } = window.jspdf || {};
  if (!jsPDF) throw new Error('Librería PDF no disponible');
  const drawBanner = window.drawReceiptPdfBanner;
  const drawFooter = window.drawReceiptPdfFooter;
  const fmtDt = window.formatReceiptDateTime || ((iso) => (iso ? new Date(iso).toLocaleString('es-MX') : '—'));
  const loadImg = window.loadReceiptImage;
  if (!drawBanner || !drawFooter) throw new Error('Carga payment-receipt-export.jsx antes de generar PDF');

  const schoolName = settings?.venue_name || window.RECEIPT_SCHOOL_NAME || 'TECOS ELITE VOLLEYBALL';
  const isEvent = kind === 'event';
  const entityLabel = isEvent ? 'Evento' : 'Aviso';
  const dark = [15, 23, 42];
  const margin = 16;

  const logoData = await loadImg(window.RECEIPT_LOGO_PATH);
  const doc = new jsPDF({ unit: 'mm', format: 'a4' });
  const pageW = doc.internal.pageSize.getWidth();
  let y = drawBanner(doc, {
    schoolName,
    titleLine: `Listado de interesados — ${entityLabel}`,
    rightTop: `${studentRegistrations.length + interestedLeads.length} registro(s)`,
    rightBottom: new Date().toLocaleString('es-MX'),
    logoData,
    margin,
    pageW,
  });

  doc.setTextColor(30, 41, 59);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(12);
  doc.text(`${entityLabel}: ${entity.title || '—'}`, margin, y);
  y += 7;
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(10);
  if (entity.location) {
    doc.text(`Lugar: ${entity.location}`, margin, y);
    y += 6;
  }
  y += 4;

  doc.setFont('helvetica', 'bold');
  doc.setFontSize(11);
  doc.text(`Alumnos registrados (${studentRegistrations.length})`, margin, y);
  y += 6;

  if (studentRegistrations.length === 0) {
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(10);
    doc.text('Sin alumnos registrados con ID.', margin, y);
    y += 10;
  } else {
    doc.autoTable({
      startY: y,
      head: [['#', 'ID', 'Nombre', 'Fecha registro']],
      body: studentRegistrations.map((r, i) => [
        i + 1,
        r.student_code || '—',
        r.student_name || '—',
        fmtDt(r.registered_at || r.confirmed_at),
      ]),
      theme: 'grid',
      headStyles: { fillColor: dark, textColor: 255, fontStyle: 'bold' },
      styles: { fontSize: 9, cellPadding: 3 },
      margin: { left: margin, right: margin },
    });
    y = doc.lastAutoTable.finalY + 12;
  }

  doc.setFont('helvetica', 'bold');
  doc.setFontSize(11);
  doc.text(`Interesados — no alumnos (${interestedLeads.length})`, margin, y);
  y += 6;

  if (interestedLeads.length === 0) {
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(10);
    doc.text('Sin contactos de personas que no son alumnos.', margin, y);
    y += 10;
  } else {
    doc.autoTable({
      startY: y,
      head: [['#', 'Nombre', 'Teléfono', 'Correo', 'Fecha']],
      body: interestedLeads.map((r, i) => [
        i + 1,
        r.name || '—',
        r.phone || '—',
        r.email || '—',
        fmtDt(r.created_at),
      ]),
      theme: 'grid',
      headStyles: { fillColor: dark, textColor: 255, fontStyle: 'bold' },
      styles: { fontSize: 9, cellPadding: 3 },
      margin: { left: margin, right: margin },
    });
    y = doc.lastAutoTable.finalY + 8;
  }

  drawFooter(doc, schoolName, y, margin, pageW);

  const safeTitle = String(entity.title || kind).replace(/[^\w\-]+/g, '-').slice(0, 40);
  doc.save(`listado-interesados-${safeTitle}.pdf`);
}

Object.assign(window, {
  exportInterestRegistrationReceiptPdf,
  exportInterestRegistrationsRosterPdf,
});
