/**
 * Fichier  : assets/js/print-template.js
 * Auteur   : KREMER Régis
 * Version  : 2.6.70
 * Date     : 2026-07-11
 * Description : JS — Trame d'impression premium commune MageStock A4.
 *
 * Changelog :
 *   v2.6.8  (2026-07-08) — Création du helper d'impression avec logo MageStock,
 *                       en-tête commun, méta, tableaux A4 portrait/paysage.
 *   v2.6.15 (2026-07-08) — Trame premium commune : logo entreprise prioritaire,
 *                       logo MageStock secondaire, éditeur, portrait/paysage au choix.
 *   v2.6.17 (2026-07-08) — Correctif anti page blanche : écriture fenêtre robuste, images/logo sans inline HTML fragile.
 *   v2.6.18 (2026-07-08) — Impression attend le rendu et les images avant print, avec message si contenu vide.
 *   v2.6.19 (2026-07-08) — Marges internes A4 protégées pour éviter les impressions bord à bord.
 *   v2.6.23 (2026-07-08) — Support impression mouvements, résumé natif et tables métier compactes.
 *   v2.6.24 (2026-07-08) — Cohérence finale : marges A4 de sécurité et logos stabilisés.
 *   v2.6.22 (2026-07-08) — Marges écran/impression renforcées pour commandes, BL et inventaires.
 *   v2.6.70 (2026-07-11) — I18N CORE LOCALE CURRENCY1 : dates localisées et langue du document imprimé.
 */
(function(){
  'use strict';

  function escapeHtml(value){
    return String(value == null ? '' : value).replace(/[&<>"']/g, function(c){
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c];
    });
  }

  function runtime(){
    return window.MageStockRuntime || {};
  }

  function baseHref(){
    try { return new URL('./', window.location.href).href; }
    catch(e){ return './'; }
  }

  function nowLabel(){
    const d = new Date();
    return Locale.formatDateTime(d);
  }

  function compactText(value, fallback){
    const v = String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
    return v || fallback || '';
  }

  function imgHtml(src, alt, cls, fallbackText){
    src = compactText(src, '');
    alt = compactText(alt, '');
    cls = compactText(cls, '').replace(/[^a-z0-9_\- ]/gi, '');
    fallbackText = compactText(fallbackText, 'MS');
    const fallback = '<span class="'+cls+' ms-print-logo-fallback" aria-hidden="true">'+escapeHtml(fallbackText)+'</span>';
    if(!src) return fallback;
    return '<img class="'+cls+'" src="'+escapeHtml(src)+'" alt="'+escapeHtml(alt)+'" onerror="this.style.display=\'none\';var n=this.nextElementSibling;if(n)n.style.display=\'inline-flex\';"><span class="'+cls+' ms-print-logo-fallback" style="display:none" aria-hidden="true">'+escapeHtml(fallbackText)+'</span>';
  }

  function summaryFromCards(container){
    if(!container) return '';
    const cards = container.querySelectorAll('.summary-card,.kpi-card,.dash-kpi,.stat-card,.inv-kpi-card');
    if(!cards.length) return '';
    let out = '<div class="ms-print-summary">';
    cards.forEach(function(card){
      const val = card.querySelector('.summary-value,.kpi-value,.dash-kpi-val,.stat-value,.inv-kpi-val')?.textContent?.trim() || '';
      const lab = card.querySelector('.summary-label,.kpi-label,.dash-kpi-label,.stat-label,.inv-kpi-label')?.textContent?.trim() || '';
      if(val || lab){
        out += '<div class="ms-print-summary-card"><div class="ms-print-summary-value">'+escapeHtml(val)+'</div><div class="ms-print-summary-label">'+escapeHtml(lab)+'</div></div>';
      }
    });
    out += '</div>';
    return out;
  }

  function metaHtml(meta){
    if(!meta) return '';
    let items = [];
    if(Array.isArray(meta)) items = meta;
    else items = Object.keys(meta).map(function(k){ return {label:k, value:meta[k]}; });
    items = items.filter(function(it){ return it && String(it.value ?? '').trim() !== ''; });
    if(!items.length) return '';
    return '<div class="ms-print-meta-grid">' + items.map(function(it){
      return '<div class="ms-print-meta-item"><span>'+escapeHtml(it.label)+'</span><strong>'+escapeHtml(it.value)+'</strong></div>';
    }).join('') + '</div>';
  }

  function summaryListHtml(summary){
    if(!summary) return '';
    const items = Array.isArray(summary) ? summary : Object.keys(summary).map(function(k){ return {label:k, value:summary[k]}; });
    const clean = items.filter(function(it){ return it && String(it.value ?? '').trim() !== ''; });
    if(!clean.length) return '';
    return '<div class="ms-print-summary">' + clean.map(function(it){
      return '<div class="ms-print-summary-card"><div class="ms-print-summary-value">'+escapeHtml(it.value)+'</div><div class="ms-print-summary-label">'+escapeHtml(it.label)+'</div></div>';
    }).join('') + '</div>';
  }

  function resolveBrand(opts){
    opts = opts || {};
    const rt = runtime();
    const company = compactText(opts.company || rt.companyName, 'MageStock');
    const companyLogoUrl = compactText(opts.companyLogoUrl || opts.logoUrl || rt.companyLogoUrl, '');
    const appLogoUrl = compactText(opts.appLogoUrl || rt.appPrintLogoUrl || rt.appLogoUrl, 'assets/img/sm_logo.png');
    const generatedBy = compactText(opts.generatedBy || rt.currentUserDisplayName, '');
    const appName = compactText(opts.appName || rt.appName, 'MageStock');
    return { company, companyLogoUrl, appLogoUrl, generatedBy, appName };
  }

  function documentHtml(opts){
    opts = opts || {};
    const brand = resolveBrand(opts);
    const title = compactText(opts.title, 'Document');
    const subtitle = compactText(opts.subtitle, '');
    const orientation = opts.orientation === 'portrait' ? 'portrait' : 'landscape';
    const generatedAt = compactText(opts.generatedAt, nowLabel());
    const bodyHtml = opts.bodyHtml || '';
    const tableHtml = opts.tableHtml || '';
    const hasContent = String(bodyHtml + tableHtml + (opts.summaryHtml || '')).replace(/<[^>]*>/g, '').trim() !== '';
    const emptyHtml = hasContent ? '' : '<div class="ms-print-note"><strong>Aucun contenu à imprimer.</strong><br>Le document a été ouvert, mais aucune donnée imprimable n’a été transmise.</div>';
    const summaryHtml = opts.summaryHtml || summaryListHtml(opts.summary) || '';
    const footer = compactText(opts.footer, 'Document généré par MageStock');
    const docRef = compactText(opts.reference || opts.docRef, '');
    const primaryLogo = imgHtml(brand.companyLogoUrl || brand.appLogoUrl, brand.companyLogoUrl ? brand.company : brand.appName, 'ms-print-primary-logo', brand.companyLogoUrl ? brand.company.slice(0, 2) : 'MS');
    const mageStockLogo = brand.companyLogoUrl ? imgHtml(brand.appLogoUrl, brand.appName, 'ms-print-secondary-logo', 'MS') : '';
    const editorLine = brand.generatedBy ? '<span>Édité par '+escapeHtml(brand.generatedBy)+'</span>' : '';
    const refLine = docRef ? '<span>Référence '+escapeHtml(docRef)+'</span>' : '';

    return '<!doctype html><html lang="'+escapeHtml(window.SM_LANG || 'fr')+'" data-orientation="'+orientation+'"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><base href="'+baseHref()+'"><title>'+escapeHtml(title)+' — MageStock</title>'+
      '<style id="msPrintDynamicCss">'+css(orientation)+'</style>'+
      '<script type="text/plain" id="msPrintCssPortrait">'+css('portrait')+'</script>'+
      '<script type="text/plain" id="msPrintCssLandscape">'+css('landscape')+'</script>'+
      '<script>function msPrintSetOrientation(o){document.documentElement.setAttribute("data-orientation",o);document.getElementById("msPrintDynamicCss").textContent=document.getElementById(o==="portrait"?"msPrintCssPortrait":"msPrintCssLandscape").textContent;}function msPrintNow(o){msPrintSetOrientation(o);setTimeout(function(){window.focus();window.print();},40);}</script>'+
      '</head><body>'+
      '<div class="ms-print-toolbar no-print" role="toolbar" aria-label="Impression"><div><strong>Format A4</strong><span>Choisir l’orientation avant impression</span></div><div class="ms-print-toolbar-actions"><button onclick="msPrintNow(\'portrait\')">Portrait</button><button onclick="msPrintNow(\'landscape\')">Paysage</button><button class="ghost" onclick="window.close()">Fermer</button></div></div>'+
      '<main class="ms-print-page">'+
      '<header class="ms-print-header"><div class="ms-print-brand"><div class="ms-print-logo-stack">'+primaryLogo+mageStockLogo+'</div><div><div class="ms-print-brand-title">'+escapeHtml(brand.company)+'</div><div class="ms-print-brand-sub">Gestion de stock · MageStock</div></div></div><div class="ms-print-docmeta"><strong>'+escapeHtml(generatedAt)+'</strong>'+editorLine+refLine+'<span class="ms-print-orientation-note">A4 '+(orientation === 'portrait' ? 'portrait' : 'paysage')+'</span></div></header>'+
      '<section class="ms-print-title"><h1>'+escapeHtml(title)+'</h1>'+(subtitle ? '<p>'+escapeHtml(subtitle)+'</p>' : '')+'</section>'+
      metaHtml(opts.meta)+summaryHtml+emptyHtml+bodyHtml+tableHtml+ 
      '<footer class="ms-print-footer"><span>'+escapeHtml(footer)+'</span><span>'+escapeHtml(brand.company)+' · MageStock · '+escapeHtml(generatedAt)+'</span></footer>'+
      '</main></body></html>';
  }

  function css(orientation){
    const pageMin = orientation === 'portrait' ? '297mm' : '210mm';
    const pageWidth = orientation === 'portrait' ? '210mm' : '297mm';
    return '@page{size:A4 '+orientation+';margin:6mm}*{box-sizing:border-box}html,body{margin:0;padding:0;background:#e8edf4;color:#0f172a;font-family:"DM Sans",Inter,Arial,Helvetica,sans-serif;font-size:11px;line-height:1.35;-webkit-print-color-adjust:exact;print-color-adjust:exact}.ms-print-toolbar{position:sticky;top:0;z-index:5;display:flex;gap:16px;align-items:center;justify-content:space-between;padding:10px 14px;background:#0f172a;color:#fff;border-bottom:1px solid #1e293b;box-shadow:0 8px 24px rgba(15,23,42,.18)}.ms-print-toolbar strong{display:block;font-size:13px}.ms-print-toolbar span{display:block;font-size:11px;color:#cbd5e1}.ms-print-toolbar-actions{display:flex;gap:8px;align-items:center}.ms-print-toolbar button{border:1px solid #2563eb;background:#2563eb;color:#fff;padding:8px 13px;border-radius:3px;font-weight:900;cursor:pointer}.ms-print-toolbar button:hover{filter:brightness(.96)}.ms-print-toolbar .ghost{background:#1e293b;border-color:#475569;color:#e2e8f0}.ms-print-page{width:'+pageWidth+';max-width:calc(100vw - 24px);min-height:'+pageMin+';margin:12px auto 28px;background:#fff;padding:13mm 14mm;box-shadow:0 10px 35px rgba(15,23,42,.16);overflow:hidden}.ms-print-header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:0 0 11px;border-bottom:4px solid #1d4ed8;margin-bottom:13px;break-inside:avoid}.ms-print-brand{display:flex;align-items:center;gap:12px;min-width:0}.ms-print-logo-stack{position:relative;display:flex;align-items:center;justify-content:center;min-width:48px}.ms-print-primary-logo{max-height:42px;max-width:165px;width:auto;object-fit:contain;display:block}.ms-print-secondary-logo{height:21px;max-width:76px;width:auto;object-fit:contain;display:block;margin-left:10px;opacity:.85}.ms-print-logo-fallback{width:42px;height:42px;background:#1d4ed8;color:#fff;display:inline-flex;align-items:center;justify-content:center;font-weight:1000;border-radius:3px;letter-spacing:-.04em}.ms-print-brand-title{font-size:15.5px;font-weight:1000;letter-spacing:-.025em;color:#0f172a}.ms-print-brand-sub{font-size:9px;color:#64748b;font-weight:900;text-transform:uppercase;letter-spacing:.08em}.ms-print-docmeta{text-align:right;font-size:9px;color:#64748b;display:flex;flex-direction:column;gap:2px;min-width:145px}.ms-print-docmeta strong{color:#0f172a;font-size:10px}.ms-print-orientation-note{color:#1d4ed8;font-weight:900}.ms-print-title{margin:0 0 10px;break-inside:avoid}.ms-print-title h1{margin:0;font-size:20px;line-height:1.08;letter-spacing:-.03em;color:#0f172a}.ms-print-title p{margin:4px 0 0;color:#475569;font-weight:800}.ms-print-meta-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:0 0 10px;break-inside:avoid}.ms-print-meta-item{border:1px solid #dde3ea;border-left:4px solid #1d4ed8;background:#f8fafc;padding:6px 8px;min-height:38px}.ms-print-meta-item span{display:block;color:#64748b;font-size:7.8px;text-transform:uppercase;letter-spacing:.07em;font-weight:1000}.ms-print-meta-item strong{display:block;margin-top:1px;font-size:10.5px;color:#0f172a}.ms-print-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:0 0 10px;break-inside:avoid}.ms-print-summary-card{border:1px solid #dde3ea;background:#fff;padding:7px 8px;border-left:4px solid #15803d}.ms-print-summary-value{font-size:14px;font-weight:1000;letter-spacing:-.02em}.ms-print-summary-label{font-size:7.8px;color:#64748b;text-transform:uppercase;letter-spacing:.07em;font-weight:1000;margin-top:1px}.ms-print-section-title{font-size:12px;font-weight:1000;margin:14px 0 6px;color:#1d4ed8;border-bottom:1px solid #bfdbfe;padding-bottom:3px;break-after:avoid}.ms-print-note{border:1px solid #dde3ea;background:#f8fafc;border-left:4px solid #1d4ed8;padding:8px;margin:0 0 10px;color:#334155;break-inside:avoid}.ms-print-signatures{display:grid;grid-template-columns:1fr 1fr;gap:28px;margin-top:22px;break-inside:avoid}.ms-print-signature{border-top:1px solid #94a3b8;padding-top:6px;color:#475569;font-size:10px}.ms-print-footer{display:flex;justify-content:space-between;gap:10px;margin-top:14px;padding-top:6px;border-top:1px solid #dde3ea;color:#94a3b8;font-size:8.5px}table{width:100%;border-collapse:collapse;margin:0 0 8px;page-break-inside:auto}thead{display:table-header-group}tfoot{display:table-footer-group}tr{page-break-inside:avoid;page-break-after:auto}th{background:#eaf1ff;color:#1e3a8a;text-align:left;font-size:7.8px;text-transform:uppercase;letter-spacing:.05em;font-weight:1000;padding:6px 7px;border-bottom:1px solid #bfdbfe}td{padding:5px 7px;border-bottom:1px solid #e5e7eb;vertical-align:top;font-size:9.2px}tbody tr:nth-child(even) td{background:#f8fafc}.badge,.tag,.pill{display:inline-block;border-radius:2px!important;padding:2px 6px!important;font-size:8px!important;font-weight:1000!important;color:#0f172a;background:#e2e8f0}.total-row{font-size:12px;font-weight:1000;text-align:right;padding:8px 0;border-top:2px solid #1d4ed8}.tr{text-align:right}.tc{text-align:center}.bold{font-weight:1000}.ms-print-product{display:flex;align-items:center;gap:8px}.ms-print-product img{width:34px;height:34px;object-fit:contain;border:1px solid #e2e8f0;border-radius:3px;background:#fff}.ms-print-product-ph{width:34px;height:34px;display:inline-flex;align-items:center;justify-content:center;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:3px;color:#64748b}.ms-print-inventory-table th,.ms-print-inventory-table td{font-size:8.8px}.ms-print-order-table th,.ms-print-order-table td{font-size:8.3px;padding:4px 5px}.ms-print-order-table th:nth-child(1),.ms-print-order-table td:nth-child(1){width:26%}.ms-print-order-table th:nth-child(4),.ms-print-order-table td:nth-child(4){width:13%}.ms-print-movements-table th,.ms-print-movements-table td{font-size:8.4px;padding:4px 5px}.ms-print-movements-table th:nth-child(1),.ms-print-movements-table td:nth-child(1){width:15%}.ms-print-movements-table th:nth-child(3),.ms-print-movements-table td:nth-child(3){width:26%}.ms-print-movements-table th:nth-child(5),.ms-print-movements-table td:nth-child(5){width:12%;white-space:nowrap}.text-danger{color:#dc2626!important}.text-success{color:#16a34a!important}.text-info{color:#2563eb!important}@media print{html,body{background:#fff}.no-print{display:none!important}.ms-print-page{box-shadow:none!important;margin:0 auto!important;width:'+pageWidth+'!important;max-width:'+pageWidth+'!important;min-height:'+pageMin+'!important;padding:10mm 11mm!important;overflow:hidden!important}a{color:inherit;text-decoration:none}.ms-print-footer{position:running(msFooter)}}@media (max-width:700px){.ms-print-toolbar{align-items:flex-start;flex-direction:column}.ms-print-toolbar-actions{width:100%;display:grid;grid-template-columns:1fr 1fr 1fr}.ms-print-meta-grid,.ms-print-summary{grid-template-columns:repeat(2,minmax(0,1fr))}.ms-print-header{align-items:flex-start;flex-direction:column}.ms-print-docmeta{text-align:left}.ms-print-secondary-logo{display:none}}';
  }

  function open(opts){
    opts = opts || {};
    const html = documentHtml(opts);
    const w = window.open('', '_blank', opts.windowFeatures || 'width=1160,height=800');
    if(!w){
      if(typeof toast === 'function') toast('Popup bloquée — autorisez les popups.', 'error');
      return false;
    }

    try {
      w.document.open('text/html', 'replace');
      w.document.write(html);
      w.document.close();
    } catch(e) {
      try {
        w.document.body.innerHTML = '<pre style="font-family:Arial,sans-serif;color:#991b1b;white-space:pre-wrap;padding:24px">Impossible de préparer l’impression. Rechargez la page puis réessayez.\n'+escapeHtml(e && e.message ? e.message : e)+'</pre>';
      } catch(_) {}
      if(typeof toast === 'function') toast('Impression impossible — voir la fenêtre ouverte.', 'error');
      return false;
    }

    const waitForImages = function(done){
      try {
        const imgs = Array.from(w.document.images || []);
        if(!imgs.length) return done();
        let left = imgs.length;
        const finish = function(){ left--; if(left <= 0) done(); };
        imgs.forEach(function(img){
          if(img.complete) return finish();
          img.addEventListener('load', finish, {once:true});
          img.addEventListener('error', finish, {once:true});
        });
        setTimeout(done, 1200);
      } catch(e) { done(); }
    };

    const triggerPrint = function(){
      if(opts.autoPrint !== true) return;
      waitForImages(function(){
        try { w.focus(); w.print(); } catch(e) {}
        if(opts.closeAfterPrint) setTimeout(function(){ try{ w.close(); }catch(e){} }, 500);
      });
    };

    // Ne pas dépendre uniquement de onload : certains navigateurs ne déclenchent
    // pas l’événement sur une fenêtre about:blank écrite par document.write().
    setTimeout(function(){
      try {
        if(!w.document.body || !w.document.body.innerHTML.trim()){
          w.document.open('text/html', 'replace');
          w.document.write(html);
          w.document.close();
        }
      } catch(_) {}
    }, 60);
    setTimeout(triggerPrint, 450);
    return true;
  }


  window.MageStockPrint = { open:open, documentHtml:documentHtml, escapeHtml:escapeHtml, summaryFromCards:summaryFromCards, css:css };
})();
