/**
 * Utility for handling printing via hidden iframe.
 * This isolates the print document from the main application styles and ensures
 * a clean print output without the common "blank page" issues caused by 
 * complex CSS frameworks or deeply nested React roots.
 */

export const printElement = (elementId, title = 'Document') => {
  console.log(`[PrintUtils] Attempting to print element: ${elementId}`);
  
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`[PrintUtils] Element with id "${elementId}" not found in DOM.`);
    return { success: false, error: 'Content not found' };
  }

  // Validation: Check dimensions to ensure content is actually visible/rendered
  if (element.offsetHeight === 0 || element.offsetWidth === 0) {
    console.error('[PrintUtils] Element has zero dimensions.', element);
    return { success: false, error: 'Content is not visible' };
  }

  // Create hidden iframe
  const iframe = document.createElement('iframe');
  iframe.style.position = 'absolute';
  iframe.style.width = '0';
  iframe.style.height = '0';
  iframe.style.border = 'none';
  iframe.title = title;
  
  // Append to body
  document.body.appendChild(iframe);
  
  const doc = iframe.contentWindow.document;

  // Gather all styles from the main document to ensure Tailwind/Custom styles carry over
  // We specifically look for style tags (Vite dev) and link stylesheets (Prod/Google Fonts)
  const styles = Array.from(document.querySelectorAll('style, link[rel="stylesheet"]'))
    .map(style => style.outerHTML)
    .join('\n');

  console.log(`[PrintUtils] Copied ${document.querySelectorAll('style').length} style tags and ${document.querySelectorAll('link[rel="stylesheet"]').length} stylesheets.`);

  // Write content to iframe
  doc.open();
  doc.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>${title}</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        ${styles}
        <style>
          /* Critical Print Resets */
          body { 
            margin: 0; 
            padding: 0; 
            background: white; 
            -webkit-print-color-adjust: exact !important; 
            print-color-adjust: exact !important;
          }
          @page { 
            size: letter; 
            margin: 0; 
          }
          /* Ensure full width in print */
          #${elementId} {
            width: 100% !important;
            max-width: none !important;
          }
        </style>
      </head>
      <body>
        ${element.outerHTML}
        <script>
           // Wait slightly for fonts and images to settle before printing
           window.onload = () => {
             setTimeout(() => {
               try {
                 window.print();
                 // We can't reliably detect when print dialog closes, but we can assume success if opened
               } catch (e) {
                 console.error('Print dialog failed:', e);
               }
             }, 500);
           };
        </script>
      </body>
    </html>
  `);
  doc.close();

  // Cleanup: Remove iframe after a delay to allow the print dialog to open
  // Browsers pause JS execution during print dialog, so this runs after it closes (mostly)
  setTimeout(() => {
    if (document.body.contains(iframe)) {
      document.body.removeChild(iframe);
    }
  }, 3000); // 3 seconds is usually safe

  return { success: true };
};