'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 and sanitizer
const [{marked}, {default: DOMPurify}] = await Promise.all([
import('marked'),
import('dompurify')
])
// 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 DOMPurify.sanitize(marked(content), {
ALLOWED_TAGS: [
'p',
'strong',
'em',
'b',
'i',
'ul',
'ol',
'li',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'code',
'pre',
'br',
'hr',
'a',
'table',
'thead',
'tbody',
'tr',
'th',
'td',
],
ALLOWED_ATTR: [
'href',
'target',
'rel',
],
ALLOW_DATA_ATTR: false,
})
} catch (error) {
console.warn('Failed to parse markdown, falling back to plain text:', error)
return content.replaceAll('\n', '
')
}
}
export default function PrintButton({versionData, isOutdated = false, voteCounts = null, 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 isExpired = createdAt < threeDaysAgo
const voteStatus = (isExpired || isOutdated) ? 'fermé' : 'ouvert'
const voteColor = voteStatus === 'ouvert' ? '#2e7d32' : '#d32f2f'
// Vote counts display
const voteTotal = voteCounts ? voteCounts.total : 0
const voteTotalColor = voteTotal > 0 ? '#2e7d32' : (voteTotal < 0 ? '#d32f2f' : '#666')
const voteTotalSign = voteTotal >= 0 ? '+' : ''
// 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 = `
📊 Résultats des votes
👍 Votes positifs : ${voteCounts.positive}
👎 Votes négatifs : ${voteCounts.negative}
🏆 Total : ${voteTotalSign}${voteTotal}