// certificate.jsx — Overlay de felicitaciones + diseño del certificado ASSYST
const { useState: useCertSt, useRef: useCertRef, useEffect: useCertFx } = React;

// ── Utilidades ────────────────────────────────────────────────────────────────
function certFmtDate(val) {
  if (!val) return '—';
  // Formato nuevo: ya viene como "15 de junio de 2026" — devolver tal cual.
  if (!/^\d{4}-\d{2}/.test(val)) return val;
  // Formato ISO heredado (compatibilidad): parsear y reformatear.
  var d = new Date(val);
  if (isNaN(d.getTime())) return val;
  return d.toLocaleDateString('es-CO', { day: 'numeric', month: 'long', year: 'numeric' });
}

// ── El documento del certificado (1123×794 — A4 landscape @96 dpi) ───────────
function CertificateDoc({ user, startDate, endDate, certNumber, logoSrc, signSrc, logo2Src, certConfig, innerRef }) {
  var cfg     = certConfig || {};
  var name    = (user.nombre  || '').toUpperCase();
  var empresa =  user.empresa || '';
  var cargo   =  user.cargo   || '';

  // ornamental divider
  function Divider({ opacity }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, width: '84%' }}>
        <div style={{ flex: 1, height: 1.5, background: 'linear-gradient(90deg, transparent, #c4b400)', opacity: opacity || 1 }} />
        <div style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
          <div style={{ width: 5, height: 5, background: '#c4b400', transform: 'rotate(45deg)', opacity: opacity || 1 }} />
          <div style={{ width: 8, height: 8, background: '#1c79b4', transform: 'rotate(45deg)', opacity: opacity || 1 }} />
          <div style={{ width: 5, height: 5, background: '#c4b400', transform: 'rotate(45deg)', opacity: opacity || 1 }} />
        </div>
        <div style={{ flex: 1, height: 1.5, background: 'linear-gradient(90deg, #c4b400, transparent)', opacity: opacity || 1 }} />
      </div>
    );
  }

  return (
    <div ref={innerRef} style={{
      width: 1123, height: 794, position: 'relative', overflow: 'hidden',
      background: '#ffffff', fontFamily: "'Montserrat', sans-serif"
    }}>

      {/* ── Marca de agua: logo ASSYST ── */}
      {logoSrc && (
        <img src={logoSrc} alt="" style={{
          position: 'absolute', top: '50%', left: '50%',
          transform: 'translate(-50%,-50%)',
          width: 460, height: 460, objectFit: 'contain',
          opacity: 0.045, userSelect: 'none', pointerEvents: 'none', zIndex: 0
        }} />
      )}

      {/* ── Borde exterior azul ── */}
      <div style={{ position: 'absolute', inset: 0, border: '11px solid #1c79b4', pointerEvents: 'none', zIndex: 20 }} />
      {/* ── Borde interior dorado ── */}
      <div style={{ position: 'absolute', inset: 16, border: '2px solid #c4b400', pointerEvents: 'none', zIndex: 20 }} />

      {/* ── Esquinas doradas ── */}
      {[['top','left'],['top','right'],['bottom','left'],['bottom','right']].map(function(c, i) {
        var s = {}; s[c[0]] = 22; s[c[1]] = 22;
        return (
          <div key={i} style={{
            position: 'absolute', width: 32, height: 32, zIndex: 21, ...s,
            borderTop:    c[0]==='top'    ? '3px solid #c4b400' : 'none',
            borderBottom: c[0]==='bottom' ? '3px solid #c4b400' : 'none',
            borderLeft:   c[1]==='left'   ? '3px solid #c4b400' : 'none',
            borderRight:  c[1]==='right'  ? '3px solid #c4b400' : 'none',
          }} />
        );
      })}

      {/* ── Contenido principal — space-between llena el área ── */}
      <div style={{
        position: 'relative', zIndex: 10,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'space-between',
        height: '100%', padding: '26px 80px 22px',
        boxSizing: 'border-box'
      }}>

        {/* 1 ── Logo + subtítulo ── */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            {logoSrc
              ? <img src={logoSrc} alt="ASSYST" style={{ width: 92, height: 92, objectFit: 'contain' }} />
              : <div style={{ width: 92, height: 92, borderRadius: '50%', background: '#1c79b4', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#c4b400', fontWeight: 900, fontSize: 20 }}>ASSYST</div>
            }
            {cfg.logoSecundarioEnabled && logo2Src && (
              <>
                <div style={{ width: 1, height: 62, background: '#d1d5db', flexShrink: 0 }} />
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                  <img src={logo2Src} alt="Aval" style={{ height: 68, maxWidth: 110, objectFit: 'contain' }} />
                  {cfg.textoAval && <div style={{ fontSize: 8, color: '#94a3b8', fontWeight: 600, letterSpacing: '0.04em', textAlign: 'center' }}>{cfg.textoAval}</div>}
                </div>
              </>
            )}
          </div>
          <div style={{ fontSize: 10, fontWeight: 700, color: '#94a3b8', letterSpacing: '0.2em', textTransform: 'uppercase' }}>
            Plataforma Virtual de Formación Profesional
          </div>
        </div>

        {/* 2 ── Divider superior ── */}
        <Divider />

        {/* 3 ── Nombre + empresa ── */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, width: '100%' }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8', letterSpacing: '0.3em', textTransform: 'uppercase' }}>
            Certifica que
          </div>
          <div style={{
            fontSize: 40, fontWeight: 900, color: '#1c79b4',
            textAlign: 'center', lineHeight: 1.1, letterSpacing: '-0.5px',
            maxWidth: 900
          }}>{name}</div>
          <div style={{ fontSize: 13, color: '#6b7280', letterSpacing: '0.04em' }}>
            {empresa}{cargo ? ' · ' + cargo : ''}
          </div>
          <div style={{
            width: 380, height: 2,
            background: 'linear-gradient(90deg, transparent, #c4b400 25%, #c4b400 75%, transparent)'
          }} />
        </div>

        {/* 4 ── Texto del entrenamiento ── */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, width: '100%' }}>
          <div style={{ fontSize: 14, color: '#4b5563', textAlign: 'center', lineHeight: 1.6 }}>
            Felicitaciones por haber completado satisfactoriamente:
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.07em', lineHeight: 1.4 }}>
              el entrenamiento en
            </div>
            {(cfg.nombreCurso || 'Diseño, Implementación y Automatización\ncon Inteligencia Artificial del\nSistema de Gestión en Seguridad y Salud en el Trabajo (SG-SST)').split('\n').filter(function(l){return l.trim();}).map(function(line, i, arr) {
              var isFirst = i === 0;
              var isLast  = i === arr.length - 1;
              return (
                <div key={i} style={{
                  fontSize: isFirst ? 20 : isLast ? 18 : 17,
                  fontWeight: isFirst || isLast ? 900 : 700,
                  color: isLast ? '#1c79b4' : '#0f2044',
                  lineHeight: isFirst ? 1.25 : 1.3,
                  textTransform: isLast ? 'uppercase' : 'none',
                  letterSpacing: isFirst ? '0.01em' : isLast ? '0.02em' : 0,
                  textAlign: 'center',
                }}>{line}</div>
              );
            })}
          </div>
        </div>

        {/* 5 ── Modalidad ── */}
        <div style={{ display: 'flex', gap: 20, alignItems: 'center', fontSize: 12, color: '#6b7280' }}>
          <span>Modalidad: <strong style={{ color: '#374151' }}>{cfg.modalidad || 'Virtual'}</strong></span>
          <span style={{ color: '#d1d5db', fontSize: 16 }}>·</span>
          <span>Intensidad: <strong style={{ color: '#374151' }}>{formatDuracion(getTotalCourseMinutes())}</strong></span>
          <span style={{ color: '#d1d5db', fontSize: 16 }}>·</span>
          <span>{cfg.pais || 'República de Colombia'}</span>
        </div>

        {/* 6 ── Divider inferior ── */}
        <Divider opacity={0.65} />

        {/* 7 ── Fechas + firma (3 columnas iguales) ── */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', width: '90%', alignItems: 'end', gap: 0 }}>

          {/* Fecha inicio */}
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 11, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 3 }}>
              Fecha de inicio
            </div>
            <div style={{ fontSize: 15, fontWeight: 800, color: '#1c79b4' }}>
              {certFmtDate(startDate)}
            </div>
            <div style={{ width: 140, height: 1.5, background: '#1c79b4', margin: '5px auto 0', opacity: 0.3 }} />
          </div>

          {/* Firma — centro exacto */}
          <div style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            {signSrc
              ? <img src={signSrc} alt="Firma" style={{ height: 62, maxWidth: 180, objectFit: 'contain', display: 'block' }} />
              : <div style={{ height: 62 }} />
            }
            <div style={{ width: 160, height: 2, background: '#1c79b4', margin: '3px 0 4px' }} />
            <div style={{ fontSize: 10, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
              {cfg.nombreFirmante || 'Firma Representante Legal'}
            </div>
            <div style={{ fontSize: 10, color: '#94a3b8' }}>{cfg.cargoFirmante || 'ASSYST · SG-SST'}</div>
          </div>

          {/* Fecha fin */}
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 11, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 3 }}>
              Fecha de finalización
            </div>
            <div style={{ fontSize: 15, fontWeight: 800, color: '#1c79b4' }}>
              {certFmtDate(endDate)}
            </div>
            <div style={{ width: 140, height: 1.5, background: '#1c79b4', margin: '5px auto 0', opacity: 0.3 }} />
          </div>

        </div>

        {/* 8 ── Código de certificado ── */}
        <div style={{
          background: '#1c79b4', borderRadius: 6,
          padding: '7px 26px', display: 'flex', alignItems: 'center', gap: 12,
          boxShadow: '0 2px 12px rgba(28,121,180,.3)'
        }}>
          <span style={{ fontSize: 10, color: 'rgba(255,255,255,.65)', textTransform: 'uppercase', letterSpacing: '0.14em' }}>
            Código de certificado:
          </span>
          <span style={{ fontSize: 14, fontWeight: 900, color: '#c4b400', letterSpacing: '0.15em' }}>
            {certNumber}
          </span>
        </div>

      </div>{/* /content */}
    </div>
  );
}

// ── Overlay de felicitaciones ─────────────────────────────────────────────────
function CertificateOverlay({ user, onClose }) {
  const certRef    = useCertRef(null);
  const [busy, setBusy]   = useCertSt(false);
  const [logo, setLogo]   = useCertSt('');
  const [sign, setSign]   = useCertSt('');
  const [logo2, setLogo2] = useCertSt('');
  const [scale, setScale] = useCertSt(0.72);
  var certCfg = window.getCertConfig ? window.getCertConfig() : {};

  // Cert data — para cuando el overlay se muestra, issueCertificate ya fue
  // llamado desde handleCertClick o el useEffect de student-view, con las
  // fechas reales ya persistidas. El fallback a issueCertificate es solo
  // seguridad ante un caso extremo (nunca debe ejecutarse en flujo normal).
  var certData = getCertInfo(user.id) || issueCertificate(user.id);

  // Pre-cargar logos y firma respetando configuración del administrador
  useCertFx(function () {
    var cfg = window.getCertConfig ? window.getCertConfig() : {};
    function loadAsBase64(url, setter) {
      fetch(url)
        .then(function (r) { return r.blob(); })
        .then(function (blob) {
          var fr = new FileReader();
          fr.onloadend = function () { setter(fr.result); };
          fr.readAsDataURL(blob);
        })
        .catch(function () {});
    }
    // Logo principal
    if (cfg.logoPrincipal) {
      if (cfg.logoPrincipal.startsWith('data:')) { setLogo(cfg.logoPrincipal); }
      else { loadAsBase64(cfg.logoPrincipal, setLogo); }
    } else {
      loadAsBase64((window.__resources && window.__resources.logoAssyst) || 'uploads/LOGO.png', setLogo);
    }
    // Firma
    if (cfg.imagenFirma) {
      setSign(cfg.imagenFirma);
    } else {
      loadAsBase64((window.__resources && window.__resources.signAssyst) || 'uploads/pasted-1781199739000-0.png', setSign);
    }
    // Logo secundario
    if (cfg.logoSecundarioEnabled && cfg.logoSecundario) {
      if (cfg.logoSecundario.startsWith('data:')) { setLogo2(cfg.logoSecundario); }
      else { loadAsBase64(cfg.logoSecundario, setLogo2); }
    }
  }, []);

  // Escala responsiva
  useCertFx(function () {
    function calcScale() {
      var avail = Math.min(window.innerWidth - 80, 1123);
      setScale(Math.min(avail / 1123, 0.78));
    }
    calcScale();
    window.addEventListener('resize', calcScale);
    return function () { window.removeEventListener('resize', calcScale); };
  }, []);

  async function handleDownload() {
    if (!window.jspdf) {
      alert('Las librerías PDF aún no están listas. Espera un momento e intenta de nuevo.');
      return;
    }
    setBusy(true);
    try {
      var { jsPDF } = window.jspdf;
      var totalDuracion = formatDuracion(getTotalCourseMinutes());
      var pdf = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });
      var W = 297, H = 210, CX = W / 2;

      // ── Paleta ────────────────────────────────────────────────────────────
      var BLUE  = [28, 121, 180];
      var DBLUE = [15, 32, 68];
      var GOLD  = [196, 180, 0];
      var GOLD2 = [176, 162, 0];    // divider inferior (más tenue)
      var GRAY  = [107, 114, 128];
      var LGRAY = [148, 163, 184];
      var DARK  = [55, 65, 81];

      function dc(c) { pdf.setDrawColor(c[0], c[1], c[2]); }
      function fc(c) { pdf.setFillColor(c[0], c[1], c[2]); }
      function tc(c) { pdf.setTextColor(c[0], c[1], c[2]); }
      function lw(n) { pdf.setLineWidth(n); }
      function ln(x1,y1,x2,y2) { pdf.line(x1,y1,x2,y2); }
      function tx(t,x,y,o) { pdf.text(t,x,y,o||{}); }

      // ── Fondo blanco ──────────────────────────────────────────────────────
      fc([255,255,255]); dc([255,255,255]);
      pdf.rect(0,0,W,H,'F');

      // ── Borde exterior azul ───────────────────────────────────────────────
      dc(BLUE); lw(3.5);
      pdf.rect(3,3,W-6,H-6);

      // ── Borde interior dorado ─────────────────────────────────────────────
      dc(GOLD); lw(0.7);
      pdf.rect(7.5,7.5,W-15,H-15);

      // ── Esquinas doradas ──────────────────────────────────────────────────
      var co=10, cl=11;
      dc(GOLD); lw(1.2);
      [[co,co,1,1],[W-co,co,-1,1],[co,H-co,1,-1],[W-co,H-co,-1,-1]].forEach(function(p){
        ln(p[0],p[1], p[0]+p[2]*cl, p[1]);
        ln(p[0],p[1], p[0],         p[1]+p[3]*cl);
      });

      // ── Logo ──────────────────────────────────────────────────────────────
      if (logo) {
        if (certCfg.logoSecundarioEnabled && logo2) {
          pdf.addImage(logo,'PNG',CX-30,11,28,28);
          pdf.addImage(logo2,'PNG',CX+2,11,28,28);
          if (certCfg.textoAval) {
            pdf.setFont('helvetica','normal'); pdf.setFontSize(5.5); tc(LGRAY);
            tx(certCfg.textoAval, CX+16, 41, {align:'center'});
          }
        } else {
          pdf.addImage(logo,'PNG',CX-14,11,28,28);
        }
      }

      // ── Subtítulo ─────────────────────────────────────────────────────────
      pdf.setFont('helvetica','bold'); pdf.setFontSize(6.5); tc(LGRAY);
      tx('PLATAFORMA VIRTUAL DE FORMACIÓN PROFESIONAL',CX,42,{align:'center'});

      // ── Divider superior ──────────────────────────────────────────────────
      function drawDiv(y,c) {
        dc(c); lw(0.5); ln(22,y,CX-7,y); ln(CX+7,y,W-22,y);
        fc(c); dc(c); lw(0.01);
        pdf.triangle(CX,y-3, CX-3,y, CX+3,y,'F');
        pdf.triangle(CX-3,y, CX+3,y, CX,y+3,'F');
      }
      drawDiv(47, GOLD);

      // ── CERTIFICA QUE ─────────────────────────────────────────────────────
      pdf.setFont('helvetica','bold'); pdf.setFontSize(8); tc(LGRAY);
      tx('C E R T I F I C A   Q U E',CX,56,{align:'center'});

      // ── Nombre estudiante (tamaño adaptado) ───────────────────────────────
      var nomUp = (user.nombre||'').toUpperCase();
      var nfs = nomUp.length > 32 ? 18 : nomUp.length > 24 ? 20 : 24;
      pdf.setFont('helvetica','bold'); pdf.setFontSize(nfs); tc(BLUE);
      tx(nomUp,CX,71,{align:'center'});

      // ── Empresa · cargo ───────────────────────────────────────────────────
      pdf.setFont('helvetica','normal'); pdf.setFontSize(9); tc(GRAY);
      tx((user.empresa||'') + (user.cargo ? '  ·  '+user.cargo : ''),CX,79,{align:'center'});

      // ── Línea dorada ──────────────────────────────────────────────────────
      dc(GOLD); lw(0.9); ln(CX-52,83,CX+52,83);

      // ── Texto cuerpo ──────────────────────────────────────────────────────
      pdf.setFont('helvetica','normal'); pdf.setFontSize(10); tc(GRAY);
      tx('Felicitaciones por haber completado satisfactoriamente:',CX,92,{align:'center'});

      // ── Título del entrenamiento ──────────────────────────────────────────
      pdf.setFont('helvetica','bold'); pdf.setFontSize(9); tc([140,150,165]);
      tx('EL ENTRENAMIENTO EN',CX,101,{align:'center'});

      var pdfCourseLines = (certCfg.nombreCurso || '').split('\n').filter(function(l){return l.trim();});
      if (!pdfCourseLines.length) pdfCourseLines = ['Diseño, Implementación y Automatización','con Inteligencia Artificial del','Sistema de Gestión en Seguridad y Salud en el Trabajo (SG-SST)'];
      pdf.setFont('helvetica','bold'); pdf.setFontSize(15); tc(DBLUE);
      tx(pdfCourseLines[0] || '', CX, 112, {align:'center'});
      if (pdfCourseLines[1]) { pdf.setFont('helvetica','bold'); pdf.setFontSize(12); tc(DBLUE); tx(pdfCourseLines[1], CX, 121, {align:'center'}); }
      if (pdfCourseLines[2]) { pdf.setFont('helvetica','bold'); pdf.setFontSize(13); tc(BLUE);  tx(pdfCourseLines[2], CX, 131, {align:'center'}); }

      // ── Modalidad ─────────────────────────────────────────────────────────
      pdf.setFont('helvetica','normal'); pdf.setFontSize(8.5); tc(GRAY);
      tx('Modalidad: ' + (certCfg.modalidad || 'Virtual') + '   ·   Intensidad: ' + totalDuracion + '   ·   ' + (certCfg.pais || 'República de Colombia'), CX, 139, {align:'center'});

      // ── Divider inferior ──────────────────────────────────────────────────
      drawDiv(145, GOLD2);

      // ── Fila de fechas + firma (baseline = fBase) ─────────────────────────
      var fBase = 171;

      // Fecha inicio — columna izquierda
      pdf.setFont('helvetica','bold'); pdf.setFontSize(7.5); tc(LGRAY);
      tx('FECHA DE INICIO',57,fBase-13,{align:'center'});
      pdf.setFont('helvetica','bold'); pdf.setFontSize(12); tc(BLUE);
      tx(certFmtDate(certData.startDate),57,fBase-4,{align:'center'});
      dc([210,220,230]); lw(0.5); ln(22,fBase,92,fBase);

      // Firma — columna central
      if (sign) { pdf.addImage(sign,'PNG',CX-27,fBase-22,54,21); }
      dc(BLUE); lw(1.3); ln(CX-30,fBase,CX+30,fBase);
      pdf.setFont('helvetica','bold'); pdf.setFontSize(8); tc(DARK);
      tx((certCfg.nombreFirmante || 'Firma Representante Legal').toUpperCase(), CX, fBase+6, {align:'center'});
      pdf.setFont('helvetica','normal'); pdf.setFontSize(7.5); tc(LGRAY);
      tx(certCfg.cargoFirmante || 'ASSYST · SG-SST', CX, fBase+12, {align:'center'});

      // Fecha fin — columna derecha
      pdf.setFont('helvetica','bold'); pdf.setFontSize(7.5); tc(LGRAY);
      tx('FECHA DE FINALIZACIÓN',W-57,fBase-13,{align:'center'});
      pdf.setFont('helvetica','bold'); pdf.setFontSize(12); tc(BLUE);
      tx(certFmtDate(certData.finishDate),W-57,fBase-4,{align:'center'});
      dc([210,220,230]); lw(0.5); ln(W-92,fBase,W-22,fBase);

      // ── Código de certificado ─────────────────────────────────────────────
      var bx=CX-55, by=185, bw=110, bh=11;
      fc(BLUE); dc(BLUE); lw(0.01);
      pdf.roundedRect(bx,by,bw,bh,2,2,'F');

      pdf.setFont('helvetica','normal'); pdf.setFontSize(7); tc([190,220,240]);
      tx('CÓDIGO DE CERTIFICADO:',CX-2,by+7.2,{align:'right'});
      pdf.setFont('helvetica','bold'); pdf.setFontSize(9.5);
      pdf.setTextColor(196,180,0);
      tx(certData.certNumber,CX,by+7.2,{align:'left'});

      // ── Guardar ───────────────────────────────────────────────────────────
      pdf.save('Certificado-' + certData.certNumber + '.pdf');

    } catch(e) {
      console.error('[CERT PDF]', e);
      alert('Error al generar el PDF: ' + e.message);
    }
    setBusy(false);
  }

  // Dimensions after scaling
  var scaledW = Math.round(1123 * scale);
  var scaledH = Math.round(794  * scale);

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(5,15,35,0.93)',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'flex-start', zIndex: 3000,
      overflowY: 'auto', padding: '28px 24px 40px',
      fontFamily: "'Montserrat', sans-serif"
    }}>

      {/* ── Encabezado de felicitaciones ── */}
      <div style={{ textAlign: 'center', marginBottom: 24, animation: 'certFadeIn .5s ease' }}>
        <div style={{ fontSize: 52, marginBottom: 8, lineHeight: 1 }}>🎓</div>
        <div style={{ fontSize: 26, fontWeight: 900, color: '#ffffff', marginBottom: 6, lineHeight: 1.2 }}>
          ¡Felicitaciones, {user.nombre.split(' ')[0]}!
        </div>
        <div style={{ fontSize: 14, color: 'rgba(255,255,255,.55)', maxWidth: 480 }}>
          Completaste el 100% del curso. Tu certificado está listo para descargar.
        </div>
      </div>

      {/* ── Certificado escalado ── */}
      <div style={{ width: scaledW, height: scaledH, flexShrink: 0, position: 'relative', marginBottom: 24, boxShadow: '0 24px 80px rgba(0,0,0,.6)' }}>
        <div style={{ transform: 'scale(' + scale + ')', transformOrigin: 'top left', position: 'absolute', top: 0, left: 0 }}>
          <CertificateDoc
            user={user}
            startDate={certData.startDate}
            endDate={certData.finishDate}
            certNumber={certData.certNumber}
            logoSrc={logo}
            signSrc={sign}
            logo2Src={logo2}
            certConfig={certCfg}
            innerRef={certRef}
          />
        </div>
      </div>

      {/* ── Botones ── */}
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
        <button
          onClick={handleDownload}
          disabled={busy}
          style={{
            background: busy ? '#1a5f8e' : '#1c79b4',
            color: 'white', border: 'none', borderRadius: 12,
            padding: '14px 30px', fontSize: 14, fontWeight: 700,
            cursor: busy ? 'wait' : 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 10,
            transition: 'background .2s', boxShadow: '0 4px 20px rgba(28,121,180,.5)'
          }}
        >
          {busy
            ? <><span style={{ fontSize: 16 }}>⏳</span> Generando PDF…</>
            : <><span style={{ fontSize: 16 }}>⬇</span> Descargar mi certificado en PDF</>
          }
        </button>
        <button
          onClick={onClose}
          style={{
            background: 'rgba(255,255,255,.08)', color: 'rgba(255,255,255,.75)',
            border: '1px solid rgba(255,255,255,.15)', borderRadius: 12,
            padding: '14px 24px', fontSize: 14, cursor: 'pointer', fontFamily: 'inherit'
          }}
        >
          Cerrar
        </button>
      </div>

      <style>{`
        @keyframes certFadeIn { from { opacity:0; transform:translateY(-16px); } to { opacity:1; transform:none; } }
      `}</style>
    </div>
  );
}

window.CertificateDoc     = CertificateDoc;
window.CertificateOverlay = CertificateOverlay;
