const { useState, useEffect, useRef } = React;

const StudentMaster = () => {
  const [students, setStudents] = useState([]);
  const [form, setForm] = useState({
    enrollment_no: '', roll_no: '', full_name: '', dept_code: 'CO', semester: 1,
    batch_name: 'A1', is_lateral_entry: false, ssc_percentage: '',
    hsc_iti_percentage: '', collegecode: '', scheme: 'I',
    year_of_admission: '', status: 'Active', year_of_exit: '',
    last_exam_status: 'Pass'
  });
  const [editingId, setEditingId] = useState(null);
  const [loading, setLoading] = useState(false);
  const [selectedStudent, setSelectedStudent] = useState(null);
  const [qrEnrollment, setQrEnrollment] = useState(null);
  
  const [filterScheme, setFilterScheme] = useState('All');
  const [filterDept, setFilterDept] = useState('All');
  const [filterSem, setFilterSem] = useState('All');
  const [filterBatch, setFilterBatch] = useState('All');

  const fileInputRef = useRef(null);
  
  const deptCodes = ['CO', 'IF', 'EJ', 'ME', 'CE', 'EE'];
  const examStatuses = ['Pass', 'Fail', 'ATKT'];
  const profileStatuses = ['Active', 'Passed out', 'Dropped out', 'Exited', 'Admission cancelled'];
  const schemes = ['I', 'K', 'G', 'E'];

  const fetchStudents = () => {
    fetch('/api/students')
      .then(res => res.json())
      .then(data => setStudents(data))
      .catch(console.error);
  };

  useEffect(() => { fetchStudents(); }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    setLoading(true);

    const payload = {
        ...form, 
        roll_no: parseInt(form.roll_no), 
        semester: parseInt(form.semester), 
        ssc_percentage: form.ssc_percentage ? parseFloat(form.ssc_percentage) : null,
        hsc_iti_percentage: form.hsc_iti_percentage ? parseFloat(form.hsc_iti_percentage) : null
    };

    const url = editingId ? `/api/students/${editingId}` : '/api/students';
    const method = editingId ? 'PUT' : 'POST';

    fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    })
    .then(res => {
      setLoading(false);
      if (res.ok) {
        setForm({ 
          enrollment_no: '', roll_no: '', full_name: '', dept_code: 'CO', semester: 1, 
          batch_name: 'A1', is_lateral_entry: false, ssc_percentage: '', 
          hsc_iti_percentage: '', collegecode: '', scheme: 'I',
          year_of_admission: '', status: 'Active', year_of_exit: '',
          last_exam_status: 'Pass' 
        });
        setEditingId(null);
        fetchStudents();
      } else alert('Error saving student');
    })
    .catch(() => setLoading(false));
  };

  const handleEdit = (student) => {
    setEditingId(student.id);
    setForm({
      enrollment_no: student.enrollment_no || '',
      roll_no: student.roll_no || '',
      full_name: student.full_name || '',
      dept_code: student.Department?.dept_code || 'CO',
      semester: student.semester || 1,
      batch_name: student.Batch?.batch_name || 'A1',
      is_lateral_entry: !!student.is_lateral_entry,
      ssc_percentage: student.ssc_percentage || '',
      hsc_iti_percentage: student.hsc_iti_percentage || '',
      collegecode: student.collegecode || '',
      scheme: student.scheme || 'I',
      year_of_admission: student.year_of_admission || '',
      status: student.status || 'Active',
      year_of_exit: student.year_of_exit || '',
      last_exam_status: student.last_exam_status || 'Pass'
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = (id) => {
    if (!confirm('Drop this student record completely?')) return;
    fetch(`/api/students/${id}`, { method: 'DELETE' }).then(res => { if (res.ok) fetchStudents(); });
  };

  const viewRecord = (id) => {
    fetch(`/api/students/${id}/record`)
      .then(res => res.json())
      .then(data => setSelectedStudent(data));
  };

  const handleDownloadTemplate = () => {
    const templateData = [{
      enrollment_no: '2100150123',
      roll_no: 1,
      full_name: 'John Doe',
      dept_code: 'CO',
      semester: 1,
      batch_name: 'A1',
      is_lateral_entry: false,
      ssc_percentage: 85.5,
      hsc_iti_percentage: 80.0,
      collegecode: '0015',
      scheme: 'I',
      year_of_admission: '2025-26',
      status: 'Active',
      year_of_exit: '',
      last_exam_status: 'Pass'
    }];
    const ws = XLSX.utils.json_to_sheet(templateData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Students Template");
    XLSX.writeFile(wb, "Student_Bulk_Upload_Template.xlsx");
  };

  const handleFileUpload = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (evt) => {
      const bstr = evt.target.result;
      const wb = XLSX.read(bstr, { type: 'binary' });
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      const data = XLSX.utils.sheet_to_json(ws);
      
      if(data.length === 0) {
        alert("The uploaded excel sheet is empty!");
        return;
      }
      
      if(!confirm(`Are you sure you want to bulk upload ${data.length} students?`)) return;
      
      setLoading(true);
      fetch('/api/students/bulk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ students: data })
      })
      .then(res => res.json())
      .then(resData => {
        setLoading(false);
        if (resData.error) {
          alert("Error uploading students: " + resData.error);
        } else {
          alert(`Successfully uploaded ${resData.count} students!`);
          fetchStudents();
        }
      })
      .catch(err => {
        setLoading(false);
        console.error(err);
        alert("Failed to perform bulk upload.");
      });
      
      fileInputRef.current.value = ""; // reset input
    };
    reader.readAsBinaryString(file);
  };

  return (
    <div className="flex flex-col gap-8 animate-fade-in-up pb-10">
      {/* QR Code Modal */}
      {qrEnrollment && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/70 backdrop-blur-md transition-all">
          <div className="bg-white rounded-[2.5rem] p-10 flex flex-col items-center max-w-sm w-full shadow-2xl relative animate-fade-in-up">
            <button onClick={() => setQrEnrollment(null)} className="absolute top-6 right-6 text-gray-400 hover:text-red-500 transition">
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
            <div className="w-16 h-16 bg-blue-100 rounded-2xl flex items-center justify-center text-blue-600 text-3xl mb-6">
              📱
            </div>
            <h2 className="text-xl font-black text-gray-800 mb-2">Student Attendance QR</h2>
            <p className="text-xs text-gray-400 font-bold uppercase tracking-widest mb-8 text-center">Scan for real-time validation</p>
            
            <div className="bg-white p-4 border-2 border-dashed border-blue-200 rounded-[2rem] shadow-inner mb-8 transform hover:scale-105 transition-transform">
               <img 
                  src={`https://api.qrserver.com/v1/create-qr-code/?size=300x300&ecc=L&margin=2&data=${encodeURIComponent(qrEnrollment.enrollment_no)}`} 
                  alt="QR" 
                  className="w-64 h-64 rounded-xl"
               />
            </div>

            <div className="text-center bg-gray-50 px-6 py-3 rounded-2xl border border-gray-100 w-full">
              <div className="text-[10px] font-black text-gray-400 uppercase tracking-tighter mb-1">Enrollment Number</div>
              <div className="text-2xl font-black text-gray-900 font-mono tracking-tighter">{qrEnrollment.enrollment_no}</div>
              <div className="text-sm font-bold text-blue-600 mt-1">{qrEnrollment.full_name}</div>
            </div>

            <p className="text-[10px] text-gray-400 font-medium mt-8 text-center px-4">
              Hold this QR towards the mobile scanner. Ensure high screen brightness.
            </p>
          </div>
        </div>
      )}

      {/* Modal Profile View - Kept largely same but augmented */}
      {selectedStudent && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
            <div className="px-6 py-5 bg-gradient-to-r from-blue-700 to-indigo-800 text-white flex justify-between items-center shadow-inner">
              <div>
                <h2 className="text-2xl font-bold tracking-tight mb-1">{selectedStudent.full_name}</h2>
                <span className="text-blue-200 text-sm font-medium tracking-wide">
                  {selectedStudent.enrollment_no} • {selectedStudent.Department?.name || 'Unknown'} • Semester {selectedStudent.semester}
                </span>
              </div>
              <button onClick={() => setSelectedStudent(null)} className="p-2 bg-white/20 hover:bg-white/30 rounded-full transition">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
              </button>
            </div>
            
            <div className="p-8 overflow-y-auto flex-1 bg-gray-50 style-scrollbar">
               <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                  <div className="bg-white p-5 rounded-xl shadow-sm border border-gray-100">
                     <h3 className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-4 border-b border-gray-100 pb-2">Full Profile Data</h3>
                     <div className="space-y-3 text-sm">
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">Roll No / ID</span><span className="font-bold text-gray-800">{selectedStudent.roll_no}</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">Scheme</span><span className="font-bold text-gray-800">{selectedStudent.scheme} Scheme</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">College Code</span><span className="font-bold text-gray-800">{selectedStudent.collegecode || 'N/A'}</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">Batch Allocation</span><span className="font-bold text-blue-600 bg-blue-50 px-2 py-0.5 rounded">{selectedStudent.Batch?.batch_name || 'N/A'}</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">Lateral Entry</span><span className="font-bold text-gray-800">{selectedStudent.is_lateral_entry ? 'Yes (DSY)' : 'No'}</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">SSC %</span><span className="font-bold text-emerald-600">{selectedStudent.ssc_percentage}%</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">HSC/ITI %</span><span className="font-bold text-emerald-600">{selectedStudent.hsc_iti_percentage ? selectedStudent.hsc_iti_percentage + '%' : 'N/A'}</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">Admission Year</span><span className="font-bold text-gray-800">{selectedStudent.year_of_admission || 'N/A'}</span></div>
                        <div className="flex justify-between"><span className="text-gray-500 font-medium">Exit Year</span><span className="font-bold text-gray-800">{selectedStudent.year_of_exit || 'N/A'}</span></div>
                     </div>
                  </div>
                  <div className="bg-white p-5 rounded-xl shadow-sm border border-gray-100 flex flex-col items-center justify-center text-center gap-6">
                     <div className="w-full">
                       <h3 className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-4 border-b border-gray-100 pb-2 text-left">Current Status</h3>
                       <div className="flex items-center justify-center">
                          <span className={`px-6 py-2 rounded-xl font-bold text-lg tracking-widest uppercase shadow-sm border ${selectedStudent.status === 'Active' ? 'bg-emerald-50 text-emerald-600 border-emerald-200' : 'bg-gray-100 text-gray-600 border-gray-300'}`}>
                             {selectedStudent.status || 'Active'}
                          </span>
                       </div>
                     </div>
                     <div className="w-full">
                       <h3 className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-4 border-b border-gray-100 pb-2 text-left">Academic Status Flag</h3>
                       <div className="flex items-center justify-center">
                          <span className={`px-6 py-2 rounded-xl font-bold text-lg tracking-widest uppercase shadow-sm border ${selectedStudent.last_exam_status === 'Pass' ? 'bg-emerald-50 text-emerald-600 border-emerald-200' : selectedStudent.last_exam_status === 'Fail' ? 'bg-red-50 text-red-600 border-red-200' : 'bg-amber-50 text-amber-600 border-amber-200'}`}>
                             {selectedStudent.last_exam_status}
                          </span>
                       </div>
                     </div>
                  </div>
               </div>
               
               <h3 className="text-lg font-bold text-gray-900 mb-4 tracking-tight">Continuous Assessments Framework (CIAAN)</h3>
               
               {/* Display K3 Lab Assessments */}
               <div className="mb-6 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                 <h4 className="font-bold text-gray-800 p-4 bg-gray-50 border-b border-gray-100 text-sm flex gap-2 items-center tracking-tight">
                   <div className="w-2 h-2 rounded-full bg-blue-500"></div> Format K3: Lab Practical Engine
                 </h4>
                 {selectedStudent.LabAssessments?.length > 0 ? (
                   <table className="w-full text-left text-sm bg-white">
                     <thead className="bg-gray-50 text-gray-500 text-xs font-semibold uppercase tracking-wider"><tr><th className="px-4 py-3 border-b">Course</th><th className="px-4 py-3 border-b text-center">Experiment No.</th><th className="px-4 py-3 border-b text-center">Marks (C/P/A)</th><th className="px-4 py-3 border-b text-right">Total</th></tr></thead>
                     <tbody className="divide-y divide-gray-50">
                       {selectedStudent.LabAssessments.map(lab => (
                         <tr key={lab.id} className="hover:bg-gray-50/50 transition">
                           <td className="px-4 py-3 font-medium text-gray-700">{lab.Course?.name || 'Unknown'} (ID: {lab.course_id})</td>
                           <td className="px-4 py-3 text-center text-gray-600 font-mono text-xs px-2 py-1 bg-gray-100 rounded ml-4 w-fit">{lab.practical_no}</td>
                           <td className="px-4 py-3 text-center text-gray-500 tracking-widest">{lab.cognitive_marks}-{lab.psychomotor_marks}-{lab.affective_marks}</td>
                           <td className="px-4 py-3 text-right font-bold text-blue-700">{lab.total_marks}<span className="text-gray-400 font-medium">/25</span></td>
                         </tr>
                       ))}
                     </tbody>
                   </table>
                 ) : <p className="text-sm text-gray-400 italic p-6 text-center bg-gray-50/50">No practical assessments recorded.</p>}
               </div>
               
               {/* Display K5 & K6 structure similarly mapped */}
               {/* Assuming identical map code here for simplicity */}
            </div>
          </div>
        </div>
      )}

      {/* Main UI Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 tracking-tight">Student Academic Master</h1>
          <p className="text-sm text-gray-500 mt-1">Central registration with bulk import capability.</p>
        </div>
        <div className="flex items-center gap-3">
          <button onClick={handleDownloadTemplate} className="bg-white border border-gray-300 text-gray-700 px-4 py-2 flex items-center justify-center gap-2 rounded-lg text-sm font-bold shadow-sm hover:bg-gray-50 transition">
             <svg className="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
             Get Excel Template
          </button>
          
          <label className="bg-green-600 text-white cursor-pointer px-4 py-2 flex items-center justify-center gap-2 rounded-lg text-sm font-bold shadow-sm hover:bg-green-700 transition">
             <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path></svg>
             Bulk Upload
             <input type="file" ref={fileInputRef} accept=".xls,.xlsx" className="hidden" onChange={handleFileUpload} />
          </label>
        </div>
      </div>
      
      <div className="flex flex-col xl:flex-row gap-8">
        {/* ADD STUDENT FORM */}
        <div className="w-full xl:w-2/5 bg-white p-7 rounded-2xl shadow-sm border border-gray-200 h-fit">
          <h2 className="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2">
            <svg className="w-5 h-5 text-blue-600" fill="currentColor" viewBox="0 0 20 20"><path d="M8 9a3 3 0 100-6 3 3 0 000 6zM8 11a6 6 0 016 6H2a6 6 0 016-6zM16 7a1 1 0 10-2 0v1h-1a1 1 0 100 2h1v1a1 1 0 102 0v-1h1a1 1 0 100-2h-1V7z"></path></svg>
            {editingId ? 'Update Active Profile' : 'Enroll New Profile'}
          </h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Full Legal Name</label>
              <input required type="text" value={form.full_name} onChange={e => setForm({...form, full_name: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
            </div>
            
            <div className="grid grid-cols-2 gap-4">
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Enrollment No.</label>
                 <input required type="text" value={form.enrollment_no} disabled={!!editingId} onChange={e => setForm({...form, enrollment_no: e.target.value})} className={`w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 transition ${editingId ? 'opacity-60 cursor-not-allowed bg-gray-100/50' : 'focus:bg-white outline-none'}`} />
               </div>
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Roll No.</label>
                 <input required type="number" value={form.roll_no} onChange={e => setForm({...form, roll_no: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Dept Code</label>
                 <select value={form.dept_code} onChange={e => setForm({...form, dept_code: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition">
                   {deptCodes.map(code => <option key={code} value={code}>{code}</option>)}
                 </select>
               </div>
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">College Code</label>
                 <input type="text" value={form.collegecode} onChange={e => setForm({...form, collegecode: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
            </div>

            <div className="grid grid-cols-3 gap-4">
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Scheme</label>
                 <select value={form.scheme} onChange={e => setForm({...form, scheme: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition">
                   {schemes.map(s => <option key={s} value={s}>{s}</option>)}
                 </select>
               </div>
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Semester</label>
                 <input required type="number" min="1" max="6" value={form.semester} onChange={e => setForm({...form, semester: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Batch</label>
                 <input required type="text" value={form.batch_name} onChange={e => setForm({...form, batch_name: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Adm. Year</label>
                 <input type="text" placeholder="2025-26" value={form.year_of_admission} onChange={e => setForm({...form, year_of_admission: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Exit Year</label>
                 <input type="text" placeholder="2028-29" value={form.year_of_exit} onChange={e => setForm({...form, year_of_exit: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">SSC %</label>
                 <input type="number" step="0.01" value={form.ssc_percentage} onChange={e => setForm({...form, ssc_percentage: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
               <div>
                 <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">HSC/ITI %</label>
                 <input type="number" step="0.01" value={form.hsc_iti_percentage} onChange={e => setForm({...form, hsc_iti_percentage: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition" />
               </div>
            </div>

            <div className="flex items-center gap-4 py-3 my-2 border-y border-gray-100">
               <label className="flex items-center gap-2 cursor-pointer text-sm font-medium text-gray-700">
                 <input type="checkbox" checked={form.is_lateral_entry} onChange={e => setForm({...form, is_lateral_entry: e.target.checked})} className="w-4 h-4 text-blue-600 rounded bg-gray-100 border-gray-300 focus:ring-blue-500" />
                 Direct Second Year (Lateral Entry)
               </label>
            </div>

            <div className="grid grid-cols-2 gap-4">
               <div>
                  <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Profile Status</label>
                  <select value={form.status} onChange={e => setForm({...form, status: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition">
                    {profileStatuses.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
               </div>
               <div>
                  <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase tracking-wider">Last Exam Flag</label>
                  <select value={form.last_exam_status} onChange={e => setForm({...form, last_exam_status: e.target.value})} className="w-full px-3 py-2 bg-gray-50/50 border border-gray-200 text-sm rounded-lg focus:ring-2 border-b-2 border-b-gray-300 focus:border-b-blue-500 focus:bg-white outline-none transition">
                    {examStatuses.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
               </div>
            </div>

            <div className="flex gap-3 mt-4">
              <button disabled={loading} type="submit" className="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 rounded-lg shadow disabled:opacity-50 transition tracking-wide">
                {loading ? 'Committing...' : (editingId ? 'Update Profile' : 'Publish Profile')}
              </button>
              {editingId && (
                <button type="button" onClick={() => { setEditingId(null); setForm({ enrollment_no: '', roll_no: '', full_name: '', dept_code: 'CO', semester: 1, batch_name: 'A1', is_lateral_entry: false, ssc_percentage: '', hsc_iti_percentage: '', collegecode: '', scheme: 'I', year_of_admission: '', status: 'Active', year_of_exit: '', last_exam_status: 'Pass' }); }} className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-3 rounded-lg shadow transition tracking-wide">
                  Cancel Edit
                </button>
              )}
            </div>
          </form>
        </div>

        {/* STUDENT DIRECTORY GRID */}
        <div className="w-full xl:w-3/5 flex flex-col gap-4">
          {/* FILTERS */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 flex flex-col gap-4">
             <h2 className="text-sm font-bold text-gray-700 uppercase tracking-widest border-b border-gray-100 pb-2">Filter Demographic Records</h2>
             <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                 <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Filter Scheme</label>
                    <select value={filterScheme} onChange={e=>setFilterScheme(e.target.value)} className="w-full border border-gray-200 rounded px-2 py-1.5 text-sm bg-gray-50">
                        <option value="All">All Schemes</option>
                        {schemes.map(s => <option key={s} value={s}>{s} Scheme</option>)}
                    </select>
                 </div>
                 <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Filter Dept</label>
                    <select value={filterDept} onChange={e=>setFilterDept(e.target.value)} className="w-full border border-gray-200 rounded px-2 py-1.5 text-sm bg-gray-50">
                        <option value="All">All Departments</option>
                        {deptCodes.map(d => <option key={d} value={d}>{d}</option>)}
                    </select>
                 </div>
                 <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Filter Sem</label>
                    <select value={filterSem} onChange={e=>setFilterSem(e.target.value)} className="w-full border border-gray-200 rounded px-2 py-1.5 text-sm bg-gray-50">
                        <option value="All">All Semesters</option>
                        {[1,2,3,4,5,6,7,8].map(s => <option key={s} value={String(s)}>Semester {s}</option>)}
                    </select>
                 </div>
                 <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Filter Batch</label>
                    <input type="text" placeholder="All" value={filterBatch} onChange={e=>setFilterBatch(e.target.value)} className="w-full border border-gray-200 rounded px-2 py-1.5 text-sm bg-white focus:bg-white" />
                 </div>
             </div>
          </div>

          <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden flex flex-col h-fit text-sm">
            <div className="p-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center shrink-0">
               <h2 className="text-xl font-bold text-gray-800">Master Directory Index</h2>
               <span className="text-xs bg-indigo-100 text-indigo-700 font-bold px-3 py-1 rounded-full shadow-inner">{students.length} Records Tracked</span>
            </div>
          <div className="overflow-x-auto w-full">
            <table className="w-full text-left whitespace-nowrap">
              <thead className="bg-gray-100/80 text-gray-500 font-bold uppercase text-[10px] tracking-widest border-b border-gray-200">
                <tr>
                  <th className="px-5 py-4">Identification Name</th>
                  <th className="px-5 py-4">Dept / Batch</th>
                  <th className="px-5 py-4">Current Status</th>
                  <th className="px-5 py-4 text-right">Operations</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {students.filter(s => {
                    if (filterScheme !== 'All' && s.scheme !== filterScheme) return false;
                    if (filterSem !== 'All' && String(s.semester) !== String(filterSem)) return false;
                    const dCode = s.Department?.dept_code || s.dept_code || 'CO'; // Defaulting visually
                    if (filterDept !== 'All' && dCode !== filterDept) return false;
                    if (filterBatch !== 'All' && filterBatch.trim() !== '') {
                        const bName = s.Batch?.batch_name || '';
                        if (!bName.toLowerCase().includes(filterBatch.toLowerCase())) return false;
                    }
                    return true;
                }).map(s => (
                  <tr key={s.id} className="hover:bg-blue-50/40 transition duration-150 relative group">
                    <td className="px-5 py-4">
                       <div className="font-bold text-gray-900 group-hover:text-blue-700 transition">{s.full_name}</div>
                       <div className="text-xs text-gray-500 font-medium font-mono mt-0.5">Roll {s.roll_no} • {s.enrollment_no}</div>
                    </td>
                    <td className="px-5 py-4">
                       <div className="font-bold text-gray-700">Sem {s.semester} <span className="text-gray-300 mx-1">|</span> {s.Department?.dept_code || 'N/A'}</div>
                       <div className="text-xs text-blue-600 bg-blue-50 w-fit px-2 py-0.5 rounded mt-1 font-semibold">{s.Batch?.batch_name || 'N/A'}</div>
                    </td>
                    <td className="px-5 py-4">
                       <div className="font-bold text-gray-800">{s.status || 'Active'}</div>
                       <div className={`mt-1 px-2 py-0.5 rounded-md text-[10px] uppercase font-bold tracking-wider inline-block ${s.last_exam_status === 'Pass' ? 'bg-green-100 text-green-700' : s.last_exam_status === 'Fail' ? 'bg-red-100 text-red-700' : 'bg-yellow-100 text-yellow-700'}`}>
                         {s.last_exam_status}
                       </div>
                    </td>
                    <td className="px-5 py-4 text-right space-x-2">
                      <button onClick={() => setQrEnrollment(s)} title="View QR" className="text-blue-600 hover:bg-blue-600 hover:text-white border border-blue-600 bg-white p-1.5 rounded-xl transition shadow-sm">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"></path></svg>
                      </button>
                      <button onClick={() => viewRecord(s.id)} className="text-indigo-600 hover:text-white hover:bg-indigo-600 border border-indigo-600 bg-white font-bold text-[10px] px-3 py-1.5 rounded-full uppercase transition tracking-wider shadow-sm">View Profile</button>
                      <button onClick={() => handleEdit(s)} className="text-blue-500 hover:text-white hover:bg-blue-500 border border-transparent hover:border-blue-500 bg-white font-bold text-[10px] px-3 py-1.5 rounded-full uppercase transition tracking-wider shadow-sm">Edit</button>
                      <button onClick={() => handleDelete(s.id)} className="text-red-500 hover:text-white hover:bg-red-500 border border-transparent hover:border-red-500 font-bold text-[10px] px-3 py-1.5 rounded-full uppercase transition tracking-wider">Drop</button>
                    </td>
                  </tr>
                ))}
                {students.filter(s => {
                    if (filterScheme !== 'All' && s.scheme !== filterScheme) return false;
                    if (filterSem !== 'All' && String(s.semester) !== String(filterSem)) return false;
                    const dCode = s.Department?.dept_code || s.dept_code || 'CO';
                    if (filterDept !== 'All' && dCode !== filterDept) return false;
                    if (filterBatch !== 'All' && filterBatch.trim() !== '') {
                        const bName = s.Batch?.batch_name || '';
                        if (!bName.toLowerCase().includes(filterBatch.toLowerCase())) return false;
                    }
                    return true;
                }).length === 0 && (
                  <tr><td colSpan="4" className="text-center py-16">
                     <svg className="w-12 h-12 text-gray-200 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path></svg>
                     <p className="text-gray-400 font-medium">No matching student profiles found.</p>
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
        </div>
      </div>
    </div>
  );
};

window.StudentMaster = StudentMaster;
