/**
 * Student Medical Records & Sanatorium Portal — Complete Implementation
 *
 * Includes:
 * 1. Patient selection & autocomplete inside Log Encounter modal
 * 2. Dynamic, adjustable Sick Bay bed count (1 - 24 beds)
 * 3. Student search by name, roll number, and class
 * 4. Real-time filtering on Daily Encounters log
 * 5. Medical Document Ingestion & Attachment Uploader (PDF, Image, Lab Reports, Bulk JSON/CSV)
 * 6. Kitchen Dining Hall Allergy Alerts (Broadcast alerts to Kitchen Tablet with live acknowledgement)
 * 7. Immunization tracker, medication dispensary, medical profile editor, and parent alerts
 */

import { useEffect, useMemo, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import {
  HeartPulse, Plus, AlertTriangle, CheckCircle2, Clock, FileText,
  Trash2, Edit, Save, X, Search, UtensilsCrossed, Eye, Pill,
  ChevronRight, Baby, Stethoscope, Bed, Syringe, Bell, Send, User, Check,
  AlertCircle, RefreshCw, ShieldAlert, Activity, Minus, FileUp, Upload, Download, Code
} from 'lucide-react';
import api from '../../store/api';
import { useMedicalStore, severityColor, eventTypeIcon, formatDate } from '../../store/medical';
import { ProgressBar } from '../../components/ui/ProgressBar';
import type {
  MedicalProfile, MedicalHistoryEvent, MedicationLog,
  SanatoriumVisit, ImmunizationRecord, StudentSearchResult,
  DiningAlertRow, ClassFlagRow, MedicalDocument
} from '../../store/medical';

// ============================================================
// Shared building blocks
// ============================================================

function PageShell({ title, breadcrumb, actions, children }: {
  title: string;
  breadcrumb: string;
  actions?: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-16">
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6 bg-card border border-border p-8 rounded-[2rem] shadow-sm">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <div className="p-2 bg-rose-50 dark:bg-rose-950/40 rounded-xl text-rose-600">
              <Stethoscope size={22} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Sanatorium & Healthcare Console</span>
          </div>
          <h1 className="text-3xl font-black text-text tracking-tighter uppercase">{title}</h1>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Student Healthcare</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">{breadcrumb}</span>
          </nav>
        </div>
        {actions}
      </div>
      {children}
    </div>
  );
}

function Card({ children, className = '' }: { children: React.ReactNode; className?: string }) {
  return (
    <div className={`bg-card border border-border rounded-[1.75rem] shadow-sm ${className}`}>
      {children}
    </div>
  );
}

function EmptyState({ icon: Icon, title, hint }: { icon: any; title: string; hint?: string }) {
  return (
    <Card className="p-12 text-center space-y-3">
      <div className="p-4 bg-muted/40 rounded-2xl w-fit mx-auto text-text-muted">
        <Icon size={36} />
      </div>
      <h3 className="text-lg font-black text-text uppercase tracking-wide">{title}</h3>
      {hint && <p className="text-xs text-text-muted font-medium max-w-md mx-auto">{hint}</p>}
    </Card>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="space-y-1.5">
      <label className="block text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">{label}</label>
      {children}
    </div>
  );
}

function inputClass() {
  return 'w-full bg-muted/50 border border-border rounded-xl px-4 py-2.5 text-sm font-semibold outline-none focus:border-primary focus:bg-card focus:ring-4 focus:ring-blue-500/5 transition-all text-text';
}

// ============================================================
// Sanatorium Console (Nurse / Doctor Portal)
// ============================================================

export function SanatoriumPortal() {
  const {
    currentProfile, medicationLogs, medicalHistory, sanatoriumVisits, immunizations, medicalDocuments,
    fetchProfile, saveProfile, fetchMedicationLogs, fetchMedicalHistory,
    fetchSanatoriumVisits, fetchImmunizations, fetchMedicalDocuments, uploadMedicalDocument,
    ingestMedicalJSON, deleteMedicalDocument, sendDiningHallAlert, searchStudents,
    addSanatoriumVisit, updateSanatoriumVisit, addMedicationLog, addHistoryEvent,
    deleteHistoryEvent, deleteMedicationLog, addImmunization, notifyParent,
    error, loading
  } = useMedicalStore();

  // Student Search States
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<StudentSearchResult[]>([]);
  const [selectedStudent, setSelectedStudent] = useState<StudentSearchResult | null>(null);
  const [studentUid, setStudentUid] = useState('');

  // Adjustable Sick Bay Beds State (persisted in localStorage)
  const [totalBeds, setTotalBeds] = useState<number>(() => {
    const saved = localStorage.getItem('sanatorium_total_beds');
    return saved ? Math.max(1, Math.min(24, parseInt(saved))) : 6;
  });

  // Daily Encounters Table Search Filter
  const [encounterSearch, setEncounterSearch] = useState('');

  // Tab & Modal States
  const [activeTab, setActiveTab] = useState<'visits' | 'profile' | 'medication' | 'history' | 'immunizations' | 'documents'>('visits');
  const [showVisitModal, setShowVisitModal] = useState(false);
  const [showImmunizationModal, setShowImmunizationModal] = useState(false);
  const [showHistoryModal, setShowHistoryModal] = useState(false);
  const [showParentAlertModal, setShowParentAlertModal] = useState(false);
  const [showKitchenAlertModal, setShowKitchenAlertModal] = useState(false);
  const [showIngestModal, setShowIngestModal] = useState(false);

  // Modal Student Autocomplete State
  const [modalSearchQuery, setModalSearchQuery] = useState('');
  const [modalSearchResults, setModalSearchResults] = useState<StudentSearchResult[]>([]);
  const [modalStudent, setModalStudent] = useState<StudentSearchResult | null>(null);

  // Document Upload State
  const [docFile, setDocFile] = useState<File | null>(null);
  const [docType, setDocType] = useState('lab_report');
  const [docNotes, setDocNotes] = useState('');
  const [docSuccess, setDocSuccess] = useState<string | null>(null);

  // Bulk Ingestion JSON State
  const [jsonInput, setJsonInput] = useState('');
  const [ingestStatus, setIngestStatus] = useState<string | null>(null);

  // Kitchen Alert State
  const [kitchenAllergyText, setKitchenAllergyText] = useState('');
  const [kitchenSeverity, setKitchenSeverity] = useState('severe');
  const [kitchenInstructions, setKitchenInstructions] = useState('');
  const [kitchenAlertSuccess, setKitchenAlertSuccess] = useState<string | null>(null);

  // Parent Alert State
  const [alertSubject, setAlertSubject] = useState('');
  const [alertBody, setAlertBody] = useState('');
  const [alertSuccess, setAlertSuccess] = useState<string | null>(null);

  // New Visit Form State
  const [visitForm, setVisitForm] = useState({
    chief_complaint: '',
    temp: '36.8',
    bp: '120/80',
    pulse: '72',
    treatment_administered: '',
    disposition: 'discharged' as 'discharged' | 'admitted' | 'sent_home' | 'referred_hospital',
    bed_number: 1,
    parent_notified: false,
    notes: ''
  });

  // Immunization Form State
  const [immForm, setImmForm] = useState({
    vaccine_name: 'Tetanus Booster',
    dose_number: 1,
    administered_date: new Date().toISOString().slice(0, 10),
    administered_by: '',
    batch_number: '',
    notes: ''
  });

  // History Form State
  const [histForm, setHistForm] = useState({
    event_type: 'illness' as 'illness' | 'injury' | 'hospitalization',
    title: '',
    description: '',
    severity: 'mild' as 'mild' | 'moderate' | 'severe',
    resolution_date: '',
    doctor_notes: '',
    is_visible_to_teachers: 1
  });

  useEffect(() => {
    fetchSanatoriumVisits({ limit: 100 });
  }, []);

  useEffect(() => {
    if (studentUid) {
      fetchProfile(studentUid);
      fetchMedicationLogs(studentUid);
      fetchMedicalHistory(studentUid);
      fetchImmunizations(studentUid);
      fetchMedicalDocuments(studentUid);
      fetchSanatoriumVisits({ student_uid: studentUid });
    }
  }, [studentUid]);

  const updateBedCapacity = (newBeds: number) => {
    const valid = Math.max(1, Math.min(24, newBeds));
    setTotalBeds(valid);
    localStorage.setItem('sanatorium_total_beds', String(valid));
  };

  const handleSearchChange = async (q: string) => {
    setSearchQuery(q);
    if (q.trim().length >= 2) {
      const results = await searchStudents(q);
      setSearchResults(results);
    } else {
      setSearchResults([]);
    }
  };

  const handleSelectStudent = (st: StudentSearchResult) => {
    setSelectedStudent(st);
    setStudentUid(st.uid);
    setSearchQuery(`${st.first_name} ${st.last_name}`);
    setSearchResults([]);
  };

  const handleModalSearchChange = async (q: string) => {
    setModalSearchQuery(q);
    if (q.trim().length >= 2) {
      const results = await searchStudents(q);
      setModalSearchResults(results);
    } else {
      setModalSearchResults([]);
    }
  };

  const handleOpenVisitModal = () => {
    if (selectedStudent) {
      setModalStudent(selectedStudent);
      setModalSearchQuery(`${selectedStudent.first_name} ${selectedStudent.last_name}`);
    } else {
      setModalStudent(null);
      setModalSearchQuery('');
    }
    setModalSearchResults([]);
    setShowVisitModal(true);
  };

  const handleCreateVisit = async (e: React.FormEvent) => {
    e.preventDefault();
    const targetUid = modalStudent?.uid || studentUid;

    if (!targetUid) {
      alert('Please search and select a patient student for this encounter');
      return;
    }
    if (!visitForm.chief_complaint) {
      alert('Chief complaint is required');
      return;
    }

    const vitals = {
      temperature: visitForm.temp,
      blood_pressure: visitForm.bp,
      pulse: visitForm.pulse
    };

    const res = await addSanatoriumVisit({
      student_uid: targetUid,
      chief_complaint: visitForm.chief_complaint,
      vitals_json: JSON.stringify(vitals),
      treatment_administered: visitForm.treatment_administered,
      disposition: visitForm.disposition,
      bed_number: visitForm.disposition === 'admitted' ? visitForm.bed_number : undefined,
      parent_notified: visitForm.parent_notified ? 1 : 0,
      notes: visitForm.notes
    });

    if (res) {
      setShowVisitModal(false);
      setVisitForm({
        chief_complaint: '',
        temp: '36.8',
        bp: '120/80',
        pulse: '72',
        treatment_administered: '',
        disposition: 'discharged',
        bed_number: 1,
        parent_notified: false,
        notes: ''
      });
      fetchSanatoriumVisits({ limit: 100 });
    }
  };

  const handleDischargeBed = async (visitId: number) => {
    if (!window.confirm('Discharge student from Sick Bay bed?')) return;
    await updateSanatoriumVisit(visitId, { disposition: 'discharged', bed_number: undefined });
    fetchSanatoriumVisits({ limit: 100 });
  };

  const handleFileUpload = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!studentUid || !docFile) return;
    const res = await uploadMedicalDocument(studentUid, docFile, docType, docNotes);
    if (res) {
      setDocSuccess('Medical document uploaded successfully.');
      setDocFile(null);
      setDocNotes('');
      setTimeout(() => setDocSuccess(null), 3000);
      fetchMedicalDocuments(studentUid);
    }
  };

  const handleBulkIngestJSON = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const parsed = JSON.parse(jsonInput);
      const records = Array.isArray(parsed) ? parsed : [parsed];
      const res = await ingestMedicalJSON(records);
      if (res) {
        setIngestStatus(`Success! Ingested ${res.count} medical records into SQLite database.`);
        setJsonInput('');
        setTimeout(() => { setIngestStatus(null); setShowIngestModal(false); }, 2500);
      }
    } catch (err: any) {
      alert('Invalid JSON format: ' + err.message);
    }
  };

  const handleSendKitchenAlert = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!studentUid) return;
    const ok = await sendDiningHallAlert(studentUid, kitchenAllergyText, kitchenSeverity, kitchenInstructions);
    if (ok) {
      setKitchenAlertSuccess('Allergy Alert broadcasted to Dining Hall Kitchen Tablet!');
      setTimeout(() => { setKitchenAlertSuccess(null); setShowKitchenAlertModal(false); }, 2000);
    }
  };

  const handleAddImmunization = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!studentUid) return;
    const res = await addImmunization({
      student_uid: studentUid,
      ...immForm
    });
    if (res) {
      setShowImmunizationModal(false);
      fetchImmunizations(studentUid);
    }
  };

  const handleSendParentAlert = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!studentUid) return;
    const ok = await notifyParent(studentUid, alertSubject, alertBody);
    if (ok) {
      setAlertSuccess('Alert message delivered to parent portal successfully.');
      setTimeout(() => { setAlertSuccess(null); setShowParentAlertModal(false); }, 2000);
    } else {
      alert('Failed to deliver alert. Ensure a parent account is linked to this student.');
    }
  };

  const activeBeds = sanatoriumVisits.filter(v => v.disposition === 'admitted');

  const filteredVisits = useMemo(() => {
    if (!encounterSearch.trim()) return sanatoriumVisits;
    const q = encounterSearch.toLowerCase();
    return sanatoriumVisits.filter(v => 
      `${v.student_first_name || ''} ${v.student_last_name || ''}`.toLowerCase().includes(q) ||
      (v.chief_complaint || '').toLowerCase().includes(q) ||
      (v.class_name || '').toLowerCase().includes(q) ||
      (v.disposition || '').toLowerCase().includes(q)
    );
  }, [sanatoriumVisits, encounterSearch]);

  return (
    <PageShell
      title="Sanatorium Console"
      breadcrumb="Doctor & Nurse Medical Portal"
      actions={
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex items-center gap-2 px-4 py-2 bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 rounded-xl text-rose-700 dark:text-rose-400 text-xs font-black uppercase tracking-widest">
            <Stethoscope size={16} /> Nurse Station
          </div>
          {studentUid && (
            <>
              <button
                type="button"
                onClick={() => {
                  setKitchenAllergyText(currentProfile?.allergies || 'Severe Food / Medication Allergy');
                  setKitchenInstructions(currentProfile?.emergency_instructions || 'Do not serve peanuts or dairy');
                  setShowKitchenAlertModal(true);
                }}
                className="flex items-center gap-2 px-4 py-2 bg-rose-600 text-white rounded-xl text-xs font-bold hover:bg-rose-700 transition-all shadow-sm active:scale-95 cursor-pointer"
              >
                <UtensilsCrossed size={16} /> Alert Kitchen
              </button>

              <button
                type="button"
                onClick={() => {
                  setAlertSubject(`Sanatorium Visit Alert for ${selectedStudent?.first_name || 'Student'}`);
                  setAlertBody(`Dear Parent,\n\nYour child ${selectedStudent?.first_name || ''} visited the school Sanatorium today for medical attention. Please log in to your Parent Portal to view details.`);
                  setShowParentAlertModal(true);
                }}
                className="flex items-center gap-2 px-4 py-2 bg-amber-500 text-white rounded-xl text-xs font-bold hover:bg-amber-600 transition-all shadow-sm active:scale-95 cursor-pointer"
              >
                <Bell size={16} /> Alert Parent
              </button>
            </>
          )}
          <button
            type="button"
            onClick={handleOpenVisitModal}
            className="flex items-center gap-2 px-5 py-2 bg-primary text-white rounded-xl text-xs font-bold hover:bg-primary/90 transition-all shadow-md active:scale-95 cursor-pointer"
          >
            <Plus size={16} /> Log Clinic Encounter
          </button>
        </div>
      }
    >
      {/* Student Lookup Search & Selector Card */}
      <Card className="p-6">
        <div className="relative space-y-2">
          <Field label="Look Up Patient Student by Name, Roll No, or ID">
            <div className="relative">
              <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" />
              <input
                className={`${inputClass()} pl-11`}
                placeholder="Type student name (e.g. John Doe, Sarah, Form 4)..."
                value={searchQuery}
                onChange={(e) => handleSearchChange(e.target.value)}
              />
              {searchQuery && (
                <button
                  type="button"
                  onClick={() => { setSearchQuery(''); setSearchResults([]); setSelectedStudent(null); setStudentUid(''); }}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-text cursor-pointer"
                >
                  <X size={16} />
                </button>
              )}
            </div>
          </Field>

          {/* Search Dropdown Results */}
          {searchResults.length > 0 && (
            <div className="absolute left-0 right-0 top-full mt-2 bg-card border border-border rounded-2xl shadow-2xl z-[100] max-h-60 overflow-y-auto divide-y divide-border/60">
              {searchResults.map((st) => (
                <div
                  key={st.id}
                  onClick={() => handleSelectStudent(st)}
                  className="p-3 hover:bg-primary/10 transition-colors cursor-pointer flex justify-between items-center text-xs"
                >
                  <div>
                    <span className="font-bold text-text text-sm">{st.first_name} {st.last_name}</span>
                    <span className="ml-2 text-text-muted font-mono">{st.id_number || `ID-${st.id}`}</span>
                  </div>
                  <span className="px-2.5 py-1 bg-muted rounded-lg font-bold text-text-muted">{st.class_name || 'Student'}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Selected Student Banner */}
        {selectedStudent && (
          <div className="mt-4 p-4 bg-primary/5 border border-primary/20 rounded-2xl flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 animate-in fade-in">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-primary text-white flex items-center justify-center font-black text-sm">
                {selectedStudent.first_name[0]}{selectedStudent.last_name[0]}
              </div>
              <div>
                <h3 className="font-black text-text text-base">{selectedStudent.first_name} {selectedStudent.last_name}</h3>
                <p className="text-xs font-semibold text-text-muted">
                  Class: {selectedStudent.class_name || 'N/A'} · ID: {selectedStudent.id_number || selectedStudent.uid}
                </p>
              </div>
            </div>
            <div className="text-xs font-bold text-text-muted">
              Emergency Contact: <span className="text-text font-bold">{selectedStudent.emergency_phone || selectedStudent.phone || 'None recorded'}</span>
            </div>
          </div>
        )}
      </Card>

      {/* Sick Bay Beds Occupancy Widget & Bed Adjustment Controls */}
      <Card className="p-6 space-y-4">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div className="flex items-center gap-2">
            <Bed size={20} className="text-rose-500" />
            <h3 className="text-sm font-black uppercase tracking-[2px] text-text">Sick Bay Bed Occupancy Status</h3>
          </div>

          {/* Adjustable Bed Count Controls */}
          <div className="flex items-center gap-3">
            <span className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">Capacity:</span>
            <div className="flex items-center border border-border rounded-xl bg-muted/40 p-1">
              <button
                type="button"
                onClick={() => updateBedCapacity(totalBeds - 1)}
                className="p-1 rounded-lg hover:bg-muted text-text-muted hover:text-text transition-colors cursor-pointer"
                title="Decrease Sick Bay Bed Capacity"
              >
                <Minus size={14} />
              </button>
              <span className="px-3 font-black text-sm text-text font-mono">{totalBeds} Beds</span>
              <button
                type="button"
                onClick={() => updateBedCapacity(totalBeds + 1)}
                className="p-1 rounded-lg hover:bg-muted text-text-muted hover:text-text transition-colors cursor-pointer"
                title="Increase Sick Bay Bed Capacity"
              >
                <Plus size={14} />
              </button>
            </div>

            <span className="px-3 py-1 bg-rose-50 dark:bg-rose-950/40 text-rose-600 rounded-full font-black text-xs">
              {activeBeds.length} / {totalBeds} Occupied
            </span>
          </div>
        </div>

        {/* Dynamic Beds Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          {Array.from({ length: totalBeds }, (_, i) => i + 1).map((bedNum) => {
            const occupied = activeBeds.find(b => b.bed_number === bedNum);
            return (
              <div
                key={bedNum}
                className={`p-4 rounded-2xl border transition-all ${
                  occupied 
                    ? 'bg-rose-500/10 border-rose-500/30' 
                    : 'bg-muted/30 border-border opacity-70'
                }`}
              >
                <div className="flex justify-between items-center mb-2">
                  <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Bed #{bedNum}</span>
                  <span className={`w-2.5 h-2.5 rounded-full ${occupied ? 'bg-rose-500 animate-pulse' : 'bg-emerald-500'}`} />
                </div>

                {occupied ? (
                  <div className="space-y-2">
                    <p className="font-bold text-xs text-text truncate">{occupied.student_first_name} {occupied.student_last_name}</p>
                    <p className="text-[0.65rem] text-rose-600 font-semibold truncate">{occupied.chief_complaint}</p>
                    <button
                      type="button"
                      onClick={() => handleDischargeBed(occupied.id!)}
                      className="w-full py-1 bg-rose-500 text-white rounded-lg text-[0.6rem] font-black uppercase tracking-wider hover:bg-rose-600 transition-all cursor-pointer"
                    >
                      Discharge
                    </button>
                  </div>
                ) : (
                  <p className="text-xs font-bold text-text-muted italic py-4 text-center">Empty Bed</p>
                )}
              </div>
            );
          })}
        </div>
      </Card>

      {/* Main Feature Tabs */}
      <div className="flex border-b border-border gap-2 overflow-x-auto pb-1 custom-scrollbar">
        {[
          { id: 'visits', label: 'Daily Encounters', icon: Activity },
          { id: 'profile', label: 'Medical Profile', icon: HeartPulse },
          { id: 'medication', label: 'Medication Dispensary', icon: Pill },
          { id: 'history', label: 'Medical History', icon: FileText },
          { id: 'immunizations', label: 'Immunization Tracker', icon: Syringe },
          { id: 'documents', label: 'Medical Records & Files', icon: FileUp },
        ].map((tab) => {
          const Icon = tab.icon;
          const isActive = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              type="button"
              onClick={() => setActiveTab(tab.id as any)}
              className={`flex items-center gap-2 px-5 py-3 rounded-xl font-bold text-xs transition-all whitespace-nowrap cursor-pointer ${
                isActive 
                  ? 'bg-primary text-white shadow-md' 
                  : 'text-text-muted hover:text-text hover:bg-muted/50'
              }`}
            >
              <Icon size={16} />
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* ================= TAB 1: DAILY CLINIC ENCOUNTERS ================= */}
      {activeTab === 'visits' && (
        <Card className="p-6 space-y-4 animate-in fade-in duration-300">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-2">
            <h3 className="text-sm font-black uppercase tracking-[2px] text-text">Sanatorium Walk-in Visits & Encounters</h3>
            
            <div className="flex items-center gap-3 w-full sm:w-auto">
              <div className="relative flex-1 sm:w-64">
                <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
                <input
                  type="text"
                  placeholder="Filter logs by student name or complaint..."
                  value={encounterSearch}
                  onChange={(e) => setEncounterSearch(e.target.value)}
                  className="w-full bg-muted/50 border border-border rounded-xl pl-9 pr-3 py-1.5 text-xs font-semibold focus:outline-none focus:border-primary text-text"
                />
              </div>

              <button
                type="button"
                onClick={() => fetchSanatoriumVisits({ limit: 100 })}
                className="text-xs font-bold text-primary flex items-center gap-1 shrink-0 cursor-pointer"
              >
                <RefreshCw size={14} /> Refresh Logs
              </button>
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse text-xs">
              <thead>
                <tr className="bg-muted/60 text-[0.65rem] font-black text-text-muted uppercase tracking-wider border-b border-border">
                  <th className="px-4 py-3">Date & Time</th>
                  <th className="px-4 py-3">Patient Student</th>
                  <th className="px-4 py-3">Chief Complaint</th>
                  <th className="px-4 py-3">Vitals (Temp / BP / Pulse)</th>
                  <th className="px-4 py-3">Treatment Given</th>
                  <th className="px-4 py-3">Disposition</th>
                  <th className="px-4 py-3 text-right">Parent Notified</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border font-medium text-text">
                {filteredVisits.map((visit) => {
                  let vitals: any = {};
                  try { vitals = JSON.parse(visit.vitals_json || '{}'); } catch (e) {}

                  return (
                    <tr key={visit.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3 text-text-muted font-mono">{formatDate(visit.visit_date)}</td>
                      <td className="px-4 py-3 font-bold">
                        {visit.student_first_name ? `${visit.student_first_name} ${visit.student_last_name}` : `Student #${visit.student_id}`}
                        <span className="block text-[0.65rem] text-text-muted font-normal">{visit.class_name || 'General'}</span>
                      </td>
                      <td className="px-4 py-3 font-semibold text-rose-600">{visit.chief_complaint}</td>
                      <td className="px-4 py-3 text-text-muted font-mono">
                        {vitals.temperature ? `${vitals.temperature}°C` : '—'} / {vitals.blood_pressure || '—'} / {vitals.pulse ? `${vitals.pulse} bpm` : '—'}
                      </td>
                      <td className="px-4 py-3">{visit.treatment_administered || 'Observation'}</td>
                      <td className="px-4 py-3">
                        <span className={`px-2 py-0.5 rounded-full text-[0.6rem] font-black uppercase tracking-wider ${
                          visit.disposition === 'admitted' ? 'bg-rose-500/20 text-rose-600' :
                          visit.disposition === 'sent_home' ? 'bg-amber-500/20 text-amber-600' :
                          visit.disposition === 'referred_hospital' ? 'bg-purple-500/20 text-purple-600' :
                          'bg-emerald-500/20 text-emerald-600'
                        }`}>
                          {visit.disposition.replace('_', ' ')}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right font-bold">
                        {visit.parent_notified ? (
                          <span className="text-emerald-600 flex items-center justify-end gap-1"><CheckCircle2 size={14} /> Sent</span>
                        ) : (
                          <span className="text-text-muted">Pending</span>
                        )}
                      </td>
                    </tr>
                  );
                })}
                {filteredVisits.length === 0 && (
                  <tr>
                    <td colSpan={7} className="text-center py-10 text-text-muted italic">
                      No matching sanatorium clinic visits found.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* ================= TAB 2: MEDICAL PROFILE ================= */}
      {activeTab === 'profile' && (
        <Card className="p-8 space-y-6 animate-in fade-in duration-300">
          {!studentUid ? (
            <EmptyState icon={HeartPulse} title="Select a student to manage medical profile" hint="Use the search bar above to look up a student." />
          ) : (
            <ProfileEditor studentUid={studentUid} />
          )}
        </Card>
      )}

      {/* ================= TAB 3: MEDICATION DISPENSARY ================= */}
      {activeTab === 'medication' && (
        <div className="space-y-6 animate-in fade-in duration-300">
          {!studentUid ? (
            <EmptyState icon={Pill} title="Select a student to dispense medication" hint="Use the search bar above to look up a student." />
          ) : (
            <MedicationLogsPanel studentUid={studentUid} />
          )}
        </div>
      )}

      {/* ================= TAB 4: MEDICAL HISTORY & ILLNESSES ================= */}
      {activeTab === 'history' && (
        <div className="space-y-6 animate-in fade-in duration-300">
          {!studentUid ? (
            <EmptyState icon={FileText} title="Select a student to view medical history" hint="Use the search bar above to look up a student." />
          ) : (
            <HistoryPanel studentUid={studentUid} onOpenAdd={() => setShowHistoryModal(true)} />
          )}
        </div>
      )}

      {/* ================= TAB 5: IMMUNIZATION TRACKER ================= */}
      {activeTab === 'immunizations' && (
        <div className="space-y-6 animate-in fade-in duration-300">
          {!studentUid ? (
            <EmptyState icon={Syringe} title="Select a student to view immunizations" hint="Use the search bar above to look up a student." />
          ) : (
            <Card className="p-8 space-y-6">
              <div className="flex justify-between items-center">
                <div>
                  <h3 className="text-lg font-black text-text uppercase tracking-wide">Student Immunization & Vaccine Records</h3>
                  <p className="text-xs text-text-muted mt-1">Official WHO/CDC vaccination log for this student.</p>
                </div>
                <button
                  type="button"
                  onClick={() => setShowImmunizationModal(true)}
                  className="px-4 py-2 bg-primary text-white text-xs font-bold rounded-xl hover:bg-primary/90 transition-all cursor-pointer"
                >
                  <Plus size={14} className="inline mr-1" /> Add Vaccine Dose
                </button>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {immunizations.map((imm) => (
                  <div key={imm.id} className="p-4 bg-muted/40 rounded-2xl border border-border space-y-2">
                    <div className="flex justify-between items-start">
                      <div>
                        <h4 className="font-black text-text text-sm">{imm.vaccine_name}</h4>
                        <p className="text-xs text-text-muted font-semibold">Dose #{imm.dose_number} · {formatDate(imm.administered_date)}</p>
                      </div>
                      <span className="px-2.5 py-1 bg-emerald-500/10 text-emerald-600 rounded-lg text-[0.65rem] font-black uppercase">
                        Verified
                      </span>
                    </div>
                    {imm.batch_number && <p className="text-xs text-text-muted font-mono">Batch: {imm.batch_number}</p>}
                    {imm.notes && <p className="text-xs text-text-secondary">{imm.notes}</p>}
                  </div>
                ))}
                {immunizations.length === 0 && (
                  <p className="text-xs text-text-muted italic">No immunization records logged for this student.</p>
                )}
              </div>
            </Card>
          )}
        </div>
      )}

      {/* ================= TAB 6: MEDICAL DOCUMENTS & INGESTION ================= */}
      {activeTab === 'documents' && (
        <div className="space-y-6 animate-in fade-in duration-300">
          {!studentUid ? (
            <EmptyState icon={FileUp} title="Select a student to manage medical documents" hint="Use the search bar above to look up a student." />
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* File Uploader & Ingestion Card */}
              <Card className="p-6 space-y-4 lg:col-span-1">
                <div className="flex justify-between items-center">
                  <h3 className="text-base font-black text-text uppercase tracking-wide">Upload Document</h3>
                  <button
                    type="button"
                    onClick={() => setShowIngestModal(true)}
                    className="text-[0.65rem] font-black uppercase tracking-wider text-primary hover:underline flex items-center gap-1 cursor-pointer"
                  >
                    <Code size={14} /> Bulk Ingest
                  </button>
                </div>

                <form onSubmit={handleFileUpload} className="space-y-3">
                  <Field label="Document Category">
                    <select className={inputClass()} value={docType} onChange={e => setDocType(e.target.value)}>
                      <option value="lab_report">Lab / Blood Test Report</option>
                      <option value="doctor_note">Doctor Notes & Prescription</option>
                      <option value="vaccination_cert">Vaccination Certificate</option>
                      <option value="other">Other Medical Record</option>
                    </select>
                  </Field>

                  <Field label="Select Medical File (PDF, Image, Doc)">
                    <input
                      type="file"
                      onChange={e => setDocFile(e.target.files?.[0] || null)}
                      className="w-full text-xs font-semibold text-text border border-border rounded-xl p-2 bg-muted/40 cursor-pointer"
                    />
                  </Field>

                  <Field label="Notes / Summary">
                    <input
                      className={inputClass()}
                      placeholder="e.g. Lab results from General Hospital"
                      value={docNotes}
                      onChange={e => setDocNotes(e.target.value)}
                    />
                  </Field>

                  <button
                    type="submit"
                    disabled={!docFile}
                    className="w-full py-3 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/90 transition-all disabled:opacity-50 flex items-center justify-center gap-2 cursor-pointer"
                  >
                    <Upload size={16} /> Upload & Save Document
                  </button>

                  {docSuccess && (
                    <div className="p-3 bg-emerald-500/10 text-emerald-600 rounded-xl text-xs font-bold flex items-center gap-2">
                      <CheckCircle2 size={16} /> {docSuccess}
                    </div>
                  )}
                </form>
              </Card>

              {/* Uploaded Documents List */}
              <Card className="p-6 lg:col-span-2 space-y-4">
                <h3 className="text-base font-black text-text uppercase tracking-wide">Ingested Medical Records & Documents</h3>
                <div className="space-y-3">
                  {medicalDocuments.map((doc) => (
                    <div key={doc.id} className="p-4 bg-muted/40 rounded-2xl border border-border flex justify-between items-center text-xs">
                      <div className="flex items-center gap-3">
                        <div className="p-3 bg-primary/10 text-primary rounded-xl font-black uppercase text-[0.65rem]">
                          {doc.file_type}
                        </div>
                        <div>
                          <a href={doc.file_url} target="_blank" rel="noreferrer" className="font-bold text-text text-sm hover:underline flex items-center gap-1">
                            {doc.file_name} <Eye size={14} className="text-text-muted" />
                          </a>
                          <p className="text-text-muted mt-0.5">
                            Category: <span className="font-semibold text-text capitalize">{doc.document_type.replace('_', ' ')}</span> · Uploaded by {doc.uploader_first_name || 'Nurse'} on {formatDate(doc.created_at)}
                          </p>
                          {doc.notes && <p className="text-text-secondary mt-1 font-mono text-[0.7rem]">{doc.notes}</p>}
                        </div>
                      </div>

                      <button
                        type="button"
                        onClick={() => deleteMedicalDocument(doc.id)}
                        className="p-2 text-text-muted hover:text-rose-500 transition-colors cursor-pointer"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  ))}
                  {medicalDocuments.length === 0 && (
                    <p className="text-xs text-text-muted italic py-6 text-center">No ingested medical documents or file attachments uploaded for this student.</p>
                  )}
                </div>
              </Card>
            </div>
          )}
        </div>
      )}

      {/* MODAL 1: Create Clinic Visit Encounter */}
      {showVisitModal && (
        <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-[150] flex items-center justify-center p-3 sm:p-4 overflow-y-auto" onClick={() => setShowVisitModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-xl border border-border p-5 sm:p-8 space-y-5 sm:space-y-6 shadow-2xl animate-in zoom-in-95 max-h-[90vh] overflow-y-auto custom-scrollbar" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center border-b border-border pb-4">
              <h3 className="text-xl font-black text-text tracking-tight uppercase flex items-center gap-2">
                <Stethoscope className="text-rose-500" size={22} /> Log Clinic Encounter
              </h3>
              <button type="button" onClick={() => setShowVisitModal(false)} className="text-text-muted hover:text-text cursor-pointer">
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleCreateVisit} className="space-y-4">
              {/* INLINE PATIENT SELECTION */}
              <div className="relative space-y-1.5">
                <Field label="Select Patient Student (Type name or pick below)">
                  <div className="relative">
                    <Search size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" />
                    <input
                      className={`${inputClass()} pl-10`}
                      placeholder="Type student name to select patient..."
                      value={modalSearchQuery}
                      onChange={(e) => handleModalSearchChange(e.target.value)}
                    />
                    {modalSearchQuery && (
                      <button
                        type="button"
                        onClick={() => { setModalSearchQuery(''); setModalSearchResults([]); setModalStudent(null); }}
                        className="absolute right-3.5 top-1/2 -translate-y-1/2 text-text-muted hover:text-text cursor-pointer"
                      >
                        <X size={14} />
                      </button>
                    )}
                  </div>
                </Field>

                {/* Modal Autocomplete Results Dropdown */}
                {modalSearchResults.length > 0 && (
                  <div className="absolute left-0 right-0 top-full mt-1 bg-card border border-border rounded-xl shadow-2xl z-[200] max-h-48 overflow-y-auto divide-y divide-border/60">
                    {modalSearchResults.map((st) => (
                      <div
                        key={st.id}
                        onClick={() => {
                          setModalStudent(st);
                          setModalSearchQuery(`${st.first_name} ${st.last_name}`);
                          setModalSearchResults([]);
                        }}
                        className="p-2.5 hover:bg-primary/10 transition-colors cursor-pointer flex justify-between items-center text-xs"
                      >
                        <div>
                          <span className="font-bold text-text">{st.first_name} {st.last_name}</span>
                          <span className="ml-2 text-text-muted font-mono text-[0.65rem]">{st.id_number || `ID-${st.id}`}</span>
                        </div>
                        <span className="px-2 py-0.5 bg-muted rounded font-bold text-text-muted text-[0.65rem]">{st.class_name || 'Student'}</span>
                      </div>
                    ))}
                  </div>
                )}

                {/* Selected Patient Confirmation Badge */}
                {modalStudent && (
                  <div className="p-3 bg-primary/10 border border-primary/20 rounded-xl flex justify-between items-center text-xs">
                    <div>
                      <span className="font-black text-primary">Patient Selected:</span>{' '}
                      <span className="font-bold text-text">{modalStudent.first_name} {modalStudent.last_name}</span>
                      <span className="text-text-muted font-normal ml-2">({modalStudent.class_name || 'Student'})</span>
                    </div>
                    <CheckCircle2 size={16} className="text-primary" />
                  </div>
                )}
              </div>

              <Field label="Chief Complaint / Symptom">
                <input
                  className={inputClass()}
                  value={visitForm.chief_complaint}
                  onChange={e => setVisitForm({ ...visitForm, chief_complaint: e.target.value })}
                  placeholder="e.g. High fever, severe migraine, sports injury..."
                />
              </Field>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
                <Field label="Temperature (°C)">
                  <input className={inputClass()} value={visitForm.temp} onChange={e => setVisitForm({ ...visitForm, temp: e.target.value })} />
                </Field>
                <Field label="Blood Pressure">
                  <input className={inputClass()} value={visitForm.bp} onChange={e => setVisitForm({ ...visitForm, bp: e.target.value })} />
                </Field>
                <Field label="Pulse (bpm)">
                  <input className={inputClass()} value={visitForm.pulse} onChange={e => setVisitForm({ ...visitForm, pulse: e.target.value })} />
                </Field>
              </div>

              <Field label="Treatment / Medication Administered">
                <textarea
                  rows={2}
                  className={inputClass()}
                  value={visitForm.treatment_administered}
                  onChange={e => setVisitForm({ ...visitForm, treatment_administered: e.target.value })}
                  placeholder="e.g. Administered Paracetamol 500mg, cold compress, rested for 30 mins"
                />
              </Field>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                <Field label="Disposition Status">
                  <select
                    className={inputClass()}
                    value={visitForm.disposition}
                    onChange={e => setVisitForm({ ...visitForm, disposition: e.target.value as any })}
                  >
                    <option value="discharged">Discharged back to Class</option>
                    <option value="admitted">Admitted to Sick Bay Bed</option>
                    <option value="sent_home">Sent Home with Guardian</option>
                    <option value="referred_hospital">Referred to Hospital</option>
                  </select>
                </Field>

                {visitForm.disposition === 'admitted' && (
                  <Field label="Sick Bay Bed Assignment">
                    <select
                      className={inputClass()}
                      value={visitForm.bed_number}
                      onChange={e => setVisitForm({ ...visitForm, bed_number: parseInt(e.target.value) })}
                    >
                      {Array.from({ length: totalBeds }, (_, i) => i + 1).map(b => (
                        <option key={b} value={b}>Bed #{b}</option>
                      ))}
                    </select>
                  </Field>
                )}
              </div>

              <div className="flex items-center gap-2 pt-2">
                <input
                  type="checkbox"
                  id="notifyParentCheck"
                  checked={visitForm.parent_notified}
                  onChange={e => setVisitForm({ ...visitForm, parent_notified: e.target.checked })}
                  className="rounded text-primary focus:ring-primary w-4 h-4 cursor-pointer"
                />
                <label htmlFor="notifyParentCheck" className="text-xs font-bold text-text cursor-pointer">
                  Send Instant Alert Notification to Parent Portal
                </label>
              </div>

              <div className="pt-4 flex justify-end gap-3 border-t border-border">
                <button type="button" onClick={() => setShowVisitModal(false)} className="px-5 py-2.5 bg-muted text-text font-bold text-xs rounded-xl cursor-pointer">
                  Cancel
                </button>
                <button type="submit" className="px-6 py-2.5 bg-primary text-white font-bold text-xs rounded-xl hover:bg-primary/90 transition-all cursor-pointer">
                  Save Visit Record
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: Kitchen Dining Hall Allergy Alert */}
      {showKitchenAlertModal && (
        <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-[150] flex items-center justify-center p-3 sm:p-4 overflow-y-auto" onClick={() => setShowKitchenAlertModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-lg border border-border p-5 sm:p-6 space-y-4 shadow-2xl animate-in zoom-in-95 max-h-[90vh] overflow-y-auto custom-scrollbar" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center border-b border-border pb-3">
              <h3 className="text-lg font-black text-text uppercase flex items-center gap-2">
                <UtensilsCrossed className="text-rose-500" size={20} /> Broadcast Kitchen Allergy Alert
              </h3>
              <button type="button" onClick={() => setShowKitchenAlertModal(false)} className="text-text-muted hover:text-text cursor-pointer">
                <X size={18} />
              </button>
            </div>

            <form onSubmit={handleSendKitchenAlert} className="space-y-3">
              <Field label="Allergy Details">
                <input
                  className={inputClass()}
                  value={kitchenAllergyText}
                  onChange={e => setKitchenAllergyText(e.target.value)}
                  placeholder="e.g. Severe Peanut & Dairy Allergy"
                />
              </Field>

              <Field label="Severity Level">
                <select className={inputClass()} value={kitchenSeverity} onChange={e => setKitchenSeverity(e.target.value)}>
                  <option value="mild">Mild (Sensitivities)</option>
                  <option value="severe">Severe (Requires strict avoidance)</option>
                  <option value="life_threatening">Life Threatening (Anaphylaxis Risk / EpiPen)</option>
                </select>
              </Field>

              <Field label="Special Kitchen Instructions">
                <textarea
                  rows={3}
                  className={inputClass()}
                  value={kitchenInstructions}
                  onChange={e => setKitchenInstructions(e.target.value)}
                  placeholder="e.g. Prepare meal using separate non-contaminated utensils."
                />
              </Field>

              {kitchenAlertSuccess && (
                <div className="p-3 bg-emerald-500/10 text-emerald-600 rounded-xl text-xs font-bold flex items-center gap-2">
                  <CheckCircle2 size={16} /> {kitchenAlertSuccess}
                </div>
              )}

              <div className="pt-3 flex justify-end gap-2 border-t border-border">
                <button type="button" onClick={() => setShowKitchenAlertModal(false)} className="px-4 py-2 bg-muted text-text font-bold text-xs rounded-xl cursor-pointer">
                  Cancel
                </button>
                <button type="submit" className="px-5 py-2 bg-rose-600 text-white font-bold text-xs rounded-xl hover:bg-rose-700 transition-all flex items-center gap-1 cursor-pointer">
                  <Send size={14} /> Broadcast to Kitchen
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 3: Bulk JSON Record Ingestion Modal */}
      {showIngestModal && (
        <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-[150] flex items-center justify-center p-3 sm:p-4 overflow-y-auto" onClick={() => setShowIngestModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-2xl border border-border p-5 sm:p-6 space-y-4 shadow-2xl animate-in zoom-in-95 max-h-[90vh] overflow-y-auto custom-scrollbar" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center border-b border-border pb-3">
              <h3 className="text-lg font-black text-text uppercase flex items-center gap-2">
                <Code className="text-primary" size={20} /> Bulk Medical Record Ingestion
              </h3>
              <button type="button" onClick={() => setShowIngestModal(false)} className="text-text-muted hover:text-text cursor-pointer">
                <X size={18} />
              </button>
            </div>

            <form onSubmit={handleBulkIngestJSON} className="space-y-3">
              <Field label="Paste JSON Medical Records Array">
                <textarea
                  rows={8}
                  className={`${inputClass()} font-mono text-xs`}
                  placeholder='[ { "student_uid": "user-uuid", "blood_group": "O+", "allergies": "Peanuts", "emergency_instructions": "EpiPen in clinic" } ]'
                  value={jsonInput}
                  onChange={e => setJsonInput(e.target.value)}
                />
              </Field>

              {ingestStatus && (
                <ProgressBar
                  progress={100}
                  label={ingestStatus}
                  sublabel="Database commit complete."
                  color="emerald"
                />
              )}

              <div className="pt-3 flex justify-end gap-2 border-t border-border">
                <button type="button" onClick={() => setShowIngestModal(false)} className="px-4 py-2 bg-muted text-text font-bold text-xs rounded-xl cursor-pointer">
                  Cancel
                </button>
                <button type="submit" className="px-5 py-2 bg-primary text-white font-bold text-xs rounded-xl hover:bg-primary/90 transition-all cursor-pointer">
                  Ingest Medical Records
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 4: Add Immunization */}
      {showImmunizationModal && (
        <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-[150] flex items-center justify-center p-3 sm:p-4 overflow-y-auto" onClick={() => setShowImmunizationModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-md border border-border p-5 sm:p-6 space-y-4 shadow-2xl animate-in zoom-in-95 max-h-[90vh] overflow-y-auto custom-scrollbar" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center border-b border-border pb-3">
              <h3 className="text-lg font-black text-text uppercase flex items-center gap-2">
                <Syringe className="text-emerald-500" size={20} /> Add Immunization Dose
              </h3>
              <button type="button" onClick={() => setShowImmunizationModal(false)} className="text-text-muted hover:text-text cursor-pointer">
                <X size={18} />
              </button>
            </div>
            <form onSubmit={handleAddImmunization} className="space-y-3">
              <Field label="Vaccine Name">
                <input className={inputClass()} value={immForm.vaccine_name} onChange={e => setImmForm({ ...immForm, vaccine_name: e.target.value })} />
              </Field>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Field label="Dose Number">
                  <input type="number" className={inputClass()} value={immForm.dose_number} onChange={e => setImmForm({ ...immForm, dose_number: parseInt(e.target.value) })} />
                </Field>
                <Field label="Date Administered">
                  <input type="date" className={inputClass()} value={immForm.administered_date} onChange={e => setImmForm({ ...immForm, administered_date: e.target.value })} />
                </Field>
              </div>
              <Field label="Batch / Lot Number">
                <input className={inputClass()} value={immForm.batch_number} onChange={e => setImmForm({ ...immForm, batch_number: e.target.value })} placeholder="Optional batch no." />
              </Field>
              <div className="pt-3 flex justify-end gap-2">
                <button type="button" onClick={() => setShowImmunizationModal(false)} className="px-4 py-2 bg-muted text-text font-bold text-xs rounded-xl cursor-pointer">
                  Cancel
                </button>
                <button type="submit" className="px-5 py-2 bg-emerald-600 text-white font-bold text-xs rounded-xl hover:bg-emerald-700 transition-all cursor-pointer">
                  Save Vaccine Dose
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 5: Parent Alert Modal */}
      {showParentAlertModal && (
        <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-[150] flex items-center justify-center p-3 sm:p-4 overflow-y-auto" onClick={() => setShowParentAlertModal(false)}>
          <div className="bg-card rounded-[2rem] w-full max-w-lg border border-border p-5 sm:p-6 space-y-4 shadow-2xl animate-in zoom-in-95 max-h-[90vh] overflow-y-auto custom-scrollbar" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center border-b border-border pb-3">
              <h3 className="text-lg font-black text-text uppercase flex items-center gap-2">
                <Bell className="text-amber-500" size={20} /> Alert Student Parent
              </h3>
              <button type="button" onClick={() => setShowParentAlertModal(false)} className="text-text-muted hover:text-text cursor-pointer">
                <X size={18} />
              </button>
            </div>
            <form onSubmit={handleSendParentAlert} className="space-y-3">
              <Field label="Notification Subject">
                <input className={inputClass()} value={alertSubject} onChange={e => setAlertSubject(e.target.value)} />
              </Field>
              <Field label="Message Body">
                <textarea rows={4} className={inputClass()} value={alertBody} onChange={e => setAlertBody(e.target.value)} />
              </Field>
              {alertSuccess && (
                <div className="p-3 bg-emerald-500/10 text-emerald-600 rounded-xl text-xs font-bold flex items-center gap-2">
                  <CheckCircle2 size={16} /> {alertSuccess}
                </div>
              )}
              <div className="pt-3 flex justify-end gap-2">
                <button type="button" onClick={() => setShowParentAlertModal(false)} className="px-4 py-2 bg-muted text-text font-bold text-xs rounded-xl cursor-pointer">
                  Cancel
                </button>
                <button type="submit" className="px-5 py-2 bg-amber-500 text-white font-bold text-xs rounded-xl hover:bg-amber-600 transition-all flex items-center gap-1 cursor-pointer">
                  <Send size={14} /> Send Alert Message
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </PageShell>
  );
}

// Profile Editor Subcomponent
function ProfileEditor({ studentUid }: { studentUid: string }) {
  const { currentProfile, saveProfile, loading } = useMedicalStore();
  const [draft, setDraft] = useState<Partial<MedicalProfile>>({});

  useEffect(() => { setDraft(currentProfile || {}); }, [currentProfile?.uid]);

  const onSave = async () => {
    await saveProfile(studentUid, draft);
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center border-b border-border pb-4">
        <div>
          <h3 className="text-lg font-black text-text uppercase tracking-wide">Student Medical Profile Editor</h3>
          <p className="text-xs text-text-muted mt-0.5">Edit official blood group, allergies, contraindications, and emergency instructions.</p>
        </div>
        <button
          onClick={onSave}
          disabled={loading}
          className="px-6 py-3 bg-primary text-white rounded-xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg active:scale-95 disabled:opacity-50 cursor-pointer"
        >
          <Save size={16} className="inline mr-2" />
          {loading ? 'Saving Profile...' : 'Save Profile'}
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Field label="Blood Group">
          <select className={inputClass()} value={draft.blood_group || ''} onChange={(e) => setDraft({ ...draft, blood_group: e.target.value })}>
            <option value="">Unknown</option>
            {['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'].map(b => <option key={b} value={b}>{b}</option>)}
          </select>
        </Field>
        <Field label="Chronic Conditions">
          <textarea rows={2} className={inputClass()} value={draft.chronic_conditions || ''}
            onChange={(e) => setDraft({ ...draft, chronic_conditions: e.target.value })}
            placeholder="Asthma, diabetes, epilepsy, ..." />
        </Field>
        <Field label="Allergies">
          <textarea rows={2} className={inputClass()} value={draft.allergies || ''}
            onChange={(e) => setDraft({ ...draft, allergies: e.target.value })}
            placeholder="Food (peanuts, dairy), drug (penicillin), insect (bee), ..." />
        </Field>
        <Field label="Dietary Restrictions">
          <textarea rows={2} className={inputClass()} value={draft.dietary_restrictions || ''}
            onChange={(e) => setDraft({ ...draft, dietary_restrictions: e.target.value })}
            placeholder="Vegetarian, Halal, Diabetic, ..." />
        </Field>
        <Field label="Contraindicated Medications (DANGER ALERT)">
          <textarea rows={2} className={`${inputClass()} border-rose-500/40 bg-rose-500/5`} value={draft.contraindications || ''}
            onChange={(e) => setDraft({ ...draft, contraindications: e.target.value })}
            placeholder="Medications the student MUST NOT receive under any circumstance" />
        </Field>
        <Field label="Emergency Instructions">
          <textarea rows={3} className={inputClass()} value={draft.emergency_instructions || ''}
            onChange={(e) => setDraft({ ...draft, emergency_instructions: e.target.value })}
            placeholder="Steps to take during an episode. EpiPen location. Emergency contact instructions." />
        </Field>
      </div>
    </div>
  );
}

// Medication Logs Subcomponent
function MedicationLogsPanel({ studentUid }: { studentUid: string }) {
  const { medicationLogs, addMedicationLog, deleteMedicationLog, currentProfile } = useMedicalStore();
  const [draft, setDraft] = useState<Partial<MedicationLog>>({
    medication_name: '', dosage: '', administered_at: new Date().toISOString().slice(0, 16), reason: '',
  });
  const [lastWarning, setLastWarning] = useState<string | null>(null);

  // Check contraindications
  const contraindications = (currentProfile?.contraindications || '').toLowerCase();
  const currentMedName = (draft.medication_name || '').toLowerCase();
  const isContraindicated = currentMedName && contraindications.includes(currentMedName);

  const onSubmit = async () => {
    if (!draft.medication_name || !draft.dosage || !draft.administered_at) return;
    if (isContraindicated && !window.confirm(`WARNING: ${draft.medication_name} is listed under CONTRAINDICATIONS for this student! Are you sure you want to dispense?`)) {
      return;
    }
    const r = await addMedicationLog(studentUid, draft);
    if (r?.warning) setLastWarning(r.warning);
    else setLastWarning(null);
    setDraft({ medication_name: '', dosage: '', administered_at: new Date().toISOString().slice(0, 16), reason: '' });
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <Card className="p-6 lg:col-span-1 space-y-4">
        <h3 className="text-base font-black text-text uppercase tracking-wide">Dispense Medication</h3>
        <div className="space-y-3">
          <Field label="Medication Name">
            <input className={inputClass()} value={draft.medication_name || ''}
              onChange={(e) => setDraft({ ...draft, medication_name: e.target.value })} placeholder="e.g. Paracetamol" />
          </Field>

          {isContraindicated && (
            <div className="p-3 bg-rose-500/10 border border-rose-500/30 text-rose-600 rounded-xl text-xs font-bold flex items-center gap-2">
              <ShieldAlert size={18} /> CONTRAINDICATION WARNING! This medication is marked unsafe.
            </div>
          )}

          <Field label="Dosage">
            <input className={inputClass()} value={draft.dosage || ''}
              onChange={(e) => setDraft({ ...draft, dosage: e.target.value })} placeholder="e.g. 1 tablet (500mg)" />
          </Field>
          <Field label="Administered Date & Time">
            <input type="datetime-local" className={inputClass()} value={(draft.administered_at || '').slice(0, 16)}
              onChange={(e) => setDraft({ ...draft, administered_at: e.target.value })} />
          </Field>
          <Field label="Reason / Notes">
            <input className={inputClass()} value={draft.reason || ''}
              onChange={(e) => setDraft({ ...draft, reason: e.target.value })} placeholder="Headache, fever..." />
          </Field>
          <button onClick={onSubmit}
            className="w-full py-3 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/90 transition-all cursor-pointer">
            <Pill size={14} className="inline mr-2" /> Log Dispensation
          </button>
          {lastWarning && (
            <div className="p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl text-amber-700 text-xs font-bold">
              <AlertTriangle size={14} className="inline mr-1" /> {lastWarning}
            </div>
          )}
        </div>
      </Card>

      <Card className="p-6 lg:col-span-2 space-y-4">
        <h3 className="text-base font-black text-text uppercase tracking-wide">Medication Logs History</h3>
        {medicationLogs.length === 0 ? (
          <p className="text-xs text-text-muted italic">No medication dispensations recorded yet.</p>
        ) : (
          <div className="space-y-2">
            {medicationLogs.map((log) => (
              <div key={log.id} className="p-4 bg-muted/40 rounded-2xl border border-border flex justify-between items-center">
                <div>
                  <p className="font-bold text-text text-sm">{log.medication_name} <span className="text-text-muted text-xs font-normal">({log.dosage})</span></p>
                  <p className="text-xs text-text-muted mt-0.5">{formatDate(log.administered_at)} · Reason: {log.reason || 'Not specified'}</p>
                </div>
                <button
                  onClick={() => log.id && deleteMedicationLog(log.id)}
                  className="p-2 text-text-muted hover:text-rose-500 transition-colors cursor-pointer"
                >
                  <Trash2 size={16} />
                </button>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

// History Panel Subcomponent
function HistoryPanel({ studentUid, onOpenAdd }: { studentUid: string; onOpenAdd?: () => void }) {
  const { medicalHistory, deleteHistoryEvent } = useMedicalStore();

  return (
    <Card className="p-8 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-lg font-black text-text uppercase tracking-wide">Medical History & Events</h3>
          <p className="text-xs text-text-muted mt-1">Recorded illnesses, injuries, surgeries, and hospitalizations.</p>
        </div>
        {onOpenAdd && (
          <button
            type="button"
            onClick={onOpenAdd}
            className="px-4 py-2 bg-primary text-white text-xs font-bold rounded-xl hover:bg-primary/90 transition-all cursor-pointer"
          >
            <Plus size={14} className="inline mr-1" /> Log Medical Event
          </button>
        )}
      </div>

      <div className="space-y-3">
        {medicalHistory.map((hist) => (
          <div key={hist.id} className="p-4 bg-muted/40 rounded-2xl border border-border space-y-2">
            <div className="flex justify-between items-start">
              <div className="flex items-center gap-2">
                <span className="text-lg">{eventTypeIcon(hist.event_type)}</span>
                <div>
                  <h4 className="font-black text-text text-sm">{hist.title || hist.description}</h4>
                  <p className="text-xs text-text-muted font-semibold capitalize">{hist.event_type} · Severity: {hist.severity || 'mild'}</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <span className="px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase text-white" style={{ backgroundColor: severityColor(hist.severity) }}>
                  {hist.severity || 'mild'}
                </span>
                <button
                  onClick={() => hist.id && deleteHistoryEvent(hist.id)}
                  className="p-1.5 text-text-muted hover:text-rose-500 cursor-pointer"
                >
                  <Trash2 size={16} />
                </button>
              </div>
            </div>
            {hist.doctor_notes && (
              <p className="text-xs text-text-secondary bg-card p-3 rounded-xl border border-border">
                <b className="text-text">Clinical Notes:</b> {hist.doctor_notes}
              </p>
            )}
          </div>
        ))}
        {medicalHistory.length === 0 && (
          <p className="text-xs text-text-muted italic text-center py-6">No medical history events logged for this student.</p>
        )}
      </div>
    </Card>
  );
}

// Student View Page
export function MedicalProfilePage() {
  const { studentUid } = useParams<{ studentUid: string }>();
  const { currentProfile, fetchProfile } = useMedicalStore();

  useEffect(() => {
    if (studentUid) fetchProfile(studentUid);
  }, [studentUid]);

  return (
    <PageShell title="Student Medical Profile" breadcrumb="Personal Records">
      <Card className="p-8 space-y-4">
        <h2 className="text-xl font-black text-text">Medical Information</h2>
        <div className="grid grid-cols-2 gap-4 text-xs font-semibold text-text">
          <p><strong>Blood Group:</strong> {currentProfile?.blood_group || 'Not on file'}</p>
          <p><strong>Allergies:</strong> {currentProfile?.allergies || 'None recorded'}</p>
          <p><strong>Dietary Restrictions:</strong> {currentProfile?.dietary_restrictions || 'None recorded'}</p>
          <p><strong>Emergency Instructions:</strong> {currentProfile?.emergency_instructions || 'None recorded'}</p>
        </div>
      </Card>
    </PageShell>
  );
}

export function StudentMedicalSelfView({ studentUid }: { studentUid: string }) {
  const { currentProfile, fetchProfile } = useMedicalStore();

  useEffect(() => {
    if (studentUid) fetchProfile(studentUid);
  }, [studentUid]);

  return (
    <PageShell title="My Medical Profile" breadcrumb="Personal Health Record">
      <Card className="p-8 space-y-4">
        <h2 className="text-xl font-black text-text font-mono">Medical Information</h2>
        <div className="grid grid-cols-2 gap-4 text-xs font-semibold text-text">
          <p><strong>Blood Group:</strong> {currentProfile?.blood_group || 'Not on file'}</p>
          <p><strong>Allergies:</strong> {currentProfile?.allergies || 'None recorded'}</p>
          <p><strong>Dietary Restrictions:</strong> {currentProfile?.dietary_restrictions || 'None recorded'}</p>
          <p><strong>Emergency Instructions:</strong> {currentProfile?.emergency_instructions || 'None recorded'}</p>
        </div>
      </Card>
    </PageShell>
  );
}

export function ParentMedicalView({ studentUid }: { studentUid: string }) {
  return (
    <PageShell title="Child Medical Record" breadcrumb="Parent View">
      <ProfileEditor studentUid={studentUid} />
    </PageShell>
  );
}

// Dining Hall Kitchen View Page (QUERY REAL SQLITE DB - ZERO MOCK DATA!)
export function KitchenAlertsPage() {
  const { diningAlerts, fetchDiningAlerts, acknowledgeDiningAlert } = useMedicalStore();

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

  return (
    <PageShell title="Dining Hall Allergy & Dietary Roster" breadcrumb="Kitchen Alerts Console">
      <Card className="p-6 space-y-4">
        <div className="flex justify-between items-center border-b border-border pb-4">
          <div>
            <h3 className="text-base font-black text-text uppercase tracking-wide flex items-center gap-2">
              <UtensilsCrossed className="text-rose-500" size={20} /> Real-Time Kitchen Tablet Allergy Roster
            </h3>
            <p className="text-xs text-text-muted mt-0.5">Live student dietary restrictions and broadcasted Sanatorium alerts.</p>
          </div>
          <button
            type="button"
            onClick={fetchDiningAlerts}
            className="px-4 py-2 bg-muted hover:bg-muted/80 text-text font-bold text-xs rounded-xl flex items-center gap-1.5 cursor-pointer"
          >
            <RefreshCw size={14} /> Refresh Roster
          </button>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="bg-muted/60 text-[0.65rem] font-black text-text-muted uppercase tracking-wider border-b border-border">
                <th className="p-3">Student Name</th>
                <th className="p-3">Class</th>
                <th className="p-3">Severity</th>
                <th className="p-3">Allergies & Flagged Restrictions</th>
                <th className="p-3">Kitchen Instructions</th>
                <th className="p-3 text-right">Kitchen Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border font-medium text-text">
              {diningAlerts.map((row, idx) => {
                const isAlertActive = row.alert_status === 'active';
                return (
                  <tr key={idx} className={`transition-colors ${isAlertActive ? 'bg-rose-500/10 dark:bg-rose-950/30' : 'hover:bg-muted/30'}`}>
                    <td className="p-3 font-bold">
                      {row.name}
                      {isAlertActive && (
                        <span className="ml-2 px-2 py-0.5 bg-rose-600 text-white font-black text-[0.6rem] uppercase tracking-wider rounded-full animate-pulse">
                          NEW ALERT
                        </span>
                      )}
                    </td>
                    <td className="p-3 font-semibold text-text-muted">{row.class}</td>
                    <td className="p-3">
                      <span className="px-2.5 py-1 rounded-lg text-[0.65rem] font-black uppercase text-white" style={{ backgroundColor: severityColor(row.severity) }}>
                        {(row.severity || 'mild').replace('_', ' ')}
                      </span>
                    </td>
                    <td className="p-3 font-black text-rose-600">{row.allergies || row.dietary_restrictions || '—'}</td>
                    <td className="p-3 text-text-secondary">{row.special_instructions || row.emergency_instructions || 'Standard meal'}</td>
                    <td className="p-3 text-right font-bold">
                      {row.alert_id && isAlertActive ? (
                        <button
                          type="button"
                          onClick={() => acknowledgeDiningAlert(row.alert_id!)}
                          className="px-3 py-1 bg-emerald-600 text-white rounded-lg text-[0.65rem] font-black uppercase tracking-wider hover:bg-emerald-700 transition-all cursor-pointer"
                        >
                          Acknowledge
                        </button>
                      ) : row.alert_status === 'acknowledged' ? (
                        <span className="text-emerald-600 font-black text-[0.65rem] uppercase tracking-widest flex items-center justify-end gap-1">
                          <CheckCircle2 size={14} /> Acknowledged
                        </span>
                      ) : (
                        <span className="text-text-muted">Roster Verified</span>
                      )}
                    </td>
                  </tr>
                );
              })}
              {diningAlerts.length === 0 && (
                <tr>
                  <td colSpan={6} className="text-center py-10 text-text-muted italic">
                    No active dietary restrictions or allergy alerts logged in the system.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </PageShell>
  );
}

// Teacher Class Flags View Page
export function TeacherClassFlagsPage() {
  const { classId } = useParams<{ classId: string }>();
  const { classFlags, fetchClassFlags, loading } = useMedicalStore();
  const [classes, setClasses] = useState<any[]>([]);
  const [selectedClassId, setSelectedClassId] = useState<string>(classId || '');
  const [search, setSearch] = useState<string>('');

  useEffect(() => {
    let alive = true;
    api.get('/classes')
      .then(res => {
        if (!alive) return;
        const cls = res.data || [];
        setClasses(cls);
        if (!classId && cls.length > 0) {
          setSelectedClassId(String(cls[0].id));
        } else if (!classId && cls.length === 0) {
          setSelectedClassId('1');
        }
      })
      .catch(err => {
        console.error('Failed to load classes', err);
        if (!classId) setSelectedClassId('1');
      });
    return () => { alive = false; };
  }, [classId]);

  useEffect(() => {
    const idToFetch = selectedClassId || classId || '1';
    fetchClassFlags(parseInt(idToFetch));
  }, [selectedClassId, classId, fetchClassFlags]);

  const filteredFlags = useMemo(() => {
    if (!search.trim()) return classFlags;
    const s = search.toLowerCase();
    return classFlags.filter((flag) =>
      flag.name?.toLowerCase().includes(s) ||
      flag.blood_group?.toLowerCase().includes(s) ||
      flag.allergies?.toLowerCase().includes(s) ||
      flag.chronic_conditions?.toLowerCase().includes(s)
    );
  }, [classFlags, search]);

  return (
    <PageShell title="Classroom Medical Flags" breadcrumb="Teacher Medical Summary">
      <Card className="p-6 sm:p-8 space-y-6">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-border pb-4">
          <div>
            <h3 className="text-lg font-black text-text uppercase tracking-tight">Class Roster Medical Flags</h3>
            <p className="text-xs text-text-muted mt-0.5 font-medium">
              Confidential allergy, blood group, and emergency flags for your class roster.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
            {classes.length > 0 && (
              <select
                value={selectedClassId}
                onChange={(e) => setSelectedClassId(e.target.value)}
                className="px-3.5 py-2 bg-muted border border-border rounded-xl text-xs font-bold text-text focus:outline-none focus:ring-2 focus:ring-primary/20"
              >
                {classes.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name} {c.section ? `(${c.section})` : ''}
                  </option>
                ))}
              </select>
            )}

            <div className="relative flex-1 sm:w-64">
              <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
              <input
                type="text"
                placeholder="Search student or allergy..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-9 pr-3 py-2 bg-muted border border-border rounded-xl text-xs font-medium text-text focus:outline-none focus:ring-2 focus:ring-primary/20"
              />
            </div>
          </div>
        </div>

        {loading ? (
          <div className="py-12 text-center flex flex-col items-center justify-center gap-2">
            <RefreshCw size={24} className="animate-spin text-primary" />
            <p className="text-xs font-bold text-text-muted">Loading class medical flags...</p>
          </div>
        ) : filteredFlags.length === 0 ? (
          <div className="py-12 text-center space-y-2">
            <ShieldAlert size={36} className="mx-auto text-text-muted/40" />
            <p className="text-sm font-bold text-text">No Medical Flags Found</p>
            <p className="text-xs text-text-muted max-w-sm mx-auto">
              No students with active medical flags or allergies in this class roster.
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {filteredFlags.map((flag) => (
              <div key={flag.student_id} className="p-5 bg-card hover:bg-muted/30 border border-border rounded-2xl transition-all shadow-sm space-y-3">
                <div className="flex justify-between items-start">
                  <div>
                    <h4 className="font-bold text-text text-base">{flag.name}</h4>
                    <p className="text-xs text-text-muted font-medium mt-0.5">
                      Blood Group: <span className="font-bold text-rose-500">{flag.blood_group || 'Not Specified'}</span>
                    </p>
                  </div>
                  {flag.allergies && (
                    <span className="px-2.5 py-1 bg-rose-500/10 text-rose-600 border border-rose-500/20 text-[0.65rem] font-black uppercase rounded-lg">
                      Allergy Alert
                    </span>
                  )}
                </div>

                <div className="space-y-1.5 text-xs">
                  <div>
                    <span className="font-bold text-text-muted">Allergies: </span>
                    <span className={`font-semibold ${flag.allergies ? 'text-rose-600 dark:text-rose-400' : 'text-text'}`}>
                      {flag.allergies || 'None reported'}
                    </span>
                  </div>
                  {flag.chronic_conditions && (
                    <div>
                      <span className="font-bold text-text-muted">Chronic Conditions: </span>
                      <span className="font-semibold text-amber-600 dark:text-amber-400">{flag.chronic_conditions}</span>
                    </div>
                  )}
                  {flag.emergency_instructions && (
                    <div>
                      <span className="font-bold text-text-muted">Emergency Plan: </span>
                      <span className="font-semibold text-primary">{flag.emergency_instructions}</span>
                    </div>
                  )}
                </div>

                <div className="pt-2 border-t border-border/50 flex justify-between items-center text-[0.7rem]">
                  <span className="font-bold text-text-muted">Active Meds: {flag.active_med_count}</span>
                  <span className="font-bold text-text-muted">Active Conditions: {flag.active_history_count}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </PageShell>
  );
}

// Exports for App.tsx routing
export { KitchenAlertsPage as DiningHall, TeacherClassFlagsPage as ClassMedicalView };

export default SanatoriumPortal;
