// Impression dediee du Programme NIS2 / CyFun 2025
// Ouvre une fenetre propre avec les styles, canvases figes, et scoring CyFun
(() => {
  const TARGET_TAB = "nis2-program";
  const PRINT_WIDTH = 1400;
  const printButton = document.getElementById("printNis2ProgramBtn");
  if (!printButton) return;

  let isPrinting = false;

  function tt(key, fallback) {
    return typeof window.t === 'function' ? window.t(key) : (fallback || key);
  }

  const wait = (ms) => new Promise(function(resolve) { setTimeout(resolve, ms); });

  const getActiveTab = () => {
    const nav = document.querySelector(".nav__item--active");
    return nav ? nav.getAttribute("data-tab") : null;
  };

  const switchToProgram = async () => {
    const current = getActiveTab();
    if (current === TARGET_TAB) return current;
    const navBtn = document.querySelector('.nav__item[data-tab="' + TARGET_TAB + '"]');
    if (navBtn) {
      navBtn.click();
      await wait(500);
    }
    return current;
  };

  const refreshCharts = () => {
    try {
      const charts = window.charts || {};
      Object.values(charts).forEach(function(chart) {
        if (!chart || !chart.canvas) return;
        var isNis2Canvas = !!chart.canvas.closest('#' + TARGET_TAB);
        if (!isNis2Canvas) return;
        if (typeof chart.resize === "function") chart.resize();
        if (typeof chart.update === "function") chart.update();
      });
    } catch (e) {
      /* noop */
    }
  };

  const snapshotCanvas = (canvas) => {
    try {
      const rect = canvas.getBoundingClientRect();
      const snapshot = document.createElement("canvas");
      const ratio = window.devicePixelRatio || 1;
      snapshot.width = Math.max(1, Math.round(rect.width * ratio));
      snapshot.height = Math.max(1, Math.round(rect.height * ratio));
      const ctx = snapshot.getContext("2d");
      const bg = getComputedStyle(canvas.parentElement || canvas).backgroundColor || "#0f172a";
      ctx.fillStyle = bg;
      ctx.fillRect(0, 0, snapshot.width, snapshot.height);
      ctx.drawImage(canvas, 0, 0, snapshot.width, snapshot.height);
      const img = document.createElement("img");
      img.src = snapshot.toDataURL("image/png");
      img.alt = canvas.getAttribute("aria-label") || "Graphique";
      img.className = "print-canvas-snapshot";
      img.style.display = "block";
      img.style.width = rect.width ? (rect.width + "px") : "100%";
      img.style.height = rect.height ? (rect.height + "px") : "auto";
      return img;
    } catch (e) {
      return null;
    }
  };


  const cloneProgram = () => {
    const program = document.getElementById(TARGET_TAB);
    if (!program) throw new Error(tt('exportLabels.nis2NotFound', "Module NIS2 introuvable."));
    var headerEl = document.querySelector(".header");
    var headerClone = headerEl ? headerEl.cloneNode(true) : null;
    const programClone = program.cloneNode(true);

    // Remplacer tous les canvases par des images figees
    const sourceCanvases = program.querySelectorAll("canvas");
    const targetCanvases = programClone.querySelectorAll("canvas");
    sourceCanvases.forEach(function(canvas, idx) {
      const target = targetCanvases[idx];
      if (!target) return;
      const img = snapshotCanvas(canvas);
      if (img) target.replaceWith(img);
    });

    // Budget Cybersécurité : pas d'annexe de scoring CyFun (onglet décorrélé de NIS2 ;
    // l'ancienne annexe était figée CyFun et erronée en mode ReCyF). Aligné sur les
    // exports HTML/PDF qui l'ont également retirée.

    const main = document.createElement("main");
    main.className = "main";
    main.style.maxWidth = PRINT_WIDTH + "px";
    main.style.margin = "0 auto";
    main.style.padding = "0";
    main.appendChild(programClone);

    const wrapper = document.createElement("div");
    wrapper.className = "app";
    if (headerClone) wrapper.appendChild(headerClone);
    wrapper.appendChild(main);
    return wrapper;
  };

  const buildPrintHtml = (contentHtml) => {
    const themeClass = document.body.classList.contains("theme-dark") ? "theme-dark" : "";
    const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'))
      .map(function(l) { return l.outerHTML; })
      .join("");
    const inlineStyles = Array.from(document.querySelectorAll("style"))
      .map(function(s) { return s.textContent || ""; })
      .join("\n");

    var overrides = [
      '<style>',
      '@page{size:A4 landscape;margin:0}',
      'html,body{margin:0;padding:0;width:100%;min-height:100%;background:var(--color-background);-webkit-print-color-adjust:exact;print-color-adjust:exact}',
      '.header,.main{width:100%}',
      '.main{padding:0}',
      '.module__header{margin:0;padding:12px 16px 8px}',
      '.nav,.nav--secondary,.nav--tertiary,.global-search,.footer,#modeBanner,#modalOverlay,#toastContainer,#autoSaveStatus{display:none !important}',
      '.module{display:none !important;opacity:1 !important}',
      '#' + TARGET_TAB + '{display:block !important}',
      '.chart-card,.socle-card,.nis2-plan-card,.chart-card__content{break-inside:avoid;page-break-inside:avoid}',
      '.charts-grid.nis2-top-grid .chart-card__content{min-height:360px;height:auto}',
      '.chart-card--actions-nis2 .chart-card__content,.chart-card--actions-domain .chart-card__content{min-height:280px;height:auto}',
      'img.print-canvas-snapshot{width:100% !important;height:auto !important;display:block}',
      '@media print{.chart-card,.socle-card,.nis2-plan-card{box-shadow:none}}',
      inlineStyles,
      '</style>'
    ].join('\n');

    var parts = [];
    parts.push('<!doctype html>');
    parts.push('<html lang="fr">');
    parts.push('<head>');
    parts.push('<meta charset="utf-8">');
    parts.push('<title>' + escapeHtmlText(tt('exportLabels.programNIS2', 'Budget Cybersécurité')) + '</title>');
    parts.push(links);
    parts.push(overrides);
    parts.push('</head>');
    parts.push('<body class="app ' + escapeHtmlText(themeClass) + '">');
    parts.push(contentHtml);
    parts.push('</body>');
    parts.push('</html>');
    return parts.join('\n');
  };

  var escapeHtmlText = window.escapeHtml;

  // Populate new print window with built HTML content
  const populatePrintWindow = (printWin, html) => {
    printWin.document.open();
    printWin.document.write(html);  // Required for cross-window print population
    printWin.document.close();
  };

  const openPrintWindow = (wrapper) => {
    const printWin = window.open("", "_blank", "width=" + PRINT_WIDTH + ",height=900");
    if (!printWin) throw new Error("Popup bloque");
    const html = buildPrintHtml(wrapper.outerHTML);
    populatePrintWindow(printWin, html);

    const afterPrint = () => {
      printWin.removeEventListener("afterprint", afterPrint);
      setTimeout(function() { printWin.close(); }, 300);
    };
    printWin.addEventListener("afterprint", afterPrint);

    setTimeout(function() {
      printWin.focus();
      printWin.print();
      setTimeout(afterPrint, 2000); // fallback
    }, 400);
  };

  const handlePrint = async () => {
    // Bloquer en mode demo
    var demoMeta = document.querySelector('meta[name="csi-mode"]');
    if (demoMeta && demoMeta.content === 'demo') {
      var toastFn = window.showToast2 || window.showToast;
      if (toastFn) toastFn(tt('exportLabels.printDisabledDemo', 'L\'impression est désactivée en mode démonstration.'), 'warning');
      return;
    }
    if (isPrinting) return;
    isPrinting = true;
    printButton.disabled = true;
    const previousTab = await switchToProgram();
    if (typeof loadNis2Program === "function") {
      loadNis2Program();
      await wait(400);
    } else {
      await wait(200);
    }
    refreshCharts();
    await wait(100);

    try {
      const wrapper = cloneProgram();
      openPrintWindow(wrapper);
    } catch (e) {
      void 0;
      alert(tt('exportLabels.printError', "Impression NIS2 impossible. Reessayez apres avoir recharge la page."));
    } finally {
      if (previousTab && previousTab !== TARGET_TAB) {
        const navBtn = document.querySelector('.nav__item[data-tab="' + previousTab + '"]');
        if (navBtn) navBtn.click();
      }
      isPrinting = false;
      printButton.disabled = false;
    }
  };

  printButton.addEventListener("click", handlePrint);
})();
