const { useState, useEffect, useRef, useMemo } = React;

const DateField = ({ value, onChange, className }) => {
   const formatted = value ? value.split('-').reverse().join('-') : '';
   return (
      <div className="relative w-full group">
         <input 
             type="text" 
             value={formatted} 
             readOnly 
             placeholder="DD-MM-YYYY" 
             className={className} 
         />
         <input 
             type="date" 
             value={value || ''} 
             onChange={onChange} 
             className="absolute inset-0 opacity-0 cursor-pointer w-full h-full" 
         />
         <div className="absolute right-0 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400 group-hover:text-blue-500">
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
         </div>
      </div>
   );
};

const LP_STORAGE_KEY = 'lessonPlanFilters';

window.LessonPlanMaster = function LessonPlanMaster({ currentUser }) {
  const [exams, setExams] = useState([]);
  
  const savedFilters = (() => { try { return JSON.parse(localStorage.getItem(LP_STORAGE_KEY)) || {}; } catch(e) { return {}; } })();
  const [selectedCourse, setSelectedCourse] = useState(savedFilters.course || '');
  const [courseSearchQuery, setCourseSearchQuery] = useState('');
  const [selectedExam, setSelectedExam] = useState(savedFilters.exam || '');
  const [copyFromExam, setCopyFromExam] = useState('');
  
  const [plans, setPlans] = useState([]);
  const [loading, setLoading] = useState(false);
  const initialLoadDone = useRef(false);
  const [isGrouped, setIsGrouped] = useState(true);

  const { filteredCourses: baseCourses, departments, loading: filterLoading } = window.useCourseFilter(exams, selectedExam, currentUser, 'Theory');
  const [selectedDept, setSelectedDept] = useState('All');

  const courses = useMemo(() => {
    return baseCourses.filter(c => {
      if (parseFloat(c.fa_th_max) <= 0 && parseFloat(c.sa_th_max) <= 0) return false;
      if (selectedDept && selectedDept !== 'All' && String(c.dept_id) !== String(selectedDept)) return false;
      return true;
    });
  }, [baseCourses, selectedDept]);

  const [showAutoDateModal, setShowAutoDateModal] = useState(false);
  const [dbHolidays, setDbHolidays] = useState([]);
  const [autoDateConfig, setAutoDateConfig] = useState({
      startDate: '',
      endDate: '',
      weekdays: [], 
      holidayDate: '',
      holidayName: '',
      holidayLevel: 'Institute'
  });

  useEffect(() => {
    if (initialLoadDone.current && selectedCourse && selectedExam) {
      try {
        localStorage.setItem(LP_STORAGE_KEY, JSON.stringify({ course: selectedCourse, exam: selectedExam }));
      } catch(e) {}
    }
  }, [selectedCourse, selectedExam]);

  useEffect(() => {
    Promise.all([
      fetch(`/api/exams`).then(r => r.json())
    ]).then(([examData]) => {
      setExams(examData);
      const saved = (() => { try { return JSON.parse(localStorage.getItem(LP_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);
      if (examData.length > 0) setCopyFromExam(examData[0].id);
    }).catch(err => console.error(err));
  }, []);

  useEffect(() => {
    if (courses.length > 0 && (!selectedCourse || !courses.find(c => String(c.id) === String(selectedCourse)))) {
      const saved = (() => { try { return JSON.parse(localStorage.getItem(LP_STORAGE_KEY)) || {}; } catch(e) { return {}; } })();
      if (saved.course && courses.find(c => String(c.id) === String(saved.course))) {
        setSelectedCourse(saved.course);
      } else setSelectedCourse(courses[0].id);
    }
  }, [courses, selectedCourse]);

  useEffect(() => {
      if (!initialLoadDone.current && courses.length > 0 && selectedCourse && selectedExam) {
         initialLoadDone.current = true;
         const saved = (() => { try { return JSON.parse(localStorage.getItem(LP_STORAGE_KEY)) || {}; } catch(e) { return {}; } })();
         if (saved.course === selectedCourse && saved.exam === selectedExam) {
            setTimeout(fetchPlan, 300);
         }
      }
  }, [courses, 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);
      }
    }
  }, [courseSearchQuery]);

  useEffect(() => {
    try {
      const saved = localStorage.getItem('ciaan_autoDatePref');
      if (saved) {
        const parsed = JSON.parse(saved);
        setAutoDateConfig(prev => ({
          ...prev,
          startDate: parsed.startDate || '',
          endDate: parsed.endDate || '',
          weekdays: parsed.weekdays || []
        }));
      }
    } catch(e) {}
  }, []);

  const formatTextWithNewlines = (text, type) => {
    if (!text) return '';
    let formatted = String(text);
    if (type === 'tlo') {
      formatted = formatted.replace(/,\s*(?=TLO\b)/gi, '\n');
      formatted = formatted.replace(/(^|[^\n])(TLO\s*\d+\.\d+)/gi, '$1\n$2');
    } else if (type === 'topic') {
      formatted = formatted.replace(/,\s*(?=\d+\.\d+\b)/g, '\n');
      formatted = formatted.replace(/(^|[^\n])(\d+\.\d+\s+)/g, '$1\n$2');
    }
    return formatted.replace(/\n+/g, '\n').trim();
  };

  const fetchPlan = () => {
    if(!selectedCourse || !selectedExam) return alert("Select Term and Course first.");
    setLoading(true);
    fetch(`/api/lesson-plans?exam_id=${selectedExam}&course_id=${selectedCourse}`)
      .then(res => res.json())
      .then(data => {
         if(data.length > 0) {
            setPlans(data.map(p => ({
               ...p,
               tlo_aligned: formatTextWithNewlines(p.tlo_aligned, 'tlo'),
               topic_title: formatTextWithNewlines(p.topic_title, 'topic')
            })));
         }
         else setPlans([]);
         setLoading(false);
      });
  };

  const handleCopyFromExam = () => {
     if(!selectedCourse || !copyFromExam) return alert("Select a Term and Course to copy from");
     if(copyFromExam === selectedExam) return alert("Cannot copy from the same active term.");
     setLoading(true);
     fetch(`/api/lesson-plans?exam_id=${copyFromExam}&course_id=${selectedCourse}`)
       .then(r=>r.json())
       .then(data => {
          if(data.length > 0) {
              const freshCopy = data.map(d => ({
                unit_no: d.unit_no,
                topic_title: formatTextWithNewlines(d.topic_title, 'topic'),
                co_mapped: d.co_mapped,
                tlo_aligned: formatTextWithNewlines(d.tlo_aligned, 'tlo'),
                allocated_hrs: d.allocated_hrs,
                planned_lectures: d.planned_lectures,
                planned_from_date: '',
                planned_to_date: '',
                actual_from_date: '',
                actual_to_date: '',
                actual_lectures: '',
                pedagogy_used: d.pedagogy_used,
                remarks: d.remarks
              }));
              if (plans.length > 0) {
                 if(window.confirm("Overwrite current grid with lesson plans from selected term?")) {
                    setPlans(freshCopy);
                 }
              } else setPlans(freshCopy);
          } else {
              alert("No lesson plan found for the selected Source Term to copy from.");
          }
          setLoading(false);
       });
  };

  const handleFetchFromSyllabus = () => {
     if(!selectedCourse) return alert("Select a Course first.");
     const c = courses.find(x => String(x.id) === String(selectedCourse));
     let units = (c && c.syllabus_units && Array.isArray(c.syllabus_units) && c.syllabus_units.length > 0) ? c.syllabus_units : null;

     // Fallback: Check baseCourses for any sister branch with same course code that has syllabus units
     if(!units && c) {
        const sister = baseCourses.find(x => x.code === c.code && Array.isArray(x.syllabus_units) && x.syllabus_units.length > 0);
        if(sister) units = sister.syllabus_units;
     }

     if(units && Array.isArray(units) && units.length > 0) {
        if(plans.length > 0 && !window.confirm("Overwrite current grid with AI-extracted syllabus units?")) {
           return;
        }
        const freshCopy = units.map(d => ({
           unit_no: d.unit_no || '',
           topic_title: formatTextWithNewlines(d.topic_title || '', 'topic'),
           co_mapped: d.co_mapped || '',
           tlo_aligned: formatTextWithNewlines(d.tlo_aligned || '', 'tlo'),
           allocated_hrs: d.allocated_hrs || d.planned_lectures || '',
           planned_lectures: d.planned_lectures || d.allocated_hrs || '',
           actual_from_date: '',
           actual_to_date: '',
           actual_lectures: '',
           pedagogy_used: d.pedagogy_used || '',
           remarks: ''
        }));
        setPlans(freshCopy);
     } else {
        alert("No syllabus units found for this subject. Ensure you have extracted this syllabus via Curriculum Master.");
     }
  };

  const handleAddRow = () => {
     setPlans([...plans, { unit_no: plans.length + 1, topic_title: '', co_mapped: '', tlo_aligned: '', allocated_hrs: '', planned_lectures: '', planned_from_date: '', planned_to_date: '', actual_from_date: '', actual_to_date: '', actual_lectures: '', pedagogy_used: '', remarks: '' }]);
  };

  const handleChange = (index, field, value) => {
     let newPlans = [...plans];
     const targetUnit = newPlans[index].unit_no;
     const groupedFields = ['allocated_hrs', 'planned_lectures', 'planned_from_date', 'planned_to_date', 'actual_from_date', 'actual_to_date', 'actual_lectures', 'pedagogy_used', 'remarks'];

     if (isGrouped && groupedFields.includes(field)) {
         newPlans.forEach((p, i) => {
            if (p.unit_no === targetUnit) {
               if (field === 'planned_lectures' || field === 'actual_lectures') {
                  const firstIdx = newPlans.findIndex(x => x.unit_no === targetUnit);
                  if (i === firstIdx) p[field] = value;
                  else p[field] = '';
               } else {
                  p[field] = value;
               }
            }
         });
     } else {
         newPlans[index][field] = value;
     }

     // Auto-update Unit Hrs to sum of planned_lectures
     if (field === 'planned_lectures') {
         const unitTotal = newPlans.filter(x => x.unit_no === targetUnit).reduce((sum, x) => sum + (parseInt(x.planned_lectures) || 0), 0);
         newPlans.forEach(x => {
             if (x.unit_no === targetUnit) {
                 x.allocated_hrs = unitTotal;
             }
         });
     }

     // RIPPLE CALCULATION FOR DATES
     if (field === 'planned_lectures' || field === 'planned_from_date') {
         let pref = { weekdays: [1,2,3,4,5,6] }; // default Mon-Sat
         try {
             const stored = localStorage.getItem('ciaan_autoDatePref');
             if (stored) {
                 const p = JSON.parse(stored);
                 if (p.weekdays && p.weekdays.length > 0) pref = p;
             }
         } catch(e) {}

         // Determine which rows to ripple. If grouped, ripple from the start of the target unit.
         let startIndex = index;
         if (isGrouped) {
             startIndex = newPlans.findIndex(p => p.unit_no === targetUnit);
         }

         let currentDate = newPlans[startIndex].planned_from_date ? new Date(newPlans[startIndex].planned_from_date) : null;
         
         if (currentDate && !isNaN(currentDate.getTime())) {
             currentDate.setHours(0,0,0,0);
             
             // Loop through from startIndex to the end sequentially
             for (let i = startIndex; i < newPlans.length; i++) {
                 // In grouped mode, only calculate for the first row of each unit, then copy to the rest
                 const isFirstOfUnit = i === 0 || newPlans[i].unit_no !== newPlans[i-1].unit_no;
                 if (isGrouped && !isFirstOfUnit) {
                     // Just copy from the first of this unit
                     const firstIdx = newPlans.findIndex(p => p.unit_no === newPlans[i].unit_no);
                     newPlans[i].planned_from_date = newPlans[firstIdx].planned_from_date;
                     newPlans[i].planned_to_date = newPlans[firstIdx].planned_to_date;
                     continue;
                 }

                 if (i > startIndex) {
                     newPlans[i].planned_from_date = `${currentDate.getFullYear()}-${String(currentDate.getMonth()+1).padStart(2,'0')}-${String(currentDate.getDate()).padStart(2,'0')}`;
                 }

                 const requiredHrs = isGrouped ? newPlans.filter(x => x.unit_no === newPlans[i].unit_no).reduce((s, x) => s + (parseInt(x.planned_lectures)||0), 0) : parseInt(newPlans[i].planned_lectures || 0);
                 if (requiredHrs <= 0) continue;

                 let hrsFound = 0;
                 let toDateStr = newPlans[i].planned_from_date;
                 let fromDateFound = false;

                 // Fast forward to a valid start date if the provided one is a holiday or invalid day
                 while (hrsFound < requiredHrs) {
                     const day = currentDate.getDay();
                     const y = currentDate.getFullYear();
                     const m = String(currentDate.getMonth() + 1).padStart(2, '0');
                     const d = String(currentDate.getDate()).padStart(2, '0');
                     const dateStr = `${y}-${m}-${d}`;
                     
                     const isHoliday = dbHolidays.some(h => h.date === dateStr);

                     if (pref.weekdays.includes(day) && !isHoliday) {
                         const dayCount = pref.weekdays.filter(dd => dd === day).length;
                         for (let lect = 0; lect < dayCount && hrsFound < requiredHrs; lect++) {
                             if (hrsFound === 0) {
                                 newPlans[i].planned_from_date = dateStr;
                                 if (i === startIndex || !newPlans[i].actual_from_date) {
                                     newPlans[i].actual_from_date = dateStr;
                                 }
                                 fromDateFound = true;
                             }
                             toDateStr = dateStr;
                             hrsFound++;
                         }
                     }
                     if (hrsFound < requiredHrs) {
                         currentDate.setDate(currentDate.getDate() + 1);
                     }
                 }

                 newPlans[i].planned_to_date = toDateStr;
                 newPlans[i].actual_to_date = toDateStr;

                 // Move to next day for the next row
                 currentDate.setDate(currentDate.getDate() + 1);
                 
                 // Fast forward to next valid working day for the start of the NEXT row
                 while(true) {
                    const nday = currentDate.getDay();
                    const ny = currentDate.getFullYear();
                    const nm = String(currentDate.getMonth() + 1).padStart(2, '0');
                    const nd = String(currentDate.getDate()).padStart(2, '0');
                    const nDateStr = `${ny}-${nm}-${nd}`;
                    if (pref.weekdays.includes(nday) && !dbHolidays.some(h => h.date === nDateStr)) {
                        break;
                    }
                    currentDate.setDate(currentDate.getDate() + 1);
                 }
             }
         }
     }
     
     setPlans(newPlans);
  };
  
  const handleDeleteRow = (index) => {
     const newPlans = plans.filter((_, i) => i !== index);
     const adjusted = newPlans.map((p, i) => ({...p, unit_no: i + 1}));
     setPlans(adjusted);
  };

  const handleClearBoard = () => {
     if(window.confirm("Are you sure you want to clear the entire matrix? Ensure you click 'Commit & Lock Plan' afterward to delete it from the database.")) {
         setPlans([]);
     }
  };

  const handleSave = () => {
     if(!selectedCourse || !selectedExam) return alert("Select Term and Course");
     
     setLoading(true);
     fetch(`/api/lesson-plans`, {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({ exam_id: selectedExam, course_id: selectedCourse, plans })
     })
     .then(res => res.json())
     .then(data => {
         setLoading(false);
         if(data.success) alert("Lesson Plan synchronized successfully!");
     }).catch(err => { setLoading(false); alert("Failed saving"); });
  };

  // HOLIDAYS FETCH
  useEffect(() => {
    if (selectedCourse) {
       const fetchCb = async () => {
          try {
             const courseRes = await fetch(`/api/courses`);
             const allCourses = await courseRes.json();
             const c = allCourses.find(x => x.id === selectedCourse);
             
             let q = `?course_id=${selectedCourse}`;
             if (c && c.dept_id) q += `&dept_id=${c.dept_id}`;
             
             const hRes = await fetch(`/api/holidays${q}`);
             if (hRes.ok) {
                const holidays = await hRes.json();
                setDbHolidays(holidays);
             }
          } catch(e) { console.error('Failed fetching holidays', e); }
       };
       fetchCb();
    }
  }, [selectedCourse]);

  const handleAddHoliday = async () => {
    if(!autoDateConfig.holidayDate || !autoDateConfig.holidayName) return alert('Date and Name required');
    try {
      const c = courses.find(x => x.id === selectedCourse);
      const payload = {
         date: autoDateConfig.holidayDate,
         name: autoDateConfig.holidayName,
         level: autoDateConfig.holidayLevel,
         course_id: autoDateConfig.holidayLevel === 'Individual' ? selectedCourse : null,
         dept_id: autoDateConfig.holidayLevel === 'Department' ? (c?.dept_id || null) : null,
         institute_id: currentUser?.institute_id
      };

      const res = await fetch(`/api/holidays`, {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify(payload)
      });
      if (res.ok) {
         const newH = await res.json();
         setDbHolidays([...dbHolidays, newH]);
         setAutoDateConfig({...autoDateConfig, holidayDate: '', holidayName: ''});
      } else {
         alert('Failed to save holiday');
      }
    } catch(e) { console.error(e); }
  };

  const handleRemoveHoliday = async (id) => {
    try {
       await fetch(`/api/holidays/${id}`, { method: 'DELETE' });
       setDbHolidays(dbHolidays.filter(h => h.id !== id));
    } catch(e) { console.error(e); }
  };

  const handleAddWeekday = (dayIdx) => {
    setAutoDateConfig(prev => ({...prev, weekdays: [...prev.weekdays, dayIdx].sort((a,b) => a-b)}));
  };

  const handleRemoveWeekday = (arrayIdxToRemove) => {
    setAutoDateConfig(prev => ({
       ...prev, 
       weekdays: prev.weekdays.filter((_, i) => i !== arrayIdxToRemove)
    }));
  };

  const handleAutoMapSubmit = () => {
      if(!autoDateConfig.startDate || !autoDateConfig.endDate) return alert("Select Start and End dates");
      if(autoDateConfig.weekdays.length === 0) return alert("Select at least one valid weekday");
      
      try {
        localStorage.setItem('ciaan_autoDatePref', JSON.stringify({
          startDate: autoDateConfig.startDate,
          endDate: autoDateConfig.endDate,
          weekdays: autoDateConfig.weekdays
        }));
      } catch (e) {}

      let currentDate = new Date(autoDateConfig.startDate);
      const end = new Date(autoDateConfig.endDate);
      
      currentDate.setHours(0,0,0,0);
      end.setHours(0,0,0,0);
      
      const newPlans = [...plans];
      
      // We process unit by unit. We need X valid dates per unit where X = allocated_hrs
      let planIndex = 0;
      let remainingLecturesOnCurrentDay = 0;
      
      while (currentDate <= end && planIndex < newPlans.length) {
         const isFirstOfUnit = planIndex === 0 || newPlans[planIndex].unit_no !== newPlans[planIndex-1].unit_no;
         if (isGrouped && !isFirstOfUnit) {
             const firstIdx = newPlans.findIndex(p => p.unit_no === newPlans[planIndex].unit_no);
             newPlans[planIndex].planned_from_date = newPlans[firstIdx].planned_from_date;
             newPlans[planIndex].planned_to_date = newPlans[firstIdx].planned_to_date;
             planIndex++;
             continue;
         }

         let requiredHrs = isGrouped ? newPlans.filter(x => x.unit_no === newPlans[planIndex].unit_no).reduce((s, x) => s + (parseInt(x.planned_lectures)||0), 0) : parseInt(newPlans[planIndex].planned_lectures || 0);
         
         if (requiredHrs <= 0) {
            planIndex++;
            continue;
         }

         let hrsFound = 0;
         let fromDateStr = null;
         let toDateStr = null;

         while (currentDate <= end && hrsFound < requiredHrs) {
            const day = currentDate.getDay();
            const y = currentDate.getFullYear();
            const m = String(currentDate.getMonth() + 1).padStart(2, '0');
            const d = String(currentDate.getDate()).padStart(2, '0');
            const dateStr = `${y}-${m}-${d}`;
            
            const isHoliday = dbHolidays.some(h => h.date === dateStr);

            if (autoDateConfig.weekdays.includes(day) && !isHoliday) {
               if (remainingLecturesOnCurrentDay === 0) {
                   remainingLecturesOnCurrentDay = autoDateConfig.weekdays.filter(dd => dd === day).length;
               }

               while (remainingLecturesOnCurrentDay > 0 && hrsFound < requiredHrs) {
                   if (hrsFound === 0) fromDateStr = dateStr;
                   toDateStr = dateStr;
                   hrsFound++;
                   remainingLecturesOnCurrentDay--;
               }
            }
            if (hrsFound < requiredHrs) {
               currentDate.setDate(currentDate.getDate() + 1);
               remainingLecturesOnCurrentDay = 0;
            }
         }

         if (hrsFound === requiredHrs) {
             newPlans[planIndex].planned_from_date = fromDateStr;
             newPlans[planIndex].planned_to_date = toDateStr;
             planIndex++;
             if (remainingLecturesOnCurrentDay === 0) {
                 currentDate.setDate(currentDate.getDate() + 1);
             }
         } else {
            // Not enough days left in term for this unit
            break;
         }
      }
      
      setPlans(newPlans);
      setShowAutoDateModal(false);
      if (planIndex < newPlans.length) {
         alert(`Warning: Only enough valid dates to schedule up to Unit ${planIndex}. Choose a longer range, more weekdays, or adjust allocated hours.`);
      }
  };

  const handleExportExcel = () => {
    if (!selectedCourse || !selectedExam) return alert('Select Term and Course first.');
    if (plans.length === 0) return alert('No plans to export!');
    
    const courseObj = courses.find(c => String(c.id) === String(selectedCourse));
    const examObj = exams.find(e => String(e.id) === String(selectedExam));
    
    const wsData = [];
    wsData.push(['', '', '', '', '', '', '', 'CIAAN \u2013 2023']);
    wsData.push(['', '', '', '', '', '', '', 'K1 (TH)']);
    wsData.push([]);
    wsData.push(['For AICTE Diploma Engineering Courses', '', '', '', '', '', '', 'wef - 2023-24']);
    wsData.push(['', '', '', 'Maharashtra State Board of Technical Education', '', '', '', '']);
    wsData.push(['', '', '', 'LESSON PLANNING', '', '', '', '']);
    wsData.push([]);
    wsData.push(['Institute Name:', 'Government Polytechnic Vikramgad', '', '', '', 'Institute Code:', '1547', '']);
    const acYear = examObj ? (examObj.season === 'Winter' ? `${examObj.year}-${String(Number(examObj.year)+1).slice(-2)}` : `${Number(examObj.year)-1}-${String(examObj.year).slice(-2)}`) : '';
    wsData.push(['Academic Year:', acYear, '', '', '', '', '', '']);
    wsData.push(['Programme:', courseObj && courseObj.Department ? courseObj.Department.name : '', '', 'Course: ' + (courseObj ? courseObj.name : ''), '', '', 'Course Code:', courseObj ? courseObj.code : '']);
    wsData.push(['Semester:', courseObj ? courseObj.semester + 'K' : '', '', '', '', '', '', '']);
    wsData.push([]);
    
    // Header
    wsData.push([
      'Unit No. (Allocated Hrs.)', 'CO', 'TLO aligned to CO\'s', 'Title / Details',
      'Plan From', 'Plan To', 'Plan Lectures', 
      'Actual From', 'Actual To', 'Actual Lectures',
      'Pedagogy used', 'Remarks'
    ]);
    
    plans.forEach(p => {
       wsData.push([
          `Unit: ${p.unit_no} (${p.allocated_hrs || 0} Hrs)`,
          p.co_mapped || '',
          p.tlo_aligned || '',
          p.topic_title || '',
          p.planned_from_date ? p.planned_from_date.split('-').reverse().join('-') : '',
          p.planned_to_date ? p.planned_to_date.split('-').reverse().join('-') : '',
          p.planned_lectures || '',
          p.actual_from_date ? p.actual_from_date.split('-').reverse().join('-') : '',
          p.actual_to_date ? p.actual_to_date.split('-').reverse().join('-') : '',
          p.actual_lectures || '',
          p.pedagogy_used || '',
          p.remarks || ''
       ]);
    });
    
    wsData.push([]);
    wsData.push(['Faculty', '', '', '', 'HOD', '', '', 'Principal']);
    
    const ws = window.XLSX.utils.aoa_to_sheet(wsData);
    ws['!cols'] = [
      {wch: 15}, // Unit No
      {wch: 8},  // CO
      {wch: 45}, // TLO
      {wch: 45}, // Title
      {wch: 12}, // Plan From
      {wch: 12}, // Plan To
      {wch: 10}, // Plan Lec
      {wch: 12}, // Act From
      {wch: 12}, // Act To
      {wch: 10}, // Act Lec
      {wch: 15}, // Pedagogy
      {wch: 20}  // Remarks
    ];
    const wb = window.XLSX.utils.book_new();
    window.XLSX.utils.book_append_sheet(wb, ws, "LessonPlan");
    window.XLSX.writeFile(wb, `K1_LessonPlan_${courseObj ? courseObj.code : 'Course'}.xlsx`);
  };

  const handlePrintPDF = () => {
    if (!selectedCourse || !selectedExam) return alert('Select Term and Course first.');
    if (plans.length === 0) return alert('No plans to export!');
    
    const courseObj = courses.find(c => String(c.id) === String(selectedCourse));
    const examObj = exams.find(e => String(e.id) === String(selectedExam));
    const acYear = examObj ? (examObj.season === 'Winter' ? `${examObj.year}-${String(Number(examObj.year)+1).slice(-2)}` : `${Number(examObj.year)-1}-${String(examObj.year).slice(-2)}`) : '';
    
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>Lesson Plan - ${courseObj ? courseObj.name : ''}</title>
          <style>
            @page { size: A4 landscape; margin: 10mm; }
            body { font-family: 'Times New Roman', serif; font-size: 11px; margin: 0; padding: 0; }
            table { width: 100%; border-collapse: collapse; table-layout: fixed; }
            th, td { border: 1px solid #000; padding: 4px; word-wrap: break-word; vertical-align: top; }
            th { background-color: #f0f0f0; text-align: center; font-weight: bold; }
            .header-info { width: 100%; margin-bottom: 10px; }
            .header-info td { border: none; padding: 2px; font-size: 12px; }
            .title-row { text-align: center; font-weight: bold; font-size: 14px; margin-bottom: 5px; }
            .sub-title { text-align: center; font-size: 12px; margin-bottom: 10px; }
            .text-center { text-align: center; }
          </style>
        </head>
        <body>
          <div style="text-align: right; font-weight: bold;">CIAAN – 2023</div>
          <div style="text-align: right; font-weight: bold;">K1 (TH)</div>
          <div class="sub-title">For AICTE Diploma Engineering Courses wef - 2023-24</div>
          <div class="title-row">Maharashtra State Board of Technical Education</div>
          <div class="title-row">LESSON PLANNING</div>
          
          <table class="header-info">
            <tr>
              <td colspan="2"><strong>Institute Name:</strong> Government Polytechnic Vikramgad</td>
              <td style="text-align: right;"><strong>Institute Code:</strong> 1547</td>
            </tr>
            <tr>
              <td colspan="2"><strong>Academic Year:</strong> ${acYear}</td>
              <td></td>
            </tr>
            <tr>
              <td><strong>Programme:</strong> ${courseObj && courseObj.Department ? courseObj.Department.name : ''}</td>
              <td><strong>Course:</strong> ${courseObj ? courseObj.name : ''}</td>
              <td style="text-align: right;"><strong>Course Code:</strong> ${courseObj ? courseObj.code : ''}</td>
            </tr>
            <tr>
              <td><strong>Semester:</strong> ${courseObj ? courseObj.semester + 'K' : ''}</td>
              <td></td>
              <td></td>
            </tr>
          </table>

          <table>
            <thead>
              <tr>
                <th style="width: 5%">Unit<br/>(Hrs)</th>
                <th style="width: 5%">CO</th>
                <th style="width: 22%">TLO aligned to CO's</th>
                <th style="width: 24%">Title / Details</th>
                <th style="width: 7%">Plan From</th>
                <th style="width: 7%">Plan To</th>
                <th style="width: 5%">Plan<br/>Lec</th>
                <th style="width: 7%">Act From</th>
                <th style="width: 7%">Act To</th>
                <th style="width: 5%">Act<br/>Lec</th>
                <th style="width: 7%">Pedagogy</th>
                <th style="width: 4%">Rem<br/>arks</th>
              </tr>
            </thead>
            <tbody>
              ${plans.map((p, index) => {
                 const firstOfUnit = index === 0 || plans[index].unit_no !== plans[index - 1].unit_no;
                 const rowSpanCount = firstOfUnit ? plans.filter(x => x.unit_no === p.unit_no).length : 1;
                 
                 let html = '<tr>';
                 
                 // Unit and CO always span
                 if (firstOfUnit) {
                    html += `<td class="text-center" rowspan="${rowSpanCount}">Unit: ${p.unit_no}<br/>(${p.allocated_hrs || 0} Hrs)</td>`;
                    html += `<td class="text-center" rowspan="${rowSpanCount}">${p.co_mapped || ''}</td>`;
                 }
                 
                 // TLO and Topic Details never span
                 html += `<td style="white-space: pre-wrap; word-break: break-word;">${(p.tlo_aligned || '').replace(/,?\s*(TLO\s*\d+\.\d+[a-z]*)/gi, '<br/>$1').replace(/^<br\/>/, '').trim()}</td>`;
                 let formattedTopic = (p.topic_title || '').trim().replace(/\n/g, '<br/>');
                 if (firstOfUnit) {
                     const firstBr = formattedTopic.indexOf('<br/>');
                     if (firstBr !== -1) {
                         formattedTopic = `<span style="font-weight: bold; font-size: 11px;">${formattedTopic.substring(0, firstBr)}</span>${formattedTopic.substring(firstBr)}`;
                     } else {
                         formattedTopic = `<span style="font-weight: bold; font-size: 11px;">${formattedTopic}</span>`;
                     }
                 }
                 html += `<td style="white-space: pre-wrap; word-break: break-word;">${formattedTopic}</td>`;
                 
                 // Grouped fields
                 if (!isGrouped || firstOfUnit) {
                    const spanAttr = isGrouped ? ` rowspan="${rowSpanCount}"` : '';
                    const finalPlanTo = isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).slice(-1)[0].planned_to_date) : p.planned_to_date;
                    const finalActTo = isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).slice(-1)[0].actual_to_date) : p.actual_to_date;
                    
                    const finalPlanLects = isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).reduce((s, x) => s + (parseInt(x.planned_lectures)||0), 0) || '') : (p.planned_lectures || '');
                    const finalActLects = isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).reduce((s, x) => s + (parseInt(x.actual_lectures)||0), 0) || '') : (p.actual_lectures || '');

                    html += `<td class="text-center"${spanAttr}>${p.planned_from_date ? p.planned_from_date.split('-').reverse().join('-') : ''}</td>`;
                    html += `<td class="text-center"${spanAttr}>${finalPlanTo ? finalPlanTo.split('-').reverse().join('-') : ''}</td>`;
                    html += `<td class="text-center"${spanAttr}>${finalPlanLects}</td>`;
                    html += `<td class="text-center"${spanAttr}>${p.actual_from_date ? p.actual_from_date.split('-').reverse().join('-') : ''}</td>`;
                    html += `<td class="text-center"${spanAttr}>${finalActTo ? finalActTo.split('-').reverse().join('-') : ''}</td>`;
                    html += `<td class="text-center"${spanAttr}>${finalActLects}</td>`;
                    html += `<td${spanAttr}>${p.pedagogy_used || ''}</td>`;
                    html += `<td${spanAttr}>${p.remarks || ''}</td>`;
                 }
                 
                 html += '</tr>';
                 return html;
              }).join('')}
            </tbody>
          </table>
          <br/><br/>
          <table class="header-info" style="margin-top: 30px;">
            <tr>
              <td style="text-align: left;"><strong>Faculty</strong></td>
              <td style="text-align: center;"><strong>HOD</strong></td>
              <td style="text-align: right;"><strong>Principal</strong></td>
            </tr>
          </table>
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
  };

  return (
    <div className="flex flex-col gap-6 animate-fade-in-up pb-12">
      <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-200">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 tracking-tight">Format K1: Teaching Plan (Lesson Plan)</h1>
          <p className="text-sm text-gray-500 mt-1">Map out theoretical schedules linking Units, Topics, Outcomes, and pedagogies.</p>
        </div>
      </div>

      <div className="bg-white border text-sm text-gray-700 border-gray-200 flex flex-wrap gap-4 items-end p-4 rounded-xl shadow-sm">
         <div className="w-[180px]">
           <label className="text-[10px] font-bold text-gray-500 uppercase block mb-1">Target Academic Term</label>
           <select value={selectedExam} onChange={e=>setSelectedExam(e.target.value)} className="w-full border border-gray-300 rounded px-3 py-2 outline-none focus:border-indigo-500 font-medium bg-indigo-50/20 border-l-4 border-l-indigo-500 text-indigo-900">
             <option value="">Select Term...</option>
             {exams.map(e => <option key={e.id} value={e.id}>{e.season} {e.year}</option>)}
           </select>
         </div>
         <div className="w-[160px]">
           <label className="text-[10px] font-bold text-gray-500 uppercase block mb-1">Branch / Dept</label>
           <select value={selectedDept} onChange={e=>{ setSelectedDept(e.target.value); setSelectedCourse(''); }} className="w-full border border-blue-300 rounded px-3 py-2 outline-none font-bold bg-blue-50/40 text-blue-900 text-xs">
             <option value="All">All Branches</option>
             {(departments || []).map(d => <option key={d.id} value={d.id}>{d.name} ({d.dept_code})</option>)}
           </select>
         </div>
         <div className="w-1/4 min-w-[200px]">
           <label className="text-[10px] font-bold text-gray-500 uppercase block mb-1">Target Course</label>
           <input 
              type="text" 
              placeholder="Search Code/Name..." 
              value={courseSearchQuery} 
              onChange={e => setCourseSearchQuery(e.target.value)} 
              className="w-full border-b border-gray-200 px-1 py-0.5 text-xs bg-white mb-1 focus:border-indigo-500 outline-none"
           />
           <select value={selectedCourse} onChange={e=>setSelectedCourse(e.target.value)} className="w-full border border-gray-300 rounded px-3 py-2 outline-none focus:border-indigo-500 font-medium">
             {courses.filter(c => (c.code + ' ' + c.name).toLowerCase().includes(courseSearchQuery.toLowerCase())).map(c => (
               <option key={c.id} value={c.id}>{c.code} - {c.name} [{c.Department?.dept_code || 'CO'}]</option>
             ))}
           </select>
         </div>
         <button onClick={fetchPlan} disabled={loading} className="bg-gray-900 hover:bg-black text-white px-5 py-2 rounded shadow transition font-bold">
           Load Matrix
         </button>
         
         <div className="w-[1px] h-10 bg-gray-200 mx-2 hidden sm:block"></div>
         
         <div className="w-1/4 min-w-[150px]">
           <label className="text-[10px] font-bold text-emerald-600 uppercase block mb-1">Copy List From Term</label>
           <select value={copyFromExam} onChange={e=>setCopyFromExam(e.target.value)} className="w-full border border-emerald-300 rounded px-3 py-2 outline-none focus:border-emerald-500 font-medium bg-emerald-50/20 text-emerald-900 border-l-4 border-l-emerald-500">
             <option value="">Select Term...</option>
             {exams.map(e => <option key={e.id} value={e.id}>{e.season} {e.year}</option>)}
           </select>
         </div>
         <button onClick={handleCopyFromExam} disabled={loading} className="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded shadow transition font-bold">
           Clone
         </button>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
         <div className="px-5 py-4 bg-gray-50 border-b border-gray-200 flex flex-wrap justify-between items-center gap-4">
             <div className="flex gap-2">
                 <button onClick={handleAddRow} className="bg-white border border-gray-300 text-gray-700 hover:bg-gray-100 px-4 py-1.5 rounded text-xs font-bold uppercase tracking-wider shadow-sm transition">
                    + Insert Unit
                 </button>
                 <button onClick={handleFetchFromSyllabus} className="bg-indigo-50 text-indigo-700 border border-indigo-200 hover:bg-indigo-100 px-4 py-1.5 rounded text-xs font-bold uppercase tracking-wider shadow-sm transition">
                    Fetch from Syllabus
                 </button>
                 <button onClick={() => setIsGrouped(!isGrouped)} className="bg-sky-50 text-sky-700 border border-sky-200 hover:bg-sky-100 px-4 py-1.5 rounded text-xs font-bold uppercase tracking-wider shadow-sm transition">
                    {isGrouped ? 'Unit-wise' : 'TLO-wise'}
                 </button>
                 <button onClick={() => setShowAutoDateModal(true)} className="bg-purple-50 text-purple-700 border border-purple-200 hover:bg-purple-100 px-4 py-1.5 rounded text-xs font-bold uppercase tracking-wider shadow-sm transition">
                    Auto Map Dates (By Hrs)
                 </button>
                 <button onClick={handleExportExcel} className="bg-white border border-teal-200 text-teal-700 hover:bg-teal-50 px-4 py-1.5 rounded text-xs font-bold uppercase tracking-wider shadow-sm transition flex gap-1 items-center">
                    Excel Export
                 </button>
                 <button onClick={handlePrintPDF} className="bg-white border border-rose-200 text-rose-700 hover:bg-rose-50 px-4 py-1.5 rounded text-xs font-bold uppercase tracking-wider shadow-sm transition flex gap-1 items-center">
                    Print PDF (K1)
                 </button>
             </div>
             <div className="flex gap-2">
                 <button onClick={handleClearBoard} disabled={loading || plans.length===0} className="bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 font-bold px-6 py-2 rounded shadow-sm transition text-sm">
                    Clear Master Plan
                 </button>
                 <button onClick={handleSave} disabled={loading} className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-6 py-2 rounded shadow transition text-sm">
                    Commit & Lock Plan
                 </button>
             </div>
         </div>

         <div className="overflow-x-auto">
             <table className="w-full text-left text-sm text-gray-700 min-w-max border border-gray-300">
                <thead className="bg-gray-100 text-gray-700 font-bold text-[10px] border-b border-gray-300">
                    <tr>
                      <th className="px-1 py-1 text-center border-r border-gray-300 w-[34px]" rowSpan="2">Unit<br/>(Hrs)</th>
                      <th className="px-1 py-1 text-center border-r border-gray-300 w-8" rowSpan="2">CO</th>
                      <th className="px-1 py-1 text-center border-r border-gray-300 w-64" rowSpan="2">TLOs</th>
                      <th className="px-2 py-1 text-center border-r border-gray-300 w-auto" rowSpan="2">Topic Details</th>
                      <th className="px-1 py-1 text-center border-r border-gray-300 bg-blue-50/50" colSpan="2">Plan (Lectures)</th>
                      <th className="px-1 py-1 text-center border-r border-gray-300 bg-purple-50/50" colSpan="2">Actual (Lectures)</th>
                      <th className="px-1 py-1 text-center border-r border-gray-300 w-24" rowSpan="2">Pedagogy</th>
                      <th className="px-1 py-1 text-center border-gray-300 w-16" rowSpan="2">Remarks</th>
                      <th className="px-1 py-1 w-6 text-center" rowSpan="2"></th>
                   </tr>
                   <tr>
                      <th className="px-1 py-1 text-center border-r border-t border-gray-300 bg-blue-50/50 w-16">From</th>
                      <th className="px-1 py-1 text-center border-r border-t border-gray-300 bg-blue-50/50 w-16">To</th>
                      <th className="px-1 py-1 text-center border-r border-t border-gray-300 bg-purple-50/50 w-16">From</th>
                      <th className="px-1 py-1 text-center border-r border-t border-gray-300 bg-purple-50/50 w-16">To</th>
                   </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 border-b border-gray-300">
                  {plans.map((p, index) => {
                     const firstOfUnit = index === 0 || plans[index].unit_no !== plans[index - 1].unit_no;
                     const rowSpanCount = firstOfUnit ? plans.filter(x => x.unit_no === p.unit_no).length : 1;
                     
                     return (
                     <tr key={index} className="hover:bg-gray-50 group">
                        {firstOfUnit && (
                        <td className="px-2 py-2 text-center border-r border-gray-200" rowSpan={rowSpanCount}>
                           <div className="flex flex-col items-center gap-1">
                              <span className="text-xs font-bold text-gray-500">Unit: {p.unit_no}</span>
                              <span className="text-sm font-bold text-indigo-700">{p.allocated_hrs || 0}</span>
                           </div>
                        </td>
                        )}
                        {firstOfUnit && (
                        <td className="px-2 py-2 border-r border-gray-200 align-top" rowSpan={rowSpanCount}>
                           <input type="text" value={p.co_mapped || ''} onChange={e=>handleChange(index, 'co_mapped', e.target.value)} className="w-full text-center outline-none bg-transparent border-b border-transparent focus:border-indigo-400 py-1 text-xs text-gray-700" placeholder="e.g. 1, 2" />
                        </td>
                        )}

                        <td className="px-2 py-2 border-r border-gray-200 align-top">
                           <textarea value={p.tlo_aligned || ''} onChange={e=>handleChange(index, 'tlo_aligned', e.target.value)} rows={Math.max(3, (p.tlo_aligned||'').split('\n').length + Math.floor((p.tlo_aligned||'').length / 30))} className="w-full resize-y outline-none bg-transparent border-b border-transparent focus:border-indigo-400 py-1 text-xs text-gray-700 whitespace-pre-wrap break-words" placeholder="TLOs..." />
                        </td>
                        <td className="px-2 py-2 border-r border-gray-200 align-top">
                           <textarea value={p.topic_title || ''} onChange={e=>handleChange(index, 'topic_title', e.target.value)} rows={Math.max(3, (p.topic_title||'').split('\n').length + Math.floor((p.topic_title||'').length / 30))} className="w-full resize-y outline-none bg-transparent border-b border-transparent focus:border-indigo-400 py-1 text-xs text-gray-700 whitespace-pre-wrap break-words" placeholder="Topic details..." />
                        </td>
                        
                        {/* Planned */}
                        {(!isGrouped || firstOfUnit) && (
                        <td className="px-2 py-2 text-center border-r border-gray-200 bg-blue-50/10 align-top" rowSpan={isGrouped ? rowSpanCount : 1}>
                           <div className="flex flex-col gap-1 items-center">
                              <DateField value={p.planned_from_date || ''} onChange={e=>handleChange(index, 'planned_from_date', e.target.value)} className="w-full bg-transparent border-b border-gray-300 outline-none text-[10px] text-blue-900 cursor-pointer pb-1 pr-4" />
                              <input type="number" value={isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).reduce((s, x) => s + (parseInt(x.planned_lectures)||0), 0) || '') : (p.planned_lectures || '')} onChange={e=>handleChange(index, 'planned_lectures', e.target.value)} className="w-12 text-center outline-none border border-gray-300 rounded text-[10px] text-gray-600 mt-1" placeholder="Lects" title="No. of Lectures" />
                           </div>
                        </td>
                        )}
                        {(!isGrouped || firstOfUnit) && (
                        <td className="px-2 py-2 text-center border-r border-gray-200 bg-blue-50/10 align-top" rowSpan={isGrouped ? rowSpanCount : 1}>
                           <div className="flex flex-col gap-1 items-center">
                              <DateField value={isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).slice(-1)[0].planned_to_date || '') : (p.planned_to_date || '')} onChange={e=>handleChange(index, 'planned_to_date', e.target.value)} className="w-full bg-transparent border-b border-gray-300 outline-none text-[10px] text-blue-900 cursor-pointer pb-1 pr-4" />
                           </div>
                        </td>
                        )}
                        
                        {/* Actual */}
                        {(!isGrouped || firstOfUnit) && (
                        <td className="px-2 py-2 text-center border-r border-gray-200 bg-purple-50/10 align-top" rowSpan={isGrouped ? rowSpanCount : 1}>
                           <div className="flex flex-col gap-1 items-center">
                              <DateField value={p.actual_from_date || ''} onChange={e=>handleChange(index, 'actual_from_date', e.target.value)} className="w-full bg-transparent border-b border-gray-300 outline-none text-[10px] text-purple-900 cursor-pointer pb-1 pr-4" />
                              <input type="number" value={isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).reduce((s, x) => s + (parseInt(x.actual_lectures)||0), 0) || '') : (p.actual_lectures || '')} onChange={e=>handleChange(index, 'actual_lectures', e.target.value)} className="w-12 text-center outline-none border border-gray-300 rounded text-[10px] text-gray-600 mt-1" placeholder="Lects" title="No. of Lectures" />
                           </div>
                        </td>
                        )}
                        {(!isGrouped || firstOfUnit) && (
                        <td className="px-2 py-2 text-center border-r border-gray-200 bg-purple-50/10 align-top" rowSpan={isGrouped ? rowSpanCount : 1}>
                           <div className="flex flex-col gap-1 items-center">
                              <DateField value={isGrouped ? (plans.filter(x => x.unit_no === p.unit_no).slice(-1)[0].actual_to_date || '') : (p.actual_to_date || '')} onChange={e=>handleChange(index, 'actual_to_date', e.target.value)} className="w-full bg-transparent border-b border-gray-300 outline-none text-[10px] text-purple-900 cursor-pointer pb-1 pr-4" />
                           </div>
                        </td>
                        )}
                        
                        {(!isGrouped || firstOfUnit) && (
                        <td className="px-2 py-2 border-r border-gray-200 align-top" rowSpan={isGrouped ? rowSpanCount : 1}>
                           <textarea value={p.pedagogy_used || ''} onChange={e=>handleChange(index, 'pedagogy_used', e.target.value)} rows={Math.max(3, (p.pedagogy_used||'').split('\n').length + Math.floor((p.pedagogy_used||'').length / 30))} className="w-full resize-y outline-none bg-transparent border-b border-transparent focus:border-indigo-400 py-1 text-xs whitespace-pre-wrap break-words" placeholder="e.g. Chalk-Board" />
                        </td>
                        )}
                        {(!isGrouped || firstOfUnit) && (
                        <td className="px-2 py-2 border-r border-gray-200 align-top" rowSpan={isGrouped ? rowSpanCount : 1}>
                           <textarea value={p.remarks || ''} onChange={e=>handleChange(index, 'remarks', e.target.value)} rows={Math.max(3, (p.remarks||'').split('\n').length + Math.floor((p.remarks||'').length / 30))} className="w-full resize-y outline-none bg-transparent border-b border-transparent focus:border-indigo-400 py-1 text-xs whitespace-pre-wrap break-words" placeholder="Remarks..." />
                        </td>
                        )}
                        <td className="px-2 py-2 text-center align-middle">
                           <button onClick={()=>handleDeleteRow(index)} className="text-gray-300 hover:text-red-500 transition opacity-0 group-hover:opacity-100 px-2 py-1">✕</button>
                        </td>
                     </tr>
                     );
                  })}
                  {plans.length === 0 && (
                     <tr><td colSpan="11" className="text-center py-12 text-gray-400 italic">No lesson plan defined. Insert rows manually or fetch from AI Ingestion Engine.</td></tr>
                  )}
               </tbody>
            </table>
         </div>
      </div>

      {showAutoDateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/40 backdrop-blur-sm animate-fade-in">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col max-h-[90vh]">
            <div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
               <div>
                  <h3 className="font-bold text-gray-900">Auto Assign Unit Dates</h3>
                  <p className="text-xs text-gray-500 mt-1">Map start and end dates for units based on their Allocated Hours and holidays.</p>
               </div>
               <button onClick={() => setShowAutoDateModal(false)} className="text-gray-400 hover:text-gray-600">✕</button>
            </div>
            
            <div className="p-6 overflow-y-auto flex flex-col gap-6">
               <div className="flex gap-4">
                  <div className="flex-1">
                     <label className="text-xs font-bold text-gray-700 uppercase block mb-2">Term Start Date</label>
                     <input type="date" value={autoDateConfig.startDate} onChange={e=>setAutoDateConfig({...autoDateConfig, startDate: e.target.value})} className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:border-purple-500 outline-none" />
                  </div>
                  <div className="flex-1">
                     <label className="text-xs font-bold text-gray-700 uppercase block mb-2">Term End Date</label>
                     <input type="date" value={autoDateConfig.endDate} onChange={e=>setAutoDateConfig({...autoDateConfig, endDate: e.target.value})} className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:border-purple-500 outline-none" />
                  </div>
               </div>
               
               <div className="flex flex-col gap-3">
                  <div>
                     <label className="text-xs font-bold text-gray-700 uppercase block mb-2">Add Weekday (Click multiple times for multiple lectures/day)</label>
                     <div className="flex flex-wrap gap-2">
                        {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((d, i) => (
                           <button key={i} onClick={() => handleAddWeekday(i)} 
                               className="px-3 py-1.5 rounded text-sm font-medium bg-white border border-gray-300 text-gray-700 hover:bg-gray-50 transition">
                              + {d}
                           </button>
                        ))}
                     </div>
                  </div>
                  <div>
                     <label className="text-xs font-bold text-gray-700 uppercase block mb-2">Selected Days (In Order)</label>
                     <div className="flex flex-wrap gap-2 min-h-[40px] p-2 bg-gray-50 border border-gray-200 rounded-lg">
                        {autoDateConfig.weekdays.map((dayIdx, arrIdx) => (
                           <div key={arrIdx} className="bg-purple-100 border border-purple-300 text-purple-800 px-3 py-1 rounded-full text-sm font-bold flex items-center gap-2 shadow-sm animate-fade-in-up">
                              {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][dayIdx]}
                              <button onClick={() => handleRemoveWeekday(arrIdx)} className="text-purple-400 hover:text-purple-900 focus:outline-none">✕</button>
                           </div>
                        ))}
                        {autoDateConfig.weekdays.length === 0 && <span className="text-gray-400 text-xs py-1 px-2 italic">None selected</span>}
                     </div>
                  </div>
               </div>
               
               <div className="border border-gray-200 rounded-lg p-4 bg-gray-50/50">
                  <label className="text-xs font-bold text-gray-700 uppercase block mb-3">Database Holidays (Skip Dates)</label>
                  <div className="flex flex-col gap-2 mb-4">
                     <div className="flex gap-2">
                         <input type="date" value={autoDateConfig.holidayDate} onChange={e=>setAutoDateConfig({...autoDateConfig, holidayDate:e.target.value})} className="border border-gray-300 rounded px-2 py-1.5 text-sm focus:border-purple-500 outline-none w-32" />
                         <input type="text" placeholder="Holiday Name (e.g. Diwali)" value={autoDateConfig.holidayName} onChange={e=>setAutoDateConfig({...autoDateConfig, holidayName:e.target.value})} className="flex-1 border border-gray-300 rounded px-2 py-1.5 text-sm focus:border-purple-500 outline-none" />
                     </div>
                     <div className="flex gap-2 items-center">
                         <select value={autoDateConfig.holidayLevel} onChange={e=>setAutoDateConfig({...autoDateConfig, holidayLevel:e.target.value})} className="border border-gray-300 rounded px-2 py-1.5 text-sm outline-none flex-1">
                            <option value="Institute">Institute Level (Common to All)</option>
                            <option value="Department">Department Level</option>
                            <option value="Individual">Individual Level</option>
                         </select>
                         <button onClick={handleAddHoliday} className="bg-gray-800 text-white px-4 rounded py-1.5 text-sm font-bold hover:bg-gray-700">Add to DB</button>
                     </div>
                  </div>
                  {dbHolidays.length > 0 ? (
                     <div className="flex flex-col gap-2 max-h-40 overflow-y-auto pr-1">
                        {dbHolidays.map(h => (
                           <div key={h.id} className="bg-white border border-gray-200 text-gray-700 text-xs px-3 py-2 rounded flex justify-between items-center shadow-sm">
                              <div className="flex items-center gap-3">
                                  <span className="font-bold text-red-600">{h.date}</span>
                                  <span className="font-semibold">{h.name}</span>
                                  <span className="text-[10px] bg-gray-100 px-2 py-0.5 rounded-full text-gray-500 border border-gray-200">{h.level}</span>
                              </div>
                              <button onClick={()=>handleRemoveHoliday(h.id)} className="text-gray-400 hover:text-red-600 font-bold px-2 py-1 rounded hover:bg-red-50">✕</button>
                           </div>
                        ))}
                     </div>
                  ) : (
                     <div className="text-xs text-gray-400 italic">No holidays stored in database yet.</div>
                  )}
               </div>
               
               <button onClick={handleAutoMapSubmit} className="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 rounded-lg shadow-sm transition mt-2 text-sm">
                  Apply Date Mapping
               </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
