// Generateur PDF cote client pour l'onglet Budget Cybersecurite (capture fidele A4 paysage).
// (audit 2026-07-10) l'ancienne annexe de scoring CyFun a ete retiree (generique multi-referentiels).

(() => {
  const TARGET_TAB = 'nis2-program';
  let printButton = null;
  let isGenerating = false;
  let originalButtonNodes = null;

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

  // Safe button content helpers (no innerHTML)
  function setButtonSpinner() {
    if (!printButton) return;
    // Save original children
    originalButtonNodes = [];
    while (printButton.firstChild) {
      originalButtonNodes.push(printButton.removeChild(printButton.firstChild));
    }
    var icon = document.createElement('i');
    icon.className = 'fas fa-spinner fa-spin';
    printButton.appendChild(icon);
    printButton.appendChild(document.createTextNode(' ' + tt('exportLabels.generation', 'Generation...')));
  }

  function restoreButton() {
    if (!printButton || !originalButtonNodes) return;
    while (printButton.firstChild) {
      printButton.removeChild(printButton.firstChild);
    }
    originalButtonNodes.forEach(function(node) {
      printButton.appendChild(node);
    });
    originalButtonNodes = null;
  }

  // Charger html2canvas localement (vendor uniquement, aucun CDN)
  function loadHtml2Canvas() {
    return new Promise((resolve, reject) => {
      if (window.html2canvas) {
        resolve(window.html2canvas);
        return;
      }
      const script = document.createElement('script');
      script.src = 'vendor/html2canvas.min.js';
      script.onload = () => resolve(window.html2canvas);
      script.onerror = () => reject(new Error('Impossible de charger html2canvas'));
      document.head.appendChild(script);
    });
  }

  // (audit 2026-07-10) annexe de scoring CyFun supprimée : débranchée depuis le passage
  // au Budget Cybersécurité générique (voir commentaire à l'étape 6) — code mort retiré.

  /**
   * Genere un PDF fidele en capturant la page NIS2
   */
  async function generateNis2Pdf() {
    // Bloquer l'export en mode demo
    const isDemo = (() => {
      const meta = document.querySelector('meta[name="csi-mode"]');
      return meta && meta.content === 'demo';
    })();
    if (isDemo) {
      const toastFn = window.showToast || window.showToast2;
      if (toastFn) {
        toastFn(tt('exportLabels.pdfExportNis2Disabled', 'L\'export PDF est desactive en mode demonstration.'), 'warning');
      } else {
        alert(tt('exportLabels.pdfExportNis2Disabled', 'L\'export PDF est desactive en mode demonstration.'));
      }
      return;
    }
    if (!printButton || isGenerating) return;

    isGenerating = true;
    printButton.disabled = true;
    setButtonSpinner();

    var savedPreviousTab = getActiveTab();
    try {
      // Etape 1: Charger html2canvas
      showToast(tt('exportLabels.loadingDependencies', 'Chargement des dependances...'), 'info');
      const html2canvas = await loadHtml2Canvas();

      // Etape 2: Naviguer vers l'onglet NIS2 Program
      showToast(tt('exportLabels.preparingContent', 'Preparation du contenu...'), 'info');
      await switchToTab(TARGET_TAB);

      // Charger les donnees NIS2 si necessaire
      if (typeof loadNis2Program === 'function') {
        loadNis2Program();
        await wait(800);
      } else {
        await wait(400);
      }

      // Etape 3: Forcer le rendu des charts
      await renderCharts();
      await wait(1000);

      // Etape 4: Preparer le DOM pour la capture
      const nis2Module = document.getElementById(TARGET_TAB);
      if (!nis2Module) throw new Error(tt('exportLabels.nis2ModuleNotFound', 'Module NIS2 non trouve'));

      // Creer un clone du module pour eviter de modifier la page
      const clone = nis2Module.cloneNode(true);
      prepareElementForCapture(clone);

      // Creer un conteneur temporaire
      const container = document.createElement('div');
      container.style.cssText = 'position:absolute;left:-9999px;top:-9999px;width:1920px;background:white;padding:20px;';
      container.appendChild(clone);
      document.body.appendChild(container);

      // Etape 5: Capturer en image haute resolution
      showToast(tt('exportLabels.capturingScreen', 'Capture de l\'ecran...'), 'info');
      const canvas = await html2canvas(container, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff',
        logging: false,
        allowTaint: true,
        windowHeight: container.scrollHeight,
        windowWidth: 1920
      });

      // Nettoyer
      document.body.removeChild(container);

      // Etape 6: Creer le PDF
      showToast(tt('exportLabels.creatingPdf', 'Creation du PDF...'), 'info');
      const { jsPDF } = window.jspdf;
      const pdf = new jsPDF({
        orientation: 'landscape',
        unit: 'mm',
        format: 'a4'
      });

      const imgWidth = 297;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      const imgData = canvas.toDataURL('image/png');
      const pageHeight = 210;

      while (heightLeft > 0) {
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
        position -= pageHeight;
        if (heightLeft > 0) {
          pdf.addPage();
        }
      }

      // Export Budget Cybersécurité : pas d'annexe de scoring CyFun (onglet générique
      // décorrélé de NIS2 ; l'ancienne annexe était figée CyFun et erronée en mode ReCyF).

      // Etape 7: Telecharger le PDF
      showToast(tt('exportLabels.downloadingPdf', 'Telechargement du PDF...'), 'info');
      var filename = 'budget-cybersecurite-' + new Date().toISOString().split('T')[0] + '.pdf';
      pdf.save(filename);

      await wait(500);
      showToast(tt('exportLabels.pdfSuccess', 'PDF genere avec succes!'), 'success');

    } catch (error) {
      void 0;
      showToast(t('common.error', 'Erreur') + ': ' + error.message, 'error');
    } finally {
      if (savedPreviousTab && savedPreviousTab !== TARGET_TAB) {
        const navBtn = document.querySelector('.nav__item[data-tab="' + savedPreviousTab + '"]');
        if (navBtn) navBtn.click();
      }

      isGenerating = false;
      printButton.disabled = false;
      restoreButton();
    }
  }

  /**
   * Prepare le DOM pour une capture PDF optimale
   */
  function prepareElementForCapture(element) {
    element.querySelectorAll('.module__actions, .icon-btn, [style*="display:none"]').forEach(function(el) {
      el.style.display = 'none';
    });

    element.querySelectorAll('canvas').forEach(function(canvas) {
      canvas.style.display = 'block';
      canvas.style.maxWidth = '100%';
      canvas.style.height = 'auto';
    });

    element.style.cssText = 'width:100%;background:white;padding:0;margin:0;display:block;opacity:1;visibility:visible;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;';
  }

  /**
   * Force le rendu des graphiques Chart.js
   */
  async function renderCharts() {
    try {
      const charts = window.charts || {};
      Object.values(charts).forEach(function(chart) {
        if (chart && typeof chart.resize === 'function') chart.resize();
        if (chart && typeof chart.update === 'function') chart.update('none');
      });
    } catch (e) {
      void 0;
    }
  }

  /**
   * Utilitaires
   */
  function getActiveTab() {
    const nav = document.querySelector('.nav__item--active');
    return nav ? nav.getAttribute('data-tab') : null;
  }

  async function switchToTab(tabName) {
    const current = getActiveTab();
    if (current === tabName) return current;
    const navBtn = document.querySelector('.nav__item[data-tab="' + tabName + '"]');
    if (navBtn) {
      navBtn.click();
      await wait(600);
    }
    return current;
  }

  function wait(ms) {
    return new Promise(function(resolve) { setTimeout(resolve, ms); });
  }

  function showToast(message, type) {
    // Deleguer au toast global si disponible
    if (typeof window.showToast2 === 'function') {
      window.showToast2(message, type);
      return;
    }
    // Fallback minimal
    type = /^[a-zA-Z0-9_-]+$/.test(type) ? type : 'info';
    const container = document.getElementById('toastContainer') || createToastContainer();
    const toast = document.createElement('div');
    toast.className = 'toast toast--' + type;
    toast.textContent = message;
    var bgColor = type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : '#1fb8cd';
    toast.style.cssText = 'padding:14px 18px;margin:10px;border-radius:6px;background:' + bgColor + ';color:white;font-size:14px;box-shadow:0 4px 6px rgba(0,0,0,0.1);animation:slideIn 0.3s ease-in;';
    container.appendChild(toast);
    setTimeout(function() {
      toast.style.animation = 'slideOut 0.3s ease-out';
      setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
  }

  function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;pointer-events:none;';
    document.body.appendChild(container);
    return container;
  }

  // Ajouter les animations CSS globales si pas deja presentes
  if (!document.querySelector('style[data-export-animations]')) {
    var animStyle = document.createElement('style');
    animStyle.setAttribute('data-export-animations', 'true');
    animStyle.textContent = '@keyframes slideIn{from{transform:translateX(400px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideOut{from{transform:translateX(0);opacity:1}to{transform:translateX(400px);opacity:0}}';
    document.head.appendChild(animStyle);
  }

  function init() {
    printButton = document.getElementById('printNis2ProgramBtn');
    if (!printButton) return;

    var handleClick = function(event) {
      if (!window.jspdf || !window.jspdf.jsPDF) return;
      event.preventDefault();
      event.stopImmediatePropagation();
      generateNis2Pdf();
    };

    printButton.addEventListener('click', handleClick, true);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init, { once: true });
  } else {
    init();
  }
})();
