"use client" import { useState } from "react" import { X, Download, Share2, Award, Calendar, User, BookOpen, Wallet, CheckCircle } from "lucide-react" import { toast } from "react-hot-toast" interface Certificate { certificate_id: string token_id?: string user_name: string course_title: string mentor_name: string completion_date: string wallet_id?: string verification_url?: string share_code?: string public_url?: string unique_url?: string message?: string } interface CertificateModalProps { isOpen: boolean onClose: () => void courseTitle: string courseMentor: string courseId: string userId: string walletId: string } export function CertificateModal({ isOpen, onClose, courseTitle, courseMentor, courseId, userId, walletId }: CertificateModalProps) { const [step, setStep] = useState<'input' | 'generating' | 'completed'>('input') const [userName, setUserName] = useState('') const [certificate, setCertificate] = useState(null) const [loading, setLoading] = useState(false) if (!isOpen) return null const handleGenerateCertificate = async () => { if (!userName.trim()) { toast.error("Please enter your name") return } setLoading(true) setStep('generating') try { console.log('šŸŽ“ Generating certificate for STUDENT:', userName.trim()) const response = await fetch('http://127.0.0.1:5000/api/certificate/mint', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ user_name: userName.trim(), course_id: courseId, wallet_id: walletId, user_id: userId, course_title: courseTitle }) }) if (response.ok) { const data = await response.json() console.log('āœ… Certificate API response:', data) const certificateData = data.certificate const certificateWithWallet = { certificate_id: certificateData.certificate_id, token_id: certificateData.token_id, user_name: certificateData.user_name, course_title: certificateData.course_title, mentor_name: certificateData.mentor_name, completion_date: certificateData.completion_date, wallet_id: walletId, verification_url: certificateData.verification_url, share_code: certificateData.share_code, public_url: certificateData.public_url, unique_url: certificateData.unique_url, message: certificateData.message } console.log('šŸŽÆ Certificate data:', certificateWithWallet) console.log('šŸ†” Unique Certificate ID:', certificateWithWallet.certificate_id) setCertificate(certificateWithWallet) setStep('completed') toast.success(`Certificate generated for ${certificateWithWallet.user_name}! šŸŽ‰`) } else { const error = await response.json() console.error('āŒ Certificate error:', error) toast.error(error.error || "Failed to generate certificate") setStep('input') } } catch (error) { console.error('āŒ Certificate generation error:', error) toast.error("Failed to generate certificate. Please check your connection.") setStep('input') } finally { setLoading(false) } } const handleDownloadCertificate = async () => { if (!certificate) return try { const certificateHTML = ` Certificate - ${certificate.user_name}
šŸ†

CERTIFICATE OF COMPLETION

This is to certify that
${certificate.user_name}
Blockchain Wallet Address
${certificate.wallet_id}
has successfully completed the course
"${certificate.course_title}"
āœ… Completed on: ${new Date(certificate.completion_date).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}
${certificate.mentor_name}
Course Instructor
Certificate ID: ${certificate.certificate_id}
OpenLearnX Learning Platform
šŸ”’ Blockchain Verified Completion
` const printWindow = window.open('', '_blank') if (printWindow) { printWindow.document.write(certificateHTML) printWindow.document.close() printWindow.onload = () => { setTimeout(() => { printWindow.print() printWindow.close() }, 500) } toast.success("Certificate PDF download initiated! Use your browser's print dialog to save as PDF.") } else { toast.error("Popup blocked. Please allow popups and try again.") } } catch (error) { console.error('PDF generation error:', error) toast.error("Failed to generate PDF") } } const handleShareCertificate = async () => { if (!certificate) return const shareText = `šŸŽ“ I just completed "${certificate.course_title}" on OpenLearnX!\n\nšŸ‘¤ Student: ${certificate.user_name}\nšŸ† Certificate ID: ${certificate.certificate_id}\nšŸ”— View: ${certificate.public_url || window.location.origin + certificate.unique_url}\n\n#OpenLearnX #Blockchain #Learning` if (navigator.share) { try { await navigator.share({ title: `Certificate of Completion - ${certificate.course_title}`, text: shareText, url: certificate.public_url || `${window.location.origin}${certificate.unique_url}` }) // Track share try { await fetch(`http://127.0.0.1:5000/api/certificate/share/${certificate.certificate_id}`, { method: 'POST' }) } catch (e) { console.log('Share tracking failed:', e) } } catch (error) { console.log('Share cancelled') } } else { try { await navigator.clipboard.writeText(shareText) toast.success("Certificate details copied to clipboard!") // Track share try { await fetch(`http://127.0.0.1:5000/api/certificate/share/${certificate.certificate_id}`, { method: 'POST' }) } catch (e) { console.log('Share tracking failed:', e) } } catch (error) { toast.error("Failed to copy certificate details") } } } const handleClose = () => { setStep('input') setUserName('') setCertificate(null) setLoading(false) onClose() } return (
{/* Step 1: Name Input */} {step === 'input' && ( <>

Generate Certificate

You've completed the course!

šŸŽ‰

Congratulations!

You have successfully completed "{courseTitle}"

Course Details:

Course: {courseTitle}
Instructor: {courseMentor}
Completed: {new Date().toLocaleDateString()}
Wallet:
{walletId}
setUserName(e.target.value)} placeholder="e.g., John Smith" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-lg" autoFocus maxLength={50} />

Your name will appear prominently on the certificate.

{userName.length}/50
)} {/* Step 2: Generating */} {step === 'generating' && (

Generating Your Certificate

Creating unique certificate ID and blockchain verification...

)} {/* Step 3: Certificate Generated */} {step === 'completed' && certificate && ( <>

Certificate Ready!

For: {certificate.user_name}

Verified
šŸ†

CERTIFICATE OF COMPLETION

This is to certify that

{certificate.user_name}

Student

Blockchain Wallet Address:

{certificate.wallet_id}

has successfully completed the course

"{certificate.course_title}"

Completed on: {new Date(certificate.completion_date).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}

{certificate.mentor_name}

Course Instructor

šŸ†” Unique Certificate ID:

{certificate.certificate_id}

OpenLearnX Learning Platform
šŸ”’ Blockchain Verified Completion

šŸŽ‰ Your certificate with unique ID {certificate.certificate_id} has been generated!

{certificate.unique_url && (

View at: {certificate.unique_url}

)}
)}
) }