import React from 'react';
import { 
  Document, 
  Page, 
  Text, 
  View, 
  StyleSheet, 
  PDFViewer,
  Image, 
  Font, 
  Link,
  pdf
} from '@react-pdf/renderer';
import { CV } from '../types/cv';

// For React PDF to properly handle local files in the public directory
// we should use the absolute path from the domain root
const RedHatLogo = '/red-hat-logo.png';

// Register system fonts for better compatibility
Font.registerHyphenationCallback(word => [word]);

// Register Red Hat Display font using fontSource approach
Font.register({
  family: 'RedHatDisplay',
  fonts: [
    { 
      src: '/fonts/RedHatDisplay-Regular.ttf',
      fontWeight: 'normal',
      fontStyle: 'normal'
    },
    { 
      src: '/fonts/RedHatDisplay-Bold.ttf',
      fontWeight: 'bold',
      fontStyle: 'normal'
    },
    { 
      src: '/fonts/RedHatDisplay-Italic.ttf',
      fontWeight: 'normal',
      fontStyle: 'italic'
    },
    { 
      src: '/fonts/RedHatDisplay-BoldItalic.ttf',
      fontWeight: 'bold',
      fontStyle: 'italic'
    }
  ]
});

// Helper function to get initials from a name
const getInitials = (name: string): string => {
  return name
    .split(' ')
    .map(part => part.charAt(0).toUpperCase())
    .join('.');
};

// Create styles - Updated to better match Red Hat CV examples
const styles = StyleSheet.create({
  page: {
    flexDirection: 'column',
    backgroundColor: 'white',
    padding: 40,
    fontFamily: 'RedHatDisplay',
    fontSize: 10,
    color: '#333333',
  },
  redColor: {
    color: '#ee0000',
  },
  blueColor: {
    color: '#0066cc',
  },
  section: {
    marginBottom: 18,
    width: '100%',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 25,
    paddingBottom: 15,
    borderBottomColor: '#d2d2d2',
    borderBottomWidth: 1,
    borderBottomStyle: 'solid',
  },
  headerContent: {
    flexGrow: 1,
  },
  headerImageContainer: {
    width: 100,
    height: 40,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  logo: {
    width: 80,
    marginRight: 5,
  },
  name: {
    fontSize: 20,
    fontFamily: 'RedHatDisplay',
    fontWeight: 'bold',
    marginBottom: 5,
  },
  jobTitle: {
    fontSize: 14,
    fontFamily: 'RedHatDisplay',
    color: '#ee0000',
    marginBottom: 5,
  },
  sectionTitle: {
    fontSize: 12,
    fontFamily: 'RedHatDisplay',
    fontWeight: 'bold',
    color: '#ee0000',
    marginBottom: 10,
    textTransform: 'uppercase',
    paddingBottom: 3,
    borderBottomColor: '#d2d2d2',
    borderBottomWidth: 0.5,
    borderBottomStyle: 'solid',
  },
  table: {
    display: 'flex',
    width: 'auto',
    marginBottom: 10,
  },
  tableRow: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: 24,
    paddingTop: 3,
    paddingBottom: 3,
    borderBottomColor: '#d2d2d2',
    borderBottomWidth: 0.5,
    borderBottomStyle: 'solid',
    break: 'avoid',
  },
  tableRowLast: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: 24,
    paddingTop: 3,
    paddingBottom: 3,
    break: 'avoid',
  },
  tableHeaderRow: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: 24,
    paddingTop: 3,
    paddingBottom: 3,
    backgroundColor: '#f5f5f5',
    borderBottomColor: '#d2d2d2',
    borderBottomWidth: 1,
    borderBottomStyle: 'solid',
  },
  tableCell: {
    padding: 3,
  },
  tableCellHeader: {
    padding:.3,
    color: '#ee0000',
    fontWeight: 'bold',
  },
  tableCol15: {
    width: '15%',
  },
  tableCol20: {
    width: '20%',
  },
  tableCol25: {
    width: '25%',
  },
  tableCol30: {
    width: '30%',
  },
  tableCol33: {
    width: '33.33%',
  },
  tableCol35: {
    width: '35%',
  },
  tableCol40: {
    width: '40%',
  },
  tableCol50: {
    width: '50%',
  },
  tableCol55: {
    width: '55%',
  },
  tableCol60: {
    width: '60%',
  },
  tableCol70: {
    width: '70%',
  },
  tableCol75: {
    width: '75%',
  },
  tableCol80: {
    width: '80%',
  },
  bold: {
    fontWeight: 'bold',
  },
  italic: {
    fontStyle: 'italic',
  },
  text: {
    lineHeight: 1.4,
  },
  listItem: {
    flexDirection: 'row',
    marginBottom: 3,
    paddingLeft: 6,
  },
  bullet: {
    width: 6,
    marginRight: 4,
  },
  footer: {
    position: 'absolute',
    bottom: 30,
    left: 40,
    right: 40,
    flexDirection: 'row',
    alignItems: 'center',
    fontSize: 8,
    color: '#666666',
    paddingTop: 8,
    borderTopColor: '#d2d2d2',
    borderTopWidth: 0.5,
    borderTopStyle: 'solid',
  },
  footerLeft: {
    width: '30%',
  },
  footerCenter: {
    width: '40%',
    textAlign: 'center',
  },
  footerRight: {
    width: '30%',
    textAlign: 'right',
  },
  sectionNumber: {
    marginRight: 5,
    fontWeight: 'bold',
  },
  paragraph: {
    marginBottom: 6,
    lineHeight: 1,
  },
  sectionRow: {
    flexDirection: 'row',
    marginBottom: 5,
  },
  educationItem: {
    marginBottom: 4,
  },
  projectTitle: {
    fontWeight: 'bold',
    fontSize: 11,
    marginBottom: 4,
  },
  technologiesTitle: {
    fontWeight: 'bold',
    marginTop: 4,
    marginBottom: 2,
  },
  bulletPoint: {
    marginRight: 4,
  },
  bulletItem: {
    flexDirection: 'row',
    marginBottom: 1,
    paddingLeft: 8,
    alignItems: 'flex-start',
  },
  projectDescription: {
    marginTop: 6,
  },
  projectContainer: {
    break: 'avoid',
    marginBottom: 6,
  },
});

// PDF Document component
const CVDocument = ({ cv }: { cv: CV }) => {
  // Get initials for header and footer
  const initials = getInitials(cv.generalInfo.name);
  
  // Last row index for each section to avoid bottom border
  const lastKeySkillIndex = cv.keySkills.length - 1;
  const lastExpIndex = cv.experiences.length - 1;
  const lastCertIndex = cv.certifications.length - 1;
  
  return (
  <Document title={`${cv.generalInfo.name} - CV`}>
    <Page size="A4" style={styles.page}>
      {/* Header with Logo */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <Text style={styles.name}>{cv.generalInfo.name}</Text>
          <Text style={styles.jobTitle}>{cv.generalInfo.jobTitle}, Red Hat Consulting</Text>
        </View>
        <View style={styles.headerImageContainer}>
          <Image src={RedHatLogo} style={styles.logo} />
        </View>
      </View>

      {/* 1. General Information */}
      <View style={styles.section}>
        <View style={styles.sectionRow}>
          <Text style={styles.sectionTitle}>1. General Information</Text>
        </View>
        
        <View style={styles.table}>
          {/* Row 1 */}
          <View style={styles.tableRow}>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text style={styles.bold}>Name</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>{initials}</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text style={styles.bold}>Nationality</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>{cv.generalInfo.nationality}</Text>
            </View>
          </View>
          
          {/* Row 2 */}
          <View style={styles.tableRow}>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text style={styles.bold}>Job Title</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>{cv.generalInfo.jobTitle}</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text style={styles.bold}>Location</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>{cv.generalInfo.location}</Text>
            </View>
          </View>
          
          {/* Row 3 - last row without bottom border */}
          <View style={styles.tableRowLast}>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text style={styles.bold}>Languages</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>{cv.generalInfo.languages}</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text style={styles.bold}>Education</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              {cv.education.map((edu, i) => (
                <Text style={styles.educationItem} key={i}>{edu.degree}</Text>
              ))}
            </View>
          </View>
        </View>
      </View>

      {/* 2. Key Skills */}
      <View style={styles.section}>
        <View style={styles.sectionRow}>
          <Text style={styles.sectionTitle}>2. Key Skills</Text>
        </View>
        
        <View style={styles.table}>
          {/* Table header */}
          <View fixed style={styles.tableHeaderRow}>
            <View style={[styles.tableCellHeader, styles.tableCol30]}>
              <Text>Area</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol70]}>
              <Text>Information</Text>
            </View>
          </View>
          
          {/* Table content - iterate through skills */}
          {cv.keySkills.map((skill, index) => (
            <View key={index} style={index === lastKeySkillIndex ? styles.tableRowLast : styles.tableRow}>
              <View style={[styles.tableCell, styles.tableCol30]}>
                <Text style={styles.bold}>{skill.category}</Text>
              </View>
              <View style={[styles.tableCell, styles.tableCol70]}>
                <Text>{skill.description}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 3. Experience */}
      <View style={styles.section}>
        <View style={styles.sectionRow}>
          <Text style={styles.sectionTitle}>3. Projects</Text>
        </View>
        
        <View style={styles.table}>
          {/* Table header */}
          <View fixed style={styles.tableHeaderRow}>
            <View style={[styles.tableCellHeader, styles.tableCol15]}>
              <Text>Industry</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol15]}>
              <Text>Date</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol15]}>
              <Text>Location</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol55]}>
              <Text>Details</Text>
            </View>
          </View>
          
          {/* Table content */}
          {cv.experiences.map((exp, index) => (
            <View key={index} style={styles.projectContainer}>
              <View style={index === lastExpIndex ? styles.tableRowLast : styles.tableRow}>
                <View style={[styles.tableCell, styles.tableCol15]}>
                  <Text>{exp.industry}</Text>
                </View>
                <View style={[styles.tableCell, styles.tableCol15]}>
                  <Text>{exp.date}</Text>
                </View>
                <View style={[styles.tableCell, styles.tableCol15]}>
                  <Text>{exp.location}</Text>
                </View>
                <View style={[styles.tableCell, styles.tableCol55]}>
                  {/* Project Title */}
                  {exp.title && (
                    <Text style={styles.projectTitle}>{exp.title}</Text>
                  )}
                  
                  {/* Technologies */}
                  {exp.technologies && (
                    <View>
                      <Text style={styles.technologiesTitle}>Technologies</Text>
                      {exp.technologies.split('*').filter(tech => tech.trim()).map((tech, i) => (
                        <View key={i} style={styles.bulletItem}>
                          <Text style={styles.bulletPoint}>•</Text>
                          <Text>{tech.trim()}</Text>
                        </View>
                      ))}
                    </View>
                  )}
                  
                  {/* Description */}
                  <Text style={styles.projectDescription}>{exp.description}</Text>
                </View>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 4. Training & Certifications */}
      <View style={styles.section}>
        <View style={styles.sectionRow}>
          <Text style={styles.sectionTitle}>4. Training & Certifications</Text>
        </View>
        
        <View style={styles.table}>
          {/* Table header */}
          <View fixed style={styles.tableHeaderRow}>
            <View style={[styles.tableCellHeader, styles.tableCol80]}>
              <Text>Qualification</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol20]}>
              <Text>Date</Text>
            </View>
          </View>
          
          {/* Table content */}
          {cv.certifications.map((cert, index) => (
            <View key={index} style={index === lastCertIndex ? styles.tableRowLast : styles.tableRow}>
              <View style={[styles.tableCell, styles.tableCol80]}>
                <Text>{cert.qualification}</Text>
              </View>
              <View style={[styles.tableCell, styles.tableCol20]}>
                <Text>{cert.date}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 5. Further Information */}
      <View style={styles.section}>
        <View style={styles.sectionRow}>
          <Text style={styles.sectionTitle}>5. Further Information</Text>
        </View>
        
        <Text style={styles.paragraph}>
          Information on availability, schedule and rates should be referred to the Services Delivery Manager (contact information below):
        </Text>
        
        <View style={styles.table}>
          {/* Table header */}
          <View fixed style={styles.tableHeaderRow}>
            <View style={[styles.tableCellHeader, styles.tableCol25]}>
              <Text>Role</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol25]}>
              <Text>Name</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol25]}>
              <Text>Email</Text>
            </View>
            <View style={[styles.tableCellHeader, styles.tableCol25]}>
              <Text>Phone</Text>
            </View>
          </View>
          
          {/* SDM information - last row without border */}
          <View style={styles.tableRowLast}>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>Services Consulting Manager</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>Wolfgang Mild</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>wmild@redhat.com</Text>
            </View>
            <View style={[styles.tableCell, styles.tableCol25]}>
              <Text>+43-676-852100209</Text>
            </View>
          </View>
        </View>
        
        <Text style={styles.paragraph}>
          Information on security clearances, visas etc. should be directed towards the SDM and are dealt with directly with the customer.
        </Text>
        
        {/* No more conditional content in Further Information section */}
      </View>

      {/* Footer with page number and initials */}
      <View fixed style={styles.footer}>
        <Text style={styles.footerLeft}>CV: {initials}</Text>
        <Text style={styles.footerCenter} render={({ pageNumber, totalPages }) => `Page ${pageNumber} of ${totalPages}`} />
        <Text style={styles.footerRight}>Red Hat Services CV</Text>
      </View>
    </Page>
  </Document>
  );
};

interface ReactPDFGeneratorProps {
  cv: CV;
}

export const ReactPDFGenerator: React.FC<ReactPDFGeneratorProps> = ({ cv }) => {
  const [isRendering, setIsRendering] = React.useState(true);
  const [renderKey, setRenderKey] = React.useState(0);
  const cvRef = React.useRef(cv);
  const timeoutRef = React.useRef<number | null>(null);
  const [pendingUpdate, setPendingUpdate] = React.useState(false);

  // Effect to debounce CV changes and only re-render after pause in typing
  React.useEffect(() => {
    // Check if CV actually changed
    if (JSON.stringify(cvRef.current) !== JSON.stringify(cv)) {
      // Signal that an update is pending
      setPendingUpdate(true);
      
      // Clear any existing timeout
      if (timeoutRef.current) {
        window.clearTimeout(timeoutRef.current);
      }
      
      // Set new timeout to update after 500ms of inactivity
      timeoutRef.current = window.setTimeout(() => {
        cvRef.current = cv;
        setIsRendering(true);
        setRenderKey(prevKey => prevKey + 1);
        setPendingUpdate(false);
      }, 500);
    }
    
    return () => {
      // Clean up timeout on unmount or when cv changes again
      if (timeoutRef.current) {
        window.clearTimeout(timeoutRef.current);
      }
    };
  }, [cv]);

  // Effect to handle rendering state
  React.useEffect(() => {
    if (isRendering) {
      // Minimal wait to let React update before showing content
      const timer = setTimeout(() => {
        setIsRendering(false);
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [isRendering]);

  // Preview container styles
  const previewContainerStyle = {
    display: 'flex',
    flexDirection: 'column' as const,
    height: '100vh',
    width: '100%',
    background: '#f5f5f5',
    overflow: 'hidden',
  };
  
  // Toolbar styles
  const toolbarStyle = {
    padding: '10px 20px',
    background: '#333',
    color: 'white',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
    zIndex: 10,
  };
  
  // Button styles
  const buttonStyle = {
    background: '#ee0000',
    color: 'white',
    border: 'none',
    padding: '8px 15px',
    borderRadius: '4px',
    cursor: 'pointer',
    fontWeight: 'bold' as const,
    fontSize: '14px',
    marginLeft: '10px',
  };
  
  // Viewer wrapper styles
  const viewerWrapperStyle = {
    flex: 1,
    overflow: 'hidden',
    position: 'relative' as const,
  };
  
  // Rendering overlay styles
  const renderingOverlayStyle = {
    position: 'absolute' as const,
    top: 15,
    right: 15,
    background: 'rgba(238, 0, 0, 0.85)',
    color: 'white',
    padding: '8px 15px',
    borderRadius: '4px',
    zIndex: 5,
    display: 'flex',
    alignItems: 'center',
    fontSize: '12px',
    boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
  };
  
  // Pending update indicator styles
  const pendingUpdateStyle = {
    position: 'absolute' as const,
    top: 15,
    right: isRendering ? 180 : 15,
    background: 'rgba(51, 51, 51, 0.85)',
    color: 'white',
    padding: '8px 15px',
    borderRadius: '4px',
    zIndex: 4,
    display: 'flex',
    alignItems: 'center',
    fontSize: '12px',
  };

  return (
    <div style={previewContainerStyle}>
      {/* Toolbar */}
      <div style={toolbarStyle}>
        <div>
          <strong>{cv.generalInfo.name}</strong> - CV Preview
        </div>
      </div>
      
      {/* PDF Viewer Wrapper */}
      <div style={viewerWrapperStyle}>
        {/* Rendering Indicator - only shows briefly during updates */}
        {isRendering && (
          <div style={renderingOverlayStyle}>
            <div style={{ 
              border: '2px solid rgba(255,255,255,0.5)',
              borderTopColor: 'white',
              borderRadius: '50%', 
              width: '14px', 
              height: '14px',
              animation: 'spin 0.8s linear infinite',
              marginRight: '8px'
            }} />
            <span>Updating preview...</span>
          </div>
        )}
        
        {/* Pending update indicator - shows when typing */}
        {pendingUpdate && !isRendering && (
          <div style={pendingUpdateStyle}>
            <span>Changes pending...</span>
          </div>
        )}
        
        {/* PDF Viewer with real-time rendering */}
        <PDFViewer 
          key={renderKey} // Force remount when CV changes
          style={{ 
            width: '100%', 
            height: '100%',
          }}
          showToolbar={false}
        >
          <CVDocument cv={cv} />
        </PDFViewer>
      </div>
      
      {/* Animation and print styles */}
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        
        /* Selection styles for PDF viewer */
        .react-pdf__Page {
          -webkit-user-select: text !important;
          -moz-user-select: text !important;
          -ms-user-select: text !important;
          user-select: text !important;
        }
        
        .react-pdf__Page ::selection {
          background-color: rgba(0, 102, 204, 0.3) !important;
          color: inherit !important;
        }
        
        /* Ensure text elements can be selected */
        .react-pdf__Page span::selection,
        .react-pdf__Page div::selection,
        .react-pdf__Page p::selection,
        .react-pdf__Page text::selection {
          background-color: rgba(0, 102, 204, 0.3) !important;
          color: inherit !important;
        }
        
        /* Canvas text selection - for Canvas-based rendering */
        canvas::selection {
          background-color: rgba(0, 102, 204, 0.3) !important;
        }
        
        /* Force selection to be visible */
        *::selection {
          background-color: rgba(0, 102, 204, 0.3) !important;
        }
        
        @media print {
          body * {
            visibility: hidden;
          }
          .react-pdf__Page {
            visibility: visible;
            position: absolute;
            left: 0;
            top: 0;
          }
          .react-pdf__Page * {
            visibility: visible;
          }
        }
      `}} />
    </div>
  );
};

// Export a function that can be called to generate and save/open the PDF
export const generatePDF = async (cv: CV) => {
  // Create a loading notification
  const loadingElement = document.createElement('div');
  loadingElement.style.position = 'fixed';
  loadingElement.style.top = '20px';
  loadingElement.style.right = '20px';
  loadingElement.style.background = '#333';
  loadingElement.style.color = 'white';
  loadingElement.style.padding = '15px 20px';
  loadingElement.style.borderRadius = '5px';
  loadingElement.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
  loadingElement.style.zIndex = '9999';
  loadingElement.style.display = 'flex';
  loadingElement.style.alignItems = 'center';
  loadingElement.style.gap = '10px';
  loadingElement.innerHTML = `
    <div style="border: 3px solid rgba(255,255,255,0.3); border-top: 3px solid white; border-radius: 50%; width: 20px; height: 20px; animation: spin 1s linear infinite;"></div>
    <div>Generating PDF...</div>
  `;
  
  // Add animation style
  const styleElement = document.createElement('style');
  styleElement.innerHTML = `
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(styleElement);
  document.body.appendChild(loadingElement);
  
  try {
    // Create the PDF document
    const doc = <CVDocument cv={cv} />;
    
    // Convert to blob with timeout
    let blob;
    try {
      const timeoutPromise = new Promise<Blob>((_, reject) => {
        setTimeout(() => reject(new Error('PDF generation timed out')), 15000);
      });
      
      blob = await Promise.race([
        pdf(doc).toBlob(),
        timeoutPromise
      ]);
    } catch (blobError) {
      console.error('Error creating PDF blob:', blobError);
      throw new Error('Failed to create PDF: ' + (blobError instanceof Error ? blobError.message : 'Unknown error'));
    }
    
    // Verify we have a valid blob
    if (!blob || blob.size < 1000) {
      throw new Error('Generated PDF is invalid or too small');
    }
    
    // Create URL and trigger download
    const url = URL.createObjectURL(blob);
    
    // Create download link
    const link = document.createElement('a');
    link.href = url;
    link.download = `${cv.generalInfo.name.replace(/\s+/g, '_')}_CV.pdf`;
    document.body.appendChild(link);
    link.click();
    
    // Clean up
    setTimeout(() => {
      URL.revokeObjectURL(url);
      document.body.removeChild(link);
      
      // Show success notification
      loadingElement.style.background = '#2e7d32';
      loadingElement.innerHTML = `
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="white"/>
        </svg>
        <div>PDF Downloaded Successfully</div>
      `;
      
      // Remove success notification after 3 seconds
      setTimeout(() => {
        if (document.body.contains(loadingElement)) {
          document.body.removeChild(loadingElement);
        }
      }, 3000);
    }, 100);
    
  } catch (err) {
    console.error('Error generating PDF:', err);
    
    // Show error notification
    loadingElement.style.background = '#c62828';
    loadingElement.innerHTML = `
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z" fill="white"/>
      </svg>
      <div>Error: ${err instanceof Error ? err.message : 'Unknown error'}</div>
    `;
    
    // Remove error notification after 5 seconds
    setTimeout(() => {
      if (document.body.contains(loadingElement)) {
        document.body.removeChild(loadingElement);
      }
    }, 5000);
  }
}; 