'use client'
import {useState} from 'react'
import PropTypes from 'prop-types'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import Snackbar from '@mui/material/Snackbar'
import Alert from '@mui/material/Alert'
import PrintIcon from '@mui/icons-material/Print'
import {formatDate} from '@/lib/format.js'
// Helper function to render markdown to HTML (reused from PDF export)
const renderMarkdownToHtml = async content => {
if (!content) {
return 'Aucun contenu disponible'
}
// Check if content contains markdown syntax
const hasMarkdown = content.includes('**')
|| content.includes('*')
|| content.includes('#')
|| content.includes('[')
|| content.includes('`')
|| content.includes('> ')
|| content.includes('- ')
|| content.includes('1. ')
if (!hasMarkdown) {
// Simple text with line breaks
return content.replaceAll('\n', '
')
}
try {
// Dynamic import of markdown parser
const {marked} = await import('marked')
// Configure marked for better print rendering
marked.setOptions({
breaks: true, // Convert \n to
gfm: true, // GitHub flavored markdown
headerIds: false, // No header IDs needed for print
mangle: false // Don't mangle email addresses
})
return marked(content)
} catch (error) {
console.warn('Failed to parse markdown, falling back to plain text:', error)
return content.replaceAll('\n', '
')
}
}
export default function PrintButton({versionData, size = 'medium', variant = 'outlined'}) {
const [isPrinting, setIsPrinting] = useState(false)
const [snackbar, setSnackbar] = useState({open: false, message: '', severity: 'success'})
const handlePrint = async () => {
setIsPrinting(true)
try {
// Calculate vote status
const authorName = versionData.user_created?.split('-')[0] || 'Système'
const createdAt = new Date(versionData.date_created)
const threeDaysAgo = new Date(Date.now() - (3 * 24 * 60 * 60 * 1000))
const voteStatus = createdAt < threeDaysAgo ? 'fermé' : 'ouvert'
const voteColor = voteStatus === 'ouvert' ? '#2e7d32' : '#d32f2f'
// Render markdown content to HTML
const renderedContent = await renderMarkdownToHtml(versionData.delta?.contenu)
// Create print window
const printWindow = window.open('', '_blank', 'width=800,height=600')
if (!printWindow) {
throw new Error('Impossible d\'ouvrir la fenêtre d\'impression. Vérifiez que les popups ne sont pas bloqués.')
}
// Build print-optimized HTML
const printHtml = `