File size: 23,381 Bytes
5463318
 
 
 
 
 
 
 
38ee1b6
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ee1b6
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ee1b6
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ee1b6
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ee1b6
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import React, { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import { ArrowLeft, Download, Printer, RotateCcw, Copy, CheckCircle2, Loader2, Lock } from "lucide-react";
import { Button } from "../../components/ui/Button";
import { cn } from "../../utils/cn";
import { ExamPinModal } from "../../components/ui/ExamPinModal";
import { supabase } from "../../utils/supabaseClient";
import { API_BASE_URL } from "../../utils/api";

export default function Preview() {
    const location = useLocation();
    const navigate = useNavigate();
    const { formData, sectionsData, generatedResult } = location.state || {};
    const [paperResult, setPaperResult] = useState(generatedResult);
    const [copiedIndex, setCopiedIndex] = useState(null);
    const [isDownloading, setIsDownloading] = useState(false);
    const [loadingQuestion, setLoadingQuestion] = useState(null); // format: "sIndex-qIndex"
    
    // Exam PIN Verification States
    const [isVerified, setIsVerified] = useState(false);
    const [isPinModalOpen, setIsPinModalOpen] = useState(false);
    const [userHasPin, setUserHasPin] = useState(false);
    const [verifiedPin, setVerifiedPin] = useState("");
    const [isInitialLoad, setIsInitialLoad] = useState(true);

    React.useEffect(() => {
        const checkUserPin = async () => {
            try {
                const { data: { session } } = await supabase.auth.getSession();
                const response = await fetch(`${API_BASE_URL}/api/profile`, {
                    method: 'GET',
                    headers: { 'Authorization': `Bearer ${session?.access_token}` }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.has_exam_password) {
                        setUserHasPin(true);
                        setIsPinModalOpen(true);
                    } else {
                        setIsVerified(true);
                    }
                }
            } catch (error) {
                console.error("Error checking PIN status:", error);
                setIsVerified(true); // Fallback to avoid locking user out on error
            } finally {
                setIsInitialLoad(false);
            }
        };

        checkUserPin();
    }, []);

    // If no state exists (direct access), send back to generate
    if (!formData) {
        return (
            <div className="flex flex-col items-center justify-center h-full space-y-4">
                <p className="text-muted-foreground">No document to preview.</p>
                <Button onClick={() => navigate("/app/generate")}>Go to Generator</Button>
            </div>
        );
    }

    const handleDownloadPDF = async () => {
        setIsDownloading(true);
        try {
            const { data: { session } } = await supabase.auth.getSession();
            const res = await fetch(`${API_BASE_URL}/download`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${session?.access_token}`
                },
                body: JSON.stringify({
                    form_data: formData,
                    generated_result: generatedResult,
                    password: verifiedPin
                })
            });
            const blob = await res.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${formData.title || 'ExamCraft_Paper'}.pdf`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } catch (error) {
            console.error("Download failed", error);
            alert("Download failed. Please try again.");
        } finally {
            setIsDownloading(false);
        }
    };

    const handleCopyQuestion = (text, index) => {
        navigator.clipboard.writeText(text);
        setCopiedIndex(index);
        setTimeout(() => setCopiedIndex(null), 2000);
    };

    const handleRegenerateSpecificQuestion = async (sectionIndex, questionIndex) => {
        const key = `${sectionIndex}-${questionIndex}`;
        setLoadingQuestion(key);
        try {
            const { data: { session } } = await supabase.auth.getSession();
            
            const res = await fetch(`${API_BASE_URL}/regenerate-question`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${session?.access_token}`
                },
                body: JSON.stringify({
                    question_data: paperResult.sections[sectionIndex].questions[questionIndex],
                    paper_id: paperResult.paper_id,
                    source_content: formData?.content_preview || "" // We might need to pass this or handle it backend
                })
            });

            if (!res.ok) throw new Error("Regeneration failed");
            const newQuestion = await res.json();

            if (newQuestion.error) throw new Error(newQuestion.error);

            // Update local state
            const updatedSections = [...paperResult.sections];
            updatedSections[sectionIndex].questions[questionIndex] = newQuestion;
            const updatedPaper = { ...paperResult, sections: updatedSections };
            setPaperResult(updatedPaper);

            // Persist the change to the database
            if (paperResult.paper_id) {
                await fetch(`${API_BASE_URL}/api/exam_papers/${paperResult.paper_id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${session?.access_token}`
                    },
                    body: JSON.stringify({
                        content: updatedPaper
                    })
                });
            }

        } catch (error) {
            console.error("Regeneration error:", error);
            alert("Failed to regenerate question. Please try again.");
        } finally {
            setLoadingQuestion(null);
        }
    };

    const handleVerifySuccess = (pin) => {
        setVerifiedPin(pin);
        setIsVerified(true);
    };

    if (isInitialLoad) {
        return (
            <div className="flex flex-col items-center justify-center p-20 min-h-[600px] bg-card rounded-2xl border border-border mt-10 shadow-sm">
                <Loader2 className="animate-spin text-primary h-10 w-10 mb-4" />
                <p className="text-muted-foreground font-medium">Securing session...</p>
            </div>
        );
    }

    if (userHasPin && !isVerified) {
        return (
            <div className="flex flex-col items-center justify-center p-20 min-h-[600px] bg-card rounded-2xl border border-border mt-10 shadow-xl border-t-4 border-t-primary">
                <div className="w-20 h-20 bg-primary/10 rounded-full flex items-center justify-center text-primary mb-6 shadow-inner ring-4 ring-primary/5">
                    <Lock size={40} className="drop-shadow-sm" />
                </div>
                <h2 className="text-2xl font-bold mb-3 tracking-tight">Paper is Encrypted</h2>
                <p className="text-muted-foreground text-center max-w-sm mb-8 leading-relaxed">
                    This document is protected by your Exam PIN. Please unlock it to view the content and download the PDF.
                </p>
                <Button 
                    className="h-12 px-10 text-lg font-bold shadow-lg shadow-primary/20 hover:scale-[1.05] transition-transform" 
                    onClick={() => setIsPinModalOpen(true)}
                >
                    Unlock Paper
                </Button>

                <ExamPinModal 
                    isOpen={isPinModalOpen} 
                    onClose={() => setIsPinModalOpen(false)} 
                    onVerified={handleVerifySuccess}
                    title="Unlock Exam Paper"
                />
            </div>
        );
    }

    return (
        <div className="max-w-5xl mx-auto py-6 space-y-6">

            <div className="sticky top-0 z-50 bg-background/80 backdrop-blur-md p-4 rounded-b-xl border-b border-border shadow-sm flex items-center justify-between mb-6 -mx-4 md:mx-0 md:rounded-xl">
                <Button variant="ghost" onClick={() => navigate('/app/generate')} className="text-muted-foreground hover:text-foreground">
                    <ArrowLeft className="mr-2" size={20} /> Back
                </Button>
                <div className="flex gap-3">
                    <Button variant="outline" className="gap-2 border-border hover:bg-muted/50" onClick={() => window.print()}>
                        <Printer size={18} /> Print
                    </Button>
                    <Button className="gap-2 glow-border" onClick={handleDownloadPDF} disabled={isDownloading}>
                        {isDownloading ? <Loader2 size={18} className="animate-spin" /> : <Download size={18} />}
                        {isDownloading ? "Exporting..." : "Export PDF"}
                    </Button>
                </div>
            </div>

            <motion.div
                initial={{ opacity: 0, scale: 0.98 }}
                animate={{ opacity: 1, scale: 1 }}
                className="bg-card shadow-xl rounded-2xl border border-border p-8 md:p-14 min-h-[800px]"
            >
                <div className="text-center border-b-2 border-primary/50 pb-8 mb-10">
                    <h1 className="text-4xl font-bold mb-3 uppercase tracking-wider text-foreground">
                        {formData.title || paperResult?.title || "Examination"}
                    </h1>
                    <p className="text-muted-foreground text-xl mb-6">Subject: {formData.subject || 'General'} | Grade: {formData.classGrade || 'N/A'}</p>

                    <div className="flex justify-center flex-wrap gap-4 text-sm font-semibold">
                        <span className="bg-muted px-4 py-2 rounded-lg border border-border">Time Allowed: {formData.duration} Mins</span>
                        <span className="bg-muted px-4 py-2 rounded-lg border border-border">Sections: {paperResult?.sections?.length || 0}</span>
                        <span className="bg-muted px-4 py-2 rounded-lg border border-border">
                            Total Marks: {formData.totalMarks || 100}
                        </span>
                    </div>
                </div>

                <div className="space-y-10">
                    {formData.instructions && (
                        <div className="mb-8 p-4 bg-muted/30 border border-border rounded-xl text-sm italic text-muted-foreground whitespace-pre-line">
                            <span className="font-semibold text-foreground not-italic block mb-2">General Instructions:</span>
                            {formData.instructions}
                        </div>
                    )}

                    {paperResult && paperResult.sections ? (
                        paperResult.sections.map((section, sIndex) => (
                            <div key={sIndex} className="mb-12">
                                <div className="mb-6 bg-muted/20 p-4 border-l-4 border-primary rounded-r-lg">
                                    <h3 className="text-2xl font-bold mb-1">{section.section_name}</h3>
                                    <p className="text-sm text-muted-foreground font-medium">{section.instructions}</p>
                                </div>

                                <div className="space-y-8 pl-2">
                                    {section.questions.map((q, qIndex) => (
                                        <div key={qIndex} className="group relative flex gap-4 p-4 -ml-4 rounded-xl border-2 border-transparent hover:border-dashed hover:border-primary/40 hover:bg-primary/5 transition-all">
                                            <div className="font-bold text-lg mt-0.5 min-w-[32px]">Q{qIndex + 1}.</div>

                                                <div className="flex-1">
                                                <div className="flex justify-between items-start gap-4">
                                                    <div className="flex-1">
                                                        <p className={cn(
                                                            "text-lg leading-relaxed text-foreground/90 font-medium transition-opacity",
                                                            loadingQuestion === `${sIndex}-${qIndex}` && "opacity-30"
                                                        )}>
                                                            {q.question_text}
                                                        </p>
                                                        {q.internal_choice_question_text && (
                                                            <div className={cn(
                                                                "mt-4 transition-opacity",
                                                                loadingQuestion === `${sIndex}-${qIndex}` && "opacity-30"
                                                            )}>
                                                                <div className="flex items-center gap-4 my-2 opacity-50">
                                                                    <div className="h-px bg-border flex-1"></div>
                                                                    <span className="text-xs font-bold uppercase tracking-wider">OR</span>
                                                                    <div className="h-px bg-border flex-1"></div>
                                                                </div>
                                                                <p className="text-lg leading-relaxed text-foreground/90 font-medium">
                                                                    {q.internal_choice_question_text}
                                                                </p>
                                                            </div>
                                                        )}
                                                    </div>
                                                    {q.marks && (
                                                        <span className="shrink-0 text-sm font-bold bg-muted px-2 py-1 border border-border rounded">[{q.marks}]</span>
                                                    )}
                                                </div>

                                                {q.options && q.options.length > 0 && (
                                                    <div className="grid md:grid-cols-2 gap-4 mt-5">
                                                        {q.options.map((opt, j) => (
                                                            <div key={j} className="flex items-start gap-3 p-3 rounded-lg border border-border/60 bg-muted/10">
                                                                <div className="h-5 w-5 rounded-full border-2 border-primary/50 shrink-0 flex items-center justify-center mt-0.5">
                                                                    <span className="text-[10px] font-bold text-primary">{String.fromCharCode(65 + j)}</span>
                                                                </div>
                                                                <span className="text-base text-foreground/80">{opt}</span>
                                                            </div>
                                                        ))}
                                                    </div>
                                                )}

                                                <div className="flex flex-wrap gap-2 mt-4">
                                                    {q.bloom_level && (
                                                        <span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-accent/10 text-accent px-2 py-1 rounded">
                                                            {q.bloom_level}
                                                        </span>
                                                    )}
                                                    {q.estimated_time_mins && (
                                                        <span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-blue-500/10 text-blue-500 px-2 py-1 rounded">
                                                            {q.estimated_time_mins} mins
                                                        </span>
                                                    )}
                                                    {q.chapter && (
                                                        <span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-purple-500/10 text-purple-500 px-2 py-1 rounded line-clamp-1 max-w-[200px]" title={q.chapter}>
                                                            CH: {q.chapter}
                                                        </span>
                                                    )}
                                                    {q.competency && (
                                                        <span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-emerald-500/10 text-emerald-500 px-2 py-1 rounded line-clamp-1 max-w-[200px]" title={q.competency}>
                                                            {q.competency}
                                                        </span>
                                                    )}
                                                </div>

                                                {(q.correct_answer || q.marking_scheme) && (
                                                    <div className="mt-4 p-4 rounded-lg bg-orange-500/5 border border-orange-500/20">
                                                        {q.correct_answer && (
                                                            <div className="mb-2">
                                                                <span className="text-xs font-bold uppercase text-orange-600 dark:text-orange-400 block mb-1">Answer Key:</span>
                                                                <p className="text-sm text-foreground/80">{q.correct_answer}</p>
                                                            </div>
                                                        )}
                                                        {q.marking_scheme && (
                                                            <div>
                                                                <span className="text-xs font-bold uppercase text-orange-600 dark:text-orange-400 block mb-1">Marking Scheme:</span>
                                                                <p className="text-sm text-foreground/80 whitespace-pre-line">{q.marking_scheme}</p>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}

                                                <div className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity bg-card shadow-lg border border-border rounded-lg p-1 flex flex-col gap-1">
                                                    <button
                                                        onClick={() => handleRegenerateSpecificQuestion(sIndex, qIndex)}
                                                        disabled={loadingQuestion === `${sIndex}-${qIndex}`}
                                                        className="p-2 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-md transition-colors disabled:opacity-50"
                                                        title="Regenerate this specific question"
                                                    >
                                                        {loadingQuestion === `${sIndex}-${qIndex}` ? <Loader2 size={16} className="animate-spin" /> : <RotateCcw size={16} />}
                                                    </button>
                                                    <button
                                                        onClick={() => handleCopyQuestion(q.question_text, `${sIndex}-${qIndex}`)}
                                                        className="p-2 text-muted-foreground hover:text-accent hover:bg-accent/10 rounded-md transition-colors"
                                                        title="Copy text"
                                                    >
                                                        {copiedIndex === `${sIndex}-${qIndex}` ? <CheckCircle2 size={16} className="text-emerald-500" /> : <Copy size={16} />}
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))
                    ) : (
                        <div className="space-y-12 animate-pulse py-10">
                            {[1, 2, 3].map(i => (
                                <div key={i} className="mb-12">
                                    <div className="mb-6 bg-muted/20 p-4 border-l-4 border-muted rounded-r-lg">
                                        <div className="h-6 bg-muted rounded w-1/4 mb-2"></div>
                                        <div className="h-4 bg-muted/60 rounded w-1/2"></div>
                                    </div>
                                    <div className="space-y-8 pl-2">
                                        {[1, 2].map(j => (
                                            <div key={j} className="flex gap-4 p-4">
                                                <div className="h-6 w-8 bg-muted rounded mt-1"></div>
                                                <div className="flex-1 space-y-4">
                                                    <div className="h-5 bg-muted rounded w-full"></div>
                                                    <div className="h-5 bg-muted rounded w-5/6"></div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </motion.div>
        </div>
    );
}