/**
 * Online Exams Module - React Views
 * Complete vertical slice: List, Create, Take Exam
 */

import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Link, useNavigate } from 'react-router-dom';
import { useExamStore, formatTime, calculateGrade } from '../../store/exams';
import { api } from '../../store/api';
import { useAuthStore } from '../../store/auth';
import { useSchoolSettingsStore } from '../../store/schoolSettings';
import { GradeBadge } from '../../components/GradeBadge';
import {
  Plus, Clock, Users, FileText, CheckCircle, X,
  Play, Trash2, Edit, ChevronRight, AlertTriangle,
  BookOpen, Award, BarChart3, Search, Filter,
  Sparkles, CheckCircle2, MoreHorizontal, Info,
  Send,
} from 'lucide-react';
import type { GradeScaleKey } from '../../lib/gradeScales';
import { useEducationTerms } from '../../utils/educationTerms';
import { T as Term } from '../../lib/terminology';

// ==========================================
// EXAM LIST PAGE (Admin/Teacher)
// ==========================================

export function ExamListPage() {
  const { user } = useAuthStore();
  const navigate = useNavigate();
  const terms = useEducationTerms();
  const { examGroups, fetchExamGroups, deleteExamGroup, fetchExamStats, submitGroup } = useExamStore();
  const schoolSettings = useSchoolSettingsStore();
  const [stats, setStats] = useState<any>(null);
  const [filter, setFilter] = useState({ exam_type: '', academic_year: '' });
  const [showCreateModal, setShowCreateModal] = useState(false);

  useEffect(() => {
    fetchExamGroups();
    fetchExamStats().then(setStats);
    schoolSettings.fetchSettings();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleDelete = async (id: number) => {
    if (confirm('Delete this exam group? This cannot be undone.')) {
      await deleteExamGroup(id);
    }
  };

  const handleSubmitForReview = async (id: number) => {
    if (!confirm('Submit this exam for admin review? You won\'t be able to edit it until it\'s reviewed.')) return;
    try {
      await submitGroup(id);
      alert('Submitted for review. The admin team will publish or reject it shortly.');
    } catch (err: any) {
      alert(err?.response?.data?.error || err?.message || 'Failed to submit for review');
    }
  };
  
  return (
    <div className="space-y-8 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight uppercase">Exam Registry</h1>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Online Assessments</span>
          </nav>
        </div>
        <button 
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
        >
          <Plus size={18} /> Create Exam
        </button>
      </div>
      
      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: 'Total Assessments', value: stats?.total_attempts || 0, icon: FileText, color: 'blue' },
          { label: 'Average Mark', value: `${stats?.avg_percentage?.toFixed(0) || 0}%`, icon: Award, color: 'emerald' },
          { label: 'Registry Attempts', value: stats?.completed_attempts || 0, icon: Users, color: 'purple' },
          { label: 'Success Rate', value: stats?.passed || 0, icon: BarChart3, color: 'orange' },
        ].map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-xl flex items-center justify-center bg-${stat.color}-50 text-${stat.color}-600 border border-${stat.color}-100 group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <p className="text-2xl font-black text-text">{stat.value}</p>
            </div>
          </div>
        ))}
      </div>
      
      {/* Exam Groups Table */}
      <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden flex flex-col">
        <div className="p-4 bg-muted/50 border-b border-border flex items-center gap-4">
          <select 
            className="bg-card border border-border rounded-xl px-4 py-2 text-[0.65rem] font-black uppercase tracking-widest text-primary outline-none cursor-pointer"
            value={filter.exam_type}
            onChange={(e) => setFilter({...filter, exam_type: e.target.value})}
          >
            <option value="">All Intel Categories</option>
            <option value="quiz">Quiz</option>
            <option value="test">Test</option>
            <option value="midterm">Midterm</option>
            <option value="final">Final</option>
          </select>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
                <tr className="bg-muted/80 border-b border-border">
                    <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Assessment Module</th>
                    <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Intel Class</th>
                    <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Duration</th>
                    <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Protocol</th>
                    <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">{Term.GRADING_COLUMN}</th>
                    <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Management</th>
                </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {examGroups.map((exam) => (
                <tr key={exam.id} className="hover:bg-muted/30 transition-colors group">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-4">
                        <div className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center border border-blue-100 group-hover:scale-110 transition-transform">
                            <FileText size={18} />
                        </div>
                        <div>
                            <div className="text-[0.9rem] font-bold text-text">{exam.name}</div>
                            <div className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">ID: EXM-2026-{exam.id}</div>
                        </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                      exam.exam_type === 'final' ? 'bg-purple-50 text-purple-600 border-purple-100' :
                      exam.exam_type === 'midterm' ? 'bg-blue-50 text-blue-600 border-blue-100' :
                      exam.exam_type === 'test' ? 'bg-orange-50 text-orange-600 border-orange-100' :
                      'bg-emerald-50 text-emerald-600 border-emerald-100'
                    }`}>
                      {exam.exam_type}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2 text-[0.8rem] font-bold text-text-secondary">
                        <Clock size={14} className="text-text-muted/50" />
                        {exam.duration_minutes} MINS
                    </div>
                  </td>
                  <td className="px-6 py-4 text-center">
                    <div className="space-y-1">
                        <p className="text-[0.85rem] font-black text-text">{exam.total_marks} Marks</p>
                        <p className="text-[0.55rem] font-black text-text-muted uppercase">Pass: {exam.passing_marks}</p>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-center">
                    <div className="space-y-1">
                        <p className="text-[0.7rem] font-black text-text uppercase tracking-widest">
                            {schoolSettings.scaleOptions.find(o => o.key === ((exam as any).grading_scale || (exam as any).resolved_scale))?.label
                              || ((exam as any).grading_scale || (exam as any).resolved_scale || '—')}
                        </p>
                        {!(exam as any).grading_scale && (
                            <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">default</p>
                        )}
                        {(exam as any).grading_scale && (
                            <p className="text-[0.55rem] font-black text-primary uppercase tracking-widest">override</p>
                        )}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-right">
                    <div className="flex justify-end gap-2 opacity-100">
                      <button
                        type="button"
                        onClick={() => navigate(`/exams/edit/${exam.id}`)}
                        className="p-2.5 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm cursor-pointer"
                        title="Edit exam"
                        aria-label="Edit exam"
                      >
                        <Edit size={16} />
                      </button>
                      {(exam.status === 'draft' || exam.status === 'rejected') && (
                        <button
                          onClick={() => handleSubmitForReview(exam.id)}
                          className="p-2.5 bg-card border border-amber-200 text-amber-600 hover:bg-amber-50 rounded-xl transition-all shadow-sm cursor-pointer"
                          title={exam.status === 'rejected' ? 'Edit and resubmit' : 'Submit for review'}
                          aria-label="Submit for review"
                        >
                          <Send size={16} />
                        </button>
                      )}
                      <button
                        onClick={() => handleDelete(exam.id)}
                        className="p-2.5 bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-100 rounded-xl transition-all shadow-sm cursor-pointer"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {examGroups.length === 0 && (
                <tr>
                  <td colSpan={6} className="px-4 py-20 text-center">
                    <FileText size={48} className="mx-auto text-text-muted/20 mb-4" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No active exam modules established</p>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
      
      {/* Create Modal */}
      {showCreateModal && (
        <CreateExamModal onClose={() => setShowCreateModal(false)} />
      )}
    </div>
  );
}

// ==========================================
// CREATE EXAM MODAL
// ==========================================

function CreateExamModal({ onClose }: { onClose: () => void }) {
  const { createExamGroup, createQuestion, bulkCreateQuestions, fetchExamGroups } = useExamStore();
  const schoolSettings = useSchoolSettingsStore();
  const terms = useEducationTerms();
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    exam_type: 'quiz',
    duration_minutes: 30,
    total_marks: 100,
    passing_marks: 50,
    max_attempts: 1,
    is_random_order: false,
    show_results: true,
    allow_review: true,
    grading_scale: '' as '' | GradeScaleKey, // empty string = use school default
  });
  const [questions, setQuestions] = useState<any[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Keep the form in sync with the school default once it loads.
  useEffect(() => {
    if (schoolSettings.loaded && formData.grading_scale === '') {
      setFormData((f) => ({ ...f, grading_scale: (schoolSettings.defaultGradingScale as GradeScaleKey) || '' }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [schoolSettings.loaded, schoolSettings.defaultGradingScale]);

  const handleSubmitExam = async () => {
    setIsSubmitting(true);
    try {
      // Send null (not '') so the backend records "explicit default" and
      // doesn't store an empty string.
      const payload = {
        ...formData,
        grading_scale: formData.grading_scale || null,
      };
      const exam = await createExamGroup(payload);

      if (questions.length > 0) {
        const questionsWithExam = questions.map(q => ({ ...q, exam_group_id: exam.id }));
        await bulkCreateQuestions(questionsWithExam);
      }

      await fetchExamGroups();
      onClose();
    } catch (error) {
      console.error('Failed to create exam:', error);
    } finally {
      setIsSubmitting(false);
    }
  };
  
  const addQuestion = () => {
    setQuestions([...questions, {
      question_type: 'multiple-choice',
      question: '',
      options: ['', '', '', ''],
      correct_answer: '',
      marks: 1,
      difficulty: 'medium'
    }]);
  };
  
  const updateQuestion = (index: number, field: string, value: any) => {
    const updated = [...questions];
    if (field === 'question_type') {
      if (value === 'true-false') {
        updated[index] = {
          ...updated[index],
          question_type: value,
          options: [],
          correct_answer: (updated[index].correct_answer === true || String(updated[index].correct_answer).toLowerCase() === 'true') ? 'true' : ''
        };
      } else if (value === 'multiple-choice') {
        updated[index] = {
          ...updated[index],
          question_type: value,
          options: Array.isArray(updated[index].options) && updated[index].options.length ? updated[index].options : ['', '', '', ''],
          correct_answer: updated[index].correct_answer || ''
        };
      } else {
        updated[index] = { ...updated[index], question_type: value };
      }
    } else {
      updated[index] = { ...updated[index], [field]: value };
    }

    setQuestions(updated);
  };
  
  return createPortal(
    <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-card border border-border rounded-[2.5rem] w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col shadow-2xl animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
        <div className="px-10 py-8 bg-muted/50 border-b border-border flex items-center justify-between relative overflow-hidden shrink-0">
            <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Sparkles size={180} />
            </div>
            <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">New Exam</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure academic evaluation logic</p>
            </div>
            <button onClick={onClose} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
            </button>
        </div>
        
        <div className="p-10 overflow-y-auto flex-1 custom-scrollbar">
          {/* Step Indicator */}
          <div className="flex items-center gap-4 mb-10 bg-muted/30 p-4 rounded-2xl border border-border">
            {[1, 2].map((s) => (
              <div key={s} className="flex items-center gap-3">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-[0.7rem] font-black ${
                  step >= s ? 'bg-primary text-white shadow-lg shadow-blue-500/20' : 'bg-muted text-text-muted border border-border'
                }`}>
                  {s}
                </div>
                <span className={`text-[0.65rem] font-black uppercase tracking-widest ${step >= s ? 'text-primary' : 'text-text-muted'}`}>
                  {s === 1 ? 'Logic Config' : 'Question Pool'}
                </span>
                {s < 2 && <ChevronRight size={14} className="text-text-muted/30" />}
              </div>
            ))}
          </div>
          
          {step === 1 && (
            <div className="space-y-6 animate-in slide-in-from-right-4 duration-300">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.chapter} Identifier (Name)</label>
                <input 
                  type="text" 
                  className="form-input"
                  value={formData.name}
                  onChange={(e) => setFormData({...formData, name: e.target.value})}
                  placeholder="e.g., Mathematics Quiz - Term 3"
                />
              </div>
              
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Contextual Description</label>
                <textarea 
                  className="form-input"
                  rows={2}
                  value={formData.description}
                  onChange={(e) => setFormData({...formData, description: e.target.value})}
                  placeholder="Briefly outline assessment objectives..."
                />
              </div>
              
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Assessment Class</label>
                  <select 
                    className="form-input appearance-none cursor-pointer"
                    value={formData.exam_type}
                    onChange={(e) => setFormData({...formData, exam_type: e.target.value})}
                  >
                    <option value="quiz">Standard Quiz</option>
                    <option value="test">Academic Test</option>
                    <option value="midterm">Midterm Window</option>
                    <option value="final">Final Assessment</option>
                    <option value="practice">Skill Practice</option>
                  </select>
                </div>
                
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Duration (minutes)</label>
                  <input 
                    type="number" 
                    className="form-input"
                    value={formData.duration_minutes}
                    onChange={(e) => setFormData({...formData, duration_minutes: parseInt(e.target.value)})}
                  />
                </div>
              </div>

              <div className="grid grid-cols-3 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Total Payload</label>
                  <input
                    type="number"
                    className="form-input"
                    value={formData.total_marks}
                    onChange={(e) => setFormData({...formData, total_marks: parseInt(e.target.value)})}
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{Term.PASS_THRESHOLD}</label>
                  <input
                    type="number"
                    className="form-input"
                    value={formData.passing_marks}
                    onChange={(e) => setFormData({...formData, passing_marks: parseInt(e.target.value)})}
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Max Iterations</label>
                  <input
                    type="number"
                    className="form-input"
                    value={formData.max_attempts}
                    onChange={(e) => setFormData({...formData, max_attempts: parseInt(e.target.value)})}
                  />
                </div>
              </div>

              {/* Grading scale override (feature/grading-scales) */}
              <div className="p-4 bg-muted/30 border border-border rounded-2xl space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                    <Award size={12} className="text-primary" /> {Term.GRADING_SCALE}
                  </label>
                  <span className="text-[0.55rem] font-black uppercase tracking-widest text-text-muted">
                    School default: {schoolSettings.defaultGradingScaleLabel}
                  </span>
                </div>
                <select
                  className="form-input appearance-none cursor-pointer"
                  value={formData.grading_scale}
                  onChange={(e) => setFormData({...formData, grading_scale: e.target.value as GradeScaleKey | ''})}
                >
                  {schoolSettings.scaleOptions.map((opt) => (
                    <option key={opt.key} value={opt.key}>
                      {opt.label}{opt.key === schoolSettings.defaultGradingScale ? ' (default)' : ''}
                    </option>
                  ))}
                </select>
                <div className="flex items-center gap-2 pt-1">
                  <Info size={12} className="text-text-muted" />
                  <span className="text-[0.55rem] text-text-muted italic">Letter preview at 85%:</span>
                  <GradeBadge
                    percentage={85}
                    gradingScale={formData.grading_scale || schoolSettings.defaultGradingScale}
                    size="sm"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4">
                {[
                    { id: 'is_random_order', label: 'Randomize Order' },
                    { id: 'show_results', label: 'Auto Disclosure' },
                    { id: 'allow_review', label: 'Allow Review' }
                ].map(opt => (
                    <label key={opt.id} className="flex items-center gap-3 p-4 bg-muted/30 border border-border rounded-2xl cursor-pointer hover:bg-muted transition-all group">
                        <input 
                            type="checkbox"
                            checked={(formData as any)[opt.id]}
                            onChange={(e) => setFormData({...formData, [opt.id]: e.target.checked})}
                            className="w-5 h-5 rounded-lg border-border text-primary focus:ring-primary/20"
                        />
                        <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted group-hover:text-text transition-colors">{opt.label}</span>
                    </label>
                ))}
              </div>
              
              <div className="flex justify-end pt-8">
                <button 
                  onClick={() => setStep(2)}
                  className="px-12 py-4 bg-primary text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-xl active:scale-95 flex items-center gap-2 group/btn"
                >
                  Next: Add Question Pool <ChevronRight size={16} className="group-hover/btn:translate-x-1 transition-transform" />
                </button>
              </div>
            </div>
          )}
          
          {step === 2 && (
            <div className="space-y-6 animate-in slide-in-from-right-4 duration-300">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-black uppercase tracking-[3px] text-text-muted">Questions Registry ({questions.length})</h3>
                <button 
                  onClick={addQuestion}
                  className="flex items-center gap-2 px-6 py-3 bg-blue-50/10 text-primary border border-blue-100/20 rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-blue-50/20 transition-all"
                >
                  <Plus size={16} /> Add Logic Node
                </button>
              </div>
              
              {questions.map((q, index) => (
                <div key={index} className="bg-muted/20 border border-border rounded-[2rem] p-8 space-y-6 relative group">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-lg bg-primary text-white flex items-center justify-center text-[0.65rem] font-black shadow-sm">
                            {index + 1}
                        </div>
                        <span className="text-[0.7rem] font-black uppercase tracking-widest text-text">Logic Node {index + 1}</span>
                    </div>
                    <button 
                      onClick={() => setQuestions(questions.filter((_, i) => i !== index))}
                      className="text-rose-500 hover:bg-rose-500/10 p-2 rounded-lg transition-all opacity-0 group-hover:opacity-100"
                    >
                      <Trash2 size={18} />
                    </button>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                      <div className="md:col-span-2">
                        <label className="text-[0.6rem] font-black uppercase text-text-muted px-1 mb-1.5 block">Format Protocol</label>
                        <select 
                            className="form-input appearance-none cursor-pointer"
                            value={q.question_type}
                            onChange={(e) => updateQuestion(index, 'question_type', e.target.value)}
                        >
                            <option value="multiple-choice">Multiple Choice Matrix</option>
                            <option value="true-false">Binary Switch (True/False)</option>
                            <option value="short-answer">Open Intel (Short Answer)</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-[0.6rem] font-black uppercase text-text-muted px-1 mb-1.5 block">Weight (%)</label>
                        <input 
                            type="number" 
                            className="form-input text-center"
                            value={q.marks}
                            onChange={(e) => updateQuestion(index, 'marks', parseInt(e.target.value))}
                        />
                      </div>
                  </div>
                  
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1 block">Logic Statement</label>
                    <textarea 
                        className="form-input"
                        rows={2}
                        placeholder="Construct question inquiry..."
                        value={q.question}
                        onChange={(e) => updateQuestion(index, 'question', e.target.value)}
                    />
                  </div>
                  
                  {q.question_type === 'multiple-choice' && (
                    <div className="space-y-3 pt-2">
                      <label className="text-[0.6rem] font-black uppercase text-text-muted px-1 block">Response Vectors</label>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {[0, 1, 2, 3].map((optIdx) => (
                            <div key={optIdx} className="flex items-center gap-3 bg-card border border-border p-3 rounded-2xl group/opt focus-within:border-primary transition-all">
                            <input 
                                type="radio" 
                                name={`correct-${index}`}
                                checked={q.correct_answer === String.fromCharCode(65 + optIdx)}
                                onChange={() => updateQuestion(index, 'correct_answer', String.fromCharCode(65 + optIdx))}
                                className="w-5 h-5 rounded-full border-border text-primary"
                            />
                            <input 
                                type="text" 
                                className="flex-1 bg-transparent border-none focus:ring-0 text-sm font-bold text-text placeholder:text-text-muted/30 p-0"
                                placeholder={`Vector ${String.fromCharCode(65 + optIdx)}`}
                                value={q.options[optIdx]}
                                onChange={(e) => {
                                const newOptions = [...q.options];
                                newOptions[optIdx] = e.target.value;
                                updateQuestion(index, 'options', newOptions);
                                }}
                            />
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                  {q.question_type === 'true-false' && (
                    <div className="space-y-3 pt-2">
                      <label className="text-[0.6rem] font-black uppercase text-text-muted px-1 block">Correct Answer</label>
                      <div className="grid grid-cols-2 gap-4">
                        {['true', 'false'].map((answer) => (
                          <button
                            key={answer}
                            type="button"
                            onClick={() => updateQuestion(index, 'correct_answer', answer)}
                            className={`px-6 py-4 rounded-2xl font-black text-[0.7rem] uppercase tracking-widest border-2 transition-all ${
                              q.correct_answer === answer
                                ? 'bg-primary text-white border-primary shadow-lg'
                                : 'bg-card text-text border-border hover:border-primary'
                            }`}
                          >
                            {answer.toUpperCase()}
                          </button>
                        ))}
                      </div>
                    </div>
                  )}
                  
                  <div className="flex justify-between items-center pt-4 border-t border-border">
                    <div className="flex items-center gap-4">
                        <label className="text-[0.6rem] font-black uppercase text-text-muted">Complexity:</label>
                        <div className="flex gap-2">
                            {['easy', 'medium', 'hard'].map(level => (
                                <button 
                                    key={level}
                                    type="button"
                                    onClick={() => updateQuestion(index, 'difficulty', level)}
                                    className={`px-3 py-1 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border transition-all ${
                                        q.difficulty === level ? 'bg-primary text-white border-primary shadow-md' : 'bg-card text-text-muted border-border hover:border-text-muted'
                                    }`}
                                >
                                    {level}
                                </button>
                            ))}
                        </div>
                    </div>
                  </div>
                </div>
              ))}
              
              {questions.length === 0 && (
                <div className="text-center py-16 opacity-30">
                  <BookOpen size={64} className="mx-auto mb-4" />
                  <p className="text-lg font-black uppercase tracking-widest">Logic Pool Empty</p>
                  <p className="text-sm font-bold mt-2">Add questions to define this assessment.</p>
                </div>
              )}
              
              <div className="flex flex-col sm:flex-row justify-between gap-4 pt-8 shrink-0">
                <button 
                  onClick={() => setStep(1)}
                  className="px-10 py-4 bg-card border border-border text-text-muted rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-muted transition-all"
                >
                  Return to Config
                </button>
                <div className="flex gap-3">
                  <button 
                    onClick={onClose}
                    className="flex-1 sm:flex-none px-8 py-4 bg-card border border-border text-text rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-muted transition-all active:scale-95"
                  >
                    Hold Progress
                  </button>
                  <button 
                    onClick={handleSubmitExam}
                    disabled={isSubmitting}
                    className="flex-1 sm:flex-none px-12 py-4 bg-primary text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-xl shadow-blue-900/10 active:scale-95 disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-3"
                  >
                    {isSubmitting ? (
                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    ) : <CheckCircle2 size={18} />}
                    {isSubmitting ? 'Transmitting...' : 'Finalize Exam'}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  ,
    document.body
  );
}

// ==========================================
// TAKE EXAM PAGE (Student)
// ==========================================

export function TakeExamPage() {
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const { 
    availableExams, 
    currentAttempt, 
    currentExam, 
    answers, 
    timeRemaining, 
    isSubmitting,
    error,
    fetchAvailableExams, 
    startExam, 
    saveAnswer, 
    submitExam,
    resetExam
  } = useExamStore();
  const [showConfirmSubmit, setShowConfirmSubmit] = useState(false);
  
  useEffect(() => {
    fetchAvailableExams();
    return () => resetExam();
  }, []);
  
  const handleStartExam = async (examId: number, scheduleId?: number) => {
    await startExam(examId, scheduleId);
  };
  
  const handleSubmit = async () => {
    try {
      await submitExam();
      setShowConfirmSubmit(false);
    } catch (error) {
      console.error('Submit failed:', error);
    }
  };
  
  // Show available exams if no active exam
  if (!currentAttempt) {
    return (
      <div className="space-y-10 animate-in fade-in duration-700 pb-10">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight text-capitalize dark:text-white">Active Examinations</h1>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Student Portal</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Available Assessments</span>
          </nav>
        </div>
        
        <div className="grid gap-6">
          {availableExams.map((exam) => (
            <div key={exam.id} className="bg-card border border-border rounded-[2.5rem] p-10 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden">
                <div className="absolute top-0 right-0 w-48 h-48 bg-blue-500/5 rounded-bl-full -mr-16 -mt-16 group-hover:bg-blue-500/10 transition-colors"></div>
              
                <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-8 relative z-10">
                    <div className="flex items-start gap-8 flex-1 min-w-0">
                        <div className="w-20 h-20 rounded-[2rem] bg-[#0f172a] border border-slate-800 flex flex-col items-center justify-center text-white shadow-2xl group-hover:scale-105 transition-transform shrink-0">
                            <span className="text-lg font-black text-blue-400">{exam.duration_minutes}</span>
                            <span className="text-[0.6rem] font-black uppercase tracking-tighter opacity-60">MINS</span>
                        </div>
                        <div className="min-w-0 flex-1">
                            <h3 className="text-2xl font-black text-text tracking-tight group-hover:text-primary transition-colors truncate">{exam.exam_name}</h3>
                            <p className="text-[0.7rem] font-black text-primary uppercase tracking-[4px] mt-1">{exam.subject_name || 'General Curriculum'}</p>
                            
                            <div className="flex flex-wrap items-center gap-8 mt-6">
                                <span className="flex items-center gap-2.5 text-[0.75rem] font-bold text-text-muted uppercase tracking-widest">
                                    <FileText size={16} className="text-text-muted/50" /> {exam.total_marks} Marks
                                </span>
                                <span className="flex items-center gap-2.5 text-[0.75rem] font-bold text-text-muted uppercase tracking-widest">
                                    <Award size={16} className="text-text-muted/50" /> {exam.passing_marks} Min. Pass
                                </span>
                                <span className="flex items-center gap-2.5 text-[0.75rem] font-bold text-text-muted uppercase tracking-widest">
                                    <Clock size={16} className="text-text-muted/50" /> System Sync: Live
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <div className="w-full md:w-auto flex flex-col items-end gap-3 shrink-0">
                        <span className={`px-4 py-1.5 rounded-xl text-[0.65rem] font-black uppercase tracking-widest border ${
                            exam.attempts_taken >= exam.max_attempts 
                            ? 'bg-muted text-text-muted/50 border-border' 
                            : 'bg-emerald-50 text-emerald-600 border-emerald-100 shadow-sm shadow-emerald-500/5'
                        }`}>
                            {exam.attempts_taken >= exam.max_attempts 
                            ? 'Completed Registry' 
                            : `${exam.attempts_taken}/${exam.max_attempts} attempts`}
                        </span>
                        
                        {exam.attempts_taken < exam.max_attempts && (
                            <button 
                                onClick={() => handleStartExam(exam.exam_group_id, exam.id)}
                                className="w-full md:w-auto flex items-center justify-center gap-3 px-10 py-4 bg-[#002147] hover:bg-black text-white rounded-2xl font-black text-[0.75rem] uppercase tracking-widest transition-all shadow-xl shadow-blue-900/10 active:scale-95 group/btn"
                            >
                                <Play size={20} className="fill-current" /> Start Assessment <ChevronRight size={18} className="group-hover/btn:translate-x-1 transition-transform" />
                            </button>
                        )}
                    </div>
                </div>
            </div>
          ))}
          
          {availableExams.length === 0 && (
            <div className="text-center py-24 bg-card border-2 border-dashed border-border rounded-[3rem] opacity-60">
              <FileText size={64} className="mx-auto text-text-muted/20 mb-6" />
              <h3 className="text-2xl font-black text-text uppercase tracking-tighter">Queue Clear</h3>
              <p className="text-text-muted font-medium mt-1">No examinations currently scheduled in your curriculum registry.</p>
            </div>
          )}
        </div>
      </div>
    );
  }
  
  // Show exam in progress
  return (
    <div className="h-[calc(100vh-120px)] flex flex-col space-y-8 animate-in fade-in duration-700">
      {/* Exam Header */}
      <div className="bg-card border border-border rounded-[2rem] p-6 flex items-center justify-between shadow-sm shrink-0">
        <div className="flex items-center gap-6">
            <div className="w-14 h-14 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center border border-blue-100 shadow-sm">
                <FileText size={28} />
            </div>
            <div>
                <h2 className="text-xl font-black text-text tracking-tight uppercase">{currentExam?.name}</h2>
                <div className="flex items-center gap-3 mt-0.5">
                    <span className="text-[0.6rem] font-black text-primary uppercase tracking-[3px]">Intel Session Active</span>
                    <div className="w-1 h-1 rounded-full bg-border"></div>
                    <p className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest">
                        Node {answers.size} of {currentExam?.questions?.length || 0}
                    </p>
                </div>
            </div>
        </div>
        
        <div className="flex items-center gap-4">
          {/* Timer */}
          <div className={`flex items-center gap-3 px-6 py-3 rounded-2xl border transition-all duration-500 ${
            timeRemaining < 300 ? 'bg-rose-50 text-rose-600 border-rose-100 animate-pulse' : 'bg-muted/50 text-text border-border'
          }`}>
            <Clock size={20} className={timeRemaining < 300 ? 'text-rose-600' : 'text-primary'} />
            <span className="font-mono text-lg font-black tracking-tighter">{formatTime(timeRemaining)}</span>
          </div>
          
          <button 
            onClick={() => setShowConfirmSubmit(true)}
            disabled={isSubmitting}
            className="px-10 py-4 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg shadow-emerald-900/10 active:scale-95 disabled:opacity-50"
          >
            {isSubmitting ? <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" /> : 'Finalize Transmission'}
          </button>
        </div>
      </div>
      
      {/* Error Display */}
      {error && (
        <div className="bg-rose-50 border border-rose-100 rounded-2xl p-5 flex items-center gap-4 animate-in slide-in-from-top-2 duration-300 shrink-0">
          <AlertTriangle className="text-rose-600" size={24} />
          <span className="text-rose-700 font-bold text-sm">{error}</span>
        </div>
      )}
      
      {/* Questions */}
      <div className="flex-1 overflow-y-auto custom-scrollbar pr-2 space-y-6">
        {currentExam?.questions?.map((question, index) => (
          <div key={question.id} className="bg-card border border-border rounded-[2.5rem] p-10 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden">
            <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 transition-colors"></div>
            
            <div className="flex items-start gap-8 relative z-10">
              <div className="w-10 h-10 rounded-xl bg-muted border border-border flex items-center justify-center font-black text-primary text-sm shadow-inner shrink-0 group-hover:scale-110 transition-transform">
                {index + 1}
              </div>
              
              <div className="flex-1 min-w-0">
                <p className="text-xl font-black text-text tracking-tight mb-8 leading-relaxed">{question.question}</p>
                
                {question.question_type === 'multiple-choice' && question.options && (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {question.options.map((option: string, optIdx: number) => (
                      <label 
                        key={optIdx}
                        className={`flex items-center gap-4 p-5 rounded-2xl border-2 cursor-pointer transition-all ${
                          answers.get(question.id) === String.fromCharCode(65 + optIdx)
                            ? 'border-primary bg-primary/5 shadow-lg shadow-blue-500/5'
                            : 'border-border bg-muted/20 hover:border-text-muted/30 hover:bg-card'
                        }`}
                      >
                        <input 
                          type="radio" 
                          name={`q-${question.id}`}
                          checked={answers.get(question.id) === String.fromCharCode(65 + optIdx)}
                          onChange={() => saveAnswer(question.id, String.fromCharCode(65 + optIdx))}
                          className="w-5 h-5 border-border text-primary focus:ring-primary/20"
                        />
                        <span className={`flex-1 text-sm font-bold ${answers.get(question.id) === String.fromCharCode(65 + optIdx) ? 'text-primary' : 'text-text-secondary'}`}>{option}</span>
                        <span className="text-[0.6rem] font-black text-text-muted/40 uppercase tracking-widest bg-muted px-2 py-1 rounded-lg">
                          Vector {String.fromCharCode(65 + optIdx)}
                        </span>
                      </label>
                    ))}
                  </div>
                )}
                
                {question.question_type === 'true-false' && (
                  <div className="grid grid-cols-2 gap-6">
                    {['True', 'False'].map((option) => (
                      <label 
                        key={option}
                        className={`flex items-center justify-center gap-3 p-8 rounded-3xl border-2 cursor-pointer transition-all ${
                          answers.get(question.id) === option.toLowerCase()
                            ? 'border-primary bg-primary/5 shadow-lg shadow-blue-500/5'
                            : 'border-border bg-muted/20 hover:border-text-muted/30 hover:bg-card'
                        }`}
                      >
                        <input 
                          type="radio" 
                          name={`q-${question.id}`}
                          checked={answers.get(question.id) === option.toLowerCase()}
                          onChange={() => saveAnswer(question.id, option.toLowerCase())}
                          className="w-5 h-5 border-border text-primary focus:ring-primary/20"
                        />
                        <span className={`text-lg font-black uppercase tracking-widest ${answers.get(question.id) === option.toLowerCase() ? 'text-primary' : 'text-text-secondary'}`}>{option}</span>
                      </label>
                    ))}
                  </div>
                )}
                
                {(question.question_type === 'short-answer') && (
                  <div className="relative">
                    <input 
                        type="text" 
                        className="form-input text-lg font-bold py-5 pl-8"
                        placeholder="Construct intellectual response..."
                        value={answers.get(question.id) || ''}
                        onChange={(e) => saveAnswer(question.id, e.target.value)}
                    />
                    <div className="absolute left-0 top-0 bottom-0 w-1.5 bg-primary rounded-l-2xl"></div>
                  </div>
                )}
                
                <div className="flex items-center gap-4 mt-8 pt-6 border-t border-border">
                    <span className="text-[0.6rem] font-black uppercase tracking-[3px] text-text-muted">Question Bank:</span>
                    <span className="px-3 py-1 bg-muted rounded-lg text-[0.6rem] font-black uppercase text-primary border border-border">
                        {question.marks} MARK{question.marks > 1 ? 'S' : ''}
                    </span>
                    <span className="px-3 py-1 bg-muted rounded-lg text-[0.6rem] font-black uppercase text-text-muted border border-border">
                        {question.difficulty} DIFFICULTY
                    </span>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
      
      {/* Confirm Submit Modal */}
      {showConfirmSubmit && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md flex items-center justify-center z-[200] p-4" onClick={() => setShowConfirmSubmit(false)}>
          <div className="bg-card border border-border rounded-[2.5rem] p-10 max-w-md w-full shadow-2xl animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
            <div className="flex flex-col items-center text-center space-y-6">
                <div className="w-20 h-20 rounded-3xl bg-amber-50 text-amber-500 flex items-center justify-center shadow-xl border border-amber-100">
                    <AlertTriangle size={40} />
                </div>
                <div>
                    <h3 className="text-2xl font-black text-text tracking-tight uppercase">Finalize Transmission?</h3>
                    <p className="text-text-muted font-medium mt-2">
                        You have constructed responses for <span className="text-primary font-black">{answers.size}</span> out of <span className="text-text font-black">{currentExam?.questions?.length}</span> nodes.
                    </p>
                </div>
            
                {answers.size < (currentExam?.questions?.length || 0) && (
                    <div className="bg-rose-50/10 border border-rose-100/20 rounded-2xl p-4 w-full">
                        <p className="text-[0.7rem] font-black uppercase tracking-widest text-rose-500">Incomplete Question Pool Identified!</p>
                    </div>
                )}
                
                <div className="flex gap-3 w-full pt-4">
                    <button 
                        onClick={() => setShowConfirmSubmit(false)}
                        className="flex-1 px-6 py-4 bg-muted hover:bg-muted/80 text-text rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all border border-border"
                    >
                        Review
                    </button>
                    <button 
                        onClick={handleSubmit}
                        className="flex-[1.5] px-6 py-4 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-xl shadow-emerald-900/10 active:scale-95"
                    >
                        Transmit Intel
                    </button>
                </div>
            </div>
          </div>
        </div>
      ,
        document.body
      )}
      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
      `}</style>
    </div>
  );
}

// ==========================================
// EXAM RESULTS PAGE (Student)
// ==========================================

export function ExamResultsPage() {
  const { currentAttempt, fetchAttemptResults } = useExamStore();
  const terms = useEducationTerms();
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    if (currentAttempt?.id) {
      fetchAttemptResults(currentAttempt.id).finally(() => setLoading(false));
    }
  }, []);
  
  if (loading) {
    return (
        <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
          <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
          <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Computing Performance Analytics...</p>
        </div>
    );
  }
  
  if (!currentAttempt) {
    return (
      <div className="text-center py-24 opacity-30">
        <FileText size={64} className="mx-auto mb-4" />
        <p className="text-xl font-black uppercase tracking-widest">No Records Available</p>
      </div>
    );
  }
  
  // Use the server-resolved letter and scale. The legacy calculateGrade from
  // useExamStore (A+/A/B+/B/C/F) ignored both the school default and any
  // per-exam override, so it would show the wrong letter for any non-ZIMSEC
  // scale. The attempt response now carries grade_letter and resolved_scale;
  // we re-derive here as a fallback in case the server response is missing
  // them (older client cache, race during submit, etc.).
  const resolvedLetter = currentAttempt.grade_letter
    || letterFor(
         currentAttempt.percentage,
         currentAttempt.resolved_scale || currentAttempt.grading_scale
       ).letter;
  const grade = resolvedLetter || '—';
  const scaleLabel = currentAttempt.resolved_scale_label
    || currentAttempt.grading_scale
    || '';
  const passed = currentAttempt.percentage >= 50;
  // Match the top-stripe / icon colors used elsewhere on this page.
  const color = passed ? '#10b981' : '#f43f5e';
  
  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10 max-w-4xl mx-auto">
      {/* Results Header */}
      <div className={`bg-card border border-border rounded-[3rem] p-12 text-center relative overflow-hidden shadow-2xl`}>
        <div className={`absolute top-0 left-0 w-full h-1.5 ${passed ? 'bg-emerald-500' : 'bg-rose-500'}`}></div>
        
        <div className="w-32 h-32 rounded-[2.5rem] mx-auto mb-8 flex items-center justify-center shadow-2xl border-4 border-card relative" style={{ backgroundColor: color }}>
          <span className="text-5xl font-black text-white">{grade}</span>
          <div className="absolute -bottom-3 -right-3 w-12 h-12 rounded-2xl bg-card border border-border flex items-center justify-center shadow-xl">
             {passed ? <CheckCircle2 className="text-emerald-500" size={24} /> : <X className="text-rose-500" size={24} />}
          </div>
        </div>
        
        <h2 className="text-4xl font-black text-text tracking-tighter uppercase">{passed ? 'Mission Successful' : 'Transmission Failure'}</h2>
        <p className="text-text-muted font-bold text-lg uppercase tracking-widest mt-2">
            Yield: <span className="text-text">{currentAttempt.obtained_marks}</span> / {currentAttempt.total_marks} Intel Points
        </p>
        
        <div className="flex justify-center gap-12 mt-12 bg-muted/30 p-8 rounded-[2rem] border border-border">
          <div>
            <p className="text-4xl font-black tracking-tighter" style={{ color }}>{currentAttempt.percentage.toFixed(0)}%</p>
            <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mt-1">
              Score Ratio{scaleLabel ? ` · ${scaleLabel}` : ''}
            </p>
          </div>
          <div className="w-px h-12 bg-border"></div>
          <div>
            <p className="text-4xl font-black text-text tracking-tighter">{Math.floor(currentAttempt.time_spent_seconds / 60)}M {currentAttempt.time_spent_seconds % 60}S</p>
            <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mt-1">Computation Time</p>
          </div>
        </div>
      </div>
      
      {/* Answer Review (if allowed) */}
      {currentAttempt.allow_review && currentAttempt.answers && (
        <div className="bg-card border border-border rounded-[3rem] overflow-hidden shadow-sm">
          <div className="p-10 bg-muted/50 border-b border-border flex items-center justify-between">
            <h3 className="text-xl font-black text-text uppercase tracking-tight">Audit</h3>
            <span className="text-[0.6rem] font-black text-primary uppercase tracking-[3px]">Verified Responses</span>
          </div>
          
          <div className="divide-y divide-border">
            {currentAttempt.answers.map((answer: any, index: number) => (
              <div key={answer.id} className="p-10 hover:bg-muted/30 transition-all group">
                <div className="flex items-start gap-8">
                  <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 shadow-lg group-hover:scale-110 transition-transform ${
                    answer.is_correct ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : 'bg-rose-50 text-rose-600 border border-rose-100'
                  }`}>
                    {answer.is_correct ? <CheckCircle2 size={24} /> : <X size={24} />}
                  </div>
                  
                  <div className="flex-1 min-w-0">
                    <p className="text-lg font-bold text-text mb-6 leading-relaxed">{answer.question}</p>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="p-6 bg-muted/50 rounded-2xl border border-border">
                            <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-2">{terms.subject} Response:</p>
                            <p className={`font-black uppercase tracking-tight text-sm ${answer.is_correct ? 'text-emerald-600' : 'text-rose-600'}`}>
                                {answer.answer || 'NODE_NULL'}
                            </p>
                        </div>
                        
                        {!answer.is_correct && (
                            <div className="p-6 bg-emerald-50/10 rounded-2xl border border-emerald-100/20">
                                <p className="text-[0.6rem] font-black uppercase tracking-widest text-emerald-600 mb-2">Validated Correct Path:</p>
                                <p className="text-emerald-600 font-black uppercase tracking-tight text-sm">{answer.correct_answer}</p>
                            </div>
                        )}
                    </div>
                    
                    <div className="flex items-center gap-4 mt-6">
                        <span className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">Node Yield:</span>
                        <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase border ${answer.is_correct ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 'bg-muted text-text-muted border-border'}`}>
                            {answer.marks_obtained} / {answer.question_marks} POINTS
                        </span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      
      <div className="flex flex-col sm:flex-row justify-center gap-4 pt-10">
        <a
          href="/exams"
          onClick={(e) => { e.preventDefault(); window.history.back(); }}
          className="px-12 py-5 bg-card border border-border text-text rounded-2xl font-black text-[0.7rem] uppercase tracking-[3px] hover:bg-muted transition-all text-center cursor-pointer"
        >
          Return to Registry
        </a>
        <a
          href="/dashboard"
          onClick={(e) => { e.preventDefault(); window.location.href = '/dashboard'; }}
          className="px-12 py-5 bg-[#002147] hover:bg-black text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-[3px] transition-all shadow-xl shadow-blue-900/10 text-center active:scale-95 cursor-pointer"
        >
          Enter Dashboard
        </a>
      </div>
    </div>
  );
}
