const { useState, useEffect } = React;

const K6_STORAGE_KEY = 'k6Filters';

const FormatK6 = () => {
  const [students, setStudents] = useState([]);
  const [courses, setCourses] = useState([]);
  const [exams, setExams] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Data State
  const [activities, setActivities] = useState([]);
  const [marks, setMarks] = useState({}); // {student_id: {activity_no: marks}}
  
  const [selectedCourse, setSelectedCourse] = useState('');
  const [courseSearchQuery, setCourseSearchQuery] = useState('');
  const [selectedExam, setSelectedExam] = useState('');

  // Modals
  const [showConfigModal, setShowConfigModal] = useState(false);
  const [configActivities, setConfigActivities] = useState([]);
  
  const [allCourses, setAllCourses] = useState([]);

  useEffect(() => {
    Promise.all([
      fetch('/api/courses').then(res => res.json()),
      fetch('/api/exams').then(res => res.json())
    ]).then(([courseData, examData]) => {
      setAllCourses(courseData);
      setExams(examData);
      const saved = (() => { try { return JSON.parse(localStorage.getItem(K6_STORAGE_KEY)) || {}; } catch(e) { return {}; } })();
      if (saved.exam && examData.find(e => String(e.id) === String(saved.exam))) setSelectedExam(saved.exam);
      else if (examData.length > 0) setSelectedExam(examData[0].id);
      setLoading(false);
    }).catch(err => {
      console.error(err);
      setLoading(false);
    });
  }, []);

  // Dynamic filtering based on selected exam
  useEffect(() => {
    const exam = exams.find(e => String(e.id) === String(selectedExam));
    if (!exam) return;
    const isSummer = exam.season === 'Summer';
    const filtered = allCourses.filter(c => {
      const hasSla = parseFloat(c.sla_max) > 0;
      const isEven = parseInt(c.semester) % 2 === 0;
      return hasSla && (isSummer ? isEven : !isEven);
    });
    setCourses(filtered);
    
    if (filtered.length > 0 && !filtered.find(c => String(c.id) === String(selectedCourse))) {
      const saved = (() => { try { return JSON.parse(localStorage.getItem(K6_STORAGE_KEY)) || {}; } catch(e) { return {}; } })();
      if (saved.course && filtered.find(c => String(c.id) === String(saved.course))) setSelectedCourse(saved.course);
      else setSelectedCourse(filtered[0].id);
    }
  }, [selectedExam, exams, allCourses]);

  // Persist filter selections
  useEffect(() => {
    if (selectedCourse && selectedExam) {
      try { localStorage.setItem(K6_STORAGE_KEY, JSON.stringify({ course: selectedCourse, exam: selectedExam })); } catch(e) {}
    }
  }, [selectedCourse, selectedExam]);

  useEffect(() => {
    if (courses.length > 0) {
      const filtered = courses.filter(c => (c.code + ' ' + c.name).toLowerCase().includes(courseSearchQuery.toLowerCase()));
      if (filtered.length > 0 && !filtered.find(c => String(c.id) === String(selectedCourse))) {
        setSelectedCourse(filtered[0].id);
      }
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [courseSearchQuery]);

  const fetchData = async () => {
    if (!selectedExam || !selectedCourse) return;
    setLoading(true);
    try {
      const [eligibleData, rosterData, plansData, marksDataRaw] = await Promise.all([
        fetch(`/api/courses/${selectedCourse}/eligible-students?exam_id=${selectedExam}&t=${Date.now()}`).then(res => res.json()),
        fetch(`/api/exams/${selectedExam}/roster?t=${Date.now()}`).then(res => res.json()),
        fetch(`/api/sla-plans?exam_id=${selectedExam}&course_id=${selectedCourse}&t=${Date.now()}`).then(res => res.ok ? res.json() : []),
        fetch(`/api/sla-assessments?exam_id=${selectedExam}&course_id=${selectedCourse}&t=${Date.now()}`).then(res => res.ok ? res.json() : [])
      ]);
      
      const mappedStudents = Array.isArray(eligibleData) ? eligibleData.map(student => {
          const registered = Array.isArray(rosterData) ? rosterData.find(r => r.student_id === student.id) : null;
          return { ...student, seat_number: registered ? registered.seat_number : '' };
      }) : [];
      setStudents(mappedStudents);

      const acts = Array.isArray(plansData) ? plansData : [];
      setActivities(acts);
      
      const marksMap = {};
      mappedStudents.forEach(s => {
          marksMap[s.id] = {};
          acts.forEach(act => {
             const m = Array.isArray(marksDataRaw) ? marksDataRaw.find(x => x.student_id === s.id && String(x.activity_no) === String(act.activity_no)) : null;
             marksMap[s.id][act.activity_no] = m ? String(m.marks) : '';
          });
      });
      setMarks(marksMap);
    } catch(err) {
      console.error(err);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, [selectedExam, selectedCourse]);

  // Activity Configuration Mode
  const openConfigModal = () => {
     setConfigActivities([...activities]);
     setShowConfigModal(true);
  };

  const handleSaveConfig = async () => {
     if (!selectedCourse || !selectedExam) return alert("Missing context.");
     // validation
     for (let i=0; i<configActivities.length; i++) {
         if (!configActivities[i].activity_name || configActivities[i].activity_name.trim() === '') return alert("Activity name cannot be empty");
         if (!configActivities[i].max_marks || parseFloat(configActivities[i].max_marks) <= 0) return alert("Valid Max Marks required for all activities");
     }
     
     try {
         const res = await fetch('/api/sla-plans', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                course_id: selectedCourse,
                exam_id: selectedExam,
                activities: configActivities.map((a, idx) => ({ ...a, activity_no: idx + 1 }))
            })
         });
         if (res.ok) {
             setShowConfigModal(false);
             fetchData();
         } else alert("Failed to save blueprint");
     } catch(e) { console.error(e); alert("Save error"); }
  };

  // Inline Mark Entry
  const handleInlineMarkChange = (studentId, activityNo, value, maxMarks) => {
      let numValue = parseFloat(value);
      if (isNaN(numValue)) numValue = '';
      else if (numValue === 401) {
          numValue = 401;
      } else {
          if (numValue > maxMarks) numValue = maxMarks;
          if (numValue < 0) numValue = 0;
      }
      setMarks(prev => ({
          ...prev, 
          [studentId]: {
              ...prev[studentId],
              [activityNo]: numValue === '' ? '' : String(numValue)
          }
      }));
  };

  const handleDuplicateDown = (startIndex, activityNo) => {
     const template = marks[students[startIndex].id]?.[activityNo] || '';
     setMarks(prev => {
         const next = { ...prev };
         for (let i = startIndex + 1; i < students.length; i++) {
             next[students[i].id] = { ...next[students[i].id], [activityNo]: template };
         }
         return next;
     });
  };

  const saveDatabaseMarks = async () => {
     const payload = [];
     students.forEach(s => {
         activities.forEach(act => {
             const val = marks[s.id]?.[act.activity_no];
             if (val !== '' && val !== undefined) {
                 payload.push({
                     student_id: s.id,
                     activity_no: act.activity_no,
                     marks: val
                 });
             }
         });
     });

     try {
         const res = await fetch('/api/sla-assessments', {
             method: 'POST',
             headers: {'Content-Type':'application/json'},
             body: JSON.stringify({
                 course_id: selectedCourse,
                 exam_id: selectedExam,
                 marksData: payload,
                 student_ids: students.map(s => s.id)
             })
         });
         if (res.ok) {
             alert("SLA Marks successfully locked into the Database!");
             fetchData();
         } else alert("Failed to save marks");
     } catch(e) { alert("Error saving."); }
  };

  const calculateSum = (studentId) => {
      const studentMks = marks[studentId] || {};
      return Object.values(studentMks).reduce((a, b) => {
          const v = parseFloat(b);
          if (isNaN(v)) return a;
          return a + (v === 401 ? 0 : v);
      }, 0);
  };

  const handleClearAll = () => {
       if(!confirm("Are you sure you want to clear all K6 UI marks?")) return;
       const newMarks = {...marks};
       Object.keys(newMarks).forEach(s_id => {
            Object.keys(newMarks[s_id]).forEach(act_no => {
                 newMarks[s_id][act_no] = '';
            });
       });
       setMarks(newMarks);
  };

  const handleDeleteAllData = async () => {
       if (!selectedCourse || !selectedExam) return alert("Select course and exam term first.");
       const course = courses.find(c => String(c.id) === String(selectedCourse));
       if (!confirm(`PERMANENTLY DELETE all K6 SLA marks for ${course?.code || 'this course'}?\n\nThis cannot be undone!`)) return;
       try {
           const res = await fetch(`/api/sla-assessments?exam_id=${selectedExam}&course_id=${selectedCourse}`, { method: 'DELETE' });
           if (res.ok) { alert("All K6 data deleted successfully."); fetchData(); }
           else alert("Failed to delete data.");
       } catch(e) { alert("Error deleting data."); }
  };

  const handleClearStudent = (studentId) => {
       setMarks(prev => {
            if(!prev[studentId]) return prev;
            const upd = {...prev[studentId]};
            Object.keys(upd).forEach(act_no => upd[act_no] = '');
            return {...prev, [studentId]: upd};
       });
  };

  const totalMaxMarks = activities.reduce((sum, act) => sum + parseFloat(act.max_marks || 0), 0);

  const handleExportExcel = () => {
    if (!selectedCourse || !selectedExam) return alert('Select course and exam term');
    if (activities.length === 0) return alert('No activities configured to export!');
    
    const course = courses.find(c => String(c.id) === String(selectedCourse));
    const exam = exams.find(e => String(e.id) === String(selectedExam));
    
    const subjectSlaMax = course.sla_max || 0;
    
    // Total Columns = Roll, Enr, Seat, Name + N (activities) + 3 (Total, SLA marks, Signature)
    const baseColsCount = 4;
    const endColsCount = 3;
    const totalCols = baseColsCount + activities.length + endColsCount;
    
    const createRow = () => new Array(totalCols).fill('');
    
    const headerRows = [];
    const r0 = createRow(); r0[r0.length - 1] = "CIAAN - 2023"; headerRows.push(r0);
    const r1 = createRow(); r1[r1.length - 1] = "K6"; headerRows.push(r1);
    const r2 = createRow(); r2[0] = "For AICTE Diploma Engineering Courses"; r2[r2.length - 1] = "wef - 2023-24"; headerRows.push(r2);
    
    const midPoint = Math.floor(totalCols / 2) - 1;
    const r3 = createRow(); r3[midPoint] = "Maharashtra State Board of Technical Education"; headerRows.push(r3);
    const r4 = createRow(); r4[midPoint] = "SELF LEARNING ASSESSMENT (SLA)"; headerRows.push(r4);
    const r5 = createRow(); r5[midPoint] = "Micro project / Assignment / Activities for specific learning / skills development"; headerRows.push(r5);
    const r6 = createRow(); headerRows.push(r6);
    
    const r7 = createRow(); r7[0] = "Institute Name:"; r7[1] = "Government Polytechnic Vikramgad"; r7[2] = "Institute Code: 1547"; headerRows.push(r7);
    const acYear = exam.season === 'Winter' ? `${exam.year}-${String(Number(exam.year)+1).slice(-2)}` : `${Number(exam.year)-1}-${String(exam.year).slice(-2)}`;
    const r8 = createRow(); r8[0] = "Academic Year"; r8[1] = acYear; r8[totalCols - 2] = "Exam:"; r8[totalCols - 1] = `${exam.season} ${exam.year}`; headerRows.push(r8);
    const r9 = createRow(); r9[0] = "Summer / Winter ............."; headerRows.push(r9);
    
    const r10 = createRow(); r10[0]="Programme:"; r10[2]="__________________"; r10[midPoint]="Course:"; r10[midPoint+1]=course.name; r10[totalCols-2]="Course Code:"; r10[totalCols-1]=course.code; headerRows.push(r10);
    const r11 = createRow(); r11[0] = "Semester:"; r11[1] = String(course.semester) + 'K'; headerRows.push(r11);
    const r12 = createRow(); headerRows.push(r12);

    const r13 = createRow();
    r13[0] = "Roll\nNo."; r13[1] = "Enrollment\nNo."; r13[2] = "Exam Seat\nNumber"; r13[3] = "Name of the Student";
    r13[totalCols - 3] = `Total\n(Out of ${totalMaxMarks})`;
    r13[totalCols - 2] = `SLA Marks\naccording to L-\nA Scheme\n(Max\nMarks ${subjectSlaMax})`;
    r13[totalCols - 1] = "Signature\nof\nStudent";
    headerRows.push(r13);

    const r14 = createRow();
    for(let i=0; i<4; i++) r14[i] = "";
    activities.forEach((act, i) => {
       r14[4 + i] = `${i+1}*\n[MAX: ${act.max_marks}]`; 
    });
    headerRows.push(r14);
    
    const wsData = [...headerRows];

    students.forEach(s => {
       const srow = createRow();
       srow[0] = s.roll_no || '-';
       srow[1] = s.enrollment_no;
       srow[2] = s.seat_number || '-';
       srow[3] = s.full_name || s.name;
       
       let total = 0;
       activities.forEach((act, i) => {
           const scoreVal = marks[s.id]?.[act.activity_no];
           if (scoreVal !== undefined && scoreVal !== '') {
               srow[4 + i] = scoreVal;
               total += parseFloat(scoreVal);
           } else {
               srow[4 + i] = '-';
           }
       });
       
       srow[totalCols - 3] = total > 0 ? total : '-';
       
       let converted = '-';
       if (total > 0 && totalMaxMarks > 0 && subjectSlaMax > 0) {
            converted = Math.round((total / totalMaxMarks) * subjectSlaMax);
        } else if (total > 0) {
            converted = Math.round(total);
       }
       
       srow[totalCols - 2] = converted;
       srow[totalCols - 1] = "";
       wsData.push(srow);
    });

    wsData.push([]);
    const footer = createRow(); footer[0] = "Signature of Faculty"; footer[totalCols-2] = "Signature of HoD"; wsData.push(footer);
    const footer2 = createRow(); footer2[0] = "Name"; footer2[totalCols-2] = "Name"; wsData.push(footer2);

    const ws = window.XLSX.utils.aoa_to_sheet(wsData);
    
    // Setup Styling
    for (const key in ws) {
       if (key[0] === '!') continue;
       const cellAddress = window.XLSX.utils.decode_cell(key);
       ws[key].s = {
           alignment: { 
              wrapText: cellAddress.r >= 13,
              vertical: 'center', 
              horizontal: (cellAddress.r >= 13 && cellAddress.c === 3) ? 'left' : 'center'
           },
           font: { 
              name: 'Times New Roman', 
              sz: cellAddress.r >= 13 ? 11 : 12, 
              bold: cellAddress.r === 3 || cellAddress.r === 4 || cellAddress.r === 5 || cellAddress.r === 13 || cellAddress.r === 14
           }
       };
       if (cellAddress.r >= 13 && cellAddress.r < wsData.length - 3) {
           ws[key].s.border = { 
              top: {style:'thin'}, bottom: {style:'thin'}, 
              left: {style:'thin'}, right: {style:'thin'} 
           };
       }
    }
    
    ws['!merges'] = [
      { s: {r:3, c:midPoint}, e: {r:3, c: midPoint+2} },
      { s: {r:4, c:midPoint}, e: {r:4, c: midPoint+2} },
      { s: {r:5, c:midPoint}, e: {r:5, c: midPoint+2} },
      // Merge main header
      { s: {r:13, c:4}, e: {r:13, c: 4 + activities.length - 1} },
      // Vertical merges for Roll No, Enr, Seat, Name, Total, SLA Marks, Signature
      { s: {r:13, c:0}, e: {r:14, c:0} },
      { s: {r:13, c:1}, e: {r:14, c:1} },
      { s: {r:13, c:2}, e: {r:14, c:2} },
      { s: {r:13, c:3}, e: {r:14, c:3} },
      { s: {r:13, c:totalCols-3}, e: {r:14, c:totalCols-3} },
      { s: {r:13, c:totalCols-2}, e: {r:14, c:totalCols-2} },
      { s: {r:13, c:totalCols-1}, e: {r:14, c:totalCols-1} }
    ];

    const widthsConfig = [ {wch: 8}, {wch: 15}, {wch: 15}, {wch: 35} ];
    activities.forEach(() => widthsConfig.push({wch: 15}));
    widthsConfig.push({wch: 12});
    widthsConfig.push({wch: 15});
    widthsConfig.push({wch: 15});
    ws['!cols'] = widthsConfig;

    const wb = window.XLSX.utils.book_new();
    window.XLSX.utils.book_append_sheet(wb, ws, `Format_K6_SLA`);
    window.XLSX.writeFile(wb, `K6_SLA_Sheet_${course.code}.xlsx`);
  };

  if (loading && students.length === 0) return <div className="p-8 text-center text-lg">Loading SLA Environment...</div>;

  const currentCourseObj = courses.find(c => String(c.id) === String(selectedCourse));
  const activeSubjectSlaMax = currentCourseObj?.sla_max || 0;

  const COL_ROLL_W = 70;
  const COL_ENROLL_W = 150;
  const COL_SEAT_W = 130;
  const COL_NAME_W = 230;
  const STICKY_TOTAL = COL_ROLL_W + COL_ENROLL_W + COL_SEAT_W + COL_NAME_W;

  const stickyCol0 = { position: 'sticky', left: 0, zIndex: 12, minWidth: COL_ROLL_W, width: COL_ROLL_W };
  const stickyCol1 = { position: 'sticky', left: COL_ROLL_W, zIndex: 12, minWidth: COL_ENROLL_W, width: COL_ENROLL_W };
  const stickyCol2 = { position: 'sticky', left: COL_ROLL_W + COL_ENROLL_W, zIndex: 12, minWidth: COL_SEAT_W, width: COL_SEAT_W };
  const stickyCol3 = { position: 'sticky', left: COL_ROLL_W + COL_ENROLL_W + COL_SEAT_W, zIndex: 12, minWidth: COL_NAME_W, width: COL_NAME_W, borderRight: '2px solid #cbd5e1' };

  const stickyHeadCol0 = { ...stickyCol0, zIndex: 32 };
  const stickyHeadCol1 = { ...stickyCol1, zIndex: 32 };
  const stickyHeadCol2 = { ...stickyCol2, zIndex: 32 };
  const stickyHeadCol3 = { ...stickyCol3, zIndex: 32 };

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6 lg:p-8">
      <div className="bg-white rounded-xl shadow-xl overflow-hidden border border-gray-200">
        <div className="bg-gradient-to-r from-teal-700 to-emerald-800 p-6 text-white text-center shadow-inner relative">
          <h2 className="text-2xl font-bold tracking-wider">Format-K6</h2>
          <p className="text-teal-100 text-sm mt-1 uppercase font-semibold tracking-widest">Self Learning Assessment (SLA)</p>
          <div className="absolute top-4 right-6 opacity-20 text-5xl font-black italic">SLA</div>
        </div>
        
        <div className="flex flex-wrap justify-between items-center p-4 bg-gray-50 border-b border-gray-200 gap-3">
          <div className="flex items-center gap-4 text-sm font-semibold text-gray-700 flex-wrap">
            <div>
              <label className="mr-2">Term:</label>
              <select className="border border-teal-300 rounded px-2 py-1 font-bold bg-teal-50 text-teal-900" value={selectedExam} onChange={e => setSelectedExam(e.target.value)}>
                {exams.length === 0 && <option value="">No Terms</option>}
                {exams.map(e => <option key={e.id} value={e.id}>{e.season} {e.year}</option>)}
              </select>
            </div>
            <div>
              <label className="mr-2">Course:</label>
              <input 
                 type="text" 
                 placeholder="Search Code/Name..." 
                 value={courseSearchQuery} 
                 onChange={e => setCourseSearchQuery(e.target.value)} 
                 className="w-48 border border-gray-300 rounded px-2 py-1 text-sm bg-white mb-1 focus:ring-2 outline-none mr-2"
              />
              <select className="border border-gray-300 rounded px-2 py-1 font-normal bg-white" value={selectedCourse} onChange={e => setSelectedCourse(e.target.value)}>
                {courses.length === 0 && <option value="">No Course</option>}
                {courses.filter(c => (c.code + ' ' + c.name).toLowerCase().includes(courseSearchQuery.toLowerCase())).map(c => <option key={c.id} value={c.id}>{c.code} - {c.name}</option>)}
              </select>
            </div>
          </div>
          
          <div className="flex items-center bg-white p-2 px-4 rounded-lg border border-gray-200 shadow-sm gap-4">
             <div className="flex flex-col text-right">
                 <span className="text-[10px] uppercase font-bold text-gray-500">Subject Max SLA</span>
                 <span className="text-xl font-black text-emerald-800 border-b-2 border-emerald-200">{activeSubjectSlaMax}</span>
             </div>
             <div className="h-8 w-px bg-gray-200 mx-1"></div>
             <div className="flex flex-col text-right">
                 <span className="text-[10px] uppercase font-bold text-gray-500 text-teal-600/70">Blueprint Total</span>
                 <span className="text-xl font-bold text-teal-700/80">{totalMaxMarks}</span>
             </div>
             <div className="h-8 w-px bg-gray-200 mx-2"></div>
             <button onClick={openConfigModal} className="flex flex-col items-center justify-center bg-teal-50 hover:bg-teal-100 text-teal-800 border border-teal-200 transition px-4 py-1.5 rounded disabled:opacity-50" disabled={!selectedCourse||!selectedExam}>
                 <span className="text-xs font-bold uppercase tracking-wider">Configure Blueprint</span>
                 <span className="text-[10px] text-teal-600">{activities.length} Activities Linked</span>
             </button>
          </div>

          <div className="flex flex-wrap gap-2 ml-auto">
             <button onClick={handleDeleteAllData} className="flex items-center gap-2 px-5 py-2 bg-white border border-red-300 text-red-700 hover:bg-red-600 hover:text-white transition shadow rounded-md font-medium text-sm">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                Delete All Data
             </button>
             <button onClick={handleClearAll} className="flex items-center gap-2 px-6 py-2 bg-white border border-red-200 text-red-600 hover:bg-red-50 transition shadow rounded-md font-medium">
               Clear UI
             </button>
             <button onClick={handleExportExcel} disabled={activities.length===0} className="flex items-center gap-2 px-6 py-2 bg-teal-700 hover:bg-teal-800 transition shadow rounded-md text-white font-medium disabled:opacity-50">
               <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
               Generate K6 SLA Excel
             </button>
             <button onClick={saveDatabaseMarks} disabled={activities.length===0} className="flex items-center gap-2 px-6 py-2 bg-emerald-600 hover:bg-emerald-700 transition shadow rounded-md text-white font-medium shadow-emerald-800/30">
               <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7"/></svg>
               Lock Save Database
             </button>
          </div>
        </div>

        <div className="overflow-auto bg-white" style={{ maxHeight: 'calc(100vh - 200px)' }}>
          <table className="w-full text-left text-sm text-gray-700 bg-white" style={{ minWidth: STICKY_TOTAL + (activities.length * 130) + 200 }}>
            <thead className="bg-gray-100 text-gray-600 uppercase font-bold text-[10px] tracking-wider sticky top-0 border-b border-gray-200 z-20">
              <tr>
                <th className="px-4 py-4 border-b border-r border-gray-200 text-center bg-gray-100" style={stickyHeadCol0}>Roll<br/>No.</th>
                <th className="px-4 py-4 border-b border-r border-gray-200 bg-gray-100" style={stickyHeadCol1}>Enrollment<br/>Number</th>
                <th className="px-4 py-4 border-b border-r border-gray-200 text-center text-emerald-800 bg-gray-100" style={stickyHeadCol2}>Exam Seat<br/>Number</th>
                <th className="px-4 py-4 border-b border-r border-gray-200 bg-gray-100" style={stickyHeadCol3}>Name of the Student</th>
                
                {activities.map((act) => (
                    <th key={act.activity_no} className="px-4 py-4 border-b border-gray-200 text-center min-w-[130px] border-l">
                         {act.activity_name}<br />
                         <span className="lowercase font-normal opacity-70 block mt-1">Out of {act.max_marks}</span>
                    </th>
                ))}
                
                <th className="px-4 py-4 border-b border-gray-200 text-center bg-gray-50 border-l">Blueprint Total Marks<br/><span className="lowercase font-normal opacity-70 block">Out of {totalMaxMarks}</span></th>
                <th className="px-4 py-4 border-b border-gray-200 text-center bg-teal-50 text-teal-800 border-l">Converted SLA Marks<br/><span className="lowercase font-normal opacity-80 block text-teal-600">Out of {activeSubjectSlaMax}</span></th>
                <th className="px-4 py-4 border-b border-gray-200 text-center bg-gray-50 border-l border-r w-16">Clear</th>
              </tr>
            </thead>
            <tbody>
              {students.length === 0 && <tr><td colSpan={4 + activities.length} className="text-center py-12 text-gray-400 font-bold">No students registered yet for this term.</td></tr>}
              {students.map((student, index) => {
                 const sumMarks = calculateSum(student.id);
                 
                 let convertedMarks = '-';
                 const hasEntries = Object.values(marks[student.id] || {}).some(v => v !== '');
                 if (hasEntries) {
                     if (totalMaxMarks > 0 && activeSubjectSlaMax > 0) {
                          convertedMarks = Math.round((sumMarks / totalMaxMarks) * activeSubjectSlaMax);
                      } else {
                          convertedMarks = Math.round(sumMarks);
                     }
                 }

                 return (
                <tr key={student.id} className="hover:bg-teal-50 border-b border-gray-100 transition-colors group">
                  <td className="px-4 py-3 text-center font-bold text-gray-400 border-r border-gray-100 bg-white group-hover:bg-teal-50" style={stickyCol0}>{student.roll_no || '-'}</td>
                  <td className="px-4 py-3 font-mono text-gray-500 text-xs border-r border-gray-100 bg-white group-hover:bg-teal-50" style={stickyCol1}>{student.enrollment_no}</td>
                  <td className="px-4 py-3 font-mono text-center font-bold text-emerald-700 border-r border-gray-100 bg-teal-50 group-hover:bg-teal-100" style={stickyCol2}>{student.seat_number || '-'}</td>
                  <td className="px-4 py-3 font-medium text-teal-800 border-r border-gray-100 bg-white group-hover:bg-teal-50" style={stickyCol3}>
                     {student.full_name || student.name}
                  </td>
                  
                  {activities.map(act => (
                      <td key={act.activity_no} className="px-4 py-2 text-center border-l bg-white hover:bg-gray-50 transition-colors relative border-r border-gray-100">
                           <input type="number" 
                              value={marks[student.id]?.[act.activity_no] ?? ''} 
                              onChange={(e) => handleInlineMarkChange(student.id, act.activity_no, e.target.value, parseFloat(act.max_marks))} 
                              className="w-16 px-2 py-1 border border-gray-300 rounded text-center text-teal-900 font-bold focus:ring-2 focus:ring-teal-400 outline-none shadow-sm" />
                           <button onClick={() => handleDuplicateDown(index, act.activity_no)} title="Duplicate Score Down" className="absolute bottom-1 left-1/2 -translate-x-1/2 text-[9px] bg-white border border-teal-300 text-teal-600 px-1 rounded opacity-0 group-hover:opacity-100 transition shadow-sm font-bold uppercase z-10 hover:bg-teal-100">↓ DUP.</button>
                      </td>
                  ))}
                  
                  <td className="px-4 py-3 text-center bg-gray-50 border-l">
                     <span className="font-bold text-gray-700">{Object.values(marks[student.id] || {}).some(v => v !== '') ? sumMarks : '-'}</span>
                  </td>
                  <td className="px-4 py-3 text-center bg-teal-50/30 border-l">
                     <span className="inline-block bg-teal-100 text-teal-900 font-black px-3 py-1.5 rounded text-lg shadow-sm border border-teal-200/50 w-16">
                         {convertedMarks}
                     </span>
                  </td>
                  <td className="px-4 py-3 text-center border-l border-r border-gray-100">
                     <button onClick={() => handleClearStudent(student.id)} className="text-red-400 hover:text-red-600 transition" title="Clear Student Mark">
                         <svg className="w-5 h-5 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                     </button>
                  </td>
                </tr>
              )})}
            </tbody>
          </table>
        </div>
      </div>

      {/* Blueprint Config Modal */}
      {showConfigModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden animate-fade-in-up border border-teal-200">
            <div className="p-5 bg-gradient-to-r from-teal-800 to-emerald-900 text-white flex justify-between items-center shrink-0">
               <div>
                  <h3 className="font-bold text-lg tracking-wide shadow-sm">SLA Blueprint Builder</h3>
                  <p className="text-sm text-teal-100 mt-1">Configure Micro Projects and Activities for this Course Term</p>
               </div>
               <button onClick={() => setShowConfigModal(false)} className="text-white hover:text-red-200 font-bold text-2xl transition hover:scale-110">&times;</button>
            </div>
            
            <div className="p-6 overflow-y-auto flex-1 bg-gray-50/50">
               {configActivities.map((act, idx) => (
                   <div key={idx} className="flex gap-4 items-end mb-4 bg-white p-4 rounded border border-gray-200 shadow-sm relative group">
                       <span className="absolute -left-3 -top-3 w-6 h-6 bg-teal-600 text-white text-xs font-bold rounded-full flex items-center justify-center shadow">{idx+1}</span>
                       <div className="flex-1">
                           <label className="text-xs font-bold text-gray-500 uppercase">Activity Name (e.g. Unit 1 Presentation)</label>
                           <input type="text" className="w-full border border-gray-300 rounded px-3 py-2 text-sm mt-1 focus:ring-2 focus:ring-teal-500 outline-none" value={act.activity_name||''} onChange={e => {
                               const cp = [...configActivities]; cp[idx].activity_name=e.target.value; setConfigActivities(cp);
                           }}/>
                       </div>
                       <div className="w-32">
                           <label className="text-xs font-bold text-gray-500 uppercase">Max Marks</label>
                           <input type="number" className="w-full border border-gray-300 rounded px-3 py-2 text-sm mt-1 focus:ring-2 focus:ring-teal-500 outline-none text-center font-bold text-teal-800" value={act.max_marks||''} onChange={e => {
                               const cp = [...configActivities]; cp[idx].max_marks=e.target.value; setConfigActivities(cp);
                           }}/>
                       </div>
                       <button onClick={() => setConfigActivities(configActivities.filter((_, i) => i !== idx))} className="pb-2 text-red-500 hover:text-red-700 opacity-0 group-hover:opacity-100 transition">
                           <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                       </button>
                   </div>
               ))}
               
               <button onClick={() => setConfigActivities([...configActivities, {activity_name: '', max_marks: ''}])} className="w-full py-3 border-2 border-dashed border-teal-300 text-teal-600 font-bold rounded hover:bg-teal-50 hover:border-teal-400 transition flex items-center justify-center gap-2">
                   <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6"/></svg>
                   Append New Activity Matrix
               </button>
            </div>

            <div className="p-4 bg-gray-100 flex justify-between items-center shrink-0 border-t border-gray-200">
               <div className="text-sm font-bold text-gray-600">Total Activities Array Limit: <span className="text-teal-700">{configActivities.length}</span></div>
               <div className="flex gap-3">
                   <button onClick={() => setShowConfigModal(false)} className="px-5 py-2 rounded text-sm font-bold text-gray-600 hover:bg-gray-200 transition">Cancel</button>
                   <button onClick={handleSaveConfig} className="px-5 py-2 rounded text-sm font-bold text-white bg-teal-600 hover:bg-teal-700 shadow transition flex items-center gap-2">
                       Establish Blueprint
                   </button>
               </div>
            </div>
          </div>
        </div>
      )}


    </div>
  );
};

window.FormatK6 = FormatK6;
