(function(){
  function waitForImages(doc){
    var images = Array.from(doc.images || []);
    if(images.length === 0) return Promise.resolve();
    return Promise.all(images.map(function(img){
      return new Promise(function(resolve){
        if (img.complete) return resolve();
        img.addEventListener('load', function(){ resolve(); }, { once: true });
        img.addEventListener('error', function(){ resolve(); }, { once: true });
      });
    }));
  }

  function writeAndPrint(html, options){
    options = options || {};
    var title = options.title || 'document';

    var iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.setAttribute('aria-hidden', 'true');
    document.body.appendChild(iframe);

    var doc = iframe.contentDocument || iframe.contentWindow.document;
    doc.open();
    doc.write("<!DOCTYPE html><html lang='fa' dir='rtl'><head><meta charset='utf-8'>"+
      "<title>"+ title +"</title>"+
      "<link rel='stylesheet' href='/_content/MudBlazor/MudBlazor.min.css'>"+
      "<link rel='stylesheet' href='/css/site.css'>"+
      "<style>body{direction:rtl;text-align:right;padding:16px}</style>"+
      "</head><body>" + html + "</body></html>");
    doc.close();

    var win = iframe.contentWindow;

    var doPrint = function(){
      // Small delay to ensure layout
      setTimeout(function(){
        try { win.focus(); } catch(e) {}
        win.print();
        // Cleanup after some time
        setTimeout(function(){ document.body.removeChild(iframe); }, 1000);
      }, 150);
    };

    if (doc.readyState === 'complete'){
      waitForImages(doc).then(doPrint);
    } else {
      doc.addEventListener('readystatechange', function(){
        if (doc.readyState === 'complete'){
          waitForImages(doc).then(doPrint);
        }
      });
    }
  }

  window.printUtils = {
    // html: string containing html fragment or full page
    // options: { title?: string }
    printHtml: function(html, options){
      writeAndPrint(html, options || {});
    }
  };
})();

