import React, { useRef, useState, useEffect } from 'react';
import { CgProfile } from "react-icons/cg";
import { pdf, Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/renderer';
import { saveAs } from 'file-saver';

// Register fonts (optional)
Font.register({
  family: 'Helvetica',
  fonts: [
    { src: 'https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf', fontWeight: 300 },
    { src: 'https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-regular-webfont.ttf', fontWeight: 400 },
    { src: 'https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-medium-webfont.ttf', fontWeight: 500 },
    { src: 'https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-bold-webfont.ttf', fontWeight: 700 },
  ]
});

function CvTemplate({
  personalInfo,
  addressDetails,
  educations,
  experiences,
  skills,
  languages,
  drivingLicenses,
  hobbies,
  awards,
  projects
}) {
  const cvRef = useRef();
  const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
  const [pdfImageSrc, setPdfImageSrc] = useState(null);

  const getImageWithCorsProxy = (url) => {
    // Use a CORS proxy service
    return `https://corsproxy.io/?${encodeURIComponent(url)}`;
  };


  // Convert image to base64 for PDF
  useEffect(() => {
    const convertImageToBase64 = async () => {
      if (!personalInfo.profileImage) {
        setPdfImageSrc(null);
        return;
      }

      try {
        const imageUrl = getImageWithCorsProxy(
          `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${personalInfo.profileImage}`
        );
        const response = await fetch(imageUrl);
        if (!response.ok) {
          throw new Error('Failed to fetch image');
        }
        
        const blob = await response.blob();
        const reader = new FileReader();
        
        reader.onloadend = () => {
          setPdfImageSrc(reader.result);
        };
        
        reader.onerror = () => {
          console.error('Failed to convert image to base64');
          setPdfImageSrc(null);
        };
        
        reader.readAsDataURL(blob);
      } catch (error) {
        console.error('Error converting image to base64:', error);
        setPdfImageSrc(null);
      }
    };

    convertImageToBase64();
  }, [personalInfo.profileImage]);

  const formatDOB = (dateString) => {
    if (!dateString) return '-';
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return '-';
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      return `${year}-${month}-${day}`;
    } catch {
      return '-';
    }
  };

  // Helper function to safely render HTML content for website
  const renderHTML = (htmlContent) => {
    if (!htmlContent) return null;
    return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
  };

  // Improved helper function to convert HTML to plain text for PDF
  const htmlToPlainText = (htmlContent) => {
    if (!htmlContent) return '';
    
    // Create a temporary div to parse HTML
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlContent;
    
    // Function to recursively process nodes
    const processNode = (node) => {
      if (node.nodeType === Node.TEXT_NODE) {
        return node.textContent;
      }
      
      if (node.nodeType === Node.ELEMENT_NODE) {
        const tagName = node.tagName.toLowerCase();
        const children = Array.from(node.childNodes);
        const childText = children.map(processNode).join('');
        
        // Handle different HTML elements
        switch (tagName) {
          case 'div':
          case 'p':
            return childText + '\n\n';
          case 'br':
            return '\n';
          case 'li':
            return '• ' + childText + '\n';
          case 'ul':
          case 'ol':
            return childText;
          case 'strong':
          case 'b':
            return childText;
          case 'em':
          case 'i':
            return childText;
          case 'h1':
          case 'h2':
          case 'h3':
          case 'h4':
          case 'h5':
          case 'h6':
            return childText + '\n\n';
          default:
            return childText;
        }
      }
      
      return '';
    };
    
    return processNode(tempDiv).trim();
  };

  // PDF Styles
  const styles = StyleSheet.create({
    page: {
      flexDirection: 'column',
      backgroundColor: '#FFFFFF',
      padding: 30,
      fontFamily: 'Helvetica',
    },
    section: {
      marginBottom: 15,
    },
    header: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'flex-start',
      borderBottom: '2pt solid #1e3a8a',
      paddingBottom: 15,
      marginBottom: 20,
    },
    headerContent: {
      flexDirection: 'row',
      alignItems: 'center', // Center align vertically
      width: '100%',
    },
    profileInfo: {
      flex: 1,
      marginLeft: 15, // Reduced space between image and content
    },
    profileImageContainer: {
      width: 70, // Slightly smaller image
      height: 70,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    profileImage: {
      width: '100%',
      height: '100%',
      borderRadius: 35, // Half of width/height for circle
      border: '2pt solid #bfdbfe',
    },
    name: {
      fontSize: 20,
      fontWeight: 700,
      color: '#1e3a8a',
      marginBottom: 5, // Reduced margin
    },
    contactInfo: {
      fontSize: 10,
      lineHeight: 1.4, // Tighter line height
      color: '#374151',
    },
    sectionTitle: {
      fontSize: 14,
      fontWeight: 700,
      color: '#1e3a8a',
      borderBottom: '1pt solid #e5e7eb',
      paddingBottom: 5,
      marginBottom: 10,
      textTransform: 'uppercase',
    },
    item: {
      marginBottom: 12,
    },
    itemTitle: {
      fontSize: 12,
      fontWeight: 600,
      color: '#1e3a8a',
      marginBottom: 3,
    },
    itemSubtitle: {
      fontSize: 10,
      fontStyle: 'italic',
      color: '#6b7280',
      marginBottom: 5,
    },
    itemDetails: {
      fontSize: 10,
      color: '#4b5563',
      lineHeight: 1.4,
    },
    skillsContainer: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: 5,
    },
    skillItem: {
      backgroundColor: '#f3f4f6',
      padding: '3pt 6pt',
      borderRadius: 3,
      fontSize: 9,
      border: '0.5pt solid #e5e7eb',
    },
    noData: {
      fontSize: 10,
      color: '#dc2626',
      fontStyle: 'italic',
    },
    pageNumber: {
      position: 'absolute',
      fontSize: 10,
      bottom: 20,
      left: 0,
      right: 0,
      textAlign: 'center',
      color: 'grey',
    },
  });

  // PDF Document Component
  const MyDocument = () => (
    <Document>
      <Page size="A4" style={styles.page}>
        {/* Header */}
        <View style={styles.header}>
          <View style={styles.headerContent}>
            {/* Profile Image on the left side */}
            {pdfImageSrc && (
              <View style={styles.profileImageContainer}>
                <Image 
                  style={styles.profileImage}
                  src={pdfImageSrc}
                />
              </View>
            )}
            
            {/* Profile Info on the right side */}
            <View style={styles.profileInfo}>
              <Text style={styles.name}>{personalInfo.fullName || 'Full Name'}</Text>
              <View style={styles.contactInfo}>
                <Text>Nationality: {personalInfo.nationality || '-'}</Text>
                <Text>Date of Birth: {formatDOB(personalInfo.dateOfBirth)}</Text>
                <Text>Phone: {personalInfo.phoneNumber || '-'}</Text>
                <Text>Email: {personalInfo.email || '-'}</Text>
                <Text>
                  Address: {addressDetails.address || '-'}
                  {addressDetails.city ? `, ${addressDetails.city}` : ''}
                  {addressDetails.country ? `, ${addressDetails.country}` : ''}
                </Text>
              </View>
            </View>
          </View>
        </View>

        {/* About Yourself */}
        {personalInfo.aboutYourself && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>About Me</Text>
            <Text style={styles.itemDetails}>
              {htmlToPlainText(personalInfo.aboutYourself)}
            </Text>
          </View>
        )}

        {/* Education and Training */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Education and Training</Text>
          {educations.length > 0 && !educations.every(e => !e.degree_name) ? (
            educations.map((edu, index) => (
              <View key={index} style={styles.item} wrap={false}>
                <Text style={styles.itemTitle}>{edu.degree_name}</Text>
                <Text style={styles.itemSubtitle}>
                  {edu.university_name} ({edu.city}, {edu.country})
                </Text>
                <Text style={styles.itemSubtitle}>
                  {edu.start_date} - {edu.education_present ? 'Present' : edu.end_date}
                </Text>
                {edu.details && (
                  <Text style={styles.itemDetails}>
                    {htmlToPlainText(edu.details)}
                  </Text>
                )}
              </View>
            ))
          ) : (
            <Text style={styles.noData}>No education records added</Text>
          )}
        </View>

        {/* Work Experience */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Work Experience</Text>
          {experiences.length > 0 && !experiences.every(e => !e.position) ? (
            experiences.map((exp, index) => (
              <View key={index} style={styles.item} wrap={false}>
                <Text style={styles.itemTitle}>{exp.position}</Text>
                <Text style={styles.itemSubtitle}>
                  {exp.employer} ({exp.city}, {exp.country})
                </Text>
                <Text style={styles.itemSubtitle}>
                  {exp.start_date} - {exp.currentlyWorking ? 'Present' : exp.end_date}
                </Text>
                {exp.details && (
                  <Text style={styles.itemDetails}>
                    {htmlToPlainText(exp.details)}
                  </Text>
                )}
              </View>
            ))
          ) : (
            <Text style={styles.noData}>No work experience records added</Text>
          )}
        </View>

        {/* Language Skills */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Language Skills</Text>
          <Text style={styles.itemDetails}>
            <Text style={{ fontWeight: 600 }}>Mother tongue(s): </Text>
            {languages[0]?.name || '-'}
          </Text>
          <Text style={[styles.itemDetails, { marginTop: 5 }]}>
            <Text style={{ fontWeight: 600 }}>Other language(s):</Text>
          </Text>
          {languages.length > 1 && languages[1].name ? (
            <Text style={[styles.itemDetails, { marginLeft: 10 }]}>
              {languages[1].name}
              {languages[1].cirtificate_type ? ` (${languages[1].cirtificate_type})` : ''}
            </Text>
          ) : (
            <Text style={[styles.noData, { marginLeft: 10 }]}>No other languages added</Text>
          )}
        </View>

        {/* Digital Skills */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Digital Skills</Text>
          {skills.length && !skills.every(s => !s.name) ? (
            <View style={styles.skillsContainer}>
              {skills.map((skill, index) => (
                <Text key={index} style={styles.skillItem}>
                  {skill.name}
                  {skill.proficiency ? ` (${skill.proficiency})` : ''}
                </Text>
              ))}
            </View>
          ) : (
            <Text style={styles.noData}>No digital skills added</Text>
          )}
        </View>

        {/* Driving Licence */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Driving Licence</Text>
          {drivingLicenses.length && !drivingLicenses.every(l => !l.licenseType) ? (
            <View style={styles.skillsContainer}>
              {drivingLicenses.map((lic, index) => (
                <Text key={index} style={styles.skillItem}>
                  {lic.licenseType}
                </Text>
              ))}
            </View>
          ) : (
            <Text style={styles.noData}>No driving licenses added</Text>
          )}
        </View>

        {/* Hobbies and Interests */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Hobbies and Interests</Text>
          {hobbies.length && hobbies.some(h => typeof h === 'string' && h.trim()) ? (
            <View style={styles.skillsContainer}>
              {hobbies
                .filter(h => typeof h === 'string' && h.trim())
                .map((hobby, index) => (
                  <Text key={index} style={styles.skillItem}>
                    {hobby}
                  </Text>
                ))}
            </View>
          ) : (
            <Text style={styles.noData}>No hobbies added</Text>
          )}
        </View>

        {/* Honours and Awards */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Honours and Awards</Text>
          {awards.length && !awards.every(a => !a.awarded_title) ? (
            awards.map((award, index) => (
              <View key={index} style={styles.item} wrap={false}>
                <Text style={styles.itemTitle}>{award.awarded_title}</Text>
                <Text style={styles.itemSubtitle}>
                  {award.awarded_date}
                  {award.awarded_uni_name ? ` • ${award.awarded_uni_name}` : ''}
                </Text>
                {award.details && (
                  <Text style={styles.itemDetails}>
                    {htmlToPlainText(award.details)}
                  </Text>
                )}
              </View>
            ))
          ) : (
            <Text style={styles.noData}>No awards added</Text>
          )}
        </View>

        {/* Projects */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Projects</Text>
          {projects.length && !projects.every(p => !p.project_title && !p.details) ? (
            projects.map((project, index) => (
              <View key={index} style={styles.item} wrap={false}>
                <Text style={styles.itemTitle}>{project.project_title}</Text>
                {project.project_start_date && (
                  <Text style={styles.itemSubtitle}>
                    {project.project_start_date} - {project.project_end_date || 'Present'}
                  </Text>
                )}
                {project.details && (
                  <Text style={styles.itemDetails}>
                    {htmlToPlainText(project.details)}
                  </Text>
                )}
              </View>
            ))
          ) : (
            <Text style={styles.noData}>No projects added</Text>
          )}
        </View>

        {/* Page Number */}
        <Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => (
          `${pageNumber} / ${totalPages}`
        )} fixed />
      </Page>
    </Document>
  );

  const generatePDF = async () => {
    setIsGeneratingPDF(true);
    
    try {
      const blob = await pdf(<MyDocument />).toBlob();
      saveAs(blob, `${personalInfo.fullName || 'cv'}.pdf`);
    } catch (error) {
      console.error('Error generating PDF:', error);
      alert('Error generating PDF. Please try again.');
    } finally {
      setIsGeneratingPDF(false);
    }
  };

  // Website display styles
  const websiteStyles = {
    container: {
      maxWidth: '42rem',
      margin: '0 auto',
      backgroundColor: '#fff',
      padding: '0',
      borderRadius: '0.5rem',
      boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
      marginTop: '2rem',
      border: '1px solid #e5e7eb',
      position: 'relative',
      minHeight: '29.7cm',
      height: 'auto'
    },
    header: {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: '1.5rem 2rem 0.5rem 2rem', // Reduced top padding
      borderBottom: '1px solid #e5e7eb'
    },
    profileSection: {
      display: 'flex',
      alignItems: 'center',
      gap: '1rem' // Reduced gap
    },
    profileImage: {
      width: '5rem', // Slightly smaller
      height: '5rem',
      borderRadius: '50%',
      objectFit: 'cover',
      border: '2px solid #bfdbfe'
    },
    profilePlaceholder: {
      width: '5rem',
      height: '5rem',
      borderRadius: '50%',
      backgroundColor: '#e5e7eb',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: '1.5rem',
      color: '#9ca3af'
    },
    profileInfo: {
      display: 'flex',
      flexDirection: 'column',
      gap: '0.2rem' // Reduced gap
    },
    name: {
      fontSize: '1.25rem',
      fontWeight: 'bold',
      color: '#1e3a8a',
      marginBottom: '0.2rem' // Reduced margin
    },
    detailText: {
      fontSize: '0.75rem',
      color: '#374151',
      lineHeight: '1.3' // Tighter line height
    },
    logoSection: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'flex-end'
    },
    logo: {
      height: '2.5rem',
      marginBottom: '0.5rem'
    },
    content: {
      padding: '2rem'
    },
    section: {
      marginBottom: '1rem'
    },
    sectionTitle: {
      fontSize: '15px',
      fontWeight: 'bold',
      color: '#1e3a8a',
      borderBottom: '1px solid #e5e7eb',
      paddingBottom: '0.25rem',
      textTransform: 'uppercase',
      letterSpacing: '0.05em',
      marginBottom: '0.5rem'
    },
    sectionContent: {
      color: '#1f2937',
      fontSize: '13px',
      marginBottom: '1rem'
    },
    educationItem: {
      color: '#1f2937',
      fontSize: '13px',
      marginBottom: '0.75rem'
    },
    boldText: {
      fontWeight: '600'
    },
    italicText: {
      fontStyle: 'italic',
      color: '#4b5563'
    },
    skillsContainer: {
      display: 'flex',
      flexWrap: 'wrap',
      gap: '0.5rem'
    },
    skillItem: {
      fontSize: '0.75rem',
      color: '#1f2937',
      borderBottom: '1px dotted #9ca3af',
      paddingBottom: '0.125rem'
    },
    errorText: {
      color: '#dc2626',
      fontSize: '13px'
    },
    buttonContainer: {
      display: 'flex',
      justifyContent: 'center',
      marginTop: '1.5rem',
      marginBottom: '3rem'
    },
    downloadButton: {
      backgroundColor: isGeneratingPDF ? '#9ca3af' : '#0d9488',
      color: 'white',
      fontWeight: '600',
      padding: '0.75rem 2rem',
      borderRadius: '0.5rem',
      border: 'none',
      cursor: isGeneratingPDF ? 'not-allowed' : 'pointer',
      boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
      fontSize: '1rem'
    },
    ml4: {
      marginLeft: '1rem'
    },
    mt1: {
      marginTop: '0.25rem'
    },
    mb1: {
      marginBottom: '0.25rem'
    }
  };

  return (
    <>
      <div ref={cvRef} style={websiteStyles.container}>
        {/* Header */}
        <div style={websiteStyles.header}>
          <div style={websiteStyles.profileSection}>
            {personalInfo.profileImage ? (
              <img 
                src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${personalInfo.profileImage}`} 
                alt="Profile" 
                style={websiteStyles.profileImage} 
              />
            ) : (
              <div style={websiteStyles.profilePlaceholder}>
                <CgProfile />
              </div>
            )}
            <div style={websiteStyles.profileInfo}>
              <h2 style={websiteStyles.name}>{personalInfo.fullName || 'Full Name'}</h2>
              <div style={websiteStyles.detailText}>Nationality: {personalInfo.nationality || '-'}</div>
              <div style={websiteStyles.detailText}>
                Date of birth: {formatDOB(personalInfo.dateOfBirth)}
              </div>
              <div style={websiteStyles.detailText}>Phone number: {personalInfo.phoneNumber || '-'}</div>
              <div style={websiteStyles.detailText}>Email address: {personalInfo.email || '-'}</div>
              <div style={websiteStyles.detailText}>
                Home: {addressDetails.address || '-'}
                {addressDetails.city ? ', ' + addressDetails.city : ''}
                {addressDetails.country ? ', ' + addressDetails.country : ''}
              </div>
            </div>
          </div>
          <div style={websiteStyles.logoSection}>
            <img 
              src="/assets/europass-logo.png" 
              alt="europass" 
              style={websiteStyles.logo} 
              onError={e => e.target.style.display = 'none'} 
            />
          </div>
        </div>

        {/* Sections */}
        <div style={websiteStyles.content}>
          {/* About Yourself */}
          {personalInfo.aboutYourself && (
            <>
              <div style={websiteStyles.section}>
                <h3 style={websiteStyles.sectionTitle}>About Me</h3>
              </div>
              <div style={websiteStyles.sectionContent}>
                {renderHTML(personalInfo.aboutYourself)}
              </div>
            </>
          )}

          {/* Education and Training */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Education and Training</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {educations.length > 0 && !educations.every(e => !e.degree_name) ? (
              educations.map((edu, index) => (
                <div key={index} style={websiteStyles.educationItem}>
                  <span style={websiteStyles.boldText}>{edu.degree_name}</span> at {edu.university_name} ({edu.city}, {edu.country})<br/>
                  {edu.start_date} - {edu.education_present ? 'Present' : edu.end_date}
                  {edu.details && (
                    <div style={{...websiteStyles.mt1, ...websiteStyles.italicText}}>
                      {renderHTML(edu.details)}
                    </div>
                  )}
                </div>
              ))
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>

          {/* Work Experience */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Work Experience</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {experiences.length > 0 && !experiences.every(e => !e.position) ? (
              experiences.map((exp, i) => (
                <div key={i} style={websiteStyles.educationItem}>
                  <span style={websiteStyles.boldText}>{exp.position}</span> at {exp.employer} ({exp.city}, {exp.country})<br/>
                  {exp.start_date} - {exp.currentlyWorking ? 'Present' : exp.end_date}
                  {exp.details && (
                    <div style={websiteStyles.mt1}>
                      {renderHTML(exp.details)}
                    </div>
                  )}
                </div>
              ))
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>

          {/* Language Skills */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Language Skills</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            <div style={{...websiteStyles.detailText, ...websiteStyles.mb1}}>
              Mother tongue(s): <span style={websiteStyles.boldText}>{languages[0]?.name || '-'}</span>
            </div>
            <div style={{...websiteStyles.detailText, ...websiteStyles.mb1}}>Other language(s):</div>
            {languages.length > 1 && languages[1].name ? (
              <div style={{...websiteStyles.detailText, ...websiteStyles.ml4}}>
                <span style={websiteStyles.boldText}>{languages[1].name}</span>
                {languages[1].cirtificate_type && (
                  <span style={{marginLeft: '0.5rem', color: '#6b7280'}}>
                    ({languages[1].cirtificate_type})
                  </span>
                )}
              </div>
            ) : (
              <div style={{...websiteStyles.errorText, ...websiteStyles.ml4}}>Record Not Added</div>
            )}
          </div>

          {/* Digital Skills */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Digital Skills</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {skills.length && !skills.every(s => !s.name) ? (
              <div style={websiteStyles.skillsContainer}>
                {skills.map((skill, index) => (
                  <span key={index} style={websiteStyles.skillItem}>
                    {skill.name}
                    {skill.proficiency && (
                      <span style={{marginLeft: '0.25rem', color: '#6b7280'}}>
                        ({skill.proficiency})
                      </span>
                    )}
                  </span>
                ))}
              </div>
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>

          {/* Driving Licence */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Driving Licence</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {drivingLicenses.length && !drivingLicenses.every(l => !l.licenseType) ? (
              <div style={websiteStyles.skillsContainer}>
                {drivingLicenses.map((lic, index) => (
                  <span key={index} style={websiteStyles.detailText}>{lic.licenseType}</span>
                ))}
              </div>
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>

          {/* Hobbies and Interests */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Hobbies and Interests</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {hobbies.length && hobbies.some(h => typeof h === 'string' && h.trim()) ? (
              <div style={websiteStyles.skillsContainer}>
                {hobbies.filter(h => typeof h === 'string' && h.trim()).map((hobby, i) => (
                  <span key={i} style={websiteStyles.detailText}>{hobby}</span>
                ))}
              </div>
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>

          {/* Honours and Awards */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Honours and Awards</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {awards.length && !awards.every(a => !a.awarded_title) ? (
              awards.map((award, i) => (
                <div key={i} style={websiteStyles.educationItem}>
                  <span style={websiteStyles.boldText}>{award.awarded_title}</span> ({award.awarded_date})<br/>
                  {award.awarded_uni_name}
                  {award.details && (
                    <div style={websiteStyles.mt1}>
                      {renderHTML(award.details)}
                    </div>
                  )}
                </div>
              ))
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>

          {/* Projects */}
          <div style={websiteStyles.section}>
            <h3 style={websiteStyles.sectionTitle}>Projects</h3>
          </div>
          <div style={websiteStyles.sectionContent}>
            {projects.length && !projects.every(p => !p.project_title && !p.details) ? (
              projects.map((project, i) => (
                <div key={i} style={websiteStyles.educationItem}>
                  <span style={websiteStyles.boldText}>{project.project_title}</span> 
                  {project.project_start_date && ` (${project.project_start_date} - ${project.project_end_date || 'Present'})`}
                  <br/>
                  {project.details && (
                    <div style={websiteStyles.mt1}>
                      {renderHTML(project.details)}
                    </div>
                  )}
                </div>
              ))
            ) : (
              <div style={websiteStyles.errorText}>Record Not Added</div>
            )}
          </div>
        </div>
      </div>

      <div style={websiteStyles.buttonContainer}>
        <button
          onClick={generatePDF}
          disabled={isGeneratingPDF}
          style={websiteStyles.downloadButton}
          onMouseOver={(e) => !isGeneratingPDF && (e.target.style.backgroundColor = '#0f766e')}
          onMouseOut={(e) => !isGeneratingPDF && (e.target.style.backgroundColor = '#0d9488')}
        >
          {isGeneratingPDF ? 'Generating PDF...' : 'Download as PDF'}
        </button>
      </div>
    </>
  );
}

export default CvTemplate;