/* =====================================================================
 * Export PDF direct (html2canvas + jsPDF), sans passer par l'impression.
 * ===================================================================== */

const PDF_RENDER_WIDTH = 820;

/**
 * Rend un élément React hors écran puis l'enregistre en PDF A4.
 * Les blocs `.print-avoid-break` ne sont pas coupés entre deux pages si possible.
 */
async function exportNodeToPdf(node, filename) {
  if (!window.html2canvas || !window.jspdf) {
    throw new Error('Librairies PDF absentes : relancez « run.py » pour les télécharger.');
  }

  const host = document.createElement('div');
  host.style.cssText = `position:absolute;left:-${PDF_RENDER_WIDTH * 3}px;top:0;width:${PDF_RENDER_WIDTH}px;background:#fff;`;
  document.body.appendChild(host);
  const root = ReactDOM.createRoot(host);

  try {
    root.render(node);
    // Laisse React afficher le contenu et Tailwind générer les styles correspondants.
    await new Promise((r) => setTimeout(r, 500));

    const scale = 2;
    const canvas = await window.html2canvas(host, {
      scale,
      backgroundColor: '#ffffff',
      windowWidth: PDF_RENDER_WIDTH,
      scrollX: 0,
      scrollY: 0,
      logging: false,
    });

    const hostTop = host.getBoundingClientRect().top;
    const blocks = [...host.querySelectorAll('.print-avoid-break')].map((el) => {
      const r = el.getBoundingClientRect();
      return { top: (r.top - hostTop) * scale, bottom: (r.bottom - hostTop) * scale };
    });

    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF({ unit: 'mm', format: 'a4', orientation: 'portrait' });
    const margin = 8;
    const imgW = 210 - margin * 2;
    const pxPerMm = canvas.width / imgW;
    const pagePx = Math.floor((297 - margin * 2) * pxPerMm);

    let y = 0;
    let first = true;
    while (y < canvas.height - 1) {
      let end = Math.min(y + pagePx, canvas.height);
      if (end < canvas.height) {
        const straddling = blocks.find((b) => b.top > y + 10 && b.top < end && b.bottom > end);
        if (straddling) end = Math.floor(straddling.top) - 4;
      }
      const sliceH = end - y;
      const slice = document.createElement('canvas');
      slice.width = canvas.width;
      slice.height = sliceH;
      const ctx = slice.getContext('2d');
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, slice.width, slice.height);
      ctx.drawImage(canvas, 0, y, canvas.width, sliceH, 0, 0, canvas.width, sliceH);

      if (!first) pdf.addPage();
      pdf.addImage(slice.toDataURL('image/jpeg', 0.92), 'JPEG', margin, margin, imgW, sliceH / pxPerMm);
      first = false;
      y = end;
    }

    pdf.save(filename);
  } finally {
    root.unmount();
    host.remove();
  }
}

/** Bouton « Télécharger PDF » avec état de chargement. */
function PdfButton({ node, filename, variant = 'dark', size = 'md', label = 'Télécharger PDF', iconOnly = false }) {
  const { notify } = useApp();
  const [busy, setBusy] = useState(false);

  const run = async () => {
    setBusy(true);
    try {
      await exportNodeToPdf(node, filename);
      notify(`PDF enregistré : ${filename}`);
    } catch (err) {
      console.error(err);
      notify(err.message || 'Échec de la génération du PDF', 'red');
    } finally {
      setBusy(false);
    }
  };

  if (iconOnly) {
    return <IconButton icon={FileText} title={busy ? 'Génération…' : label} onClick={run} disabled={busy} />;
  }
  return (
    <Button variant={variant} size={size} icon={busy ? Clock : FileText} onClick={run} disabled={busy}>
      {busy ? 'Génération…' : label}
    </Button>
  );
}
