const { useState, useEffect, useRef } = React;

const CourseMaster = () => {
  const [courses, setCourses] = useState([]);

  const initialFormState = {
    code: '', name: '', semester: '', scheme: 'K', dept_code: 'CO', abbreviation: '', course_type: 'DSC',
    iks_hrs: 0, cl: '', tl: '', ll: '', sl_hrs: '', notional_hrs: '', credits: '',
    paper_duration: '', fa_th_max: '', fa_th_min: '', sa_th_max: '', sa_th_min: '', th_total_max: '', th_total_min: '',
    fa_pr_max: '', fa_pr_min: '', sa_pr_max: '', sa_pr_min: '', sla_max: '', sla_min: '', total_marks: '',
    th_sa_mode: 'Standard Offline', pr_sa_mode: 'Internal'
  };

  const [form, setForm] = useState(initialFormState);
  const [loading, setLoading] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [selectedCourse, setSelectedCourse] = useState(null);
  
  const [filterScheme, setFilterScheme] = useState('All');
  const [filterDept, setFilterDept] = useState('All');
  const [filterSem, setFilterSem] = useState('All');

  const fileInputRef = useRef(null);

  const courseTypes = ['DSC', 'SEC', 'VEC', 'AEC', 'DSE', 'INP', 'GE'];
  const deptCodes = ['CO', 'IF', 'EJ', 'ME', 'CE', 'EE'];
  const schemes = ['K', 'I'];

  const fetchCourses = () => {
    fetch('/api/courses')
      .then(res => res.json())
      .then(data => setCourses(data))
      .catch(console.error);
  };

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

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

    // Convert to strict payload numbers securely
    const payload = { ...form };
    const numericFields = ['iks_hrs', 'cl', 'tl', 'll', 'sl_hrs', 'notional_hrs', 'credits', 'fa_th_max', 'fa_th_min', 'sa_th_max', 'sa_th_min', 'th_total_max', 'th_total_min', 'fa_pr_max', 'fa_pr_min', 'sa_pr_max', 'sa_pr_min', 'sla_max', 'sla_min', 'total_marks'];
    numericFields.forEach(f => { if (payload[f]) payload[f] = parseInt(payload[f]) || 0; });
    if (payload.paper_duration) payload.paper_duration = parseFloat(payload.paper_duration) || 0;
    if (payload.semester) payload.semester = parseInt(payload.semester) || 1;

    const url = editingId ? `/api/courses/${editingId}` : '/api/courses';
    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(initialFormState);
          setEditingId(null);
          fetchCourses();
        } else alert('Error saving course boundary');
      })
      .catch(() => setLoading(false));
  };

  const handleEdit = (course) => {
    setEditingId(course.id);
    const m = { ...initialFormState, ...course };
    // Map relations locally purely for UI mapping if expanded by Sequelize implicitly
    m.dept_code = course.Department?.dept_code || course.dept_code || 'CO';
    // ensure text representations for numbers when editing to avoid form bugs
    setForm(m);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = (id) => {
    if (!confirm('Are you sure you want to drop this entire course matrix?')) return;
    fetch(`/api/courses/${id}`, { method: 'DELETE' }).then(res => { if (res.ok) fetchCourses(); });
  };

  const handleConditionalClear = () => {
    if (filterScheme === 'All' && filterDept === 'All' && filterSem === 'All') {
        return alert("Please select at least one filter (Scheme, Dept, or Sem) to clear data conditionally.");
    }
    const msg = `Are you absolutely sure you want to clear all courses matching Scheme: ${filterScheme}, Dept: ${filterDept}, Semester: ${filterSem}?`;
    if (!confirm(msg)) return;

    fetch('/api/courses-conditional', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ scheme: filterScheme, dept_code: filterDept, semester: filterSem })
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) alert(data.error);
        else {
            alert(`Cleared ${data.count} courses successfully!`);
            fetchCourses();
        }
    })
    .catch(console.error);
  };


  const handleDownloadTemplate = () => {
    const templateData = [
      {
        code: '314301', name: 'ENVIRONMENTAL ED & SUSTAINABILITY', abbreviation: 'EES', course_type: 'VEC',
        scheme: 'K', dept_code: 'CO', semester: 4, iks_hrs: 2, cl: 3, tl: 0, ll: 0, sl_hrs: 1,
        notional_hrs: 4, credits: 2, paper_duration: 1.5,
        fa_th_max: 30, fa_th_min: 0, sa_th_max: 70, sa_th_min: 40, th_total_max: 100, th_total_min: 40,
        fa_pr_max: 0, fa_pr_min: 0, sa_pr_max: 0, sa_pr_min: 0, sla_max: 25, sla_min: 10, total_marks: 125,
        th_sa_mode: 'Standard Offline', pr_sa_mode: 'Internal'
      },
      {
        code: '[INFO]', name: 'MUST BE EXACT VALUES FOR MODES ->', abbreviation: '', course_type: 'DSC/SEC/VEC/AEC/DSE/INP/GE',
        scheme: 'K or I', dept_code: 'CO/IF/EJ/ME/CE/EE', semester: '1 to 6', iks_hrs: '', cl: '', tl: '', ll: '', sl_hrs: '',
        notional_hrs: '', credits: '', paper_duration: '',
        fa_th_max: '', fa_th_min: '', sa_th_max: '', sa_th_min: '', th_total_max: '', th_total_min: '',
        fa_pr_max: '', fa_pr_min: '', sa_pr_max: '', sa_pr_min: '', sla_max: '', sla_min: '', total_marks: '',
        th_sa_mode: 'Standard Offline / External Online / Internal Online / Not Applicable', 
        pr_sa_mode: 'Internal / External / Not Applicable'
      }
    ];
    const ws = window.XLSX.utils.json_to_sheet(templateData);
    
    for (const key in ws) {
       if (key[0] === '!') continue;
       const cellAddress = window.XLSX.utils.decode_cell(key);
       ws[key].s = { alignment: { vertical: 'center', horizontal: 'center', wrapText: true } };
       if (cellAddress.r === 0) ws[key].s.font = { bold: true };
       if (cellAddress.r === 2) ws[key].s.font = { italic: true, color: { rgb: "555555" } }; // Row index 2 = info row
       ws[key].s.border = { top: {style:'thin'}, bottom: {style:'thin'}, left: {style:'thin'}, right: {style:'thin'} };
    }

    // Set column widths to be wider for the mode columns
    ws['!cols'] = Array(30).fill({wch: 12});
    ws['!cols'][1] = {wch: 35}; // name
    ws['!cols'][28] = {wch: 30}; // th_sa_mode
    ws['!cols'][29] = {wch: 30}; // pr_sa_mode

    const wb = window.XLSX.utils.book_new();
    window.XLSX.utils.book_append_sheet(wb, ws, "K-Scheme Courses");
    window.XLSX.writeFile(wb, "Course_Matrix_Bulk_Upload.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 = window.XLSX.read(bstr, { type: 'binary' });
      const wsname = wb.SheetNames[0];
      const data = window.XLSX.utils.sheet_to_json(wb.Sheets[wsname]);

      if (data.length === 0) return alert("The sheet is empty!");
      if (!confirm(`Bulk import ${data.length} Subject Matrices?`)) return;

      setLoading(true);
      fetch('/api/courses/bulk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ courses: data })
      })
        .then(res => res.json())
        .then(resData => {
          setLoading(false);
          if (resData.error) alert("Error bulk loading: " + resData.error);
          else { alert(`Matrix built for ${resData.count} courses!`); fetchCourses(); }
        })
        .catch(err => { setLoading(false); console.error(err); alert("Failed to parse sheet."); });

      fileInputRef.current.value = "";
    };
    reader.readAsBinaryString(file);
  };

  return (
    <div className="flex flex-col gap-6 animate-fade-in-up pb-12">

      {/* Detail View Modal */}
      {selectedCourse && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm shadow-inner">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-5xl 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">{selectedCourse.name}</h2>
                <span className="text-blue-200 text-sm font-medium tracking-wide">
                  {selectedCourse.code} • {selectedCourse.course_type} • Sem {selectedCourse.semester} • {selectedCourse.scheme} Scheme
                </span>
              </div>
              <button onClick={() => setSelectedCourse(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 style-scrollbar flex flex-col gap-6 bg-gray-50">

              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 shrink-0">
                <div className="bg-white p-4 rounded-xl border border-gray-200 text-center"><p className="text-xs text-gray-500 uppercase tracking-widest font-bold">Total Marks</p><p className="text-3xl font-black text-indigo-700">{selectedCourse.total_marks || '-'}</p></div>
                <div className="bg-white p-4 rounded-xl border border-gray-200 text-center"><p className="text-xs text-gray-500 uppercase tracking-widest font-bold">Credits</p><p className="text-3xl font-black text-emerald-600">{selectedCourse.credits || '-'}</p></div>
                <div className="bg-white p-4 rounded-xl border border-gray-200 text-center"><p className="text-xs text-gray-500 uppercase tracking-widest font-bold">Notional Hrs</p><p className="text-3xl font-black text-blue-600">{selectedCourse.notional_hrs || '-'}</p></div>
                <div className="bg-white p-4 rounded-xl border border-gray-200 text-center"><p className="text-xs text-gray-500 uppercase tracking-widest font-bold">IKS Hrs</p><p className="text-3xl font-black text-amber-600">{selectedCourse.iks_hrs || '0'}</p></div>
              </div>

              <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden shrink-0">
                <h3 className="bg-gray-100 font-bold text-gray-700 px-5 py-3 border-b border-gray-200 flex items-center gap-2"><div className="w-2 h-2 rounded-full bg-blue-500"></div> Learning Scheme (Contact Hrs/Week)</h3>
                <div className="grid grid-cols-4 p-5 divide-x divide-gray-100">
                  <div className="text-center"><span className="block text-xs font-bold text-gray-400 uppercase">Classroom (CL)</span><span className="block text-xl font-bold mt-1 text-gray-800">{selectedCourse.cl || '-'}</span></div>
                  <div className="text-center"><span className="block text-xs font-bold text-gray-400 uppercase">Tutorial (TL)</span><span className="block text-xl font-bold mt-1 text-gray-800">{selectedCourse.tl || '-'}</span></div>
                  <div className="text-center"><span className="block text-xs font-bold text-gray-400 uppercase">Laboratory (LL)</span><span className="block text-xl font-bold mt-1 text-gray-800">{selectedCourse.ll || '-'}</span></div>
                  <div className="text-center"><span className="block text-xs font-bold text-gray-400 uppercase">Self Learn (SL)</span><span className="block text-xl font-bold mt-1 text-gray-800">{selectedCourse.sl_hrs || '-'}</span></div>
                </div>
              </div>

              <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden shrink-0">
                <h3 className="bg-gray-100 font-bold text-gray-700 px-5 py-3 border-b border-gray-200 flex items-center gap-2"><div className="w-2 h-2 rounded-full bg-purple-500"></div> Assessment Scheme Constraint Matrix</h3>
                <div className="p-5 overflow-x-auto">
                  <table className="w-full text-center text-sm border-collapse">
                    <thead>
                      <tr className="bg-gray-50 text-xs uppercase tracking-wider text-gray-500 border-b-2 border-gray-200">
                        <th className="py-2 border-r border-gray-200">Mode</th>
                        <th className="py-2 border-r border-gray-200">Paper (Hrs)</th>
                        <th colSpan="2" className="py-2 border-r border-gray-200 bg-blue-50/50">Formative (FA)</th>
                        <th colSpan="2" className="py-2 border-r border-gray-200 bg-green-50/50">Summative (SA)</th>
                        <th colSpan="2" className="py-2 bg-indigo-50/50">Total Array</th>
                      </tr>
                      <tr className="text-[10px] text-gray-400 font-bold bg-gray-50 border-b border-gray-200">
                        <th className="border-r border-gray-200"></th>
                        <th className="border-r border-gray-200"></th>
                        <th className="py-1 bg-blue-50/50">Max</th><th className="py-1 border-r border-gray-200 bg-blue-50/50">Min</th>
                        <th className="py-1 bg-green-50/50">Max</th><th className="py-1 border-r border-gray-200 bg-green-50/50">Min</th>
                        <th className="py-1 bg-indigo-50/50">Max</th><th className="py-1 bg-indigo-50/50">Min</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr className="border-b border-gray-100 hover:bg-gray-50">
                        <td className="py-3 font-bold text-gray-700 border-r border-gray-200 text-left pl-4">Theory</td>
                        <td className="py-3 border-r border-gray-200">{selectedCourse.paper_duration || '-'}</td>
                        <td className="py-3 font-medium">{selectedCourse.fa_th_max || '-'}</td><td className="py-3 border-r border-gray-200 text-gray-300">N/A</td>
                        <td className="py-3 font-medium"><div className="flex flex-col items-center justify-center"><span>{selectedCourse.sa_th_max || '-'}</span>{selectedCourse.sa_th_max > 0 && selectedCourse.th_sa_mode && selectedCourse.th_sa_mode !== 'Not Applicable' && <span className="text-[8px] bg-gray-100 text-gray-500 rounded px-1 mt-1 font-bold tracking-widest uppercase">{selectedCourse.th_sa_mode === 'Standard Offline' ? 'OFFLINE' : selectedCourse.th_sa_mode === 'External Online' ? 'EXT. ONLINE' : 'INT. ONLINE'}</span>}</div></td><td className="py-3 border-r border-gray-200 text-gray-300">N/A</td>
                        <td className="py-3 font-bold text-indigo-700">{selectedCourse.th_total_max || '-'}</td><td className="py-3 text-indigo-500 font-bold bg-indigo-50/50">{selectedCourse.th_total_min || '-'}</td>
                      </tr>
                      <tr className="border-b border-gray-100 hover:bg-gray-50">
                        <td className="py-3 font-bold text-gray-700 border-r border-gray-200 text-left pl-4">Practical (Sep. Pass)</td>
                        <td className="py-3 border-r border-gray-200 text-gray-300">N/A</td>
                        <td className="py-3 font-medium">{selectedCourse.fa_pr_max || '-'}</td><td className="py-3 border-r border-gray-200 text-gray-400">{selectedCourse.fa_pr_min || '-'}</td>
                        <td className="py-3 font-medium"><div className="flex flex-col items-center justify-center"><span>{selectedCourse.sa_pr_max || '-'}</span>{selectedCourse.sa_pr_max > 0 && selectedCourse.pr_sa_mode && selectedCourse.pr_sa_mode !== 'Not Applicable' && <span className={`text-[8px] rounded px-1 mt-1 font-bold tracking-widest uppercase ${selectedCourse.pr_sa_mode === 'External' ? 'bg-red-100 text-red-600' : 'bg-emerald-100 text-emerald-600'}`}>{selectedCourse.pr_sa_mode === 'External' ? 'EXTERNAL' : 'INTERNAL'}</span>}</div></td><td className="py-3 border-r border-gray-200 text-gray-400">{selectedCourse.sa_pr_min || '-'}</td>
                        <td className="py-3 font-bold text-gray-300" colSpan="2">Aggregated ↑</td>
                      </tr>
                      <tr className="hover:bg-gray-50 bg-gray-50/50">
                        <td className="py-3 font-bold text-amber-700 border-r border-gray-200 text-left pl-4">Self Learning (SLA)</td>
                        <td className="py-3 border-r border-gray-200 text-gray-300">N/A</td>
                        <td className="py-3 font-medium text-amber-600" colSpan="2">SLA Max: <span className="font-bold">{selectedCourse.sla_max || '-'}</span></td>
                        <td className="py-3 font-medium text-amber-600 border-r border-gray-200" colSpan="2">SLA Min: <span className="font-bold bg-amber-100 px-1 rounded">{selectedCourse.sla_min || '-'}</span></td>
                        <td className="py-3 font-bold text-gray-300" colSpan="2">Aggregated ↑</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

            </div>
          </div>
        </div>
      )}

      {/* Main UI Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-5 rounded-2xl shadow-sm border border-gray-200">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 tracking-tight">Course Matrix Master</h1>
          <p className="text-sm text-gray-500 mt-1">Configure structural bounds based on MSBTE scheme guidelines.</p>
        </div>
        <div className="flex items-center gap-3">
          <button onClick={handleDownloadTemplate} className="bg-white border text-blue-700 border-blue-200 px-4 py-2 flex items-center justify-center gap-2 rounded-lg text-sm font-bold shadow-sm hover:bg-blue-50 transition">
            Download Strict Template
          </button>
          <label className="bg-blue-700 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-blue-800 transition">
            Bulk Inject Matrix
            <input type="file" ref={fileInputRef} accept=".xls,.xlsx" className="hidden" onChange={handleFileUpload} />
          </label>
        </div>
      </div>

      <div className="flex flex-col lg:flex-row gap-6">
        {/* ADD COURSE MODULAR FORM */}
        <div className="w-full lg:w-[45%] h-fit flex flex-col gap-5">
          <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
            <h2 className="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2">
              <div className="w-3 h-3 bg-indigo-600 rounded-sm"></div>
              {editingId ? 'Modify Schema Grid' : 'Construct Course Identity'}
            </h2>

            <form onSubmit={handleSubmit} className="space-y-6">

              {/* Identity Group */}
              <div className="p-4 bg-gray-50 rounded-xl border border-gray-100 space-y-4">
                <h3 className="text-xs font-bold text-gray-400 uppercase tracking-widest border-b border-gray-200 pb-2">1. Identity Vectors</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Course Code</label>
                    <input required type="text" value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} className="w-full px-3 py-2 bg-white border border-gray-200 text-sm rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="e.g. 314301" />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Abbreviation</label>
                    <input type="text" value={form.abbreviation} onChange={e => setForm({ ...form, abbreviation: e.target.value })} className="w-full px-3 py-2 bg-white border border-gray-200 text-sm rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="e.g. EES" />
                  </div>
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Full Course Title</label>
                  <input required type="text" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} className="w-full px-3 py-2 bg-white border border-gray-200 text-sm rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="e.g. ENVIRONMENTAL ED & SUSTAINABILITY" />
                </div>
                <div className="grid grid-cols-4 gap-3">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Scheme</label>
                    <select value={form.scheme} onChange={e => setForm({ ...form, scheme: e.target.value })} className="w-full px-3 py-2 text-sm bg-white border border-gray-200 rounded-lg"><option>I</option><option>K</option></select>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Type</label>
                    <select value={form.course_type} onChange={e => setForm({ ...form, course_type: e.target.value })} className="w-full px-3 py-2 text-sm bg-white border border-gray-200 rounded-lg">{courseTypes.map(c => <option key={c}>{c}</option>)}</select>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Sem</label>
                    <input type="number" required value={form.semester} onChange={e => setForm({ ...form, semester: e.target.value })} className="w-full px-3 py-2 text-sm bg-white border border-gray-200 rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 mb-1 uppercase">Dept</label>
                    <select value={form.dept_code} onChange={e => setForm({ ...form, dept_code: e.target.value })} className="w-full px-3 py-2 text-sm bg-white border border-gray-200 rounded-lg">{deptCodes.map(c => <option key={c}>{c}</option>)}</select>
                  </div>
                </div>
              </div>

              {/* Learning Scheme Group */}
              <div className="p-4 bg-blue-50 rounded-xl border border-blue-100 space-y-4">
                <h3 className="text-xs font-bold text-blue-400 uppercase tracking-widest border-b border-blue-200 pb-2">2. Learning Scheme (Hrs/Wk)</h3>
                <div className="grid grid-cols-5 gap-2">
                  <div><label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">CL</label><input type="number" value={form.cl} onChange={e => setForm({ ...form, cl: e.target.value })} className="w-full px-2 py-1 text-xs border border-blue-200 rounded bg-white text-center" /></div>
                  <div><label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">TL</label><input type="number" value={form.tl} onChange={e => setForm({ ...form, tl: e.target.value })} className="w-full px-2 py-1 text-xs border border-blue-200 rounded bg-white text-center" /></div>
                  <div><label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">LL</label><input type="number" value={form.ll} onChange={e => setForm({ ...form, ll: e.target.value })} className="w-full px-2 py-1 text-xs border border-blue-200 rounded bg-white text-center" /></div>
                  <div><label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">SL</label><input type="number" value={form.sl_hrs} onChange={e => setForm({ ...form, sl_hrs: e.target.value })} className="w-full px-2 py-1 text-xs border border-blue-200 rounded bg-white text-center" /></div>
                  <div><label className="block text-[10px] font-bold text-amber-500 mb-1 uppercase">IKS</label><input type="number" value={form.iks_hrs} onChange={e => setForm({ ...form, iks_hrs: e.target.value })} className="w-full px-2 py-1 text-xs border border-amber-200 rounded bg-white text-center" /></div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div><label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">Notional Learning Hrs</label><input type="number" value={form.notional_hrs} onChange={e => setForm({ ...form, notional_hrs: e.target.value })} className="w-full px-3 py-1.5 text-sm border border-blue-200 rounded bg-white" /></div>
                  <div><label className="block text-[10px] font-bold text-blue-500 mb-1 uppercase">Total Credits</label><input type="number" value={form.credits} onChange={e => setForm({ ...form, credits: e.target.value })} className="w-full px-3 py-1.5 text-sm border border-blue-200 rounded bg-white text-emerald-600 font-bold" /></div>
                </div>
              </div>

              {/* Assessment Scheme Group */}
              <div className="p-4 bg-green-50 rounded-xl border border-green-100 space-y-4">
                <div className="flex justify-between items-center border-b border-green-200 pb-2">
                  <h3 className="text-xs font-bold text-green-500 uppercase tracking-widest">3. Assessment Scheme Grid</h3>
                </div>

                {/* Theory / Practical / SLA Sections */}
                <div className="space-y-4">
                  {/* Theory */}
                  <div className="p-3 bg-white border border-gray-200 rounded-lg shadow-sm">
                    <div className="flex justify-between items-center mb-2">
                      <h4 className="text-xs font-bold text-indigo-600 uppercase">3.1 Theory Assessment</h4>
                      <div className="flex items-center gap-2"><label className="text-[10px] font-bold text-gray-500 uppercase">Paper Hrs</label><input type="number" step="0.5" value={form.paper_duration} onChange={e => setForm({ ...form, paper_duration: e.target.value })} className="w-16 px-2 py-1 text-xs rounded border border-indigo-200 bg-indigo-50/50" /></div>
                    </div>
                    <div className="grid grid-cols-3 gap-3">
                      <div className="space-y-1"><label className="block text-[10px] font-bold text-gray-500 uppercase">Formative (FA)</label><div className="grid grid-cols-2 gap-1"><input placeholder="Max" value={form.fa_th_max} onChange={e => setForm({ ...form, fa_th_max: e.target.value })} className="w-full px-2 py-1 text-xs rounded border" /><input disabled value="N/A" className="w-full px-2 py-1 text-xs rounded border bg-gray-50 text-gray-400 text-center cursor-not-allowed" /></div></div>
                      <div className="space-y-1"><label className="block text-[10px] font-bold text-gray-500 uppercase">Summative (SA)</label><div className="grid grid-cols-2 gap-1"><input placeholder="Max" value={form.sa_th_max} onChange={e => setForm({ ...form, sa_th_max: e.target.value })} className="w-full px-2 py-1 text-xs rounded border" /><input disabled value="N/A" className="w-full px-2 py-1 text-xs rounded border bg-gray-50 text-gray-400 text-center cursor-not-allowed" /></div><select value={form.th_sa_mode} onChange={e => setForm({ ...form, th_sa_mode: e.target.value })} className="w-full px-1 py-1 text-[10px] uppercase font-bold text-gray-600 rounded border border-gray-200 bg-gray-50 outline-none"><option>Standard Offline</option><option>External Online</option><option>Internal Online</option><option>Not Applicable</option></select></div>
                      <div className="space-y-1"><label className="block text-[10px] font-bold text-indigo-500 uppercase">Total (Comb. Pass)</label><div className="grid grid-cols-2 gap-1"><input placeholder="Max" value={form.th_total_max} onChange={e => setForm({ ...form, th_total_max: e.target.value })} className="w-full px-2 py-1 text-xs rounded border border-indigo-200" /><input placeholder="Min" value={form.th_total_min} onChange={e => setForm({ ...form, th_total_min: e.target.value })} className="w-full px-2 py-1 text-xs rounded border border-indigo-500 bg-indigo-50 outline-indigo-500" /></div></div>
                    </div>
                  </div>

                  {/* Practical */}
                  <div className="p-3 bg-white border border-gray-200 rounded-lg shadow-sm">
                    <h4 className="text-xs font-bold text-emerald-600 uppercase mb-2">3.2 Practical Assessment</h4>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1"><label className="block text-[10px] font-bold text-gray-500 uppercase">Formative (FA) Max/Min</label><div className="grid grid-cols-2 gap-2"><input placeholder="Max" value={form.fa_pr_max} onChange={e => setForm({ ...form, fa_pr_max: e.target.value })} className="w-full px-2 py-1 text-xs rounded border" /><input placeholder="Min (Req)" value={form.fa_pr_min} onChange={e => setForm({ ...form, fa_pr_min: e.target.value })} className="w-full px-2 py-1 text-xs rounded border outline-emerald-500 border-emerald-300 bg-emerald-50/50" /></div></div>
                      <div className="space-y-1"><label className="block text-[10px] font-bold text-gray-500 uppercase">Summative (SA) Max/Min</label><div className="grid grid-cols-2 gap-2"><input placeholder="Max" value={form.sa_pr_max} onChange={e => setForm({ ...form, sa_pr_max: e.target.value })} className="w-full px-2 py-1 text-xs rounded border" /><input placeholder="Min (Req)" value={form.sa_pr_min} onChange={e => setForm({ ...form, sa_pr_min: e.target.value })} className="w-full px-2 py-1 text-xs rounded border outline-emerald-500 border-emerald-300 bg-emerald-50/50" /></div><select value={form.pr_sa_mode} onChange={e => setForm({ ...form, pr_sa_mode: e.target.value })} className="w-full px-1 py-1 text-[10px] uppercase font-bold text-emerald-700 bg-emerald-50 border border-emerald-200 rounded outline-none shadow-sm"><option value="Internal">Internal Assess (@)</option><option value="External">External Assess (#)</option><option>Not Applicable</option></select></div>
                    </div>
                  </div>

                  {/* SLA */}
                  <div className="p-3 bg-white border border-gray-200 rounded-lg shadow-sm">
                    <h4 className="text-xs font-bold text-amber-600 uppercase mb-2">3.3 Self Learning (SLA)</h4>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1"><label className="block text-[10px] font-bold text-gray-500 uppercase">SLA Max/Min Constraints</label><div className="grid grid-cols-2 gap-2"><input placeholder="Max" value={form.sla_max} onChange={e => setForm({ ...form, sla_max: e.target.value })} className="w-full px-2 py-1 text-xs rounded border" /><input placeholder="Min (Req)" value={form.sla_min} onChange={e => setForm({ ...form, sla_min: e.target.value })} className="w-full px-2 py-1 text-xs rounded border outline-amber-500 border-amber-300 bg-amber-50" /></div></div>
                    </div>
                  </div>
                </div>

                <div className="pt-2">
                  <label className="block text-[10px] font-bold text-green-700 mb-1 uppercase">Absolute Total Marks</label>
                  <input type="number" required value={form.total_marks} onChange={e => setForm({ ...form, total_marks: e.target.value })} className="w-full px-3 py-2 text-sm rounded bg-white border border-green-400 font-bold shadow-inner" placeholder="e.g. 150" />
                </div>
              </div>

              <div className="flex gap-3">
                <button disabled={loading} type="submit" className="flex-1 bg-gray-900 hover:bg-black text-white font-bold py-3 rounded-xl shadow disabled:opacity-50 transition tracking-wide">
                  {loading ? 'Locking Matrix...' : (editingId ? 'Modify Matrix' : 'Assemble Grid')}
                </button>
                {editingId && (
                  <button type="button" onClick={() => { setEditingId(null); setForm(initialFormState); }} className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-3 rounded-xl shadow transition tracking-wide">
                    Cancel Edit
                  </button>
                )}
              </div>
            </form>
          </div>
        </div>

        {/* COMPACT DIRECTORY VIEW */}
        <div className="w-full lg:w-[55%] h-fit flex flex-col gap-4">
          {/* UI FILTERS SECTION */}
          <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 Network Grid</h2>
             <div className="flex items-end gap-3 flex-wrap">
                 <div className="flex-1 min-w-[120px]">
                    <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 className="flex-1 min-w-[120px]">
                    <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 className="flex-1 min-w-[120px]">
                    <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>
             <button onClick={handleConditionalClear} className="w-full mt-2 bg-red-50 hover:bg-red-500 text-red-600 hover:text-white border border-red-200 transition px-4 py-2 text-sm font-bold rounded flex items-center justify-center gap-2">
                 <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>
                 Clear Filtered Scope Data
             </button>
          </div>

          <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden flex flex-col">
            <div className="px-5 py-4 border-b border-gray-100 bg-gray-50 flex justify-between items-center shrink-0">
              <h2 className="text-lg font-bold text-gray-800 tracking-tight">Active Matrix Definitions</h2>
              <span className="text-[10px] uppercase tracking-widest bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded-full shadow-inner">{courses.length} Grid Nodes</span>
            </div>
            <div className="overflow-x-auto w-full">
              <table className="w-full text-left whitespace-nowrap">
                <thead className="bg-gray-100/50 text-gray-500 font-bold uppercase text-[10px] tracking-widest border-b border-gray-200">
                  <tr>
                    <th className="px-4 py-3">Subject ID</th>
                    <th className="px-4 py-3 text-center">Structure</th>
                    <th className="px-4 py-3 text-center">Values</th>
                    <th className="px-4 py-3 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {courses.filter(c => {
                      if (filterScheme !== 'All' && c.scheme !== filterScheme) return false;
                      if (filterSem !== 'All' && String(c.semester) !== String(filterSem)) return false;
                      // Mapping to dept_code safely (it is mapped locally inside course.Department or implicit db join)
                      const dCode = c.Department?.dept_code || c.dept_code;
                      if (filterDept !== 'All' && dCode !== filterDept) return false;
                      return true;
                  }).map(s => (
                    <tr key={s.id} className="hover:bg-blue-50/30 transition text-sm">
                      <td className="px-4 py-3">
                        <div className="font-bold text-gray-900 truncate max-w-[180px]">{s.name}</div>
                        <div className="text-[10px] font-mono text-gray-500 mt-1">{s.code} • {s.abbreviation || 'N/A'}</div>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className="font-bold text-gray-700">{s.scheme || 'N/A'} Sch.</span><span className="text-gray-300 mx-1">|</span>Sem {s.semester}
                        <div className="text-[10px] font-bold text-indigo-600 bg-indigo-50 mt-1 mx-auto w-fit px-2 py-0.5 rounded uppercase">{s.course_type}</div>
                      </td>
                      <td className="px-4 py-3 text-center text-[10px] font-bold">
                        <div className="text-emerald-600">{s.credits || 0} Credits</div>
                        <div className="text-gray-500 mt-1">{s.total_marks || 0} Marks</div>
                      </td>
                      <td className="px-4 py-3 text-right space-x-2">
                        <button onClick={() => setSelectedCourse(s)} className="text-indigo-600 hover:text-white hover:bg-indigo-600 border border-indigo-600 bg-white font-bold text-[10px] px-2 py-1 rounded uppercase transition tracking-wider">Inspect</button>
                        <button onClick={() => handleEdit(s)} className="text-blue-500 hover:text-white hover:bg-blue-500 border border-transparent hover:border-blue-500 font-bold text-[10px] px-2 py-1 rounded uppercase transition tracking-wider">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-2 py-1 rounded uppercase transition tracking-wider">Drop</button>
                      </td>
                    </tr>
                  ))}
                  {courses.filter(c => {
                      if (filterScheme !== 'All' && c.scheme !== filterScheme) return false;
                      if (filterSem !== 'All' && String(c.semester) !== String(filterSem)) return false;
                      const dCode = c.Department?.dept_code || c.dept_code;
                      if (filterDept !== 'All' && dCode !== filterDept) return false;
                      return true;
                  }).length === 0 && (
                    <tr><td colSpan="4" className="text-center py-12 text-gray-400 italic text-sm">No course matrices match criteria.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.CourseMaster = CourseMaster;
