"use client";

import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from 'recharts';
import * as XLSX from 'xlsx';
import { getScheduleInfo, getSchedule } from '@/lib/scheduleStorage';
import { getDepartmentSectionNames, getDepartmentSectionColors } from '@/lib/types';
import type { Department, DayOfWeek } from '@/lib/types';

// Types
interface Student {
  name: string;
  idNumber?: string;
  startDate: string;
  endDate: string;
  phone: string;
  originalDepartment?: string;
  suspendDate?: string;
  university?: string;            // For regular students: their university. For trainers: their GRADUATION university
  graduatedUniversity?: string;  // 🎓 الجامعة المتخرج منها — personal academic credential (trainers only)
  contractedUniversity?: string; // 🤝 الجامعة المتعاقد معها — hospital partner (drives classification & stats for trainers)
  contractedUniversities?: string[]; // Multiple contracted universities (array form)
  previousContractedUniversity?: string; // Legacy field for migration
  graduationYear?: string;
  department?: string;
  deptLabel?: string;
  globalStartDate?: string;
  globalEndDate?: string;
  address?: string;
  studySystem?: string;
  internshipYear?: string;
  shiftSystem?: string;
  photoBase64?: string;
  doctorPhotoBase64?: string;
  unionPaperBase64?: string;
  unionPaperFileName?: string;
  remainingDepartments?: string[];
  rotationNumber?: number;
  totalRotations?: number;
  allRotations?: {num: number; dept: string; start: string; end: string}[];
  attendanceDays?: string;
  status?: string;
  isGraduate?: boolean;
  leavingDate?: string;
  assignedTrainer?: string;   // 👤 اسم المدرب السريري المعيّن لهذا الطالب
  [key: string]: any;
}

interface StudentsData {
  [key: string]: Student[];
}

// ══════════════════════════════════════════════════════════════════════════════
// 🎓 Comprehensive University Name Normalizer & Deduplication Engine
// ══════════════════════════════════════════════════════════════════════════════
export function normalizeUniversityName(rawUni?: string | null): string {
  if (!rawUni || typeof rawUni !== 'string' || !rawUni.trim()) {
    return 'جامعات أخرى / غير محدد';
  }

  const originalTrimmed = rawUni.trim();
  const clean = originalTrimmed
    .replace(/[\u064B-\u065F]/g, '') // remove arabic tashkeel diacritics
    .replace(/[إأآا]/g, 'ا')
    .replace(/[ة]/g, 'ه')
    .replace(/[ى]/g, 'ي')
    .toLowerCase();

  // ══════════════════════════════════════════════════════════════════
  // 🇪🇬 EGYPTIAN UNIVERSITIES — ALL grouped as "جامعات مصر"
  // (Alexandria, Cairo/Qasr el-Ainy, Mansoura, Tanta, Kafr el-Sheikh,
  //  Ain Shams, Banha, Al-Azhar, Zagazig, Menofia, Damietta, Assiut…)
  // ══════════════════════════════════════════════════════════════════
  const isEgyptian = (
    // explicit "مصر" keyword
    clean.includes('مصر') ||
    // city/university names that are exclusively Egyptian
    clean.includes('اسكندر') ||    // Alexandria
    clean.includes('منصور') ||     // Mansoura
    clean.includes('طنطا') ||      // Tanta
    clean.includes('كفر الشيخ') || // Kafr El-Sheikh
    clean.includes('عين شمس') ||   // Ain Shams
    clean.includes('بنها') ||      // Banha
    clean.includes('زقازيق') ||    // Zagazig
    clean.includes('منوفيه') || clean.includes('منوفيا') || // Menoufia
    clean.includes('دمياط') ||     // Damietta
    clean.includes('اسيوط') ||     // Assiut
    clean.includes('سوهاج') ||     // Sohag
    clean.includes('قصر العيني') || // Qasr El-Ainy (Cairo University)
    (clean.includes('قاهر') && !clean.includes('قدس'))  // Cairo (but not Al-Quds!)
  );
  if (isEgyptian) return 'جامعات مصر';

  // English check
  if (clean.includes('polytechnic')) return 'جامعة بوليتكنك فلسطين';

  // 1. Palestine Polytechnic University (بوليتكنك، بولتكنك، بوليتيكن، بولتكنيك، بلوتكنيك، كلية المهن التطبيقية)
  if (
    clean.includes('بوليتكنك') || 
    clean.includes('بولتكنك') || 
    clean.includes('بوليتيكن') || 
    clean.includes('بولتيكن') || 
    clean.includes('بولتكنيك') || 
    clean.includes('بلوتكنيك') || 
    clean.includes('بوليتكنيك') || 
    (clean.includes('مهن') && clean.includes('تطبيق'))
  ) {
    return 'جامعة بوليتكنك فلسطين';
  }

  // 2. Al-Quds Open University (جامعة القدس المفتوحة)
  if (clean.includes('مفتوح')) {
    return 'جامعة القدس المفتوحة';
  }

  // 3. Hebron & Al-Quds joint application or Al-Quds University Abu Dis
  if (clean.includes('خليل') && (clean.includes('قدس') || clean.includes('ابو ديس') || clean.includes('ابوديس'))) {
    return 'جامعة القدس (أبو ديس)';
  }

  // 4. Hebron University (جامعة الخليل، كلية التمريض، الصيدلة والعلوم الطبية)
  if (clean.includes('خليل')) {
    return 'جامعة الخليل';
  }

  // 5. Al-Quds University Abu Dis (جامعة القدس، أبو ديس)
  if (clean.includes('قدس') || clean.includes('ابو ديس') || clean.includes('ابوديس')) {
    return 'جامعة القدس (أبو ديس)';
  }

  // 6. Smart University College (الكلية الذكية الجامعية للتعليم الحديث)
  if (clean.includes('ذكيه') || clean.includes('ذكية')) {
    return 'الكلية الذكية الجامعية للتعليم الحديث';
  }

  // 7. Modern University College (الكلية العصرية الجامعية / الكلية الجامعية الحديثة)
  if (clean.includes('عصريه') || clean.includes('عصرية') || clean.includes('جامعيه حديثه') || clean.includes('جامعية حديثة')) {
    return 'الكلية العصرية الجامعية';
  }

  // 8. Arab American University (الجامعة العربية الأمريكية)
  if (clean.includes('عربيه امريكيه') || clean.includes('عربية امريكية') || (clean.includes('عربيه') && clean.includes('امريكيه'))) {
    return 'الجامعة العربية الأمريكية';
  }

  // 9. Bethlehem University (جامعة بيت لحم)
  if (clean.includes('بيت لحم')) {
    return 'جامعة بيت لحم';
  }

  // 10. Nablus Vocational University (جامعة نابلس للتعليم المهني والتقني)
  if (clean.includes('نابلس')) {
    return 'جامعة نابلس للتعليم المهني والتقني';
  }

  // 11. Palestine Ahliya University (جامعة فلسطين الأهلية)
  if (clean.includes('اهلي') || clean.includes('أهلي')) {
    return 'جامعة فلسطين الأهلية';
  }

  // 12. Birzeit University (جامعة بيرزيت)
  if (clean.includes('بيرزيت')) {
    return 'جامعة بيرزيت';
  }

  // 13. An-Najah National University (جامعة النجاح الوطنية)
  if (clean.includes('نجاح')) {
    return 'جامعة النجاح الوطنية';
  }

  // 14. Al-Azhar University — note: check AFTER Egyptian block above so Gaza/Palestine branch stays here
  if (clean.includes('ازهر') || clean.includes('أزهر')) {
    return 'جامعة الأزهر';
  }

  // 15. Hashemite University (الجامعة الهاشمية - الأردن)
  if (clean.includes('هاشمي') || clean.includes('هاشميه')) {
    return 'الجامعة الهاشمية';
  }

  // 16. Red Sea University (جامعة البحر الأحمر - السودان/اليمن)
  if (clean.includes('بحر الاحمر') || clean.includes('بحر احمر')) {
    return 'جامعة البحر الأحمر';
  }

  // 17. Washington University for Health Sciences (جامعة واشنطن للصحة والعلوم)
  if (clean.includes('واشنطن') || clean.includes('washington')) {
    return 'جامعة واشنطن للصحة والعلوم';
  }

  // 18. International Medical University (الجامعة الطبية الدولية / IMU)
  if (clean.includes('دوليه') || clean.includes('دوليه') || clean.includes('imu')) {
    return 'الجامعة الطبية الدولية';
  }

  // 19. Dnipro Medical University (جامعة دنيبرو الطبية)
  if (clean.includes('dnipro') || clean.includes('دنيبرو')) {
    return 'جامعة دنيبرو الطبية (Dnipro)';
  }

  return originalTrimmed;
}


export const cleanStr = (s: string) => (s || '')
  .trim()
  .toLowerCase()
  .replace(/[أإآءئؤ]/g, 'ا')
  .replace(/ة/g, 'ه')
  .replace(/ى/g, 'ي')
  .replace(/[\u064B-\u065F\u0670\u0640]/g, '')
  .replace(/\s+/g, ' ');

export const cleanPhone = (ph: string) => {
  const d = (ph || '').replace(/\D/g, '');
  return d.length >= 9 ? d.slice(-9) : d;
};

export const normalizeContractedPartner = (raw?: string | null): string | null => {
  if (!raw || typeof raw !== 'string') return null;
  const clean = raw.trim()
    .replace(/[\u064B-\u065F]/g, '')
    .replace(/[إأآا]/g, 'ا')
    .replace(/[ة]/g, 'ه')
    .replace(/[ى]/g, 'ي')
    .toLowerCase();

  if (clean.includes('قدس') || clean.includes('ابو ديس') || clean.includes('ابوديس')) {
    return 'جامعة القدس (أبو ديس)';
  }
  if (clean.includes('بوليتكنك') || clean.includes('بولتكنك') || clean.includes('polytechnic') || clean.includes('بولتكنيك') || clean.includes('بلوتكنيك')) {
    return 'جامعة بوليتكنك فلسطين';
  }
  if (clean.includes('خليل')) {
    return 'جامعة الخليل';
  }
  if (clean.includes('ذكيه') || clean.includes('ذكية') || clean.includes('smart')) {
    return 'الكلية الذكية الجامعية للتعليم الحديث';
  }
  if (clean.includes('نجاح')) {
    return 'جامعة النجاح الوطنية';
  }
  if (clean.includes('امريكيه') || clean.includes('أمريكية') || clean.includes('aauj')) {
    return 'الجامعة العربية الأمريكية';
  }
  if (clean.includes('لحم')) {
    return 'جامعة بيت لحم';
  }
  return raw.trim();
};

// Trainer department detection and mappings
export const isTrainerDepartment = (dept?: string | null): boolean => {
  if (!dept) return false;
  return dept === 'تدريب تمريض الجامعات' || dept.startsWith('مدربي ');
};

export const getRelatedTraineeDepts = (trainerDept?: string | null): string[] => {
  if (!trainerDept) return [];
  switch (trainerDept) {
    case 'مدربي أشعة':
      return ['أشعة'];
    case 'مدربي مختبر':
      return ['مختبرات طبية', 'مختبر', 'المختبر'];
    case 'مدربي علاج طبيعي':
      return ['العلاج الطبيعي', 'علاج طبيعي تدريب', 'علاج طبيعي امتياز'];
    case 'مدربي علاج وظيفي':
      return ['العلاج الوظيفي', 'علاج وظيفي'];
    case 'مدربي صيدلية':
      return ['صيدلة', 'الصيدلة'];
    case 'مدربي تغذية':
      return ['تغذية', 'التغذية'];
    case 'مدربي هندسة طبية':
      return ['هندسة طبية', 'الهندسة الطبية'];
    case 'تدريب تمريض الجامعات':
      return ['تمريض تدريب', 'تمريض امتياز', 'التمريض', 'تمريض تطوع'];
    default:
      return [];
  }
};

export const getTrainerDeptForStudentDept = (dept?: string | null): string => {
  if (!dept) return 'تدريب تمريض الجامعات';
  if (dept.includes('أشعة') || dept.includes('اشعة')) return 'مدربي أشعة';
  if (dept.includes('مختبر')) return 'مدربي مختبر';
  if (dept.includes('علاج طبيعي')) return 'مدربي علاج طبيعي';
  if (dept.includes('علاج وظيفي')) return 'مدربي علاج وظيفي';
  if (dept.includes('صيدل')) return 'مدربي صيدلية';
  if (dept.includes('تغذي')) return 'مدربي تغذية';
  if (dept.includes('هندس')) return 'مدربي هندسة طبية';
  if (dept.includes('تمريض') || dept.includes('التمريض')) return 'تدريب تمريض الجامعات';
  return 'تدريب تمريض الجامعات';
};

export const isEligibleForTrainerAssignment = (dept?: string, student?: any): boolean => {
  const d = dept || student?.department || student?.originalDepartment || '';
  if (student?.assignedTrainer) return true;
  if (isTrainerDepartment(d)) return true;
  if (d.includes('تمريض') || d.includes('أشعة') || d.includes('اشعة') || d.includes('مختبر') || d.includes('علاج') || d.includes('صيدل') || d.includes('تغذي') || d.includes('هندس')) return true;
  return false;
};

const defaultData: StudentsData = {
  "جراحة": [
    { "name": "عبدالله علي احمد عطوان", "startDate": "1/3/2026", "endDate": "15/10/2026", "phone": "566038063", "attendanceDays": "سبت /اتنين /اربعاء", "address": "خاراس", "idNumber": "405507898", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2024" },
    { "name": "حازم عماد كامل الطل", "startDate": "1/3/2026", "endDate": "15/10/2026", "phone": "566840216", "attendanceDays": "سبت /اتنين /اربعاء", "address": "الظاهرية", "idNumber": "406230797", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2024" },
    { "name": "اسامة عيسى احمد قزاز", "startDate": "1/9/2025", "endDate": "1/6/2026", "phone": "569516507", "attendanceDays": "سبت /اتنين /اربعاء", "address": "دورا", "idNumber": "405508888", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2024" },
    { "name": "تقي الدين جواد مرار", "startDate": "1/3/2026", "endDate": "1/12/2026", "phone": "593023952", "attendanceDays": "سبت /اتنين /اربعاء", "address": "رأس الجورة", "idNumber": "405731183", "university": "جامعة واشنطن", "graduationYear": "2025" },
    { "name": "محمود رائد سراحين", "startDate": "1/4/2025", "endDate": "1/1/2026", "phone": "599966611", "attendanceDays": "سبت /اتنين /اربعاء", "address": "الخليل/بيت اولا", "idNumber": "406745653", "university": "جامعة المنصورة - مصر", "graduationYear": "2024" },
    { "name": "اديب روحي محمود شلالدة", "startDate": "15/4/2026", "endDate": "15/1/2027", "phone": "594779221", "attendanceDays": "سبت /اتنين /اربعاء", "address": "سعير", "idNumber": "406181172", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2025" },
    { "name": "خلود محمود أبو طماعة", "startDate": "1/9/2025", "endDate": "1/6/2026", "phone": "599141158", "attendanceDays": "سبت /اتنين /اربعاء", "address": "مخيم العروب", "idNumber": "405768938", "university": "جامعة المنصورة - مصر", "graduationYear": "2025" },
    { "name": "أحمد زياد محمد سعدي بكري", "startDate": "15/12/2025", "endDate": "1/8/2026", "phone": "566575884", "attendanceDays": "سبت /اتنين /اربعاء", "address": "الخليل", "idNumber": "401124524", "university": "Dnipro medical uni", "graduationYear": "2025" },
    { "name": "يزن عيسى محمود حميدات", "startDate": "1/11/2025", "endDate": "15/6/2026", "phone": "567380245", "attendanceDays": "احد /ثلاثاء /خميس", "address": "صوريف", "idNumber": "407277151", "university": "جامعة بوليتكنك فلسطين", "graduationYear": "2025" },
    { "name": "ابي محمد تيسير اسعيد", "startDate": "1/2/2026", "endDate": "15/9/2026", "phone": "595287451", "attendanceDays": "احد /ثلاثاء /خميس", "address": "الخليل", "idNumber": "407432467", "university": "جامعة النجاح الوطنية", "graduationYear": "2025" },
    { "name": "سيف الدين مازن قفيشه", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "569686003", "attendanceDays": "احد /ثلاثاء /خميس", "address": "الخليل", "idNumber": "407417484", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2025" },
    { "name": "احمد عبد العظيم رجبي", "startDate": "1/4/2026", "endDate": "15/11/2026", "phone": "597336534", "attendanceDays": "احد /ثلاثاء /خميس", "address": "المشارقة التحتا", "idNumber": "405543323", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2024" },
    { "name": "محمد يوسف محمد حروب", "startDate": "1/10/2025", "endDate": "16/5/2026", "phone": "594682507", "attendanceDays": "احد /ثلاثاء /خميس", "address": "دورا", "idNumber": "405501628", "university": "جامعة ابو ديس - القدس", "graduationYear": "2025" }
  ],
  "نسائية": [
    { "name": "محمد إبراهيم حريبات", "startDate": "17/5/2025", "endDate": "17/2/2026", "phone": "595440149", "attendanceDays": "سبت /اتنين /اربعاء", "address": "رابود", "idNumber": "407346329", "university": "جامعة طنطا - مصر", "graduationYear": "2024" },
    { "name": "رناد خالد السيد أحمد", "startDate": "17/5/2025", "endDate": "17/2/2026", "phone": "569736095", "attendanceDays": "سبت /اتنين /اربعاء", "address": "دورا", "idNumber": "406187625", "university": "جامعة القصر العيني - مصر", "graduationYear": "2024" },
    { "name": "عندليب غبن محمد الجبارين", "startDate": "1/11/2025", "endDate": "15/6/2026", "phone": "593022438", "attendanceDays": "سبت /اتنين /اربعاء", "address": "الظاهريّة", "idNumber": "406487074", "university": "جامعة الخليل", "graduationYear": "2025" },
    { "name": "محمد حمدي احمد حلاحلة", "startDate": "1/2/2026", "endDate": "15/9/2026", "phone": "598633204", "attendanceDays": "سبت /اتنين /اربعاء", "address": "خاراس", "idNumber": "860175546", "university": "IMU kyrgyzstan", "graduationYear": "2024" },
    { "name": "قاسم بلال محمد شرباتي", "startDate": "15/9/2025", "endDate": "15/6/2026", "phone": "568621019", "attendanceDays": "سبت / اثنين / أربعاء", "address": "الخليل", "idNumber": "323027581", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2024" },
    { "name": "تيماء محمود جميل بشارات", "startDate": "15/10/2025", "endDate": "1/6/2026", "phone": "594016882", "attendanceDays": "سبت / اثنين / أربعاء", "address": "الخليل", "idNumber": "407490853", "university": "جامعة بوليتكنك فلسطين", "graduationYear": "2025" },
    { "name": "انسام زهير خلف مناصره", "startDate": "15/10/2025", "endDate": "1/6/2026", "phone": "592189264", "attendanceDays": "احد /ثلاثاء /خميس", "address": "بني نعيم", "idNumber": "407341973", "university": "جامعة الخليل", "graduationYear": "2025" },
    { "name": "حمزة حسين حرب خلاف", "startDate": "1/2/2026", "endDate": "15/9/2026", "phone": "593223640", "attendanceDays": "احد /ثلاثاء /خميس", "address": "دورا", "idNumber": "859753857", "university": "جامعة البحر الاحمر", "graduationYear": "2022" },
    { "name": "حسن وسام أبو زهرة", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "569770962", "attendanceDays": "احد /ثلاثاء /خميس", "address": "يطا", "idNumber": "408811875", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2024" },
    { "name": "عبد الناصر جاسر دودين", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "566810566", "attendanceDays": "احد /ثلاثاء /خميس", "address": "دورا", "idNumber": "405535816", "university": "جامعة المنصورة - مصر", "graduationYear": "2025" },
    { "name": "محمد باسم محمد ابو قبيطه", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "566885455", "attendanceDays": "احد /ثلاثاء /خميس", "address": "يطا", "idNumber": "408649994", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2025" },
    { "name": "محمد اياد طالب الجندي", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "566220141", "attendanceDays": "احد /ثلاثاء /خميس", "address": "يطا", "idNumber": "408200871", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2025" },
    { "name": "حمزة فهمي حربي ابو هدوان", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "566310610", "attendanceDays": "احد /ثلاثاء /خميس", "address": "راس الجورة", "idNumber": "408678761", "university": "جامعة القاهرة - مصر", "graduationYear": "2024" }
  ],
  "الاطفال": [
    { "name": "محمد جمال أبو رميله", "startDate": "2/8/2025", "endDate": "2/5/2026", "phone": "592788290", "attendanceDays": "سبت /اتنين /اربعاء", "address": "الخليل", "idNumber": "407345180", "university": "جامعة الإسكندرية - مصر", "graduationYear": "2025" },
    { "name": "محمد خضر كايد سياعره", "startDate": "1/5/2025", "endDate": "1/2/2026", "phone": "568474673", "attendanceDays": "سبت /اتنين /اربعاء", "address": "الخليل - خاراس", "idNumber": "406569897", "university": "جامعة المنصورة - مصر", "graduationYear": "2024" },
    { "name": "هيثم سيف الدين هشلمون", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "599014027", "attendanceDays": "سبت /اتنين /اربعاء", "address": "سنجر", "idNumber": "407439538", "university": "جامعة المنصورة - مصر", "graduationYear": "2024" },
    { "name": "براءه زهير محمود الحروب", "startDate": "1/10/2025", "endDate": "1/7/2026", "phone": "569035758", "attendanceDays": "سبت /اتنين /اربعاء", "address": "ديرسامت", "idNumber": "406312132", "university": "جامعة المنصورة - مصر", "graduationYear": "2024" },
    { "name": "رامي راقي مصطفى ابوعقيل", "startDate": "1/4/2026", "endDate": "15/11/2026", "phone": "592104450", "attendanceDays": "سبت /اتنين /اربعاء", "address": "السموع", "idNumber": "405499823", "university": "جامعة المنصورة - مصر", "graduationYear": "2024" },
    { "name": "داوود يوسف حسين فحيلي", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "597472976", "attendanceDays": "سبت /اتنين /اربعاء", "address": "بني نعيم", "idNumber": "406189464", "university": "جامعة طنطا - مصر", "graduationYear": "2025" },
    { "name": "عروب عبد الرحيم الفطافطة", "startDate": "15/11/2025", "endDate": "15/8/2026", "phone": "599451789", "attendanceDays": "احد /ثلاثاء /خميس", "address": "ترقوميا", "idNumber": "403968761", "university": "جامعة الازهر الشريف", "graduationYear": "2025" },
    { "name": "مرام نافذ الشريف", "startDate": "14/9/2025", "endDate": "14/11/2025", "phone": "569540751", "attendanceDays": "احد /ثلاثاء /خميس", "address": "الخليل", "idNumber": "406185603", "university": "جامعة الخليل", "graduationYear": "2025" },
    { "name": "زهير نزار زهير ابو زهره", "startDate": "1/4/2026", "endDate": "15/11/2026", "phone": "569695941", "attendanceDays": "احد /ثلاثاء /خميس", "address": "يطا", "idNumber": "421015983", "university": "جامعة بنها - مصر", "graduationYear": "2025" },
    { "name": "تامر حامد علي شلالده", "startDate": "1/4/2026", "endDate": "1/1/2027", "phone": "598341230", "attendanceDays": "احد /ثلاثاء /خميس", "address": "سعير", "idNumber": "408284297", "university": "جامعة المنصورة - مصر", "graduationYear": "2025" },
    { "name": "جهاد ابراهيم الخوره", "startDate": "1/4/2026", "endDate": "15/11/2026", "phone": "569447612", "attendanceDays": "احد /ثلاثاء /خميس", "address": "الفوار", "idNumber": "406315523", "university": "جامعه كفر الشيخ - مصر", "graduationYear": "2024" },
    { "name": "لؤي ناصر عبد الحافظ جياوي", "startDate": "15/4/2026", "endDate": "1/12/2026", "phone": "566991588", "attendanceDays": "احد /ثلاثاء /خميس", "address": "اذنا", "idNumber": "406743740", "university": "جامعه كفر الشيخ - مصر", "graduationYear": "2024" },
    { "name": "ابراهيم خليل طفيحه", "startDate": "", "endDate": "", "phone": "", "attendanceDays": "", "address": "بني نعيم", "idNumber": "", "university": "جامعة الإسكندرية - مصر", "graduationYear": "" }
  ],
  "طب تطوع": [],
  "تمريض تطوع": [],
  "المغادرين": [
    {
      "name": "أنس حسن محمود النواجعة",
      "startDate": "01/03/2024",
      "endDate": "01/02/2025",
      "phone": "",
      "university": "جامعة القدس - ابو ديس"
    },
    {
      "name": "شهد أحمد عبد الحليم الحلايقة",
      "startDate": "02/01/2024",
      "endDate": "02/01/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "مقداد عبد الحليم محمود الحروب",
      "startDate": "12/12/2024",
      "endDate": "12/03/2025",
      "phone": "",
      "university": "جامعة المنصورة - مصر"
    },
    {
      "name": "آلاء زياد عبد الرحمن عيايدة",
      "startDate": "12/02/2024",
      "endDate": "12/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "فاطمة ماهر سليم نيروخ",
      "startDate": "01/03/2024",
      "endDate": "15/12/2024",
      "phone": "",
      "university": "جامعة بوليتكنك فلسطين"
    },
    {
      "name": "عدي رياض احمد ابو عجمية",
      "startDate": "01/03/2024",
      "endDate": "01/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "شهد عمر عيسى شلالدة",
      "startDate": "16/04/2024",
      "endDate": "15/04/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "راما محمد فلاح عابدين",
      "startDate": "01/03/2024",
      "endDate": "01/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "محمد حسين إبراهيم شحادة",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "شذى هشام جميل السويطي",
      "startDate": "16/04/2024",
      "endDate": "15/04/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "نور الهدى عيسى محمد أبو هشهش",
      "startDate": "12/02/2024",
      "endDate": "12/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "يوسف محمد يوسف أبو سنينة",
      "startDate": "15/04/2024",
      "endDate": "15/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "فايزة عاهد فايز القصراوي",
      "startDate": "16/04/2024",
      "endDate": "15/04/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ليلى نبيل إبراهيم القواسمة",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "عبلة عدنان موسى أبو دية",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "اسراء نعمان محمد الفروخ",
      "startDate": "01/06/2024",
      "endDate": "01/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "سنابل أحمد محمد زرد",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "جامعة بوليتكنك فلسطين"
    },
    {
      "name": "رغد ابراهيم مسلم عوض",
      "startDate": "01/06/2024",
      "endDate": "01/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "روان فوزي احمد دودين",
      "startDate": "01/06/2024",
      "endDate": "01/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "اسراء هشام جميل السويطي",
      "startDate": "01/06/2024",
      "endDate": "01/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "رهف ناصر زكي البدارين",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "لمى عز الدين حمدي الاطرش",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "أسيل عبد الفتاح موسى جوابرة",
      "startDate": "16/04/2024",
      "endDate": "15/04/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "أفنان ماهر عبد القادر أبو الحلاوة",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "هدى كمال خليل مسالمة",
      "startDate": "12/03/2024",
      "endDate": "12/02/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "سعاد إبراهيم حسن العواودة",
      "startDate": "16/04/2024",
      "endDate": "15/04/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "أماني كمال يعقوب الحروب",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة بوليتكنك فلسطين"
    },
    {
      "name": "لارا أسامة يعقوب مرقه",
      "startDate": "12/05/2024",
      "endDate": "12/04/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "لين خالد محمود مخارزة",
      "startDate": "04/05/2024",
      "endDate": "04/04/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "غرام محمود أحمد التلاحمة",
      "startDate": "04/05/2024",
      "endDate": "04/04/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "اسراء صبحي محمد شريتح",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة مؤتة - الأردن"
    },
    {
      "name": "شروق سامي عبد الفتاح الحلايقة",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة بوليتكنك فلسطين"
    },
    {
      "name": "إسلام أحمد إبراهيم مرعب",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "محمد حسن خليل سياعرة",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة القدس - ابو ديس"
    },
    {
      "name": "أفراح خليل محمود العواودة",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ميار محمد وليد الكركي",
      "startDate": "12/07/2024",
      "endDate": "12/06/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "تالا نزار خالد العويوي",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "منال فايس حسن الطيطي",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "لجين بسام عثمان ابو شرار",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ندى رائد أحمد دودين",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "آرام رياض جودت ناصر الدين",
      "startDate": "12/07/2024",
      "endDate": "12/06/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "الاء سليم عيسى الحروب",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "الجامعة الاردنية - الاردن"
    },
    {
      "name": "سالي عيسى محمد مراد",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ايمان خليل عبد المعطي الرجوب",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "مريم ابراهيم اسماعيل حلاحلة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ريناد منير عيسى الهذلين",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "جامعة العلوم والتكنولوجيا الاردنية"
    },
    {
      "name": "إسلام وائل حلمي الشرباتي",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "جامعة العلوم والتكنولوجيا الاردنية"
    },
    {
      "name": "محي الدين منذر احمد زغير",
      "startDate": "18/08/2024",
      "endDate": "18/02/2025",
      "phone": "",
      "university": "جامعة القدس - ابو ديس"
    },
    {
      "name": "ليال يوسف عثمان الزعتري",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة بوليتكنك فلسطين"
    },
    {
      "name": "أمين عزمي أمين حريبات",
      "startDate": "18/08/2024",
      "endDate": "18/07/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "رنا خليل محمد اعطية",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "نورسين سفيان حسني مساروة",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "صقر احمد صقر ابو حسين",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "مريم ابراهيم مصطفى بدران",
      "startDate": "18/08/2024",
      "endDate": "18/07/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "هبة الله وليد محمد رفاعية",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "الجامعة الاردنية - الاردن"
    },
    {
      "name": "بيان عمر احمد السويطي",
      "startDate": "18/08/2024",
      "endDate": "18/07/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "تقى زياد محمد غطاشة",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة النجاح الوطنية"
    },
    {
      "name": "عقبة زكريا نمر عبد الله",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة اليرموك - الاردن"
    },
    {
      "name": "حنين إبراهيم إسماعيل طرايرة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "لانا طلب سليمان السويطي",
      "startDate": "18/08/2024",
      "endDate": "18/07/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "ميساء عصام علي الرجوب",
      "startDate": "18/08/2024",
      "endDate": "18/07/2025",
      "phone": "",
      "university": "جامعة مؤتة - الأردن"
    },
    {
      "name": "نغم محمد كامل مناصرة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ايوب جمال ربحي غطاشة",
      "startDate": "01/06/2024",
      "endDate": "01/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "وسيم حسين خليل عمرو",
      "startDate": "01/06/2024",
      "endDate": "01/05/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "رولا علي محمد الشتلة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "شهد محمد علي سلهب طميمي",
      "startDate": "01/02/2024",
      "endDate": "01/01/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ربى عثمان عبد العزيز سويطي",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "سجا فايز ابراهيم سياعرة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "ربى ابراهيم صيام السمامرة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "رعد نايف راغب دغامين",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "عزيزة منجد محمد عبد النبي التلاينة",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "جامعة مؤتة - الأردن"
    },
    {
      "name": "اسراء جمال أحمد ابو سيف",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "أسيل هشام محمد سلهب",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "فخر الدين محمود فخر الدين الحلايقة",
      "startDate": "03/09/2024",
      "endDate": "03/08/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "ربى يوسف طالب مسالمة",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "لؤي مروان نعمان عمايرة",
      "startDate": "15/10/2024",
      "endDate": "14/10/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "اية محمد طلب زماعرة",
      "startDate": "15/10/2024",
      "endDate": "14/10/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "سجى حسين عطية سلهب",
      "startDate": "15/10/2024",
      "endDate": "15/01/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "نداء محمود عبد الرحيم عويضات",
      "startDate": "15/10/2024",
      "endDate": "14/10/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "اية حاتم هاشم دوفش",
      "startDate": "15/10/2024",
      "endDate": "14/10/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "شذى يوسف محمد شرباتي",
      "startDate": "15/10/2024",
      "endDate": "14/10/2025",
      "phone": "",
      "university": "الجامعة الهاشمية - الأردن"
    },
    {
      "name": "تالا نادر يوسف ابنين",
      "startDate": "16/07/2024",
      "endDate": "15/07/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "توليب مازن طلال أبو عريش",
      "startDate": "15/10/2024",
      "endDate": "14/10/2025",
      "phone": "",
      "university": "جامعة مؤتة - الأردن"
    },
    {
      "name": "جوان ابراهيم محمد سويطي",
      "startDate": "26/02/2024",
      "endDate": "26/02/2025",
      "phone": "",
      "university": "جامعة الخليل"
    },
    {
      "name": "انوار حسن دياب عصافرة",
      "startDate": "26/02/2024",
      "endDate": "26/02/2025",
      "phone": "",
      "university": "جامعة النجاح الوطنية"
    }
  ],
  "الاستئناف": [],
  "التمريض": [],
  "تمريض تدريب": [],
  "تمريض امتياز": [],
  "العلاج الطبيعي": [],
  "علاج طبيعي تدريب": [],
  "علاج طبيعي امتياز": [],
  "الصحة النفسية": [],
  "أشعة": [],
  "تغذية": [],
  "خدمة اجتماعية": [],
  "إدارة": [],
  "المحاسبة": [],
  "المطبخ": [],
  "ضباط الإسعاف": [],
  "العمل المجتمعي": [],
  "مدربي أشعة": [],
  "مدربي هندسة طبية": [],
  "مدربي تغذية": [],
  "مدربي صيدلية": [],
  "مدربي مختبر": [],
  "مدربي علاج طبيعي": [],
  "مدربي علاج وظيفي": []
};

// API Config
const API_URL = '/api/students';

// Deduplicate Students Dataset helper to guarantee zero duplicate records in state or cloud
const deduplicateStudentsDataset = (data: any): StudentsData => {
  if (!data || typeof data !== 'object') return data;
  const clean: Record<string, any[]> = {};
  for (const [dept, list] of Object.entries(data)) {
    if (!Array.isArray(list)) {
      clean[dept] = list as any;
      continue;
    }
    const seen = new Set<string>();
    clean[dept] = list.filter((s: any) => {
      const cleanName = (s?.name || '').trim().toLowerCase();
      const cleanPhone = (s?.phone || '').trim();
      const cleanId = (s?.idNumber || '').trim();
      const key = (cleanPhone || cleanId)
        ? `${cleanName}:::${cleanPhone || cleanId}`
        : (s?.id ? `${cleanName}:::${s.id}` : `${cleanName}:::${s?.startDate || ''}:::${s?.assignedTrainer || ''}`);
      if (seen.has(key)) return false;
      seen.add(key);
      return true;
    });
  }
  return clean as StudentsData;
};

export default function Dashboard() {
  const router = useRouter();
  const [studentsData, setStudentsData] = useState<StudentsData>(defaultData);
  const [currentDepartment, setCurrentDepartment] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [toastMessage, setToastMessage] = useState<string | null>(null);
  const [expandedUniversity, setExpandedUniversity] = useState<string | null>(null);
  const [universityFilter, setUniversityFilter] = useState<string>('all');
  const [showAllDepts, setShowAllDepts] = useState(false);
  const [expandedCategory, setExpandedCategory] = useState<string | null>(null);
  const [showHealthTrainersPanel, setShowHealthTrainersPanel] = useState(false);
  const [hideNames, setHideNames] = useState(false);
  const [currentUser, setCurrentUser] = useState<{username: string; displayName: string; role: string} | null>(null);
  const [lastSynced, setLastSynced] = useState<string>('');
  const [onlineUsers, setOnlineUsers] = useState<{username: string; displayName: string}[]>([]);
  const [departureFilterDays, setDepartureFilterDays] = useState<number>(30);
  const [collapsedDepartureDepts, setCollapsedDepartureDepts] = useState<{[key: string]: boolean}>({});
  const [departureViewMode, setDepartureViewMode] = useState<'byDept' | 'timeline'>('byDept');
  const [showDepartureNames, setShowDepartureNames] = useState<boolean>(false);

  // ═══════════ Move Student Modal State ═══════════
  const [moveCustomStartDate, setMoveCustomStartDate] = useState<string>('');
  const [moveCustomEndDate, setMoveCustomEndDate] = useState<string>('');
  const [keepExistingDates, setKeepExistingDates] = useState<boolean>(false);
  const [moveDeptSearch, setMoveDeptSearch] = useState<string>('');

  // ═══════════ Statistical & Periodic Report Modal State ═══════════
  const [showStatsReportModal, setShowStatsReportModal] = useState(false);
  const [reportDept, setReportDept] = useState<string>('All');
  const [reportStartDate, setReportStartDate] = useState<string>('');
  const [reportEndDate, setReportEndDate] = useState<string>('');
  const [reportStatus, setReportStatus] = useState<string>('all');
  const [reportSearch, setReportSearch] = useState<string>('');
  const [reportActiveTab, setReportActiveTab] = useState<'all' | 'trainees' | 'trainers'>('all');
  const [trainerUniFilter, setTrainerUniFilter] = useState<string>('');
  // ═══════════ University & Contracted Doctors Modal State ═══════════
  const [showUniversitiesModal, setShowUniversitiesModal] = useState(false);
  const [allApplications, setAllApplications] = useState<any[]>([]);
  const [selectedUniApp, setSelectedUniApp] = useState<any>(null);
  const [isEditingUniApp, setIsEditingUniApp] = useState<boolean>(false);
  const [uniAppEditForm, setUniAppEditForm] = useState<any>({});
  const [customDeptInput, setCustomDeptInput] = useState<string>('');
  const [customUniInput, setCustomUniInput] = useState<string>('');
  const [uniFilterTab, setUniFilterTab] = useState<'all' | 'nursing' | 'doctors'>('all');
  const [uniSearch, setUniSearch] = useState<string>('');
  const [isProcessingUniApp, setIsProcessingUniApp] = useState(false);
  const [tableScrollPercent, setTableScrollPercent] = useState<number>(0);
  const uniTableRef = useRef<HTMLDivElement>(null);
  // ═══════════ Golden University Stats Modal ═══════════
  const [showUniStatsModal, setShowUniStatsModal] = useState(false);
  const [uniStatsTab, setUniStatsTab] = useState<'all' | 'doctors' | 'nursing'>('all');
  const [selectedUniStatsName, setSelectedUniStatsName] = useState<string | null>(null);
  const [uniStatsSearch, setUniStatsSearch] = useState<string>('');

  // ── Dynamic custom partner universities & adjustable staff ──
  const [customPartnerUnis, setCustomPartnerUnis] = useState<Array<{ name: string; color: string; icon: string; isDefault?: boolean }>>([]);
  const [customPartnerStaff, setCustomPartnerStaff] = useState<any[]>([]);
  const [partnerStaffOverrides, setPartnerStaffOverrides] = useState<Record<string, any>>({});
  const [hiddenPartnerStaffKeys, setHiddenPartnerStaffKeys] = useState<string[]>([]);

  // Modals for adding/editing university & staff in partner report
  const [showAddUniModal, setShowAddUniModal] = useState(false);
  const [editingUniName, setEditingUniName] = useState<string | null>(null);
  const [newUniNameInput, setNewUniNameInput] = useState('');
  const [newUniColorInput, setNewUniColorInput] = useState('#2563eb');
  const [newUniIconInput, setNewUniIconInput] = useState('🎓');

  const [showStaffEditModal, setShowStaffEditModal] = useState(false);

  const [editingStaffItem, setEditingStaffItem] = useState<any | null>(null);
  const [staffFormName, setStaffFormName] = useState('');
  const [staffFormIdNumber, setStaffFormIdNumber] = useState('');
  const [staffFormType, setStaffFormType] = useState<'doctor' | 'trainer'>('doctor');
  const [staffFormUni, setStaffFormUni] = useState('');
  const [staffFormSpecialty, setStaffFormSpecialty] = useState('');
  const [staffFormDept, setStaffFormDept] = useState('');
  const [staffFormPhone, setStaffFormPhone] = useState('');
  const [staffFormStartDate, setStaffFormStartDate] = useState('');
  const [staffFormEndDate, setStaffFormEndDate] = useState('');
  const [staffFormStatus, setStaffFormStatus] = useState<'auto' | 'active' | 'completed' | 'upcoming'>('auto');
  const [staffFormNotes, setStaffFormNotes] = useState('');

  // ── Faculty Move Modal State ──
  const [showFacultyMoveModal, setShowFacultyMoveModal] = useState<boolean>(false);
  const [moveTargetStaff, setMoveTargetStaff] = useState<any | null>(null);
  const [moveCurrentUni, setMoveCurrentUni] = useState<string>('');
  const [moveSelectedNewUni, setMoveSelectedNewUni] = useState<string>('جامعة الخليل');
  const [moveCustomUniText, setMoveCustomUniText] = useState<string>('');
  const [moveMode, setMoveMode] = useState<'replace' | 'append'>('replace');
  const [isSavingMove, setIsSavingMove] = useState<boolean>(false);

  // Load custom partner data from localStorage on client
  useEffect(() => {
    try {
      const savedUnis = localStorage.getItem('crescent_custom_partner_unis');
      if (savedUnis) setCustomPartnerUnis(JSON.parse(savedUnis));
      const savedStaff = localStorage.getItem('crescent_custom_partner_staff');
      if (savedStaff) setCustomPartnerStaff(JSON.parse(savedStaff));
      const savedOverrides = localStorage.getItem('crescent_partner_staff_overrides');
      if (savedOverrides) setPartnerStaffOverrides(JSON.parse(savedOverrides));
      const savedHidden = localStorage.getItem('crescent_partner_hidden_staff');
      if (savedHidden) setHiddenPartnerStaffKeys(JSON.parse(savedHidden));
    } catch (e) {
      console.error('Error loading partner university custom data:', e);
    }
  }, []);

  const handleSaveUni = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = newUniNameInput.trim();
    if (!trimmed) {
      alert('يرجى إدخال اسم الجامعة أو الجهة الشريكة');
      return;
    }

    if (editingUniName) {
      const updated = customPartnerUnis.map(u => u.name === editingUniName ? { ...u, name: trimmed, color: newUniColorInput, icon: newUniIconInput } : u);
      setCustomPartnerUnis(updated);
      try { localStorage.setItem('crescent_custom_partner_unis', JSON.stringify(updated)); } catch {}
      if (selectedUniStatsName === editingUniName) {
        setSelectedUniStatsName(trimmed);
      }
      showToast(`تم تعديل الجامعة الشريكة (${trimmed}) بنجاح ✓`);
    } else {
      const exists = customPartnerUnis.some(u => u.name.toLowerCase() === trimmed.toLowerCase());
      if (!exists) {
        const updated = [...customPartnerUnis, { name: trimmed, color: newUniColorInput, icon: newUniIconInput }];
        setCustomPartnerUnis(updated);
        try { localStorage.setItem('crescent_custom_partner_unis', JSON.stringify(updated)); } catch {}
      }
      setSelectedUniStatsName(trimmed);
      showToast(`تم إضافة الجامعة الشريكة (${trimmed}) بنجاح ✓`);
    }

    setShowAddUniModal(false);
    setEditingUniName(null);
    setNewUniNameInput('');
  };

  const handleDeleteUni = (uniName: string) => {
    if (!confirm(`هل أنت متأكد من حذف أو إخفاء جامعة (${uniName}) من التقرير؟`)) return;
    const updated = customPartnerUnis.filter(u => u.name !== uniName);
    setCustomPartnerUnis(updated);
    try { localStorage.setItem('crescent_custom_partner_unis', JSON.stringify(updated)); } catch {}
    if (selectedUniStatsName === uniName) setSelectedUniStatsName(null);
    showToast(`تم حذف الجامعة (${uniName}) بنجاح ✓`);
  };

  const handleOpenAddStaff = (defaultUni?: string) => {
    setEditingStaffItem(null);
    setStaffFormName('');
    setStaffFormIdNumber('');
    setStaffFormType(uniStatsTab === 'nursing' ? 'trainer' : 'doctor');
    setStaffFormUni(defaultUni || (selectedUniStatsName && selectedUniStatsName !== 'all' ? selectedUniStatsName : 'جامعة بوليتكنك فلسطين'));
    setStaffFormSpecialty('');
    setStaffFormDept('');
    setStaffFormPhone('');
    setStaffFormStartDate('');
    setStaffFormEndDate('');
    setStaffFormStatus('auto');
    setStaffFormNotes('');
    setShowStaffEditModal(true);
  };

  const handleOpenEditStaff = (staff: any, currentUniName: string) => {
    setEditingStaffItem(staff);
    const key = staff.idNumber || staff.name;
    const override = partnerStaffOverrides[key] || {};
    setStaffFormName(override.name || staff.name || '');
    setStaffFormIdNumber(staff.idNumber || '');
    setStaffFormType(staff.type || (isContractedDoctorStudent(staff) ? 'doctor' : 'trainer'));
    setStaffFormUni(override.partnerUniversity || staff.partnerUniversity || currentUniName);
    setStaffFormSpecialty(override.specialty !== undefined ? override.specialty : (staff.specialty || staff.nursingSpecialty || ''));
    setStaffFormDept(override.department !== undefined ? override.department : (staff.department || staff.deptLabel || ''));
    setStaffFormPhone(override.phone !== undefined ? override.phone : (staff.phone || ''));
    setStaffFormStartDate(override.startDate !== undefined ? override.startDate : (staff.startDate || ''));
    setStaffFormEndDate(override.endDate !== undefined ? override.endDate : (staff.endDate || ''));
    setStaffFormStatus(override.manualStatus || staff.manualStatus || staff._status || 'auto');
    setStaffFormNotes(override.notes !== undefined ? override.notes : (staff.notes || ''));
    setShowStaffEditModal(true);
  };

  const handleOpenMoveStaff = (staff: any, currentUniName: string) => {
    setMoveTargetStaff(staff);
    setMoveCurrentUni(currentUniName);
    const defaultNext = currentUniName === 'جامعة بوليتكنك فلسطين' ? 'جامعة الخليل' : 'جامعة بوليتكنك فلسطين';
    setMoveSelectedNewUni(defaultNext);
    setMoveCustomUniText('');
    setMoveMode('replace');
    setShowFacultyMoveModal(true);
  };

  // Direct 1-Click Move Staff between partner universities/faculties
  const handleDirectMoveStaff = async (staff: any, currentUniName: string, targetUni: string) => {
    if (!staff || !targetUni) return;
    const normTarget = normalizeContractedPartner(targetUni) || targetUni.trim();
    const staffName = staff.name || 'الكادر';
    
    try {
      const key = staff.idNumber || staff.name;

      // 1. Update partnerStaffOverrides in state and localStorage
      const currentOverride = partnerStaffOverrides[key] || {};
      const newOverrides = {
        ...partnerStaffOverrides,
        [key]: {
          ...currentOverride,
          name: staff.name,
          partnerUniversity: normTarget
        }
      };
      setPartnerStaffOverrides(newOverrides);
      try { localStorage.setItem('crescent_partner_staff_overrides', JSON.stringify(newOverrides)); } catch {}

      // 2. Update customPartnerStaff if applicable
      if (staff.isCustomItem) {
        const updatedCustom = customPartnerStaff.map(item => {
          if (item.id === staff.id || item.name === staff.name) {
            return { ...item, partnerUniversity: normTarget };
          }
          return item;
        });
        setCustomPartnerStaff(updatedCustom);
        try { localStorage.setItem('crescent_custom_partner_staff', JSON.stringify(updatedCustom)); } catch {}
      }

      // 3. Update in studentsData and persist to Cloudflare D1
      const newData: Record<string, any[]> = {};
      Object.keys(studentsData).forEach(dept => {
        newData[dept] = Array.isArray(studentsData[dept]) ? [...studentsData[dept]] : [];
      });

      const sName = (staff.name || '').trim();
      const sIdNum = String(staff.idNumber || staff.id_number || '').trim();
      const sPhone = (staff.phone || '').trim();

      let updatedInDb = false;
      Object.keys(newData).forEach(dept => {
        newData[dept] = newData[dept].map((s: any) => {
          const matchId = staff.id && s.id && s.id === staff.id;
          const matchIdNum = sIdNum && s.idNumber && String(s.idNumber).trim() === sIdNum;
          const matchName = sName && cleanStr(s.name) === cleanStr(sName);
          const matchPhone = sPhone && s.phone && cleanPhone(s.phone) === cleanPhone(sPhone);

          if (matchId || matchIdNum || (matchName && matchPhone) || (matchName && !s.phone)) {
            updatedInDb = true;
            let currentUnis: string[] = [];
            if (Array.isArray(s.contractedUniversities)) currentUnis = [...s.contractedUniversities];
            else if (s.contractedUniversities) currentUnis = [s.contractedUniversities];

            let nextUnis = currentUnis.filter(u => u !== currentUniName);
            if (!nextUnis.includes(normTarget)) nextUnis.push(normTarget);
            if (nextUnis.length === 0) nextUnis = [normTarget];

            return {
              ...s,
              contractedUniversities: nextUnis,
              contractedUniversity: normTarget,
              university: normTarget
            };
          }
          return s;
        });
      });

      if (!updatedInDb) {
        const isDoc = staff.type === 'doctor' || isContractedDoctorStudent(staff);
        const targetDept = isDoc ? 'الأطباء المتعاقدون' : 'تدريب تمريض الجامعات';
        if (!newData[targetDept]) newData[targetDept] = [];
        newData[targetDept].push({
          ...staff,
          contractedUniversities: [normTarget],
          contractedUniversity: normTarget,
          university: normTarget
        });
        updatedInDb = true;
      }

      await saveData(newData);

      // 4. Update application if matching
      const matchingApp = allApplications.find((a: any) => 
        (sIdNum && a.idNumber && String(a.idNumber).trim() === sIdNum) ||
        (sName && cleanStr(a.name) === cleanStr(sName))
      );
      if (matchingApp) {
        const appId = matchingApp._supabaseId || matchingApp.id;
        if (appId) {
          try {
            const appData = matchingApp.applicantData || matchingApp;
            await fetch('/api/applications', {
              method: 'PATCH',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                id: appId,
                applicantData: {
                  ...appData,
                  contractedUniversities: [normTarget],
                  contractedUniversity: normTarget,
                  university: normTarget
                }
              })
            });
            fetchAllApplications();
          } catch {}
        }
      }

      showToast(`✅ تم نقل (${staffName}) بنجاح إلى (${normTarget})`);
    } catch (err) {
      console.error('Error direct moving staff:', err);
      showToast('❌ حدث خطأ أثناء النقل السريع');
    }
  };

  // Helper to persist staff edits directly into studentsData in D1
  const syncStaffToStudentsData = async (staffData: any, newUniName: string, isNew: boolean = false) => {
    const normUni = normalizeContractedPartner(newUniName) || newUniName.trim();
    const newData: Record<string, any[]> = {};
    Object.keys(studentsData).forEach(dept => {
      newData[dept] = Array.isArray(studentsData[dept]) ? [...studentsData[dept]] : [];
    });

    const staffName = (staffData.name || '').trim();
    const staffIdNumber = (staffData.idNumber || staffData.id_number || '').trim();
    const staffPhone = (staffData.phone || '').trim();
    const isDoc = staffData.type === 'doctor' || isContractedDoctorStudent(staffData);
    const targetDept = isDoc ? 'الأطباء المتعاقدون' : 'تدريب تمريض الجامعات';

    if (!newData[targetDept]) newData[targetDept] = [];

    let updated = false;
    Object.keys(newData).forEach(dept => {
      newData[dept] = newData[dept].map((s: any) => {
        const matchId = staffData.id && s.id && s.id === staffData.id;
        const matchIdNum = staffIdNumber && s.idNumber && String(s.idNumber).trim() === staffIdNumber;
        const matchName = staffName && cleanStr(s.name) === cleanStr(staffName);
        const matchPhone = staffPhone && s.phone && cleanPhone(s.phone) === cleanPhone(staffPhone);

        if (matchId || matchIdNum || (matchName && matchPhone) || (matchName && !s.phone)) {
          updated = true;
          const currentUnis = Array.isArray(s.contractedUniversities) ? [...s.contractedUniversities] : (s.contractedUniversities ? [s.contractedUniversities] : []);
          const nextUnis = currentUnis.includes(normUni) ? currentUnis : [...currentUnis, normUni];
          return {
            ...s,
            name: staffName || s.name,
            phone: staffPhone || s.phone,
            idNumber: staffIdNumber || s.idNumber,
            specialty: staffData.specialty !== undefined ? staffData.specialty : s.specialty,
            crescentJobNature: isDoc ? (staffData.specialty || 'طبيب متعاقد') : (staffData.specialty || 'مدرب سريري'),
            contractedUniversities: nextUnis,
            contractedUniversity: normUni,
            startDate: staffData.startDate || s.startDate,
            endDate: staffData.endDate || s.endDate,
          };
        }
        return s;
      });
    });

    if (!updated && isNew) {
      const newRecord: any = {
        id: staffData.id || `staff_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
        name: staffName,
        phone: staffPhone,
        idNumber: staffIdNumber,
        department: targetDept,
        specialty: staffData.specialty || (isDoc ? 'طبيب متعاقد' : 'مدرب سريري'),
        crescentJobNature: isDoc ? (staffData.specialty || 'طبيب متعاقد') : 'مدرب سريري',
        internshipYear: isDoc ? 'طبيب متعاقد' : 'مدرب سريري',
        contractedUniversities: [normUni],
        contractedUniversity: normUni,
        university: normUni,
        startDate: staffData.startDate || '',
        endDate: staffData.endDate || '',
        studySystem: isDoc ? 'أطباء متعاقدون' : 'تمريض جامعات',
      };
      newData[targetDept].push(newRecord);
    }

    await saveData(newData);
  };

  const handleExecuteMoveFaculty = async () => {
    if (!moveTargetStaff) return;
    const finalNewUni = (moveSelectedNewUni === 'custom' ? moveCustomUniText : moveSelectedNewUni).trim();
    if (!finalNewUni) {
      alert('يرجى اختيار أو كتابة اسم الكلية/الجامعة الجديدة');
      return;
    }
    setIsSavingMove(true);
    try {
      const normTarget = normalizeContractedPartner(finalNewUni) || finalNewUni;
      const key = moveTargetStaff.idNumber || moveTargetStaff.name;

      // 1. Update partnerStaffOverrides
      const currentOverride = partnerStaffOverrides[key] || {};
      const newOverrides = {
        ...partnerStaffOverrides,
        [key]: {
          ...currentOverride,
          name: moveTargetStaff.name,
          partnerUniversity: normTarget
        }
      };
      setPartnerStaffOverrides(newOverrides);
      try { localStorage.setItem('crescent_partner_staff_overrides', JSON.stringify(newOverrides)); } catch {}

      // 2. Update customPartnerStaff if applicable
      if (moveTargetStaff.isCustomItem) {
        const updatedCustom = customPartnerStaff.map(item => {
          if (item.id === moveTargetStaff.id || item.name === moveTargetStaff.name) {
            return { ...item, partnerUniversity: normTarget };
          }
          return item;
        });
        setCustomPartnerStaff(updatedCustom);
        try { localStorage.setItem('crescent_custom_partner_staff', JSON.stringify(updatedCustom)); } catch {}
      }

      // 3. Update in studentsData and persist to Cloudflare D1
      const newData: Record<string, any[]> = {};
      Object.keys(studentsData).forEach(dept => {
        newData[dept] = Array.isArray(studentsData[dept]) ? [...studentsData[dept]] : [];
      });

      const sName = (moveTargetStaff.name || '').trim();
      const sIdNum = String(moveTargetStaff.idNumber || moveTargetStaff.id_number || '').trim();
      const sPhone = (moveTargetStaff.phone || '').trim();

      let updatedInDb = false;
      Object.keys(newData).forEach(dept => {
        newData[dept] = newData[dept].map((s: any) => {
          const matchId = moveTargetStaff.id && s.id && s.id === moveTargetStaff.id;
          const matchIdNum = sIdNum && s.idNumber && String(s.idNumber).trim() === sIdNum;
          const matchName = sName && cleanStr(s.name) === cleanStr(sName);
          const matchPhone = sPhone && s.phone && cleanPhone(s.phone) === cleanPhone(sPhone);

          if (matchId || matchIdNum || (matchName && matchPhone) || (matchName && !s.phone)) {
            updatedInDb = true;
            let currentUnis: string[] = [];
            if (Array.isArray(s.contractedUniversities)) currentUnis = [...s.contractedUniversities];
            else if (s.contractedUniversities) currentUnis = [s.contractedUniversities];

            let nextUnis: string[] = [];
            if (moveMode === 'append') {
              nextUnis = currentUnis.includes(normTarget) ? currentUnis : [...currentUnis, normTarget];
            } else {
              nextUnis = currentUnis.filter(u => u !== moveCurrentUni);
              if (!nextUnis.includes(normTarget)) nextUnis.push(normTarget);
            }
            if (nextUnis.length === 0) nextUnis = [normTarget];

            return {
              ...s,
              contractedUniversities: nextUnis,
              contractedUniversity: normTarget,
              university: normTarget
            };
          }
          return s;
        });
      });

      if (!updatedInDb) {
        const isDoc = moveTargetStaff.type === 'doctor' || isContractedDoctorStudent(moveTargetStaff);
        const targetDept = isDoc ? 'الأطباء المتعاقدون' : 'تدريب تمريض الجامعات';
        if (!newData[targetDept]) newData[targetDept] = [];
        newData[targetDept].push({
          ...moveTargetStaff,
          contractedUniversities: [normTarget],
          contractedUniversity: normTarget,
          university: normTarget
        });
        updatedInDb = true;
      }

      if (updatedInDb) {
        await saveData(newData);
      }

      // 4. Update application if matching
      const matchingApp = allApplications.find((a: any) => 
        (sIdNum && a.idNumber && String(a.idNumber).trim() === sIdNum) ||
        (sName && cleanStr(a.name) === cleanStr(sName))
      );
      if (matchingApp) {
        const appId = matchingApp._supabaseId || matchingApp.id;
        if (appId) {
          try {
            const appData = matchingApp.applicantData || matchingApp;
            await fetch('/api/applications', {
              method: 'PATCH',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                id: appId,
                applicantData: {
                  ...appData,
                  contractedUniversities: moveMode === 'append' ? [...(appData.contractedUniversities || []), normTarget] : [normTarget],
                  contractedUniversity: normTarget,
                  university: normTarget
                }
              })
            });
            fetchAllApplications();
          } catch {}
        }
      }

      setShowFacultyMoveModal(false);
      setMoveTargetStaff(null);
      showToast(`✅ تم نقل (${moveTargetStaff.name}) بنجاح إلى (${normTarget})`);
    } catch (err) {
      console.error('Error moving faculty:', err);
      showToast('❌ حدث خطأ أثناء النقل، يرجى المحاولة مجدداً');
    } finally {
      setIsSavingMove(false);
    }
  };

  const handleSaveStaff = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!staffFormName.trim()) {
      alert('يرجى إدخال اسم الطبيب أو المدرب');
      return;
    }
    if (!staffFormUni.trim()) {
      alert('يرجى اختيار أو إدخال الجامعة الشريكة');
      return;
    }

    const normUni = normalizeContractedPartner(staffFormUni) || staffFormUni.trim();

    if (editingStaffItem) {
      if (editingStaffItem.isCustomItem) {
        const updated = customPartnerStaff.map(item => {
          if (item.id === editingStaffItem.id) {
            return {
              ...item,
              name: staffFormName.trim(),
              idNumber: staffFormIdNumber.trim(),
              type: staffFormType,
              partnerUniversity: normUni,
              specialty: staffFormSpecialty.trim(),
              department: staffFormDept.trim(),
              phone: staffFormPhone.trim(),
              startDate: staffFormStartDate.trim(),
              endDate: staffFormEndDate.trim(),
              manualStatus: staffFormStatus !== 'auto' ? staffFormStatus : undefined,
              notes: staffFormNotes.trim()
            };
          }
          return item;
        });
        setCustomPartnerStaff(updated);
        try { localStorage.setItem('crescent_custom_partner_staff', JSON.stringify(updated)); } catch {}
      } else {
        const key = editingStaffItem.idNumber || editingStaffItem.name;
        const newOverrides = {
          ...partnerStaffOverrides,
          [key]: {
            name: staffFormName.trim(),
            type: staffFormType,
            partnerUniversity: normUni,
            specialty: staffFormSpecialty.trim(),
            department: staffFormDept.trim(),
            phone: staffFormPhone.trim(),
            startDate: staffFormStartDate.trim(),
            endDate: staffFormEndDate.trim(),
            manualStatus: staffFormStatus !== 'auto' ? staffFormStatus : undefined,
            notes: staffFormNotes.trim()
          }
        };
        setPartnerStaffOverrides(newOverrides);
        try { localStorage.setItem('crescent_partner_staff_overrides', JSON.stringify(newOverrides)); } catch {}

        try {
          await syncStaffToStudentsData({
            ...editingStaffItem,
            name: staffFormName.trim(),
            idNumber: staffFormIdNumber.trim(),
            phone: staffFormPhone.trim(),
            specialty: staffFormSpecialty.trim(),
            startDate: staffFormStartDate.trim(),
            endDate: staffFormEndDate.trim(),
            type: staffFormType
          }, normUni, false);
        } catch (err) {
          console.error('Error persisting edited staff to D1:', err);
        }
      }
      showToast(`تم تعديل وحفظ بيانات (${staffFormName.trim()}) بنجاح ✓`);
    } else {
      const newItem = {
        id: `partner-staff-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`,
        isCustomItem: true,
        name: staffFormName.trim(),
        idNumber: staffFormIdNumber.trim(),
        type: staffFormType,
        partnerUniversity: normUni,
        specialty: staffFormSpecialty.trim(),
        department: staffFormDept.trim(),
        phone: staffFormPhone.trim(),
        startDate: staffFormStartDate.trim(),
        endDate: staffFormEndDate.trim(),
        manualStatus: staffFormStatus !== 'auto' ? staffFormStatus : undefined,
        notes: staffFormNotes.trim()
      };
      const updated = [...customPartnerStaff, newItem];
      setCustomPartnerStaff(updated);
      try { localStorage.setItem('crescent_custom_partner_staff', JSON.stringify(updated)); } catch {}

      try {
        await syncStaffToStudentsData(newItem, normUni, true);
      } catch (err) {
        console.error('Error persisting new staff to D1:', err);
      }

      showToast(`تمت إضافة (${newItem.name}) بنجاح ✓`);
    }

    setShowStaffEditModal(false);
    setEditingStaffItem(null);
  };

  const handleDeleteStaff = (staff: any) => {
    if (!confirm(`هل أنت متأكد من حذف وإزالة (${staff.name || 'الكادر'}) من تقرير هذه الجامعة؟`)) return;
    const key = staff.idNumber || staff.name;
    if (staff.isCustomItem) {
      const updated = customPartnerStaff.filter(item => item.id !== staff.id);
      setCustomPartnerStaff(updated);
      try { localStorage.setItem('crescent_custom_partner_staff', JSON.stringify(updated)); } catch {}
    } else {
      if (key && !hiddenPartnerStaffKeys.includes(key)) {
        const updated = [...hiddenPartnerStaffKeys, key];
        setHiddenPartnerStaffKeys(updated);
        try { localStorage.setItem('crescent_partner_hidden_staff', JSON.stringify(updated)); } catch {}
      }
    }
    showToast(`تم إزالة (${staff.name || 'الكادر'}) من تقرير الجامعات ✓`);
  };

  const handleResetAdjustments = () => {
    if (!confirm('هل تريد بالتأكيد إعادة ضبط كافة التعديلات والإضافات المخصصة على تقرير الجامعات الشريكة واستعادة الوضع الافتراضي؟')) return;
    setCustomPartnerStaff([]);
    setPartnerStaffOverrides({});
    setHiddenPartnerStaffKeys([]);
    setCustomPartnerUnis([]);
    try {
      localStorage.removeItem('crescent_custom_partner_staff');
      localStorage.removeItem('crescent_partner_staff_overrides');
      localStorage.removeItem('crescent_partner_hidden_staff');
      localStorage.removeItem('crescent_custom_partner_unis');
    } catch {}
    showToast('تمت استعادة الوضع الافتراضي بنجاح ✓');
  };

  // ── Modal for assigning student to clinical trainer across all specialties ──
  const [showAssignTrainerModal, setShowAssignTrainerModal] = useState<boolean>(false);
  const [assignModalStudent, setAssignModalStudent] = useState<any>(null);
  const [assignModalSourceDept, setAssignModalSourceDept] = useState<string>('');
  const [assignTrainerSearch, setAssignTrainerSearch] = useState<string>('');
  const [assignTrainerFilter, setAssignTrainerFilter] = useState<string>('all');
  const [isAssigningTrainer, setIsAssigningTrainer] = useState<boolean>(false);

  const openAssignModal = (student: any, sourceDept: string) => {
    setAssignModalStudent(student);
    setAssignModalSourceDept(sourceDept);
    setAssignTrainerSearch('');
    const sDept = (sourceDept || student?.department || student?.originalDepartment || '').toLowerCase();
    if (sDept.includes('أشعة') || sDept.includes('اشعة')) {
      setAssignTrainerFilter('radiology');
    } else if (sDept.includes('مختبر')) {
      setAssignTrainerFilter('lab');
    } else if (sDept.includes('علاج طبيعي')) {
      setAssignTrainerFilter('pt');
    } else if (sDept.includes('علاج وظيفي')) {
      setAssignTrainerFilter('ot');
    } else if (sDept.includes('صيدل')) {
      setAssignTrainerFilter('pharmacy');
    } else if (sDept.includes('تغذي')) {
      setAssignTrainerFilter('nutrition');
    } else if (sDept.includes('هندس')) {
      setAssignTrainerFilter('biomedical');
    } else if (sDept.includes('تمريض')) {
      setAssignTrainerFilter('nursing');
    } else {
      setAssignTrainerFilter('all');
    }
    setShowAssignTrainerModal(true);
  };

  // ── Modal: إضافة طالب مباشرة تحت إشراف مدرب محدد ──
  const [quickTrainerStudentModal, setQuickTrainerStudentModal] = useState<{
    isOpen: boolean;
    trainerName: string;
    dept: string;
  }>({ isOpen: false, trainerName: '', dept: '' });

  const [quickStudentForm, setQuickStudentForm] = useState({
    name: '',
    phone: '',
    idNumber: '',
    university: '',
    startDate: '',
    endDate: '',
    attendanceDays: '',
    address: '',
  });

  const openQuickTrainerStudentModal = (trainerName: string, dept: string) => {
    setQuickTrainerStudentModal({ isOpen: true, trainerName, dept });
    setQuickStudentForm({
      name: '',
      phone: '',
      idNumber: '',
      university: '',
      startDate: new Date().toISOString().split('T')[0],
      endDate: '',
      attendanceDays: 'سبت / اثنين / أربعاء',
      address: '',
    });
  };

  // ── Modal: تعيين طالب مسجل في النظام تحت إشراف مدرب محدد ──
  const [quickAssignModal, setQuickAssignModal] = useState<{
    isOpen: boolean;
    trainerName: string;
    dept: string;
    search: string;
    showAllStudents: boolean;
  }>({ isOpen: false, trainerName: '', dept: '', search: '', showAllStudents: false });

  const openQuickAssignModal = (trainerName: string, dept: string) => {
    setQuickAssignModal({ isOpen: true, trainerName, dept, search: '', showAllStudents: false });
  };

  // ── Modal: إضافة مدرب سريري جديد في قسم ──
  const [quickAddTrainerModal, setQuickAddTrainerModal] = useState<{
    isOpen: boolean;
    dept: string;
  }>({ isOpen: false, dept: '' });

  const [quickTrainerForm, setQuickTrainerForm] = useState({
    name: '',
    phone: '',
    university: '',
    idNumber: '',
    startDate: '',
    endDate: '',
    specialty: '',
  });

  const openQuickAddTrainerModal = (dept?: string | null) => {
    const safeDept = dept || 'تدريب تمريض الجامعات';
    const defaultSpecialty = safeDept.startsWith('مدربي ') ? `مدرب ${safeDept.replace('مدربي ', '')} سريري` : 'مدرب تمريض سريري';
    setQuickAddTrainerModal({ isOpen: true, dept: safeDept });
    setQuickTrainerForm({
      name: '',
      phone: '',
      university: 'جامعة بوليتكنك فلسطين',
      idNumber: '',
      startDate: new Date().toISOString().split('T')[0],
      endDate: '',
      specialty: defaultSpecialty,
    });
  };

  // Scroll functions for University Table (supports RTL)
  const scrollTableLeft = () => {
    if (!uniTableRef.current) return;
    const el = uniTableRef.current;
    const prev = el.scrollLeft;
    el.scrollBy({ left: -360, behavior: 'smooth' });
    setTimeout(() => {
      if (uniTableRef.current && uniTableRef.current.scrollLeft === prev) {
        uniTableRef.current.scrollBy({ left: 360, behavior: 'smooth' });
      }
    }, 60);
  };

  const scrollTableRight = () => {
    if (!uniTableRef.current) return;
    const el = uniTableRef.current;
    const prev = el.scrollLeft;
    el.scrollBy({ left: 360, behavior: 'smooth' });
    setTimeout(() => {
      if (uniTableRef.current && uniTableRef.current.scrollLeft === prev) {
        uniTableRef.current.scrollBy({ left: -360, behavior: 'smooth' });
      }
    }, 60);
  };

  const handleSliderScroll = (percent: number) => {
    if (!uniTableRef.current) return;
    setTableScrollPercent(percent);
    const el = uniTableRef.current;
    const maxScroll = el.scrollWidth - el.clientWidth;
    if (maxScroll <= 0) return;
    const target = (percent / 100) * maxScroll;
    el.scrollLeft = -target;
    if (el.scrollLeft === 0 && target > 0) {
      el.scrollLeft = target;
    }
  };

  const handleTableScroll = () => {
    if (!uniTableRef.current) return;
    const el = uniTableRef.current;
    const maxScroll = el.scrollWidth - el.clientWidth;
    if (maxScroll <= 0) {
      setTableScrollPercent(0);
      return;
    }
    const current = Math.abs(el.scrollLeft);
    const pct = Math.min(100, Math.max(0, Math.round((current / maxScroll) * 100)));
    setTableScrollPercent(pct);
  };

  // Fetch applications
  const fetchAllApplications = useCallback(async () => {
    try {
      const res = await fetch('/api/applications');
      if (res.ok) {
        const data = await res.json();
        setAllApplications(data.applications || []);
      }
    } catch (e) {
      console.error('Error fetching applications for topbar:', e);
    }
  }, []);

  useEffect(() => {
    fetchAllApplications();
    const interval = setInterval(fetchAllApplications, 30000);
    return () => clearInterval(interval);
  }, [fetchAllApplications]);

  const isUniversityNursingTrainer = (app: any) => {
    if (
      app.department === 'تمريض تدريب' ||
      app.acceptedDept === 'تمريض تدريب' ||
      app.originalDepartment === 'تمريض تدريب' ||
      app.internshipYear === 'طالب متدرب' ||
      app.crescentJobNature === 'طالب تمريض متدرب' ||
      app.crescentJobNature === 'طالب متدرب' ||
      (typeof app.internshipYear === 'string' && app.internshipYear.includes('طالب'))
    ) {
      return false;
    }
    const c = (app.category || app.categoryId || '').toLowerCase();
    return (
      c.includes('university-nursing-trainers') || 
      c.includes('تمريض الجامعات') || 
      c.includes('جامعات شريكة') ||
      c.includes('تقديم طلبات لتدريب طلاب التمريض في الجامعات')
    );
  };

  const isContractedDoctor = (app: any) => {
    const c = (app.category || app.categoryId || '').toLowerCase();
    return (
      c.includes('متعاقد') || 
      c.includes('contracted-doctors') || 
      c.includes('طبيب متعاقد')
    );
  };

  const universityApplications = useMemo(() => {
    return allApplications.filter(app => isUniversityNursingTrainer(app) || isContractedDoctor(app));
  }, [allApplications]);

  const nursingTrainersCount = useMemo(() => {
    return universityApplications.filter(isUniversityNursingTrainer).length;
  }, [universityApplications]);

  const contractedDoctorsCount = useMemo(() => {
    return universityApplications.filter(isContractedDoctor).length;
  }, [universityApplications]);

  const pendingUniCount = useMemo(() => {
    return universityApplications.filter(a => {
      const s = (a.status || '').toLowerCase();
      return !s || s === 'pending' || s === 'new' || s === 'قيد الانتظار';
    }).length;
  }, [universityApplications]);

  const filteredUniApps = useMemo(() => {
    return universityApplications.filter(app => {
      if (uniFilterTab === 'nursing' && !isUniversityNursingTrainer(app)) return false;
      if (uniFilterTab === 'doctors' && !isContractedDoctor(app)) return false;
      if (uniSearch.trim()) {
        const q = uniSearch.trim().toLowerCase();
        const matchName = (app.name || '').toLowerCase().includes(q);
        const matchPhone = (app.phone || '').toLowerCase().includes(q);
        const matchId = (app.idNumber || '').toLowerCase().includes(q);
        const matchUni = (app.university || '').toLowerCase().includes(q);
        return matchName || matchPhone || matchId || matchUni;
      }
      return true;
    });
  }, [universityApplications, uniFilterTab, uniSearch]);

  // ── Available clinical trainers across all departments (Radiology, Lab, PT, Nursing, Pharmacy, etc.) ──
  const availableTrainersList = useMemo(() => {
    const trainersMap = new Map<string, {
      name: string;
      university: string;
      department: string;
      badge: string;
      isNursingTrainer: boolean;
      source: 'website' | 'approved';
      phone?: string;
      specialtyGroup: 'nursing' | 'radiology' | 'lab' | 'pt' | 'pharmacy' | 'nutrition' | 'biomedical' | 'ot' | 'other';
    }>();

    const cleanName = (n: string) => (n || '').trim();

    const getResolvedTrainerUni = (item: any): string => {
      const n = (item.name || '').trim();
      const idNum = String(item.idNumber || item.id_number || '').replace(/\D/g, '');
      if ((n.includes('مهران') && n.includes('درويش')) || idNum === '860162031') return 'جامعة بوليتكنك فلسطين';
      if ((n.includes('باسل') && (n.includes('عمرو') || n.includes('عمر'))) || idNum === '402724918') return 'جامعة بوليتكنك فلسطين';
      if ((n.includes('عمر') && (n.includes('رجوب') || n.includes('ارجوب'))) || idNum === '854113719') return 'جامعة بوليتكنك فلسطين';
      if (n.includes('طلحه') || n.includes('طلحة') || idNum === '402066195') return 'جامعة بوليتكنك فلسطين';
      if (n.toLowerCase().includes('dababsa') || n.includes('دبابسة') || n.includes('دبابسه') || idNum === '403139025') return 'جامعة بوليتكنك فلسطين';
      if (n.includes('محمد راتب') || n.includes('جلق') || idNum === '854614047') return 'جامعة بوليتكنك فلسطين';
      if ((n.includes('بلال') && (n.includes('امواس') || n.includes('مناصرة'))) || idNum === '954308822') return 'الكلية الذكية الجامعية للتعليم الحديث';
      if (n.includes('محمود فخري') || idNum === '854997632') return 'الكلية الذكية الجامعية للتعليم الحديث';

      const contracted = item.contractedUniversities || item.contracted_universities || item.contractedUniversity || item.contracted_university;
      if (contracted) {
        if (Array.isArray(contracted) && contracted.length > 0) {
          const valid = contracted.filter((u: any) => !String(u).includes('قدس') && !String(u).includes('نجاح') && !String(u).includes('امريك'));
          if (valid.length > 0) return valid.join('، ');
        } else if (typeof contracted === 'string' && contracted.trim()) {
          const s = contracted.trim();
          if (!s.includes('قدس') && !s.includes('نجاح') && !s.includes('امريك')) return s;
        }
      }

      // Check if item.university is a recognized partner (never graduation university)
      const u = item.university || '';
      if (u.includes('بوليتكنك') || u.includes('بولتكنك')) return 'جامعة بوليتكنك فلسطين';
      if (u.includes('خليل')) return 'جامعة الخليل';
      if (u.includes('ذكية') || u.includes('ذكيه')) return 'الكلية الذكية الجامعية للتعليم الحديث';
      return 'جامعة بوليتكنك فلسطين';
    };

    // 1. All website trainer applications across all medical/health categories
    allApplications.forEach((a: any) => {
      let c = (a.category || a.categoryId || '').toLowerCase();
      try { c = decodeURIComponent(c); } catch {}
      const name = cleanName(a.name);
      if (!name) return;

      let specialtyGroup: 'nursing' | 'radiology' | 'lab' | 'pt' | 'pharmacy' | 'nutrition' | 'biomedical' | 'ot' | 'other' = 'other';
      let deptName = 'تدريب تمريض الجامعات';
      let badge = '🎓 مدرب سريري (الموقع)';

      if (c.includes('أشعة') || c.includes('اشعة') || c.includes('radiology') || c.includes('تصوير')) {
        specialtyGroup = 'radiology';
        deptName = 'مدربي أشعة';
        badge = '☢️ مدرب أشعة (الموقع)';
      } else if (c.includes('مختبر') || c.includes('تحاليل') || c.includes('lab')) {
        specialtyGroup = 'lab';
        deptName = 'مدربي مختبر';
        badge = '🧪 مدرب مختبر (الموقع)';
      } else if (c.includes('علاج طبيعي') || c.includes('physiotherapy')) {
        specialtyGroup = 'pt';
        deptName = 'مدربي علاج طبيعي';
        badge = '🏃 مدرب علاج طبيعي (الموقع)';
      } else if (c.includes('صيدل') || c.includes('pharmacy')) {
        specialtyGroup = 'pharmacy';
        deptName = 'مدربي صيدلية';
        badge = '💊 مدرب صيدلة (الموقع)';
      } else if (c.includes('تغذي') || c.includes('nutrition')) {
        specialtyGroup = 'nutrition';
        deptName = 'مدربي تغذية';
        badge = '🥗 مدرب تغذية (الموقع)';
      } else if (c.includes('هندسة') || c.includes('biomedical')) {
        specialtyGroup = 'biomedical';
        deptName = 'مدربي هندسة طبية';
        badge = '⚙️ مدرب هندسة طبية (الموقع)';
      } else if (c.includes('علاج وظيفي') || c.includes('وظيفي') || c.includes('occupational')) {
        specialtyGroup = 'ot';
        deptName = 'مدربي علاج وظيفي';
        badge = '🤲 مدرب علاج وظيفي (الموقع)';
      } else if (
        c.includes('تدريب طلاب التمريض') ||
        c.includes('university-nursing-trainers') ||
        c.includes('تمريض الجامعات') ||
        c.includes('جامعات شريكة') ||
        (c.includes('تمريض') && (c.includes('مدرب') || c.includes('trainer') || c.includes('مشرف')))
      ) {
        specialtyGroup = 'nursing';
        deptName = 'تدريب تمريض الجامعات';
        badge = '🩺 مدرب تمريض (الموقع)';
      } else if (c.includes('مدرب') || c.includes('trainer') || c.includes('مشرف')) {
        specialtyGroup = 'other';
        badge = '🎓 مدرب معتمد (الموقع)';
      } else {
        return; // Not a trainer application
      }

      if (!trainersMap.has(name)) {
        trainersMap.set(name, {
          name,
          university: getResolvedTrainerUni(a),
          department: deptName,
          badge,
          isNursingTrainer: specialtyGroup === 'nursing',
          source: 'website',
          phone: a.phone,
          specialtyGroup
        });
      }
    });

    // 2. Approved staff from all trainer departments in studentsData
    const trainerDeptsConfig: { dept: string; group: 'nursing' | 'radiology' | 'lab' | 'pt' | 'pharmacy' | 'nutrition' | 'biomedical' | 'ot'; badge: string }[] = [
      { dept: 'تدريب تمريض الجامعات', group: 'nursing',    badge: '🩺 مدرب تمريض معتمد' },
      { dept: 'مدربي أشعة',          group: 'radiology',  badge: '☢️ مدرب أشعة معتمد' },
      { dept: 'مدربي مختبر',         group: 'lab',        badge: '🧪 مدرب مختبرات معتمد' },
      { dept: 'مدربي علاج طبيعي',     group: 'pt',         badge: '🏃 مدرب علاج طبيعي معتمد' },
      { dept: 'مدربي صيدلية',        group: 'pharmacy',   badge: '💊 مدرب صيدلة معتمد' },
      { dept: 'مدربي تغذية',         group: 'nutrition',  badge: '🥗 مدرب تغذية معتمد' },
      { dept: 'مدربي هندسة طبية',    group: 'biomedical', badge: '⚙️ مدرب هندسة طبية معتمد' },
      { dept: 'مدربي علاج وظيفي',    group: 'ot',         badge: '🤲 مدرب علاج وظيفي معتمد' },
    ];

    trainerDeptsConfig.forEach(({ dept, group, badge }) => {
      const staffList = studentsData[dept] || [];
      if (Array.isArray(staffList)) {
        staffList.forEach((s: any) => {
          // Exclude students who are under a trainer
          if (s.assignedTrainer) return;
          if (s.internshipYear === 'طالب متدرب' || (s.crescentJobNature && s.crescentJobNature.includes('طالب'))) return;
          const name = cleanName(s.name);
          if (name) {
            trainersMap.set(name, {
              name,
              university: getResolvedTrainerUni(s),
              department: dept,
              badge,
              isNursingTrainer: group === 'nursing',
              source: 'approved',
              phone: s.phone,
              specialtyGroup: group
            });
          }
        });
      }
    });

    return Array.from(trainersMap.values()).sort((a, b) => a.name.localeCompare(b.name, 'ar'));
  }, [allApplications, studentsData]);

  // ── Handle assigning a student to a clinical trainer from the main dashboard ──
  const handleAssignTrainerFromMain = async (trainerName: string) => {
    if (!assignModalStudent || !trainerName) return;
    setIsAssigningTrainer(true);
    try {
      const student = assignModalStudent;
      const applicantName = (student.name || '').trim();
      const applicantPhone = (student.phone || '').trim();
      const applicantId = (student.idNumber || '').trim();
      const sourceDept = assignModalSourceDept || currentDepartment || 'تمريض تدريب';
      const foundTrainer = availableTrainersList.find(t => t.name === trainerName);
      let TARGET_DEPT = 'تدريب تمريض الجامعات';
      if (foundTrainer && isTrainerDepartment(foundTrainer.department)) {
        TARGET_DEPT = foundTrainer.department;
      } else if (currentDepartment && isTrainerDepartment(currentDepartment)) {
        TARGET_DEPT = currentDepartment;
      } else {
        TARGET_DEPT = getTrainerDeptForStudentDept(sourceDept);
      }

      const cleanStr = (s: string) => (s || '')
        .trim()
        .toLowerCase()
        .replace(/[أإآءئؤ]/g, 'ا')
        .replace(/ة/g, 'ه')
        .replace(/ى/g, 'ي')
        .replace(/[\u064B-\u065F\u0670\u0640]/g, '')
        .replace(/\s+/g, ' ');

      const cleanPhone = (ph: string) => {
        const d = (ph || '').replace(/\D/g, '');
        return d.length >= 9 ? d.slice(-9) : d;
      };

      const cAppName = cleanStr(applicantName);
      const cAppPhone = cleanPhone(applicantPhone);
      const cAppId = (applicantId || '').trim();

      const newData: Record<string, any[]> = {};
      Object.keys(studentsData).forEach(dept => {
        newData[dept] = Array.isArray(studentsData[dept]) ? [...studentsData[dept]] : [];
      });
      if (!newData[TARGET_DEPT]) newData[TARGET_DEPT] = [];

      // 1. REMOVE the student from ANY other department (leaves 'تمريض تدريب' completely)
      Object.keys(newData).forEach(dept => {
        if (dept !== TARGET_DEPT && Array.isArray(newData[dept])) {
          newData[dept] = newData[dept].filter((s: any) => {
            const sName = cleanStr(s.name);
            const sPhone = cleanPhone(s.phone);
            const sId = (s.idNumber || '').trim();

            const matchPhone = cAppPhone.length >= 7 && sPhone.length >= 7 && sPhone === cAppPhone;
            const matchId = cAppId && sId && sId === cAppId;
            const matchName = sName.length > 2 && cAppName.length > 2 && (
              sName === cAppName || 
              (sName.split(' ').length >= 3 && cAppName.split(' ').length >= 3 && (sName.includes(cAppName) || cAppName.includes(sName)))
            );

            if (matchPhone || matchId || matchName) {
              return false; // Leave this department completely!
            }
            return true;
          });
        }
      });

      // 2. Add or update in TARGET_DEPT
      const existingIdx = newData[TARGET_DEPT].findIndex((s: any) => {
        const sName = cleanStr(s.name);
        const sPhone = cleanPhone(s.phone);
        const sId = (s.idNumber || '').trim();
        return (
          (cAppPhone.length >= 7 && sPhone.length >= 7 && sPhone === cAppPhone) ||
          (cAppId && sId && sId === cAppId) ||
          (sName === cAppName)
        );
      });

      if (existingIdx !== -1) {
        newData[TARGET_DEPT][existingIdx] = {
          ...newData[TARGET_DEPT][existingIdx],
          assignedTrainer: trainerName,
          internshipYear: 'طالب متدرب',
          crescentJobNature: 'طالب تمريض متدرب',
          isUniversityTrainer: false,
          department: TARGET_DEPT
        };
      } else {
        const newStudent = {
          ...student,
          department: TARGET_DEPT,
          originalDepartment: sourceDept,
          assignedTrainer: trainerName,
          internshipYear: 'طالب متدرب',
          crescentJobNature: 'طالب تمريض متدرب',
          isUniversityTrainer: false,
          studySystem: 'تمريض جامعات'
        };
        newData[TARGET_DEPT].push(newStudent);
      }

      // 3. Deduplicate TARGET_DEPT
      const seen = new Set<string>();
      newData[TARGET_DEPT] = newData[TARGET_DEPT].filter((s: any) => {
        const key = (cleanPhone(s.phone) || (s.idNumber || '').trim())
          ? `${cleanStr(s.name)}___${cleanPhone(s.phone) || (s.idNumber || '').trim()}`
          : `${cleanStr(s.name)}___${s.id || s.startDate || s.assignedTrainer || ''}`;
        if (seen.has(key)) return false;
        seen.add(key);
        return true;
      });

      // 4. Save data safely (updates local state, localStorage, and persists to /api/students in D1)
      await saveData(newData);

      // 6. If matching application exists in allApplications, update it too
      const matchingApp = allApplications.find(a => 
        (cAppPhone.length >= 7 && cleanPhone(a.phone) === cAppPhone) ||
        (cleanStr(a.name) === cAppName)
      );
      if (matchingApp) {
        const appId = matchingApp._supabaseId || matchingApp.id;
        if (appId) {
          try {
            await fetch('/api/applications', {
              method: 'PATCH',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                id: appId,
                status: 'accepted',
                assignedTrainer: trainerName,
                department: TARGET_DEPT,
                applicantData: {
                  ...matchingApp,
                  status: 'accepted',
                  assignedTrainer: trainerName,
                  department: TARGET_DEPT
                }
              })
            });
            fetchAllApplications();
          } catch {}
        }
      }

      setShowAssignTrainerModal(false);
      setAssignModalStudent(null);
      showToast(`✅ تم نقل "${applicantName}" من قسم ${sourceDept} وتعيينه للمدرب "${trainerName}" في قسم "${TARGET_DEPT}" بنجاح`);
    } catch (e) {
      console.error('Error assigning student to trainer:', e);
      showToast('❌ حدث خطأ أثناء التعيين، يرجى المحاولة مجدداً');
    } finally {
      setIsAssigningTrainer(false);
    }
  };

  // ── Quick Handler: إضافة طالب تحت إشراف مدرب محدد ──
  const handleSaveQuickStudent = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!quickStudentForm.name.trim()) {
      showToast('⚠️ يرجى كتابة اسم الطالب');
      return;
    }
    const dept = quickTrainerStudentModal.dept || currentDepartment || 'تدريب تمريض الجامعات';
    const trainerName = quickTrainerStudentModal.trainerName;
    const formattedStart = formatDate(quickStudentForm.startDate);
    const formattedEnd = formatDate(quickStudentForm.endDate);

    const newStudent: Student = {
      name: quickStudentForm.name.trim(),
      phone: quickStudentForm.phone.trim(),
      idNumber: quickStudentForm.idNumber.trim(),
      university: quickStudentForm.university.trim() || 'جامعة بوليتكنك فلسطين',
      startDate: formattedStart,
      endDate: formattedEnd,
      globalStartDate: formattedStart,
      globalEndDate: formattedEnd,
      attendanceDays: quickStudentForm.attendanceDays.trim(),
      address: quickStudentForm.address.trim(),
      assignedTrainer: trainerName,
      internshipYear: 'طالب متدرب',
      crescentJobNature: dept === 'تدريب تمريض الجامعات' ? 'طالب تمريض متدرب' : `طالب متدرب (${dept.replace('مدربي ', '')})`,
      isUniversityTrainer: false,
      department: dept,
      originalDepartment: dept,
      studySystem: dept === 'تدريب تمريض الجامعات' ? 'تمريض جامعات' : `تدريب ${dept.replace('مدربي ', '')}`
    };

    const newData: Record<string, any[]> = {};
    Object.keys(studentsData).forEach(d => {
      newData[d] = Array.isArray(studentsData[d]) ? [...studentsData[d]] : [];
    });
    if (!newData[dept]) newData[dept] = [];

    // Remove if existed elsewhere
    const cName = cleanStr(newStudent.name);
    const cPhone = cleanPhone(newStudent.phone);
    const cId = newStudent.idNumber;
    Object.keys(newData).forEach(d => {
      if (d !== dept && Array.isArray(newData[d])) {
        newData[d] = newData[d].filter((s: any) => {
          const matchPhone = cPhone.length >= 7 && cleanPhone(s.phone) === cPhone;
          const matchId = cId && s.idNumber && s.idNumber === cId;
          const matchName = cleanStr(s.name) === cName;
          return !(matchPhone || matchId || matchName);
        });
      }
    });

    newData[dept].push(newStudent);
    await saveData(newData);
    setQuickTrainerStudentModal({ isOpen: false, trainerName: '', dept: '' });
    setQuickStudentForm({ name: '', phone: '', idNumber: '', university: '', startDate: '', endDate: '', attendanceDays: '', address: '' });
    showToast(`✅ تم إضافة الطالب "${newStudent.name}" تحت إشراف المدرب "${trainerName}" بنجاح`);
  };

  // ── Quick Handler: إضافة مدرب سريري جديد في قسم ──
  const handleSaveQuickTrainer = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!quickTrainerForm.name.trim()) {
      showToast('⚠️ يرجى كتابة اسم المدرب السريري');
      return;
    }
    const dept = quickAddTrainerModal.dept || currentDepartment || 'تدريب تمريض الجامعات';
    const formattedStart = formatDate(quickTrainerForm.startDate);
    const formattedEnd = formatDate(quickTrainerForm.endDate);

    const newTrainer: Student = {
      name: quickTrainerForm.name.trim(),
      phone: quickTrainerForm.phone.trim(),
      university: quickTrainerForm.university.trim() || 'جامعة بوليتكنك فلسطين',
      idNumber: quickTrainerForm.idNumber.trim(),
      startDate: formattedStart,
      endDate: formattedEnd,
      globalStartDate: formattedStart,
      globalEndDate: formattedEnd,
      internshipYear: 'مدرب سريري',
      crescentJobNature: quickTrainerForm.specialty.trim() || 'مدرب سريري',
      isUniversityTrainer: true,
      department: dept,
      originalDepartment: dept
    };

    const newData: Record<string, any[]> = {};
    Object.keys(studentsData).forEach(d => {
      newData[d] = Array.isArray(studentsData[d]) ? [...studentsData[d]] : [];
    });
    if (!newData[dept]) newData[dept] = [];

    newData[dept].push(newTrainer);
    await saveData(newData);
    setQuickAddTrainerModal({ isOpen: false, dept: '' });
    setQuickTrainerForm({ name: '', phone: '', university: '', idNumber: '', startDate: '', endDate: '', specialty: '' });
    showToast(`✅ تم إضافة المدرب السريري "${newTrainer.name}" إلى قسم "${dept}" بنجاح`);
  };

  const printUniApplication = async (app: any) => {
    if (!app) return;
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      alert('يرجى السماح بالنوافذ المنبثقة لطباعة الاستمارة الرسمية');
      return;
    }

    // Immediate responsive loading splash
    printWindow.document.write(`
      <!DOCTYPE html>
      <html dir="rtl" lang="ar">
      <head>
        <meta charset="utf-8" />
        <title>جاري تحضير استمارة الطباعة...</title>
        <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@500;700;800&display=swap" rel="stylesheet">
        <style>
          body { font-family: 'Tajawal', sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #f8fafc; color: #1e293b; direction: rtl; }
          .loader { width: 44px; height: 44px; border: 4px solid #e2e8f0; border-top: 4px solid #0284c7; border-radius: 50%; animation: spin 0.8s linear infinite; margin-bottom: 16px; }
          @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        </style>
      </head>
      <body>
        <div class="loader"></div>
        <div style="font-size: 18px; font-weight: 800;">جاري إعداد استمارة المتقدم الرسمية والصور للطباعة...</div>
        <div style="font-size: 13px; color: #64748b; margin-top: 6px;">يرجى الانتظار لحظة واحدة</div>
      </body>
      </html>
    `);

    // Ensure we have full-resolution photo
    let targetApp = { ...app };
    const appId = targetApp._supabaseId || targetApp.id;
    let applicantPhoto = targetApp.photoBase64 || targetApp.doctorPhotoBase64 || targetApp.personalPhoto || targetApp.photo || targetApp.personalPhotoBase64 || targetApp.image || '';

    if (!applicantPhoto && (targetApp.hasPhoto || appId)) {
      try {
        const res = await fetch(`/api/applications?id=${appId}`);
        if (res.ok) {
          const detail = await res.json();
          if (detail.application) {
            targetApp = { ...targetApp, ...detail.application };
            applicantPhoto = targetApp.photoBase64 || targetApp.doctorPhotoBase64 || targetApp.personalPhoto || targetApp.photo || targetApp.personalPhotoBase64 || targetApp.image || '';
          }
        }
      } catch (e) {
        console.warn('Could not load full photo for printing:', e);
      }
    }

    const trainDepts = (Array.isArray(targetApp.trainingDepartments) ? targetApp.trainingDepartments.join(' ') : (targetApp.trainingDepartments || ''));
    const rotDepts = (Array.isArray(targetApp.rotations) ? targetApp.rotations.map((r: any) => r.dept || r.name || '') : []).join(' ');

    const searchBlob = [
      targetApp.category,
      targetApp.categoryId,
      targetApp.department,
      targetApp.assignedDept,
      targetApp.targetDept,
      targetApp.volunteerDepartment,
      targetApp.nursingSpecialty,
      targetApp.qualification,
      targetApp.trainingType,
      targetApp.notes,
      targetApp.employmentType,
      targetApp.crescentJobNature,
      trainDepts,
      rotDepts
    ].filter(Boolean).join(' ').toLowerCase();

    let isNursing = 
      isUniversityNursingTrainer(targetApp) ||
      searchBlob.includes('تمريض') ||
      searchBlob.includes('ممرض') ||
      searchBlob.includes('ممرضه') ||
      searchBlob.includes('ممرضة') ||
      searchBlob.includes('nursing') ||
      searchBlob.includes('nurse') ||
      searchBlob.includes('قبالة') ||
      searchBlob.includes('قباله') ||
      searchBlob.includes('midwife') ||
      Boolean(targetApp.nursingSpecialty && targetApp.nursingSpecialty.trim().length > 0);

    const isDoctor = !isNursing && ((targetApp.category || '').includes('طبيب') || (targetApp.category || '').includes('متعاقد') || (targetApp.categoryId || '').includes('doctor'));
    const categoryName = targetApp.category || (isNursing ? 'تدريب طلاب التمريض في الجامعات' : 'الأطباء المتعاقدون مع الجامعات');

    // Extract exact department for University Nursing Trainers
    const uniTrainDeptsDisplay = (targetApp.trainingDepartments && targetApp.trainingDepartments.length > 0)
      ? (Array.isArray(targetApp.trainingDepartments) ? targetApp.trainingDepartments.join('، ') : targetApp.trainingDepartments)
      : '';

    const uniCoursesDisplay = (targetApp.teachingCourses && targetApp.teachingCourses.length > 0)
      ? (Array.isArray(targetApp.teachingCourses) ? targetApp.teachingCourses.join('، ') : targetApp.teachingCourses)
      : '';

    let targetDept = uniTrainDeptsDisplay || targetApp.assignedDept || targetApp.targetDept || targetApp.department || '';
    if (isNursing) {
      if (!targetDept || targetDept === 'تدريب تمريض الجامعات' || targetDept.includes('تقديم طلبات لتدريب طلاب التمريض')) {
        targetDept = uniTrainDeptsDisplay || 'قسم التمريض العام والطوارئ';
      }
    } else {
      if (!targetDept) targetDept = 'الأطباء المتعاقدون';
    }

    if (
      targetDept.includes('تمريض') || 
      targetDept.includes('nursing') || 
      targetDept.includes('ممرض') || 
      targetDept.includes('قبالة') ||
      targetDept.includes('قباله') ||
      targetDept === 'التمريض' ||
      targetDept === 'التمريض العام' ||
      targetDept === 'تمريض تدريب' ||
      targetDept === 'تمريض امتياز' ||
      targetDept === 'تمريض تطوع' ||
      targetDept === 'تدريب تمريض الجامعات'
    ) {
      isNursing = true;
    }

    const formatPrintDate = (rawDate?: string) => {
      if (!rawDate) {
        const d = new Date();
        const day = String(d.getDate()).padStart(2, '0');
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const year = d.getFullYear();
        return `${day}-${month}-${year}`;
      }
      const clean = String(rawDate).split('T')[0].replace(/\//g, '-');
      const parts = clean.split('-');
      if (parts.length === 3) {
        if (parts[0].length === 4) {
          return `${parts[2].padStart(2, '0')}-${parts[1].padStart(2, '0')}-${parts[0]}`;
        } else {
          return `${parts[0].padStart(2, '0')}-${parts[1].padStart(2, '0')}-${parts[2]}`;
        }
      }
      return rawDate;
    };

    const formatIsoDate = (rawDate?: string) => {
      if (!rawDate) return '—';
      const clean = String(rawDate).split('T')[0].replace(/\//g, '-');
      const parts = clean.split('-');
      if (parts.length === 3) {
        if (parts[0].length === 4) {
          return `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`;
        } else {
          return `${parts[2]}-${parts[1].padStart(2, '0')}-${parts[0]}`;
        }
      }
      return rawDate;
    };

    const rawStart = targetApp.trainingStartDate || targetApp.startDate || targetApp.date || targetApp.createdAt || targetApp.created_at;
    let rawEnd = targetApp.trainingEndDate || targetApp.endDate;
    if (!rawEnd && rawStart) {
      const d = new Date(rawStart);
      if (!isNaN(d.getTime())) {
        d.setMonth(d.getMonth() + 3);
        rawEnd = d.toISOString().split('T')[0];
      } else {
        rawEnd = '2026-12-31';
      }
    }

    const printDate = formatPrintDate(targetApp.date || targetApp.createdAt || targetApp.created_at);
    const startDate = formatIsoDate(rawStart);
    const endDate = formatIsoDate(rawEnd);
    
    const workDaysDisplay = (targetApp.workDays && targetApp.workDays.length > 0)
      ? (Array.isArray(targetApp.workDays) ? targetApp.workDays.join('، ') : targetApp.workDays)
      : (targetApp.workHours || targetApp.shiftSystem || targetApp.workShift || 'حسب جدول القسم المعتمد');

    const uniDisplay = targetApp.contractedUniversities && targetApp.contractedUniversities.length > 0 
      ? (Array.isArray(targetApp.contractedUniversities) ? targetApp.contractedUniversities.join('، ') : targetApp.contractedUniversities)
      : (targetApp.university || targetApp.previousContractedUniversity || '—');

    const rawStatus = (targetApp.status || '').toLowerCase();
    const statusLabel = (rawStatus === 'accepted' || rawStatus === 'مقبول') 
      ? 'مقبول ومعتمد' 
      : (rawStatus === 'rejected' || rawStatus === 'مرفوض') 
        ? 'مرفوض' 
        : 'قيد المعالجة';

    // Rotations / Schedule rows
    const rawDepts = targetApp.trainingDepartments;
    const deptsList: string[] = Array.isArray(rawDepts)
      ? rawDepts.map((d: any) => String(d).trim()).filter(Boolean)
      : (typeof rawDepts === 'string' && rawDepts.trim()
          ? rawDepts.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean)
          : []);

    let rotationsRows = '';
    if (deptsList.length > 0) {
      rotationsRows = deptsList.map((deptName: string, idx: number) => `
        <tr>
          <td style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12px; font-weight: 700; color: #0f172a;">قسم معتمد ${idx + 1}</td>
          <td style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 13.5px; font-weight: 800; color: #1e3a8a;">${deptName}</td>
          <td dir="ltr" style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12.5px; font-weight: 700; color: #0f172a;">${startDate}</td>
          <td dir="ltr" style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12.5px; font-weight: 700; color: #0f172a;">${endDate}</td>
          <td style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12px; font-weight: 700; color: #0f172a;">${workDaysDisplay}</td>
        </tr>
      `).join('');
    } else {
      rotationsRows = `
        <tr>
          <td style="border: 1.2px solid #94a3b8; padding: 16px 8px; font-size: 12px; font-weight: 700; color: #0f172a;">اعتماد 1</td>
          <td style="border: 1.2px solid #94a3b8; padding: 16px 8px; font-size: 13px; font-weight: 800; color: #0f172a;">${targetDept}</td>
          <td dir="ltr" style="border: 1.2px solid #94a3b8; padding: 16px 8px; font-size: 13px; font-weight: 800; color: #1e3a8a;">${startDate}</td>
          <td dir="ltr" style="border: 1.2px solid #94a3b8; padding: 16px 8px; font-size: 13px; font-weight: 800; color: #1e3a8a;">${endDate}</td>
          <td style="border: 1.2px solid #94a3b8; padding: 16px 8px; font-size: 12px; font-weight: 700; color: #0f172a;">${workDaysDisplay}</td>
        </tr>
      `;
    }

    const parentOrigin = typeof window !== 'undefined' ? window.location.origin : '';

    const htmlContent = `
      <!DOCTYPE html>
      <html dir="rtl" lang="ar">
      <head>
        <meta charset="utf-8" />
        <title>استمارة طلب وتوزيع قسم رسمية - ${targetApp.name || 'متقدم'}</title>
        <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800;900&display=swap" rel="stylesheet">
        <style>
          @page {
            size: A4 portrait;
            margin: 12mm 15mm;
          }
          * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Tajawal', sans-serif;
          }
          body {
            direction: rtl;
            color: #0f172a;
            background: #ffffff;
            padding: 16px 24px;
            line-height: 1.5;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
          }
          img {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
          }
          @media print {
            body {
              padding: 0;
            }
            .no-print {
              display: none !important;
            }
          }

          /* Header */
          .header-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 4px 6px 12px 6px;
          }
          .header-right {
            text-align: right;
          }
          .org-name {
            font-size: 20px;
            font-weight: 900;
            color: #0f172a;
            margin-bottom: 3px;
          }
          .hosp-unit {
            font-size: 13px;
            font-weight: 700;
            color: #334155;
            margin-bottom: 3px;
          }
          .supervisor-name {
            font-size: 12px;
            font-weight: 700;
            color: #475569;
          }
          .header-left {
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .supervisor-frame {
            width: 78px;
            height: 78px;
            border-radius: 50%;
            border: 2.5px solid #1e293b;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            overflow: hidden;
            background: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 4px;
          }
          .supervisor-frame img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center 18%;
          }
          .header-divider {
            border-bottom: 2px solid #1e293b;
            margin-top: 8px;
            margin-bottom: 18px;
          }

          /* Form Title */
          .title-section {
            text-align: center;
            margin-bottom: 18px;
          }
          .form-title {
            font-size: 21px;
            font-weight: 900;
            color: #0f172a;
            margin-bottom: 4px;
          }
          .form-date {
            font-size: 11px;
            font-weight: 700;
            color: #64748b;
          }

          /* Target Department Box */
          .dept-box {
            border: 1.5px solid #64748b;
            border-radius: 14px;
            padding: 14px 20px;
            text-align: center;
            margin-bottom: 22px;
            background: #ffffff;
          }
          .dept-box-label {
            font-size: 13px;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 6px;
          }
          .dept-box-name {
            font-size: 24px;
            font-weight: 900;
            color: #0f172a;
            margin-bottom: 6px;
            letter-spacing: 0.5px;
          }
          .dept-box-sub {
            font-size: 11.5px;
            font-weight: 700;
            color: #475569;
          }

          /* Personal Info Section */
          .sec-header {
            font-size: 13.5px;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 6px;
          }
          .sec-divider {
            border-bottom: 1px solid #cbd5e1;
            margin-bottom: 16px;
          }
          .info-grid {
            display: grid;
            grid-template-columns: 1.25fr 1fr;
            row-gap: 16px;
            column-gap: 24px;
            font-size: 12.5px;
            color: #334155;
          }
          .info-row {
            display: flex;
            align-items: baseline;
            gap: 8px;
          }
          .info-label {
            font-weight: 700;
            color: #475569;
          }
          .info-value {
            font-weight: 800;
            color: #0f172a;
          }

          /* Rotations Table */
          .rotations-title {
            font-size: 13.5px;
            font-weight: 800;
            color: #1e293b;
            margin-top: 26px;
            margin-bottom: 10px;
          }
          .rotations-table {
            width: 100%;
            border-collapse: collapse;
            text-align: center;
            margin-bottom: 10px;
          }
          .rotations-table th {
            background: #f8fafc;
            border: 1.2px solid #94a3b8;
            padding: 10px 8px;
            font-size: 12.5px;
            font-weight: 800;
            color: #334155;
          }

          /* Signatures */
          .signatures-divider {
            border-top: 1.5px dashed #94a3b8;
            margin-top: 45px;
            margin-bottom: 30px;
          }
          .signatures-grid {
            display: grid;
            grid-template-columns: ${isNursing ? 'repeat(5, 1fr)' : 'repeat(4, 1fr)'};
            gap: ${isNursing ? '10px' : '16px'};
            text-align: center;
          }
          .sig-title {
            font-size: ${isNursing ? '12.5px' : '13.5px'};
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 5px;
          }
          .sig-sub {
            font-size: ${isNursing ? '11px' : '12px'};
            font-weight: 700;
            color: #475569;
            margin-bottom: 18px;
            min-height: 18px;
          }
          .sig-line {
            border-bottom: 1.5px solid #334155;
            width: 85%;
            margin: 0 auto 6px;
          }
          .sig-date {
            font-size: ${isNursing ? '10px' : '11px'};
            color: #64748b;
            font-weight: 600;
          }
        </style>
      </head>
      <body>

        <!-- Top Controls Toolbar (Hidden in Print) -->
        <div class="print-toolbar no-print" style="position: fixed; top: 0; left: 0; right: 0; background: #0f172a; color: #ffffff; padding: 10px 24px; display: flex; align-items: center; justify-content: space-between; z-index: 99999; box-shadow: 0 4px 16px rgba(0,0,0,0.3); font-family: 'Tajawal', sans-serif;">
          <div style="display: flex; align-items: center; gap: 12px;">
            <span style="font-size: 13.5px; font-weight: 800; color: #38bdf8;">📄 استمارة طلب وتوزيع قسم رسمية</span>
            <span style="font-size: 12px; color: #cbd5e1;">- ${targetApp.name || ''}</span>
            <span style="font-size: 11px; background: rgba(56,189,248,0.15); color: #7dd3fc; padding: 2px 8px; border-radius: 6px; border: 1px solid rgba(56,189,248,0.3);">
              ${isNursing ? `القسم: ${targetDept}` : `القسم: ${targetDept}`}
            </span>
          </div>
          <div style="display: flex; align-items: center; gap: 10px;">
            <button onclick="triggerPrintNow()" style="background: linear-gradient(135deg, #059669, #047857); color: white; border: none; padding: 6px 18px; border-radius: 8px; font-weight: 800; font-size: 13px; cursor: pointer; display: flex; align-items: center; gap: 6px; box-shadow: 0 2px 6px rgba(5,150,105,0.4);">
              🖨️ طباعة الاستمارة
            </button>
            <button onclick="window.close()" style="background: #334155; color: #cbd5e1; border: none; padding: 6px 14px; border-radius: 8px; font-weight: 700; font-size: 12px; cursor: pointer;">
              ✕ إغلاق
            </button>
          </div>
        </div>

        <div style="height: 38px;" class="no-print"></div>

        <!-- Top Header -->
        <div class="header-container">
          <div class="header-right">
            <div class="org-name">جمعية الهلال الأحمر الفلسطيني</div>
            <div class="hosp-unit">مستشفى الهلال الأحمر – وحدة التطوير والتدريب</div>
            <div class="supervisor-name">إشراف أ. نسرين عابدين</div>
          </div>
        </div>

        <div class="header-divider"></div>

        <!-- Form Title & Date -->
        <div class="title-section">
          <div class="form-title">استمارة طلب وتوزيع قسم رسمية</div>
          <div class="form-date">تاريخ الطلب والطباعة: ${printDate}</div>
        </div>

        <!-- Target Department Box -->
        <div class="dept-box">
          <div class="dept-box-label">💫 ${isNursing ? 'القسم المخصص والوجهة المعتمدة لتدريب تمريض الجامعات:' : 'القسم المخصص والوجهة المعتمدة للأطباء المتعاقدين:'}</div>
          <div class="dept-box-name">${targetDept}</div>
          <div class="dept-box-sub">التصنيف المعتمد: ${categoryName} ${uniCoursesDisplay ? ` | المساقات التدريبية: ${uniCoursesDisplay}` : ''}</div>
        </div>

        <!-- Personal Info Section -->
        <div class="sec-header">👤 البيانات الشخصية للمتقدم</div>
        <div class="sec-divider"></div>

        <div style="display: flex; gap: 20px; align-items: flex-start; justify-content: space-between;">
          <div class="info-grid" style="flex: 1;">
            <!-- Col 1 (Right in RTL) -->
            <div class="info-row">
              <span class="info-label" style="min-width: 125px;">${isDoctor ? 'اسم الطبيب المتعاقد:' : 'اسم المدرب / الأستاذ:'}</span>
              <span class="info-value" style="font-size: 14px; font-weight: 900;">${targetApp.name || '—'}</span>
            </div>
            <!-- Col 2 (Left in RTL) -->
            <div class="info-row">
              <span class="info-label" style="min-width: 105px;">رقم الهوية:</span>
              <span class="info-value" dir="ltr">${targetApp.idNumber || '—'}</span>
            </div>

            <!-- Col 1 (Right in RTL) -->
            <div class="info-row">
              <span class="info-label" style="min-width: 125px;">رقم الهاتف:</span>
              <span class="info-value" dir="ltr">${targetApp.phone || '—'}</span>
            </div>
            <!-- Col 2 (Left in RTL) -->
            <div class="info-row">
              <span class="info-label" style="min-width: 105px;">حالة الطلب:</span>
              <span class="info-value">${statusLabel}</span>
            </div>

            <!-- Col 1 (Right in RTL) -->
            <div class="info-row">
              <span class="info-label" style="min-width: 125px;">الجامعة / الجامعات:</span>
              <span class="info-value">${uniDisplay}</span>
            </div>
            <!-- Col 2 (Left in RTL) -->
            <div class="info-row">
              <span class="info-label" style="min-width: 105px;">فترة التدريب / التعاقد:</span>
              <span class="info-value" dir="ltr" style="color: #1e3a8a; font-weight: 900;">
                من ${startDate} إلى ${endDate}
              </span>
            </div>

            <!-- Col 1 Extra for Trainers -->
            <div class="info-row">
              <span class="info-label" style="min-width: 125px;">طبيعة الوظيفة / الصفة:</span>
              <span class="info-value">${targetApp.crescentJobNature || targetApp.employmentType || 'على كادر المستشفى'}</span>
            </div>
            <!-- Col 2 Extra for Trainers -->
            <div class="info-row">
              <span class="info-label" style="min-width: 105px;">أيام الدوام المقررة:</span>
              <span class="info-value">${workDaysDisplay}</span>
            </div>

            ${isNursing ? `
            <!-- Prominent Department row for University Nursing Trainers -->
            <div class="info-row" style="grid-column: span 2; background: #f0fdf4; padding: 7px 14px; border-radius: 8px; border: 1.5px solid #86efac; margin: 4px 0;">
              <span class="info-label" style="min-width: 140px; color: #166534; font-weight: 800; font-size: 13px;">القسم المخصص للتدريب:</span>
              <span class="info-value" style="color: #14532d; font-size: 14px; font-weight: 900;">${targetDept}</span>
              ${uniCoursesDisplay ? `<span style="margin-right: auto; font-size: 11.5px; color: #15803d; font-weight: 700;">(المساقات التدريبية: ${uniCoursesDisplay})</span>` : ''}
            </div>
            ` : ''}
          </div>

          <!-- Applicant Photo Frame with Clean Placeholder Fallback -->
          <div style="display: flex; flex-direction: column; align-items: center; justify-content: flex-start; padding-left: 6px;">
            ${applicantPhoto ? `
            <div style="width: 110px; height: 135px; border-radius: 8px; border: 2px solid #1e293b; overflow: hidden; background: #ffffff; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: flex; align-items: center; justify-content: center;">
              <img src="${applicantPhoto}" alt="صورة المتقدم" style="width: 100%; height: 100%; object-fit: cover; object-position: center 20%; display: block; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important;" onerror="this.parentElement.innerHTML='<div style=\\'text-align:center;padding:10px;color:#64748b;font-size:11px;font-weight:700;\\'>تعذر تحميل الصورة</div>';" />
            </div>
            <span style="font-size: 11px; font-weight: 800; color: #334155; margin-top: 6px;">صورة المتقدم الرسمية</span>
            ` : `
            <div style="width: 110px; height: 135px; border-radius: 8px; border: 2px dashed #94a3b8; overflow: hidden; background: #f8fafc; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px;">
              <span style="font-size: 28px; opacity: 0.5;">👤</span>
              <span style="font-size: 10px; font-weight: 700; color: #64748b;">مكان الصورة</span>
              <span style="font-size: 8.5px; font-weight: 600; color: #94a3b8;">(غير مرفقة)</span>
            </div>
            <span style="font-size: 10px; font-weight: 700; color: #94a3b8; margin-top: 6px;">صورة المتقدم</span>
            `}
          </div>
        </div>

        <!-- Rotations / Schedule Table -->
        <div class="rotations-title">تفاصيل فترة التدريب / التعاقد والجدول الزمني المعتمد</div>
        <table class="rotations-table">
          <thead>
            <tr>
              <th style="width: 14%;">رقم الاعتماد</th>
              <th style="width: 28%;">القسم والوجهة المعتمدة</th>
              <th style="width: 20%;">تاريخ البدء (من)</th>
              <th style="width: 20%;">تاريخ الانتهاء (إلى)</th>
              <th style="width: 18%;">أيام وساعات الدوام</th>
            </tr>
          </thead>
          <tbody>
            ${rotationsRows}
          </tbody>
        </table>

        <!-- Dashed Divider -->
        <div class="signatures-divider"></div>

        <!-- Official Signatures -->
        <div class="signatures-grid">
          <!-- 1. Department Head — hidden for contracted doctors -->
          ${!isDoctor ? `
          <div>
            <div class="sig-title">رئيس القسم</div>
            <div class="sig-sub">${targetDept ? (targetDept.startsWith('قسم') ? targetDept : 'قسم ' + targetDept) : 'القسم المعني بالتدريب'}</div>
            <div class="sig-line"></div>
            <div class="sig-date">التاريخ: .... / .... / 2026</div>
          </div>
          ` : ''}

          <!-- 2. Medical Director (In ALL departments) -->
          <div>
            <div class="sig-title">المدير الطبي</div>
            <div class="sig-sub">د. خالد سراحنة</div>
            <div class="sig-line"></div>
            <div class="sig-date">التاريخ: .... / .... / 2026</div>
          </div>

          <!-- 3. Nursing Director (In ALL nursing departments & nursing trainers) -->
          ${isNursing ? `
          <div>
            <div class="sig-title">مدير التمريض</div>
            <div class="sig-sub">أ. زياد حمد</div>
            <div class="sig-line"></div>
            <div class="sig-date">التاريخ: .... / .... / 2026</div>
          </div>
          ` : ''}

          <!-- 4. Unit Head -->
          <div>
            <div class="sig-title">مسؤول وحدة التطوير والتدريب</div>
            <div class="sig-sub">أ. نسرين عابدين</div>
            <div class="sig-line"></div>
            <div class="sig-date">التاريخ: .... / .... / 2026</div>
          </div>

          <!-- 5. Society President (On ALL applications) -->
          <div>
            <div class="sig-title">رئيس الجمعية</div>
            <div class="sig-sub">د. طارق الجعبري</div>
            <div class="sig-line"></div>
            <div class="sig-date">التاريخ: .... / .... / 2026</div>
          </div>
        </div>

        <script>
          function triggerPrintNow() {
            window.focus();
            window.print();
          }

          function ensureImagesLoaded(onComplete) {
            var imgs = Array.from(document.images);
            if (imgs.length === 0) {
              setTimeout(onComplete, 250);
              return;
            }
            var promises = imgs.map(function(img) {
              if (img.complete && img.naturalWidth !== 0) {
                return (img.decode ? img.decode().catch(function(){}) : Promise.resolve());
              }
              return new Promise(function(resolve) {
                var done = function() {
                  if (img.decode) {
                    img.decode().catch(function(){}).then(resolve);
                  } else {
                    resolve();
                  }
                };
                img.addEventListener('load', done, { once: true });
                img.addEventListener('error', done, { once: true });
              });
            });

            Promise.all(promises).then(function() {
              setTimeout(onComplete, 400);
            });
          }

          if (document.readyState === 'complete') {
            ensureImagesLoaded(triggerPrintNow);
          } else {
            window.addEventListener('load', function() {
              ensureImagesLoaded(triggerPrintNow);
            });
          }
        </script>
      </body>
      </html>
    `;

    printWindow.document.open();
    printWindow.document.write(htmlContent);
    printWindow.document.close();
  };

  // Handle Accept / Approve University application directly from dashboard
  const handleAcceptUniApp = async (app: any) => {
    if (!app || isProcessingUniApp) return;
    setIsProcessingUniApp(true);
    try {
      const isNursing = isUniversityNursingTrainer(app);
      const targetDept = isNursing ? 'تدريب تمريض الجامعات' : 'الأطباء المتعاقدون';
      
      const uniName = app.contractedUniversities && app.contractedUniversities.length > 0 
        ? (Array.isArray(app.contractedUniversities) ? app.contractedUniversities.join('، ') : app.contractedUniversities)
        : (app.university || app.previousContractedUniversity || '');

      const todayStr = new Date().toISOString().split('T')[0];
      const endDate = new Date();
      endDate.setMonth(endDate.getMonth() + 4);
      const endDateStr = endDate.toISOString().split('T')[0];

      const newStudent: Student = {
        name: app.name || '',
        phone: app.phone || '',
        idNumber: app.idNumber || '',
        university: uniName,
        graduationYear: app.graduationYear || '',
        address: app.address || '',
        studySystem: app.studySystem || (isNursing ? 'تمريض جامعات' : 'تعاقد جامعي'),
        internshipYear: isNursing ? 'مدرب سريري' : 'طبيب متعاقد',
        startDate: app.startDate || app.date || todayStr,
        endDate: app.endDate || endDateStr,
        trainingDepartments: app.trainingDepartments || [],
        crescentJobNature: app.crescentJobNature || app.employmentType || (isNursing ? 'مدرب سريري' : 'طبيب متعاقد'),
        originalDepartment: targetDept,
        deptLabel: targetDept
      };

      const updatedStudentsData = { ...studentsData };
      if (!updatedStudentsData[targetDept]) {
        updatedStudentsData[targetDept] = [];
      }
      
      // Avoid duplicate by idNumber or name+phone
      const exists = updatedStudentsData[targetDept].some(s => 
        (app.idNumber && s.idNumber === app.idNumber) || 
        (s.name === app.name && s.phone === app.phone)
      );

      if (!exists) {
        updatedStudentsData[targetDept].push(newStudent);
        await saveData(updatedStudentsData);
      }

      // Update status in API
      const appId = app.id || app._supabaseId;
      if (appId) {
        let patchDone = false;
        try {
          const res = await fetch('/api/applications', {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              id: appId,
              status: 'accepted',
              applicantData: {
                ...app,
                status: 'accepted',
                acceptedAt: todayStr,
                acceptedDept: targetDept
              }
            })
          });
          if (res.ok) patchDone = true;
        } catch (e) {
          console.warn('Initial PATCH in handleAcceptUniApp failed:', e);
        }

        if (!patchDone) {
          await fetch('/api/applications', {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              id: appId,
              status: 'accepted'
            })
          });
        }
      }

      await fetchAllApplications();
      showToast('تم قبول ' + app.name + ' وإضافته لقسم (' + targetDept + ') بنجاح ✓');
      setSelectedUniApp(null);
    } catch (err) {
      console.error('Error accepting university application:', err);
      showToast('حدث خطأ أثناء اعتماد الطلب');
    } finally {
      setIsProcessingUniApp(false);
    }
  };

  // Handle Reject / Archive University application directly from dashboard
  const handleRejectUniApp = async (app: any) => {
    if (!app || isProcessingUniApp) return;
    if (!confirm('هل أنت متأكد من رغبتك في رفض طلب (' + app.name + ')؟')) return;
    setIsProcessingUniApp(true);
    try {
      const appId = app.id || app._supabaseId;
      if (appId) {
        await fetch('/api/applications', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: appId,
            status: 'rejected',
            applicantData: {
              ...app,
              status: 'rejected',
              rejectedAt: new Date().toISOString().split('T')[0]
            }
          })
        });
      }
      await fetchAllApplications();
      showToast('تم رفض وأرشفة طلب (' + app.name + ') بنجاح');
      setSelectedUniApp(null);
    } catch (err) {
      console.error('Error rejecting university application:', err);
      showToast('حدث خطأ أثناء رفض الطلب');
    } finally {
      setIsProcessingUniApp(false);
    }
  };

  // ═══════════ Partner Universities & Departments Constants ═══════════
  const PARTNER_UNIVERSITIES_LIST = [
    'جامعة الخليل',
    'جامعة بوليتكنك فلسطين',
    'الكلية الذكية الجامعية للتعليم الحديث'
  ];

  const HOSPITAL_TRAINING_DEPTS = [
    'الاطفال',
    'جراحة',
    'نسائية',
    'التمريض',
    'طوارئ',
    'باطني',
    'عناية مكثفة',
    'عمليات',
    'العلاج الطبيعي',
    'مختبرات طبية',
    'أشعة',
    'العلاج الوظيفي',
    'تغذية',
    'ضباط الإسعاف'
  ];

  const WEEK_DAYS_LIST = ['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس'];

  // Helper to open Uni App modal in either view or edit mode
  const openUniAppModal = (app: any, startInEditMode = false) => {
    setSelectedUniApp(app);
    setIsEditingUniApp(startInEditMode);
    
    // Normalize trainingDepartments into clean array
    let depts: string[] = [];
    if (Array.isArray(app.trainingDepartments)) {
      depts = app.trainingDepartments.map((d: any) => String(d).trim()).filter(Boolean);
    } else if (typeof app.trainingDepartments === 'string' && app.trainingDepartments.trim()) {
      depts = app.trainingDepartments.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean);
    } else if (app.department && !['غير مصنف', 'عام'].includes(app.department)) {
      depts = [app.department.trim()];
    }
    
    // Normalize contracted universities
    let unis: string[] = [];
    if (Array.isArray(app.contractedUniversities)) {
      unis = app.contractedUniversities.map((u: any) => String(u).trim()).filter(Boolean);
    } else if (typeof app.contractedUniversities === 'string' && app.contractedUniversities.trim()) {
      unis = app.contractedUniversities.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean);
    } else if (app.university) {
      unis = [app.university.trim()];
    }

    // Normalize workDays
    let days: string[] = [];
    if (Array.isArray(app.workDays)) {
      days = app.workDays.map((w: any) => String(w).trim()).filter(Boolean);
    } else if (typeof app.workDays === 'string' && app.workDays.trim()) {
      days = app.workDays.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean);
    }

    const todayStr = new Date().toISOString().split('T')[0];
    const defaultEnd = new Date();
    defaultEnd.setMonth(defaultEnd.getMonth() + 4);
    const defaultEndStr = defaultEnd.toISOString().split('T')[0];

    setUniAppEditForm({
      id: app.id || app._supabaseId,
      _supabaseId: app._supabaseId || app.id,
      name: app.name || '',
      idNumber: app.idNumber || '',
      phone: app.phone || '',
      address: app.address || '',
      contractedUniversities: unis,
      university: unis.join('، '),
      graduationYear: app.graduationYear || '',
      crescentJobNature: app.crescentJobNature || app.employmentType || (isUniversityNursingTrainer(app) ? 'مدرب سريري' : 'طبيب متعاقد'),
      specialty: app.specialty || '',
      startDate: app.startDate || app.trainingStartDate || app.date || todayStr,
      endDate: app.endDate || app.trainingEndDate || defaultEndStr,
      trainingDepartments: depts,
      workDays: days,
      teachingCourses: Array.isArray(app.teachingCourses) ? app.teachingCourses : (app.teachingCourses ? [app.teachingCourses] : []),
      teachingCoursesText: Array.isArray(app.teachingCourses) ? app.teachingCourses.join('، ') : (app.teachingCourses || ''),
      notes: app.notes || '',
      status: app.status || 'pending',
      category: app.category || (isUniversityNursingTrainer(app) ? 'تقديم طلبات لتدريب طلاب التمريض في الجامعات' : 'الأطباء المتعاقدون مع الجامعات'),
      categoryId: app.categoryId || (isUniversityNursingTrainer(app) ? 'university-nursing-trainers' : 'contracted-doctors')
    });
    setCustomDeptInput('');
    setCustomUniInput('');
  };

  // Add a department to the edit form
  const handleAddDeptToForm = (deptToAdd: string) => {
    if (!deptToAdd || !deptToAdd.trim()) return;
    const clean = deptToAdd.trim();
    const current = uniAppEditForm.trainingDepartments || [];
    if (!current.includes(clean)) {
      setUniAppEditForm((prev: any) => ({
        ...prev,
        trainingDepartments: [...(prev.trainingDepartments || []), clean]
      }));
    }
  };

  // Remove a department from the edit form
  const handleRemoveDeptFromForm = (idx: number) => {
    setUniAppEditForm((prev: any) => ({
      ...prev,
      trainingDepartments: (prev.trainingDepartments || []).filter((_: any, i: number) => i !== idx)
    }));
  };

  // Toggle university in edit form
  const handleToggleUniInForm = (uniName: string) => {
    const current = uniAppEditForm.contractedUniversities || [];
    let updated: string[] = [];
    if (current.includes(uniName)) {
      updated = current.filter((u: string) => u !== uniName);
    } else {
      updated = [...current, uniName];
    }
    setUniAppEditForm((prev: any) => ({
      ...prev,
      contractedUniversities: updated,
      university: updated.join('، ')
    }));
  };

  // Toggle work day in edit form
  const handleToggleWorkDayInForm = (day: string) => {
    const current = uniAppEditForm.workDays || [];
    let updated: string[] = [];
    if (current.includes(day)) {
      updated = current.filter((d: string) => d !== day);
    } else {
      updated = [...current, day];
    }
    setUniAppEditForm((prev: any) => ({
      ...prev,
      workDays: updated
    }));
  };

  // Save Full Edit for University Application
  const handleSaveUniAppEdit = async () => {
    if (!uniAppEditForm || isProcessingUniApp) return;
    setIsProcessingUniApp(true);
    try {
      const appId = uniAppEditForm.id || uniAppEditForm._supabaseId;
      if (!appId) {
        showToast('خطأ: معرّف الطلب غير متوفر');
        return;
      }

      const cleanTeachingCourses = uniAppEditForm.teachingCoursesText
        ? uniAppEditForm.teachingCoursesText.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean)
        : (uniAppEditForm.teachingCourses || []);

      const uniString = (uniAppEditForm.contractedUniversities && uniAppEditForm.contractedUniversities.length > 0)
        ? uniAppEditForm.contractedUniversities.join('، ')
        : (uniAppEditForm.university || '');

      const updatedApplicantData = {
        ...selectedUniApp,
        ...uniAppEditForm,
        name: (uniAppEditForm.name || '').trim(),
        phone: (uniAppEditForm.phone || '').trim(),
        idNumber: (uniAppEditForm.idNumber || '').trim(),
        address: (uniAppEditForm.address || '').trim(),
        graduationYear: (uniAppEditForm.graduationYear || '').trim(),
        crescentJobNature: (uniAppEditForm.crescentJobNature || '').trim(),
        specialty: (uniAppEditForm.specialty || '').trim(),
        teachingCourses: cleanTeachingCourses,
        university: uniString,
        contractedUniversities: uniAppEditForm.contractedUniversities || [],
        trainingDepartments: uniAppEditForm.trainingDepartments || [],
        workDays: uniAppEditForm.workDays || [],
        updatedAt: new Date().toISOString()
      };

      // 1. Send PATCH to API
      const res = await fetch('/api/applications', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: appId,
          status: uniAppEditForm.status || 'pending',
          applicantData: updatedApplicantData
        })
      });

      // 2. Synchronize with studentsData in hospital roster if accepted or already present
      const isNursing = isUniversityNursingTrainer(updatedApplicantData);
      const targetDept = isNursing ? 'تدريب تمريض الجامعات' : 'الأطباء المتعاقدون';
      
      const updatedStudentsData = { ...studentsData };
      if (updatedStudentsData[targetDept]) {
        const idx = updatedStudentsData[targetDept].findIndex((s: Student) => 
          (selectedUniApp.idNumber && s.idNumber === selectedUniApp.idNumber) ||
          (s.name === selectedUniApp.name && s.phone === selectedUniApp.phone) ||
          (s.name === uniAppEditForm.name)
        );

        if (idx !== -1) {
          if (uniAppEditForm.status === 'rejected') {
            // If changed to rejected, remove from active list
            updatedStudentsData[targetDept].splice(idx, 1);
            await saveData(updatedStudentsData);
          } else {
            // Update active student record
            updatedStudentsData[targetDept][idx] = {
              ...updatedStudentsData[targetDept][idx],
              name: updatedApplicantData.name,
              phone: updatedApplicantData.phone,
              idNumber: updatedApplicantData.idNumber,
              university: uniString || updatedStudentsData[targetDept][idx].university,
              graduationYear: updatedApplicantData.graduationYear,
              address: updatedApplicantData.address,
              startDate: updatedApplicantData.startDate,
              endDate: updatedApplicantData.endDate,
              trainingDepartments: updatedApplicantData.trainingDepartments,
              crescentJobNature: updatedApplicantData.crescentJobNature,
              notes: updatedApplicantData.notes
            };
            await saveData(updatedStudentsData);
          }
        } else if (uniAppEditForm.status === 'accepted') {
          // If newly approved, append to studentsData
          const newStudent: Student = {
            name: updatedApplicantData.name,
            phone: updatedApplicantData.phone,
            idNumber: updatedApplicantData.idNumber,
            university: uniString,
            graduationYear: updatedApplicantData.graduationYear,
            address: updatedApplicantData.address,
            studySystem: isNursing ? 'تمريض جامعات' : 'تعاقد جامعي',
            internshipYear: isNursing ? 'مدرب سريري' : 'طبيب متعاقد',
            startDate: updatedApplicantData.startDate || new Date().toISOString().split('T')[0],
            endDate: updatedApplicantData.endDate || '',
            trainingDepartments: updatedApplicantData.trainingDepartments,
            originalDepartment: targetDept,
            deptLabel: targetDept,
            crescentJobNature: updatedApplicantData.crescentJobNature,
            notes: updatedApplicantData.notes
          };
          updatedStudentsData[targetDept].push(newStudent);
          await saveData(updatedStudentsData);
        }
      }

      // 3. Update view
      setSelectedUniApp(updatedApplicantData);
      setIsEditingUniApp(false);
      await fetchAllApplications();
      showToast('تم حفظ وتحديث كامل بيانات الطلب والأقسام بنجاح ✓');
    } catch (err) {
      console.error('Error updating university application:', err);
      showToast('حدث خطأ أثناء حفظ التعديلات');
    } finally {
      setIsProcessingUniApp(false);
    }
  };

  // Delete University Application
  const handleDeleteUniApp = async (app: any) => {
    if (!app || isProcessingUniApp) return;
    const appId = app.id || app._supabaseId;
    if (!appId) return;

    if (!confirm(`هل أنت متأكد تماماً من حذف طلب (${app.name || 'المتقدم'}) نهائياً؟\nسيتم حذف الطلب بالكامل ولن يمكن استرجاعه.`)) {
      return;
    }

    setIsProcessingUniApp(true);
    try {
      await fetch('/api/applications', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: appId })
      });

      // Also remove from studentsData if active
      const isNursing = isUniversityNursingTrainer(app);
      const targetDept = isNursing ? 'تدريب تمريض الجامعات' : 'الأطباء المتعاقدون';
      const updatedStudentsData = { ...studentsData };
      if (updatedStudentsData[targetDept]) {
        const idx = updatedStudentsData[targetDept].findIndex((s: Student) => 
          (app.idNumber && s.idNumber === app.idNumber) ||
          (s.name === app.name && s.phone === app.phone)
        );
        if (idx !== -1) {
          updatedStudentsData[targetDept].splice(idx, 1);
          await saveData(updatedStudentsData);
        }
      }

      setSelectedUniApp(null);
      setIsEditingUniApp(false);
      await fetchAllApplications();
      showToast('تم حذف الطلب نهائياً بنجاح ✓');
    } catch (err) {
      console.error('Error deleting university application:', err);
      showToast('حدث خطأ أثناء حذف الطلب');
    } finally {
      setIsProcessingUniApp(false);
    }
  };

  // Auth Check — redirect to login if not logged in
  useEffect(() => {
    const session = localStorage.getItem('crescentSession');
    if (!session) {
      router.push('/login');
      return;
    }
    try {
      const parsed = JSON.parse(session);
      if (!parsed.loggedIn) {
        router.push('/login');
        return;
      }
      setCurrentUser({ username: parsed.username, displayName: parsed.displayName, role: parsed.role });

      // Start presence heartbeat
      const sendHeartbeat = async () => {
        try {
          const res = await fetch('/api/presence', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username: parsed.username, displayName: parsed.displayName })
          });
          if (res.ok) {
            const data = await res.json();
            setOnlineUsers(data.online || []);
          }
        } catch {}
      };
      sendHeartbeat();
      const heartbeatInterval = setInterval(sendHeartbeat, 25000);
      return () => clearInterval(heartbeatInterval);
    } catch {
      router.push('/login');
    }
  }, [router]);

  // Logout handler
  const handleLogout = async () => {
    // Remove from presence
    if (currentUser) {
      try {
        await fetch('/api/presence', {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username: currentUser.username })
        });
      } catch {}
    }
    localStorage.removeItem('crescentSession');
    router.push('/login');
  };

  // Modals State
  const [activeModal, setActiveModal] = useState<string | null>(null);
  const [selectedStudentIndex, setSelectedStudentIndex] = useState<number | null>(null);
  const [editTargetDept, setEditTargetDept] = useState<string | null>(null);
  
  // ID Card Modal State & Handlers
  const [idCardData, setIdCardData] = useState<{
    name: string;
    title: string;
    dept: string;
    endDate: string;
    idNumber: string;
    bloodType: string;
  }>({
    name: '',
    title: 'طبيب امتياز',
    dept: 'طب الأطفال',
    endDate: '',
    idNumber: '',
    bloodType: ''
  });

  const openIdCardModal = (student: any, deptName?: string) => {
    const d = student.department || student.originalDepartment || deptName || currentDepartment || '';
    const deptMap: Record<string, string> = {
      'جراحة': 'الجراحة العامة',
      'الجراحة': 'الجراحة العامة',
      'نسائية': 'النسائية والتوليد',
      'النسائية': 'النسائية والتوليد',
      'الاطفال': 'طب الأطفال',
      'أطفال': 'طب الأطفال',
      'اطفال': 'طب الأطفال',
      'الأطفال': 'طب الأطفال',
      'طوارئ': 'الطوارئ',
      'باطني': 'الباطني',
      'عمليات': 'العمليات الجراحية',
      'التمريض': 'التمريض العام',
      'العلاج الطبيعي': 'العلاج الطبيعي والتأهيل',
      'أشعة': 'الأشعة والتصوير الطبي',
      'تغذية': 'التغذية السريرية والحميات'
    };
    const deptDisplay = deptMap[d] || d || 'طب الأطفال';
    const endDate = student.globalEndDate || student.endDate || '';
    setIdCardData({
      name: student.name || '',
      title: student.internshipYear || 'طبيب امتياز',
      dept: deptDisplay,
      endDate: endDate,
      idNumber: student.idNumber || '',
      bloodType: student.bloodType || ''
    });
    setActiveModal('idcard');
  };

  const handlePrintIdCardFromModal = () => {
    const cardHtml = `
      <div style="width:85mm;height:54mm;border:1px solid #bbb;overflow:hidden;display:flex;flex-direction:column;font-family:'Tajawal',sans-serif;background:white;position:relative;box-sizing:border-box;">
        <div style="display:flex;align-items:center;justify-content:space-between;padding:5px 7px;border-bottom:2.5px solid #CE1126;background:#f9f9f9;">
          <div style="text-align:right;flex:1;direction:rtl;">
            <div style="font-size:7px;font-weight:800;color:#CE1126;">جمعية الهلال الأحمر الفلسطيني - الخليل</div>
            <div style="font-size:6px;font-weight:700;color:#333;">مستشفى الهلال الأحمر التخصصي - الخليل</div>
          </div>
          <div style="margin:0 5px;flex-shrink:0;width:30px;height:30px;border-radius:50%;border:1px solid #CE1126;overflow:hidden;display:flex;align-items:center;justify-content:center;background:white;">
            <img src="/prcs-logo.png" style="width:24px;height:24px;object-fit:contain;" alt="Logo" />
          </div>
          <div style="text-align:left;flex:1;">
            <div style="font-size:6px;font-weight:800;color:#CE1126;">Palestine Red Crescent Society- Hebron</div>
            <div style="font-size:5px;font-weight:600;color:#555;">Red Crescent Specilized Hospital - Hebron</div>
          </div>
        </div>
        <div style="flex:1;padding:5px 10px;direction:rtl;display:flex;flex-direction:column;justify-content:center;gap:4px;">
          <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
            <span style="font-size:9px;font-weight:800;min-width:60px;color:#222;">الاسم :</span>
            <span style="font-size:10px;font-weight:800;color:#CE1126;" contenteditable="true">${idCardData.name}</span>
          </div>
          <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
            <span style="font-size:9px;font-weight:800;min-width:60px;color:#222;">المسمى:</span>
            <span style="font-size:9px;font-weight:700;color:#333;" contenteditable="true">${idCardData.title}</span>
          </div>
          <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
            <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">القسم :</span>
            <span style="font-size:9px;font-weight:700;color:#333;background:#eff6ff;padding:1px 4px;border-radius:3px;" contenteditable="true">${idCardData.dept}</span>
          </div>
          <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
            <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">تاريخ الإنتهاء :</span>
            <span style="font-size:9px;font-weight:700;color:#333;" contenteditable="true">${idCardData.endDate}</span>
          </div>
          ${(idCardData.idNumber || idCardData.bloodType) ? `
            <div style="display:flex;align-items:center;justify-content:center;gap:12px;margin-top:1px;">
              ${idCardData.idNumber ? `<div style="background:#f1f5f9;border:1px solid #cbd5e1;border-radius:3px;padding:1px 5px;display:flex;align-items:center;"><span style="font-size:7px;font-weight:800;color:#334155;margin-left:3px;">الهوية:</span><span style="font-size:8px;font-weight:700;color:#0f172a;">${idCardData.idNumber}</span></div>` : ''}
              ${idCardData.bloodType ? `<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:3px;padding:1px 5px;display:flex;align-items:center;"><span style="font-size:7px;font-weight:800;color:#ef4444;margin-left:3px;">فصيلة الدم:</span><span style="font-size:8px;font-weight:800;color:#b91c1c;" dir="ltr">${idCardData.bloodType}</span></div>` : ''}
            </div>` : ''}
        </div>
        <div style="padding:3px 10px;direction:rtl;display:flex;justify-content:flex-end;">
          <span style="font-size:8px;font-weight:700;color:#555;">المدير الطبي</span>
        </div>
        <div style="height:6px;background:linear-gradient(to bottom,#CE1126,#8B0000);position:absolute;bottom:0;width:100%;"></div>
      </div>`;

    const pw = window.open('', '_blank');
    if (!pw) return;
    pw.document.write(`<html lang="ar" dir="rtl">
      <head>
        <title>بطاقة - ${idCardData.name}</title>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;800&display=swap');
          * { margin:0; padding:0; box-sizing:border-box; }
          @page { size: 85mm 54mm; margin: 0; }
          body {
            width: 85mm; height: 54mm;
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            -webkit-print-color-adjust: exact; print-color-adjust: exact;
            font-family: 'Tajawal', sans-serif;
            background: #f8fafc;
          }
          .print-toolbar {
            position: fixed; top: 8px; left: 50%; transform: translateX(-50%);
            background: #0f172a; color: white; padding: 7px 16px; border-radius: 30px;
            display: flex; align-items: center; gap: 12px; z-index: 9999;
            box-shadow: 0 4px 20px rgba(0,0,0,0.35); font-size: 11px; white-space: nowrap;
          }
          .print-toolbar button {
            background: #059669; color: white; border: none; padding: 5px 14px;
            border-radius: 20px; font-family: 'Tajawal'; font-weight: 800; cursor: pointer;
            display: flex; align-items: center; gap: 6px; font-size: 12px;
          }
          @media print {
            body { background: white; }
            .print-toolbar { display: none !important; }
          }
        </style>
      </head>
      <body>
        <div class="print-toolbar">
          <span>✏️ يمكنك تعديل القسم أو أي حقل بالنقر عليه مباشرة</span>
          <button onclick="window.print()">🖨️ طباعة البطاقة</button>
        </div>
        ${cardHtml}
      </body>
    </html>`);
    pw.document.close();
  };
  const [inlineEdit, setInlineEdit] = useState<{dept: string; index: number; name: string; endDate?: string; startDate?: string; phone?: string; university?: string} | null>(null);
  const [departureSearch, setDepartureSearch] = useState<string>('');
  
  // Form States
  const [formData, setFormData] = useState<any>({});
  const [showScheduleCard, setShowScheduleCard] = useState(false);

  // Load Data
  useEffect(() => {
    // Dark Mode
    const savedDarkMode = localStorage.getItem('darkMode') === 'enabled';
    setIsDarkMode(savedDarkMode);
    if (savedDarkMode) document.body.classList.add('dark-mode');

    // Load Data
    const loadData = async () => {
      setIsLoading(true);
      try {
        const timestamp = new Date().getTime();
        const response = await fetch(`${API_URL}?_t=${timestamp}`, {
          cache: 'no-store',
          headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });
        if (response.ok) {
          const data = await response.json();
          if (data && data['جراحة'] && data['جراحة'].length > 0) {
            // Ensure all keys exist
            if (!data['المغادرين']) data['المغادرين'] = [];
            if (!data['الاستئناف']) data['الاستئناف'] = [];
            if (!data['ضباط الإسعاف']) data['ضباط الإسعاف'] = [];
            const cleanData = deduplicateStudentsDataset(data);
            setStudentsData(cleanData);
            try {
              localStorage.setItem('studentsData', JSON.stringify(cleanData));
            } catch {}
            showToast('تم تحميل البيانات من السيرفر ✓');
          } else {
            // API returned empty or partial — NEVER overwrite the server database with defaultData!
            console.warn('API returned unexpected data, attempting localStorage fallback...');
            const localData = localStorage.getItem('studentsData');
            if (localData) {
              try {
                const parsed = JSON.parse(localData);
                if (parsed && typeof parsed === 'object') {
                  setStudentsData(parsed);
                  showToast('تم استعادة البيانات من الذاكرة المحلية ✓');
                }
              } catch {
                setStudentsData(defaultData);
              }
            } else {
              setStudentsData(defaultData);
            }
          }
        } else {
          throw new Error("Network response not ok");
        }
      } catch (error) {
        console.error("Cloud error:", error);
        const localData = localStorage.getItem('studentsData');
        if (localData) {
          setStudentsData(JSON.parse(localData));
          showToast('تم تحميل البيانات المحلية');
        } else {
          // Even on error, save defaultData to localStorage
          localStorage.setItem('studentsData', JSON.stringify(defaultData));
        }
      } finally {
        setIsLoading(false);
      }
    };

    loadData();

    // Live Sync: Auto-refresh every 30 seconds so all users see changes
    const syncInterval = setInterval(async () => {
      try {
        const timestamp = new Date().getTime();
        const response = await fetch(`${API_URL}?_t=${timestamp}`, {
          cache: 'no-store',
          headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });
        if (response.ok) {
          const data = await response.json();
          if (data && data['\u062c\u0631\u0627\u062d\u0629'] && data['\u062c\u0631\u0627\u062d\u0629'].length > 0) {
            if (!data['\u0627\u0644\u0645\u063a\u0627\u062f\u0631\u064a\u0646']) data['\u0627\u0644\u0645\u063a\u0627\u062f\u0631\u064a\u0646'] = [];
            if (!data['\u0627\u0644\u0627\u0633\u062a\u0626\u0646\u0627\u0641']) data['\u0627\u0644\u0627\u0633\u062a\u0626\u0646\u0627\u0641'] = [];
            if (!data['ضباط الإسعاف']) data['ضباط الإسعاف'] = [];
            const cleanData = deduplicateStudentsDataset(data);
            setStudentsData(cleanData);
            try {
              localStorage.setItem('studentsData', JSON.stringify(cleanData));
            } catch (storageErr) {
              console.warn('localStorage quota reached during sync:', storageErr);
            }
            setLastSynced(new Date().toLocaleTimeString('ar-EG'));
          }
        }
      } catch (e) {
        // Silent fail for background sync
      }
    }, 15000);

    return () => clearInterval(syncInterval);
  }, []);

  // Save Data
  const saveData = async (newData: StudentsData) => {
    const cleanData = deduplicateStudentsDataset(newData);
    setStudentsData(cleanData);
    try {
      localStorage.setItem('studentsData', JSON.stringify(cleanData));
    } catch (storageErr) {
      console.warn('localStorage quota reached during saveData:', storageErr);
    }
    
    try {
      await fetch(API_URL, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(cleanData)
      });
      console.log('Synced to cloud');
    } catch (error) {
      console.error('Sync error:', error);
    }
  };

  // Toast Helper
  const showToast = (msg: string) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(null), 3000);
  };

  // Toggle Dark Mode
  const toggleDarkMode = () => {
    const newMode = !isDarkMode;
    setIsDarkMode(newMode);
    document.body.classList.toggle('dark-mode', newMode);
    localStorage.setItem('darkMode', newMode ? 'enabled' : 'disabled');
  };

  // CRUD Operations
  const handleAddStudent = (e: React.FormEvent) => {
    e.preventDefault();
    if (!currentDepartment) return;
    
    const newData = { ...studentsData };
    if (!newData[currentDepartment]) newData[currentDepartment] = [];

    const formattedStart = formatDate(formData.startDate);
    const formattedEnd = formatDate(formData.endDate);

    const newStudent: Student = {
      name: formData.name,
      startDate: formattedStart,
      endDate: formattedEnd,
      globalStartDate: formattedStart,
      globalEndDate: formattedEnd,
      phone: formData.phone,
      university: formData.university || '',
      department: currentDepartment,
      deptLabel: currentDepartment,
      idNumber: formData.idNumber || '',
      graduationYear: formData.graduationYear || '',
      address: formData.address || '',
      attendanceDays: formData.attendanceDays || '',
      shiftSystem: formData.shiftSystem || '',
      studySystem: formData.studySystem || '',
      internshipYear: formData.internshipYear || ''
    };
    
    newData[currentDepartment].push(newStudent);
    saveData(newData);
    setActiveModal(null);
    showToast('تم إضافة المتدرب/الطبيب بنجاح ✓');
  };

  // Direct Add (from main dashboard with department selector)
  const handleAddStudentDirect = (e: React.FormEvent) => {
    e.preventDefault();
    const dept = formData.department;
    if (!dept) {
      alert('يرجى اختيار القسم أولاً');
      return;
    }
    
    const newData = { ...studentsData };
    if (!newData[dept]) newData[dept] = [];

    const formattedStart = formatDate(formData.startDate);
    const formattedEnd = formatDate(formData.endDate);

    const newStudent: Student = {
      name: formData.name,
      startDate: formattedStart,
      endDate: formattedEnd,
      globalStartDate: formattedStart,
      globalEndDate: formattedEnd,
      phone: formData.phone,
      university: formData.university || '',
      department: dept,
      deptLabel: dept,
      idNumber: formData.idNumber || '',
      graduationYear: formData.graduationYear || '',
      address: formData.address || '',
      attendanceDays: formData.attendanceDays || '',
      shiftSystem: formData.shiftSystem || '',
      studySystem: formData.studySystem || '',
      internshipYear: formData.internshipYear || ''
    };
    
    newData[dept].push(newStudent);
    saveData(newData);
    setActiveModal(null);
    showToast(`تم إضافة ${formData.name} إلى قسم ${dept} بنجاح ✓`);
  };

  const handleSaveInlineName = () => {
    if (!inlineEdit || !inlineEdit.name.trim()) return;
    const { dept, index, name, endDate, startDate, phone, university } = inlineEdit;
    const newData = { ...studentsData };
    if (!newData[dept]) return;

    let targetIdx = index;
    if (!newData[dept][targetIdx]) {
      const found = newData[dept].findIndex(s => s.name === name || (phone && s.phone === phone));
      if (found !== -1) targetIdx = found;
      else return;
    }

    newData[dept] = [...newData[dept]];
    const oldStudent = newData[dept][targetIdx];
    const newName = name.trim();
    let newEndDate = oldStudent.endDate;
    if (endDate && endDate.trim()) {
      newEndDate = endDate.includes('-') ? formatDate(endDate.trim()) : endDate.trim();
    }
    let newStartDate = oldStudent.startDate;
    if (startDate && startDate.trim()) {
      newStartDate = startDate.includes('-') ? formatDate(startDate.trim()) : startDate.trim();
    }

    newData[dept][targetIdx] = {
      ...oldStudent,
      name: newName,
      endDate: newEndDate,
      globalEndDate: newEndDate,
      startDate: newStartDate,
      ...(phone !== undefined ? { phone: phone.trim() } : {}),
      ...(university !== undefined ? { university: university.trim() } : {})
    };
    saveData(newData);
    setInlineEdit(null);
    showToast(`تم حفظ تعديل بيانات "${newName}" بنجاح ✓`);
  };

  const handleReactivateGraduateStudent = (index: number, targetDept?: string) => {
    const student = studentsData['المغادرين']?.[index];
    if (!student) return;
    const destDept = targetDept || student.originalDepartment || 'جراحة';
    if (!confirm(`هل تريد إعادة تفعيل تدريب (${student.name}) وإرجاعه/ا إلى قسم (${destDept})؟`)) return;

    const newData = { ...studentsData };
    newData['المغادرين'] = newData['المغادرين'].filter((_, i) => i !== index);
    if (!newData[destDept]) newData[destDept] = [];

    const reactivatedStudent: Student = {
      ...student,
      startDate: formatDate(new Date().toISOString().split('T')[0]),
      department: destDept,
      originalDepartment: destDept,
      status: 'active',
      isGraduate: false
    };
    newData[destDept].push(reactivatedStudent);

    saveData(newData);
    showToast(`تمت إعادة (${student.name}) إلى قسم ${destDept} بنجاح ✓`);
  };

  const handleQuickGraduateStudent = (dept: string, index: number, studentName?: string) => {
    let targetIndex = index;
    if (studentName && studentsData[dept]) {
      const found = studentsData[dept].findIndex((s, idx) => idx === index && s.name === studentName);
      if (found === -1) {
        const byName = studentsData[dept].findIndex(s => s.name === studentName);
        if (byName !== -1) targetIndex = byName;
      }
    }
    const student = studentsData[dept]?.[targetIndex];
    if (!student) return;
    if (!confirm(`هل أنت متأكد من إنهاء فترة التدريب للمتدرب/ة (${student.name}) ونقله/ا إلى قائمة المغادرين؟`)) return;

    const newData = { ...studentsData };
    if (!newData['المغادرين']) newData['المغادرين'] = [];

    const todayStr = formatDate(new Date().toISOString().split('T')[0]);
    const movingStudent: Student = {
      ...student,
      originalDepartment: dept,
      department: dept,
      status: 'مغادر',
      isGraduate: true,
      endDate: student.endDate || todayStr,
      globalEndDate: student.globalEndDate || student.endDate || todayStr
    };

    newData[dept] = newData[dept].filter((_, i) => i !== targetIndex);
    newData['المغادرين'] = [movingStudent, ...newData['المغادرين']];

    saveData(newData);
    showToast(`تم إنهاء التدريب ونقل (${student.name}) إلى قائمة المغادرين بنجاح ✓`);
  };

  const handleEditStudent = (e: React.FormEvent) => {
    e.preventDefault();
    const targetDept = editTargetDept || currentDepartment;
    if (!targetDept || selectedStudentIndex === null) return;

    const newData = { ...studentsData };
    if (!newData[targetDept] || !newData[targetDept][selectedStudentIndex]) return;

    // Deep copy the specific department array to avoid mutation
    newData[targetDept] = [...newData[targetDept]];
    const updatedStudent: Student = {
      ...newData[targetDept][selectedStudentIndex],
      name: formData.name,
      startDate: formatDate(formData.startDate),
      endDate: formatDate(formData.endDate),
      globalEndDate: formatDate(formData.endDate),
      phone: formData.phone,
      university: formData.university || '',
      address: formData.address || '',
      shiftSystem: formData.shiftSystem || '',
      idNumber: formData.idNumber || '',
      graduationYear: formData.graduationYear || '',
      attendanceDays: formData.attendanceDays || '',
      studySystem: formData.studySystem || '',
      internshipYear: formData.internshipYear || '',
    };

    // Check if department changed in modal
    const destDept = formData.department;
    if (destDept && destDept !== targetDept) {
      newData[targetDept].splice(selectedStudentIndex, 1);
      if (!newData[destDept]) newData[destDept] = [];
      if (destDept === 'المغادرين') {
        updatedStudent.originalDepartment = targetDept;
        updatedStudent.department = targetDept;
        updatedStudent.status = 'مغادر';
        updatedStudent.isGraduate = true;
      }
      newData[destDept].push(updatedStudent);
      showToast(`تم حفظ ونقل ${formData.name} إلى قسم ${destDept} بنجاح ✓`);
    } else {
      newData[targetDept][selectedStudentIndex] = updatedStudent;
      showToast(`تم حفظ تعديل بيانات ${formData.name} بنجاح ✓`);
    }

    saveData(newData);
    setActiveModal(null);
    setEditTargetDept(null);
  };

  const handleDeleteStudent = (index: number, dept?: string) => {
    const targetDept = dept || currentDepartment;
    if (!targetDept || !confirm('هل أنت متأكد من حذف هذا المتدرب؟')) return;
    // Use filter() to create a NEW array — avoids shallow-copy mutation bug
    const newData = { ...studentsData };
    newData[targetDept] = studentsData[targetDept].filter((_, i) => i !== index);
    saveData(newData);
    showToast('تم حذف المتدرب بنجاح ✓');
  };

  const openMoveModal = (dept: string, index: number, student?: Student) => {
    setEditTargetDept(dept);
    setSelectedStudentIndex(index);
    const today = new Date();
    const endDate = new Date();
    endDate.setMonth(endDate.getMonth() + 2);
    setMoveCustomStartDate(today.toISOString().split('T')[0]);
    setMoveCustomEndDate(endDate.toISOString().split('T')[0]);
    setKeepExistingDates(false);
    setMoveDeptSearch('');
    setActiveModal('move');
  };

  const handleMoveStudent = (newDept: string) => {
    const sourceDept = editTargetDept || currentDepartment;
    if (!sourceDept || selectedStudentIndex === null) return;
    if (!studentsData[sourceDept] || !studentsData[sourceDept][selectedStudentIndex]) return;
    
    const newData = { ...studentsData };
    const student = { ...newData[sourceDept][selectedStudentIndex] };
    
    // Update department property if stored
    student.department = newDept;
    if (newDept === 'المغادرين') {
      student.originalDepartment = sourceDept;
      student.status = 'مغادر';
      student.isGraduate = true;
    }
    
    // Dates update
    if (!keepExistingDates) {
      if (moveCustomStartDate) {
        student.startDate = formatDate(moveCustomStartDate);
      } else {
        const today = new Date();
        student.startDate = formatDate(today.toISOString().split('T')[0]);
      }

      if (moveCustomEndDate) {
        student.endDate = formatDate(moveCustomEndDate);
      } else {
        const endDate = new Date();
        endDate.setMonth(endDate.getMonth() + 2);
        student.endDate = formatDate(endDate.toISOString().split('T')[0]);
      }
    }

    // Move from sourceDept to newDept
    newData[sourceDept].splice(selectedStudentIndex, 1);
    if (!newData[newDept]) newData[newDept] = [];
    newData[newDept].push(student);

    saveData(newData);
    setActiveModal(null);
    setEditTargetDept(null);
    setSelectedStudentIndex(null);
    showToast(`تم نقل ${student.name} من قسم "${sourceDept}" إلى قسم "${newDept}" بنجاح ✓`);
  };

  const handleMoveToSuspended = () => {
    const sourceDept = editTargetDept || currentDepartment;
    if (!sourceDept || selectedStudentIndex === null) return;
    if (!studentsData[sourceDept] || !studentsData[sourceDept][selectedStudentIndex]) return;
    
    const newData = { ...studentsData };
    const student = { ...newData[sourceDept][selectedStudentIndex] };
    
    student.originalDepartment = sourceDept;
    student.suspendDate = formatDate(new Date().toISOString().split('T')[0]);

    newData[sourceDept].splice(selectedStudentIndex, 1);
    if (!newData['الاستئناف']) newData['الاستئناف'] = [];
    newData['الاستئناف'].push(student);

    saveData(newData);
    setActiveModal(null);
    setEditTargetDept(null);
    setSelectedStudentIndex(null);
    showToast(`تم نقل ${student.name} إلى قائمة الاستئناف بنجاح ✓`);
  };

  const handleReturnFromSuspension = (index: number) => {
    const newData = { ...studentsData };
    const student = { ...newData['الاستئناف'][index] };
    const originalDept = student.originalDepartment || 'جراحة';

    student.startDate = formatDate(new Date().toISOString().split('T')[0]);
    delete student.originalDepartment;
    delete student.suspendDate;

    newData['الاستئناف'].splice(index, 1);
    newData[originalDept].push(student);

    saveData(newData);
    showToast(`تم إرجاع الطبيب إلى قسم ${originalDept}`);
  };

  // Helper: Format Date YYYY-MM-DD -> DD/MM/YYYY
  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const parts = dateStr.split('-');
    if (parts.length === 3) return `${parts[2]}/${parts[1]}/${parts[0]}`;
    return dateStr;
  };

  // Helper: Parse Date DD/MM/YYYY -> YYYY-MM-DD (for input)
  const parseDateForInput = (dateStr: string) => {
    if (!dateStr) return '';
    const parts = dateStr.split('/');
    if (parts.length === 3) return `${parts[2]}-${parts[1]}-${parts[0]}`;
    return dateStr;
  };

  const currentStudents = currentDepartment ? studentsData[currentDepartment] || [] : [];

  // Excel Export Function
  const exportToExcel = (exportAll: boolean = false) => {
    const wb = XLSX.utils.book_new();
    
    if (exportAll) {
      // Export all departments
      Object.keys(studentsData).forEach(dept => {
        if (studentsData[dept].length > 0) {
          const data = studentsData[dept].map((s, i) => ({
            '#': i + 1,
            'الاسم': s.name,
            'الجامعة': normalizeUniversityName(s.university),
            'تاريخ البدء': s.startDate,
            'تاريخ الانتهاء': s.endDate,
            'الهاتف': s.phone
          }));
          const ws = XLSX.utils.json_to_sheet(data);
          XLSX.utils.book_append_sheet(wb, ws, dept);
        }
      });
      XLSX.writeFile(wb, 'جميع_الأطباء.xlsx');
      showToast('تم تصدير جميع البيانات بنجاح');
    } else if (currentDepartment) {
      // Export current department
      const students = currentDepartment === 'All' ? allStudents : (studentsData[currentDepartment] || []);
      const data = students.map((s, i) => ({
        '#': i + 1,
        'الاسم': s.name,
        'الجامعة': normalizeUniversityName(s.university),
        'تاريخ البدء': s.startDate,
        'تاريخ الانتهاء': s.endDate,
        'الهاتف': s.phone
      }));
      const ws = XLSX.utils.json_to_sheet(data);
      const sheetName = currentDepartment === 'All' ? 'الكل' : currentDepartment;
      XLSX.utils.book_append_sheet(wb, ws, sheetName);
      XLSX.writeFile(wb, `${sheetName}.xlsx`);
      showToast('تم التصدير بنجاح');
    }
  };

  // Active Departments Calculation (Excludes system/inactive folders for main dashboard cards)
  const activeDepartments = useMemo(() => {
    return Object.keys(studentsData).filter(key => key !== 'المغادرين' && key !== 'الاستئناف');
  }, [studentsData]);

  // All valid active students for dashboard quick view
  const allStudents = useMemo(() => {
    return activeDepartments.flatMap(dept => 
      (studentsData[dept] || []).map(student => ({
        ...student,
        department: dept,
        deptLabel: dept
      }))
    );
  }, [studentsData, activeDepartments]);

  // ═══════════ Statistical & Periodic Report Calculations & Helpers ═══════════
  const parseDateToMs = (dateStr?: string): number | null => {
    if (!dateStr || typeof dateStr !== 'string') return null;
    const s = dateStr.trim();
    if (!s) return null;
    if (s.includes('/')) {
      const parts = s.split('/');
      if (parts.length === 3) {
        const d = parseInt(parts[0], 10);
        const m = parseInt(parts[1], 10) - 1;
        const y = parseInt(parts[2], 10);
        const dt = new Date(y, m, d);
        return isNaN(dt.getTime()) ? null : dt.getTime();
      }
    }
    if (s.includes('-')) {
      const parts = s.split('-');
      if (parts.length === 3) {
        const y = parseInt(parts[0], 10);
        const m = parseInt(parts[1], 10) - 1;
        const d = parseInt(parts[2], 10);
        const dt = new Date(y, m, d);
        return isNaN(dt.getTime()) ? null : dt.getTime();
      }
      const dt = new Date(s);
      return isNaN(dt.getTime()) ? null : dt.getTime();
    }
    return null;
  };

  // ═══════════ Master Hospital Department Directory & Specialized Report Metadata ═══════════
  interface DeptReportConfig {
    key: string;
    name: string;
    shortName: string;
    category: 'medicine' | 'nursing' | 'allied' | 'health-trainers' | 'admin' | 'special';
    categoryLabel: string;
    icon: string;
    badgeColor: string;
    color?: string;
    badgeBg: string;
    tableType: 'medical' | 'contracted_doctors' | 'nursing_trainers' | 'nursing' | 'allied' | 'health_trainers' | 'admin' | 'graduates' | 'general';
    description: string;
  }

  const DEPARTMENT_CONFIGS: Record<string, DeptReportConfig> = {
    'All': { key: 'All', name: 'التقرير الشامل لجميع أقسام المستشفى', shortName: 'كل الأقسام', category: 'special', categoryLabel: 'شامل المستشفى', icon: 'fas fa-hospital-alt', badgeColor: '#2563eb', badgeBg: 'rgba(37, 99, 235, 0.12)', tableType: 'general', description: 'تقرير إحصائي رسمي شامل ومقسم لكافة الكوادر الطبية والتمريضية والمساندة والإدارية' },
    'CATEGORY_ALL_medicine': { key: 'CATEGORY_ALL_medicine', name: 'كلية الطب البشري (شامل كافة الأقسام الطبية)', shortName: 'الطب البشري', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-stethoscope', badgeColor: '#8B1A2B', badgeBg: 'rgba(139, 26, 43, 0.12)', tableType: 'medical', description: 'تقرير أطباء الامتياز والأطباء المتدربين بكافة التخصصات الطبية والجراحية' },
    'جراحة': { key: 'جراحة', name: 'قسم الجراحة العامة والعمليات', shortName: 'الجراحة العامة', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-procedures', badgeColor: '#4f46e5', badgeBg: 'rgba(79, 70, 229, 0.12)', tableType: 'medical', description: 'تقرير أطباء امتياز وتدريب قسم الجراحة العامة، العمليات، وغرف العناية الجراحية' },
    'نسائية': { key: 'نسائية', name: 'قسم النسائية والتوليد', shortName: 'النسائية والتوليد', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-female', badgeColor: '#7c3aed', badgeBg: 'rgba(124, 58, 237, 0.12)', tableType: 'medical', description: 'تقرير أطباء امتياز وتدريب قسم أمراض النساء والتوليد وغرف الولادة' },
    'الاطفال': { key: 'الاطفال', name: 'قسم طب الأطفال والخداج', shortName: 'طب الأطفال', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-baby', badgeColor: '#d97706', badgeBg: 'rgba(217, 119, 6, 0.12)', tableType: 'medical', description: 'تقرير أطباء امتياز وتدريب قسم الأطفال العام وحضانات الخداج (NICU)' },
    'الأطباء المتعاقدون': { key: 'الأطباء المتعاقدون', name: 'كادر الأطباء المتعاقدون مع الجامعات', shortName: 'الأطباء المتعاقدون', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-user-md', badgeColor: '#4338ca', badgeBg: 'rgba(67, 56, 202, 0.12)', tableType: 'contracted_doctors', description: 'تقرير الأطباء والاستشاريين المتعاقدين مع الجامعات الفلسطينية الشريكة للإشراف والتدريب الطبي' },
    'طب تدريب': { key: 'طب تدريب', name: 'قسم طب تدريب وتأهيل سريري', shortName: 'طب تدريب', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-hospital-user', badgeColor: '#c2185b', badgeBg: 'rgba(194, 24, 91, 0.12)', tableType: 'medical', description: 'تقرير أطباء برنامج التدريب والتأهيل السريري في الأقسام الطبية' },
    'طب تطوع': { key: 'طب تطوع', name: 'قسم طب بشري تطوع', shortName: 'طب تطوع', category: 'medicine', categoryLabel: 'الطب البشري', icon: 'fas fa-hands-helping', badgeColor: '#4f46e5', badgeBg: 'rgba(79, 70, 229, 0.12)', tableType: 'medical', description: 'تقرير الأطباء المتطوعين في الأقسام الطبية والجراحية' },

    'CATEGORY_ALL_nursing': { key: 'CATEGORY_ALL_nursing', name: 'كلية التمريض والقبالة (شامل أقسام التمريض)', shortName: 'التمريض والقبالة', category: 'nursing', categoryLabel: 'التمريض والقبالة', icon: 'fas fa-user-nurse', badgeColor: '#0d9488', badgeBg: 'rgba(13, 148, 136, 0.12)', tableType: 'nursing', description: 'تقرير شامل لكافة كوادر التمريض (تدريب، امتياز، كادر مدربي الجامعات، والتمريض العام)' },
    'تدريب تمريض الجامعات': { key: 'تدريب تمريض الجامعات', name: 'كادر مدربي تمريض الجامعات الشريكة', shortName: 'مدربو تمريض الجامعات', category: 'nursing', categoryLabel: 'التمريض والقبالة', icon: 'fas fa-graduation-cap', badgeColor: '#7c3aed', badgeBg: 'rgba(124, 58, 237, 0.12)', tableType: 'nursing_trainers', description: 'تقرير كادر مدربي ومشرفي التمريض السريريين المعتمدين من الجامعات الشريكة' },
    'تمريض تدريب': { key: 'تمريض تدريب', name: 'قسم تمريض تدريب سريري', shortName: 'تمريض تدريب', category: 'nursing', categoryLabel: 'التمريض والقبالة', icon: 'fas fa-syringe', badgeColor: '#0891b2', badgeBg: 'rgba(8, 145, 178, 0.12)', tableType: 'nursing', description: 'تقرير طلبة كليات التمريض المتدربين عملياً في الأقسام السريرية' },
    'تمريض امتياز': { key: 'تمريض امتياز', name: 'قسم تمريض امتياز', shortName: 'تمريض امتياز', category: 'nursing', categoryLabel: 'التمريض والقبالة', icon: 'fas fa-stethoscope', badgeColor: '#7c3aed', badgeBg: 'rgba(124, 58, 237, 0.12)', tableType: 'nursing', description: 'تقرير خريجي التمريض والقبالة في سنة الامتياز المهني' },
    'التمريض': { key: 'التمريض', name: 'قسم التمريض العام', shortName: 'التمريض العام', category: 'nursing', categoryLabel: 'التمريض والقبالة', icon: 'fas fa-heartbeat', badgeColor: '#0d9488', badgeBg: 'rgba(13, 148, 136, 0.12)', tableType: 'nursing', description: 'تقرير كادر التمريض العام وأقسام المبيت والطوارئ' },
    'تمريض تطوع': { key: 'تمريض تطوع', name: 'قسم تمريض تطوع', shortName: 'تمريض تطوع', category: 'nursing', categoryLabel: 'التمريض والقبالة', icon: 'fas fa-hand-holding-medical', badgeColor: '#00bcd4', badgeBg: 'rgba(0, 188, 212, 0.12)', tableType: 'nursing', description: 'تقرير الممرضين والممرضات المتطوعين في أقسام المستشفى' },

    'CATEGORY_ALL_allied': { key: 'CATEGORY_ALL_allied', name: 'المهن الطبية المساندة والمختبرات (شامل)', shortName: 'المهن المساندة', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-vial', badgeColor: '#d97706', badgeBg: 'rgba(217, 119, 6, 0.12)', tableType: 'allied', description: 'تقرير شامل لكافة متدربي المهن الطبية المساندة والمختبرات والأشعة والتأهيل' },
    'مختبرات طبية': { key: 'مختبرات طبية', name: 'قسم المختبرات الطبية وبنك الدم', shortName: 'المختبرات الطبية', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-flask', badgeColor: '#0284c7', badgeBg: 'rgba(2, 132, 199, 0.12)', tableType: 'allied', description: 'تقرير متدربي وأخصائيي التحاليل الطبية المخبرية وبنك الدم' },
    'أشعة': { key: 'أشعة', name: 'قسم الأشعة والتصوير الطبي', shortName: 'الأشعة والتصوير', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-radiation', badgeColor: '#7c3aed', badgeBg: 'rgba(124, 58, 237, 0.12)', tableType: 'allied', description: 'تقرير متدربي التصوير الإشعاعي، الطبقي، الرنين المغناطيسي والموجات فوق الصوتية' },
    'العلاج الطبيعي': { key: 'العلاج الطبيعي', name: 'قسم العلاج الطبيعي والتأهيل الحركي', shortName: 'العلاج الطبيعي', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-walking', badgeColor: '#16a34a', badgeBg: 'rgba(22, 163, 74, 0.12)', tableType: 'allied', description: 'تقرير متدربي وأخصائيي العلاج الطبيعي وإعادة التأهيل الفيزيائي' },
    'علاج طبيعي تدريب': { key: 'علاج طبيعي تدريب', name: 'قسم علاج طبيعي تدريب', shortName: 'علاج طبيعي تدريب', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-walking', badgeColor: '#16a34a', badgeBg: 'rgba(22, 163, 74, 0.12)', tableType: 'allied', description: 'تقرير طلبة كليات العلاج الطبيعي المتدربين عملياً' },
    'علاج طبيعي امتياز': { key: 'علاج طبيعي امتياز', name: 'قسم علاج طبيعي امتياز', shortName: 'علاج طبيعي امتياز', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-user-graduate', badgeColor: '#059669', badgeBg: 'rgba(5, 150, 105, 0.12)', tableType: 'allied', description: 'تقرير أخصائيي العلاج الطبيعي في سنة الامتياز' },
    'العلاج الوظيفي': { key: 'العلاج الوظيفي', name: 'قسم العلاج الوظيفي والتكامل الحسي', shortName: 'العلاج الوظيفي', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-hands', badgeColor: '#16a085', badgeBg: 'rgba(22, 160, 133, 0.12)', tableType: 'allied', description: 'تقرير متدربي وأخصائيي العلاج الوظيفي والتأهيل العصبي والإدراكي' },
    'تغذية': { key: 'تغذية', name: 'قسم التغذية السريرية والحميات العلاجية', shortName: 'التغذية السريرية', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-apple-alt', badgeColor: '#10b981', badgeBg: 'rgba(16, 185, 129, 0.12)', tableType: 'allied', description: 'تقرير متدربي التغذية العلاجية وإدارة النظم الغذائية للمرضى' },
    'الصحة النفسية': { key: 'الصحة النفسية', name: 'قسم الصحة النفسية والدعم الإرشادي', shortName: 'الصحة النفسية', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-brain', badgeColor: '#059669', badgeBg: 'rgba(5, 150, 105, 0.12)', tableType: 'allied', description: 'تقرير متدربي وأخصائيي الصحة النفسية والدعم الإكلينيكي' },
    'ضباط الإسعاف': { key: 'ضباط الإسعاف', name: 'قسم ضباط الإسعاف وطب الطوارئ', shortName: 'ضباط الإسعاف', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-ambulance', badgeColor: '#ea580c', badgeBg: 'rgba(234, 88, 12, 0.12)', tableType: 'allied', description: 'تقرير متدربي وكوادر الإسعاف والطوارئ والإنقاذ' },
    'هندسة طبية': { key: 'هندسة طبية', name: 'قسم الهندسة الطبية وصيانة الأجهزة', shortName: 'الهندسة الطبية', category: 'allied', categoryLabel: 'المهن المساندة', icon: 'fas fa-microchip', badgeColor: '#1d4ed8', badgeBg: 'rgba(29, 78, 216, 0.12)', tableType: 'allied', description: 'تقرير متدربي الهندسة الطبية وصيانة ومعايرة المعدات الحيوية' },

    'CATEGORY_ALL_health-trainers': { key: 'CATEGORY_ALL_health-trainers', name: 'كادر مدربي المهن الصحية المساندة (شامل)', shortName: 'مدربو المهن الصحية', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-chalkboard-teacher', badgeColor: '#0891b2', badgeBg: 'rgba(8, 145, 178, 0.12)', tableType: 'health_trainers', description: 'تقرير كادر مدربي ومشرفي التدريب العملي لكافة المهن الصحية المساندة' },
    'مدربي أشعة': { key: 'مدربي أشعة', name: 'مدربو الأشعة والتصوير الطبي', shortName: 'مدربو الأشعة', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-radiation', badgeColor: '#7c3aed', badgeBg: 'rgba(124, 58, 237, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب السريري في قسم الأشعة' },
    'مدربي مختبر': { key: 'مدربي مختبر', name: 'مدربو المختبرات والتحاليل الطبية', shortName: 'مدربو المختبرات', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-flask', badgeColor: '#0284c7', badgeBg: 'rgba(2, 132, 199, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب السريري في قسم المختبرات وبنك الدم' },
    'مدربي علاج طبيعي': { key: 'مدربي علاج طبيعي', name: 'مدربو العلاج الطبيعي والتأهيل', shortName: 'مدربو العلاج الطبيعي', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-walking', badgeColor: '#059669', badgeBg: 'rgba(5, 150, 105, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب السريري في قسم العلاج الطبيعي' },
    'مدربي علاج وظيفي': { key: 'مدربي علاج وظيفي', name: 'مدربو العلاج الوظيفي', shortName: 'مدربو العلاج الوظيفي', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-hands', badgeColor: '#0f766e', badgeBg: 'rgba(15, 118, 110, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب السريري في قسم العلاج الوظيفي' },
    'مدربي صيدلية': { key: 'مدربي صيدلية', name: 'مدربو الصيدلة السريرية', shortName: 'مدربو الصيدلة', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-pills', badgeColor: '#b45309', badgeBg: 'rgba(180, 83, 9, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب السريري الصيدلاني' },
    'مدربي تغذية': { key: 'مدربي تغذية', name: 'مدربو التغذية السريرية', shortName: 'مدربو التغذية', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-apple-alt', badgeColor: '#16a34a', badgeBg: 'rgba(22, 163, 74, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب السريري في قسم التغذية' },
    'مدربي هندسة طبية': { key: 'مدربي هندسة طبية', name: 'مدربو الهندسة الطبية والأجهزة', shortName: 'مدربو الهندسة الطبية', category: 'health-trainers', categoryLabel: 'مدربو المهن الصحية', icon: 'fas fa-microchip', badgeColor: '#1d4ed8', badgeBg: 'rgba(29, 78, 216, 0.12)', tableType: 'health_trainers', description: 'مشرفو التدريب العملي في الهندسة الطبية' },

    'CATEGORY_ALL_admin': { key: 'CATEGORY_ALL_admin', name: 'الشؤون الإدارية والخدمات (شامل)', shortName: 'الإدارة والخدمات', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-briefcase', badgeColor: '#3f3f46', badgeBg: 'rgba(63, 63, 70, 0.12)', tableType: 'admin', description: 'تقرير شامل لمتدربي وكوادر الشؤون الإدارية والمالية والخدمات المساندة' },
    'إدارة': { key: 'إدارة', name: 'الإدارة العامة والموارد البشرية', shortName: 'الإدارة العامة', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-building', badgeColor: '#52525b', badgeBg: 'rgba(82, 82, 91, 0.12)', tableType: 'admin', description: 'تقرير متدربي الإدارة العامة، التنسيق الإداري، والموارد البشرية' },
    'المحاسبة': { key: 'المحاسبة', name: 'الدائرة المالية والمحاسبة', shortName: 'المحاسبة والمالية', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-calculator', badgeColor: '#78716c', badgeBg: 'rgba(120, 113, 108, 0.12)', tableType: 'admin', description: 'تقرير متدربي التدقيق المالي، المحاسبة، وصناديق المرضى' },
    'سكرتارية طبية': { key: 'سكرتارية طبية', name: 'السكرتارية الطبية والأرشيف والسجلات', shortName: 'السكرتارية الطبية', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-file-invoice', badgeColor: '#00838f', badgeBg: 'rgba(0, 131, 143, 0.12)', tableType: 'admin', description: 'تقرير متدربي السكرتارية الطبية، إدارة المواعيد، والسجلات الصحية' },
    'المطبخ': { key: 'المطبخ', name: 'قسم المطبخ والخدمات الغذائية والإعاشة', shortName: 'المطبخ والإعاشة', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-utensils', badgeColor: '#b45309', badgeBg: 'rgba(180, 83, 9, 0.12)', tableType: 'admin', description: 'تقرير كوادر ومتدربي تحضير الوجبات وضبط معايير الجودة الغذائية' },
    'العمل المجتمعي': { key: 'العمل المجتمعي', name: 'قسم العمل والأنشطة المجتمعية', shortName: 'العمل المجتمعي', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-handshake', badgeColor: '#00695c', badgeBg: 'rgba(0, 105, 92, 0.12)', tableType: 'admin', description: 'تقرير متدربي المبادرات والأنشطة المجتمعية والتوعوية' },
    'خدمة اجتماعية': { key: 'خدمة اجتماعية', name: 'قسم الخدمة الاجتماعية ودعم المرضى', shortName: 'الخدمة الاجتماعية', category: 'admin', categoryLabel: 'الإدارة والخدمات', icon: 'fas fa-users', badgeColor: '#854d0e', badgeBg: 'rgba(133, 77, 14, 0.12)', tableType: 'admin', description: 'تقرير متدربي الإرشاد والدعم الاجتماعي للمرضى وعائلاتهم' },

    'المغادرين': { key: 'المغادرين', name: 'سجل الخريجين والمغادرين (أنهوا فترات التدريب)', shortName: 'الخريجون والمغادرون', category: 'special', categoryLabel: 'المغادرين والخريجين', icon: 'fas fa-user-graduate', badgeColor: '#475569', badgeBg: 'rgba(71, 85, 105, 0.12)', tableType: 'graduates', description: 'السجل الرسمي المعتمد لكافة الأطباء والممرضين والمتدربين الذين أتموا فتراتهم التدريبية بنجاح' },
    'الاستئناف': { key: 'الاستئناف', name: 'سجل الاستئناف والإجازات المؤقتة', shortName: 'الاستئناف المؤقت', category: 'special', categoryLabel: 'حالات خاصة', icon: 'fas fa-pause-circle', badgeColor: '#eab308', badgeBg: 'rgba(234, 179, 8, 0.12)', tableType: 'general', description: 'سجل المتدربين الحاصلين على فترات استئناف مؤقتة أو إجازات رسمية معتمدة' }
  };

  const getDeptConfig = (key: string): DeptReportConfig => {
    if (DEPARTMENT_CONFIGS[key]) return DEPARTMENT_CONFIGS[key];
    return {
      key,
      name: `قسم ${key}`,
      shortName: key,
      category: 'allied',
      categoryLabel: 'الأقسام السريرية',
      icon: 'fas fa-hospital-alt',
      badgeColor: '#059669',
      badgeBg: 'rgba(5, 150, 105, 0.12)',
      tableType: 'general',
      description: `التقرير الإحصائي الرسمي لقسم ${key}`
    };
  };

  // ═══════════ Statistical Student Pool (ALL Active + Departed/Graduates Across ALL Departments) ═══════════
  const allStatisticalStudents = useMemo(() => {
    const list: (Student & { 
      department: string; 
      deptLabel: string; 
      originalDepartment?: string;
      isGraduated: boolean; 
      isSuspended: boolean;
      folderKey: string;
      computedStatus: 'active' | 'completed' | 'upcoming';
    })[] = [];

    const now = Date.now();

    Object.entries(studentsData).forEach(([deptKey, students]) => {
      if (!Array.isArray(students)) return;
      students.forEach(s => {
        const isGradFolder = deptKey === 'المغادرين';
        const isSuspFolder = deptKey === 'الاستئناف';
        
        // Effective Department determination:
        // For students in "المغادرين", where did they train?
        const origDept = s.originalDepartment || (s.allRotations && s.allRotations[0]?.dept) || (s.department && s.department !== 'المغادرين' ? s.department : '');
        const effectiveDept = isGradFolder 
          ? (origDept || 'المغادرين')
          : (isSuspFolder ? (origDept || 'الاستئناف') : deptKey);

        const sStart = parseDateToMs(s.startDate || s.globalStartDate) || 0;
        const sEnd = parseDateToMs(s.endDate || s.globalEndDate) || Infinity;
        
        let computedStatus: 'active' | 'completed' | 'upcoming' = 'active';
        if (isGradFolder || s.isGraduate || s.status === 'مغادر' || s.status === 'completed' || (sEnd !== Infinity && now > sEnd)) {
          computedStatus = 'completed';
        } else if (sStart > now) {
          computedStatus = 'upcoming';
        } else {
          computedStatus = 'active';
        }

        list.push({
          ...s,
          department: effectiveDept,
          deptLabel: effectiveDept,
          originalDepartment: origDept || effectiveDept,
          isGraduated: isGradFolder || computedStatus === 'completed',
          isSuspended: isSuspFolder || s.status === 'suspended',
          folderKey: deptKey,
          computedStatus
        });
      });
    });

    // Merge website applications for Contracted Doctors & Nursing Trainers
    const existingDoctorIds = new Set(list.filter(s => s.department === 'الأطباء المتعاقدون').map(s => (s.phone || s.idNumber || s.name || '').trim()));
    const existingTrainerIds = new Set(list.filter(s => s.department === 'تدريب تمريض الجامعات').map(s => (s.phone || s.idNumber || s.name || '').trim()));

    if (Array.isArray(allApplications)) {
      allApplications.forEach(app => {
        let cat = (app.category || app.categoryId || '').toLowerCase();
        try { cat = decodeURIComponent(cat); } catch {}
        const isDocApp = cat.includes('الأطباء المتعاقدون') || cat.includes('contracted-doctors');
        const isTrainerApp = cat.includes('تدريب طلاب التمريض') || cat.includes('university-nursing-trainers') || cat.includes('تمريض الجامعات');

        const appKey = (app.phone || app.idNumber || app.name || '').trim();
        if (!appKey) return;

        if (isDocApp && !existingDoctorIds.has(appKey)) {
          const sStart = parseDateToMs(app.startDate || app.trainingStartDate) || 0;
          const sEnd = parseDateToMs(app.endDate || app.trainingEndDate) || Infinity;
          let computedStatus: 'active' | 'completed' | 'upcoming' = 'active';
          if (app.status === 'completed' || (sEnd !== Infinity && now > sEnd)) computedStatus = 'completed';
          else if (sStart > now) computedStatus = 'upcoming';

          list.push({
            id: app.id || String(Date.now()),
            name: app.name,
            phone: app.phone || '',
            idNumber: app.idNumber || '',
            department: 'الأطباء المتعاقدون',
            deptLabel: 'الأطباء المتعاقدون',
            originalDepartment: 'الأطباء المتعاقدون',
            university: app.graduatedUniversity || app.university || '',
            contractedUniversity: app.contractedUniversity || (Array.isArray(app.contractedUniversities) ? app.contractedUniversities.join('، ') : app.contractedUniversities) || app.previousContractedUniversity || '',
            contractedUniversities: app.contractedUniversities || [],
            specialty: app.specialty || '',
            crescentJobNature: app.crescentJobNature || app.employmentType || 'أخصائي متعاقد',
            workDays: app.workDays || [],
            trainingDepartments: app.trainingDepartments || [],
            startDate: app.startDate || app.trainingStartDate || '',
            endDate: app.endDate || app.trainingEndDate || '',
            isGraduated: computedStatus === 'completed',
            isSuspended: false,
            folderKey: 'الأطباء المتعاقدون',
            computedStatus
          } as any);
          existingDoctorIds.add(appKey);
        } else if (isTrainerApp && !existingTrainerIds.has(appKey)) {
          const sStart = parseDateToMs(app.startDate || app.trainingStartDate) || 0;
          const sEnd = parseDateToMs(app.endDate || app.trainingEndDate) || Infinity;
          let computedStatus: 'active' | 'completed' | 'upcoming' = 'active';
          if (app.status === 'completed' || (sEnd !== Infinity && now > sEnd)) computedStatus = 'completed';
          else if (sStart > now) computedStatus = 'upcoming';

          list.push({
            id: app.id || String(Date.now()),
            name: app.name,
            phone: app.phone || '',
            idNumber: app.idNumber || '',
            department: 'تدريب تمريض الجامعات',
            deptLabel: 'تدريب تمريض الجامعات',
            originalDepartment: 'تدريب تمريض الجامعات',
            university: app.university || '',
            graduatedUniversity: app.graduatedUniversity || app.university || '',
            contractedUniversity: app.contractedUniversity || (Array.isArray(app.contractedUniversities) ? app.contractedUniversities.join('، ') : app.contractedUniversities) || app.previousContractedUniversity || '',
            contractedUniversities: app.contractedUniversities || [],
            studySystem: 'تمريض جامعات',
            internshipYear: 'مدرب سريري',
            crescentJobNature: app.crescentJobNature || app.employmentType || '',
            trainingDepartments: app.trainingDepartments || [],
            startDate: app.startDate || app.trainingStartDate || '',
            endDate: app.endDate || app.trainingEndDate || '',
            isGraduated: computedStatus === 'completed',
            isSuspended: false,
            folderKey: 'تدريب تمريض الجامعات',
            computedStatus
          } as any);
          existingTrainerIds.add(appKey);
        }
      });
    }

    return list;
  }, [studentsData, allApplications]);

  // Distinct departments available in system for statistical filtering (including all master configs)
  const allStatisticalDepartments = useMemo(() => {
    const set = new Set<string>();
    // 1. Add all configured department keys (excluding groups/virtual)
    Object.keys(DEPARTMENT_CONFIGS).forEach(k => {
      if (k !== 'All' && !k.startsWith('CATEGORY_ALL_') && k !== 'المغادرين' && k !== 'الاستئناف') {
        set.add(k);
      }
    });
    // 2. Add any live keys from studentsData
    Object.keys(studentsData).forEach(k => {
      if (k !== 'المغادرين' && k !== 'الاستئناف') {
        set.add(k);
      }
    });
    (studentsData['المغادرين'] || []).forEach(s => {
      if (s.originalDepartment && s.originalDepartment !== 'المغادرين' && s.originalDepartment !== 'الاستئناف') {
        set.add(s.originalDepartment);
      }
    });
    return Array.from(set).sort((a, b) => a.localeCompare(b, 'ar'));
  }, [studentsData]);

  // Counts using the proper generalized array
  const totalCount = allStudents.length;

  // Helper: get the university that drives classification/stats
  // For trainers: contractedUniversity (partner hospital), for students: university (graduation)
  const getClassificationUniversity = useCallback((student: Student): string => {
    const isTrainer = (
      student.department === 'تدريب تمريض الجامعات' ||
      student.originalDepartment === 'تدريب تمريض الجامعات' ||
      student.folderKey === 'تدريب تمريض الجامعات' ||
      student.department === 'الأطباء المتعاقدون' ||
      student.originalDepartment === 'الأطباء المتعاقدون' ||
      // health dept trainers
      (student.department || '').startsWith('مدربي ') ||
      (student.originalDepartment || '').startsWith('مدربي ') ||
      student.studySystem === 'تمريض جامعات' ||
      student.internshipYear === 'مدرب سريري' ||
      student.isUniversityTrainer
    );
    if (isTrainer) {
      // 🤝 Use contracted university for classification
      const contracted = student.contractedUniversity ||
        (Array.isArray(student.contractedUniversities) && student.contractedUniversities.length > 0 ? student.contractedUniversities[0] : '') ||
        student.previousContractedUniversity;
      if (contracted) return contracted;
    }
    // For regular students (or trainers without contracted uni set yet), fall back to university field
    return student.university || '';
  }, []);

  // Calculate University Stats
  const universityStats = useMemo(() => {
    const stats: { [key: string]: number } = {};
    let withoutUni = 0;

    allStudents.forEach(student => {
      const u = normalizeUniversityName(getClassificationUniversity(student));
      if (u === 'جامعات أخرى / غير محدد') {
        withoutUni++;
      } else {
        stats[u] = (stats[u] || 0) + 1;
      }
    });

    // Convert to array and sort — جامعة الخليل is ALWAYS pinned first
    const data = Object.entries(stats)
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => {
        // Pin جامعة الخليل to position 1 always
        if (a.name === 'جامعة الخليل') return -1;
        if (b.name === 'جامعة الخليل') return 1;
        // Pin جامعات مصر to position 2 always
        if (a.name === 'جامعات مصر') return -1;
        if (b.name === 'جامعات مصر') return 1;
        // Rest sorted by count descending
        return b.value - a.value;
      });
    
    // Add "بدون جامعة" at the end if needed
    if (withoutUni > 0) {
      data.push({ name: 'بدون جامعة / أخرى', value: withoutUni });
    }
    
    return data;
  }, [allStudents, getClassificationUniversity]);

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8', '#82ca9d', '#ffc658', '#8dd1e1', '#a4de6c', '#d0ed57'];

  const filteredStudents = useMemo(() => {
    let students: Student[] = [];
    if (currentDepartment === 'All') {
        students = allStudents;
    } else if (currentDepartment?.startsWith('CATEGORY_ALL_')) {
      const cat = currentDepartment.replace('CATEGORY_ALL_', '');
      let targetKeys: string[] = [];
      if (cat === 'medicine') targetKeys = ['جراحة', 'نسائية', 'الاطفال', 'طب تطوع', 'طب تدريب', 'الأطباء المتعاقدون'];
      else if (cat === 'nursing') targetKeys = ['التمريض', 'تمريض تدريب', 'تمريض امتياز', 'تدريب تمريض الجامعات'];
      else if (cat === 'volunteer') targetKeys = ['طب تطوع', 'تمريض تطوع', 'العلاج الطبيعي', 'تغذية', 'الصحة النفسية', 'الصحة النفسية تطوع', 'خدمة اجتماعية'];
      else if (cat === 'allied') targetKeys = ['العلاج الطبيعي', 'الصحة النفسية', 'الصحة النفسية تطوع', 'أشعة', 'تغذية', 'مختبرات طبية', 'العلاج الوظيفي', 'خدمة اجتماعية', 'سكرتارية طبية'];
      else if (cat === 'admin') targetKeys = ['إدارة', 'المحاسبة', 'المطبخ', 'ضباط الإسعاف', 'العمل المجتمعي'];
      else if (cat === 'health-trainers') targetKeys = ['مدربي أشعة', 'مدربي هندسة طبية', 'مدربي تغذية', 'مدربي صيدلية', 'مدربي مختبر', 'مدربي علاج طبيعي', 'مدربي علاج وظيفي'];

      students = allStudents.filter(s => targetKeys.includes(s.department));
    } else if (currentDepartment) {
      if (isTrainerDepartment(currentDepartment)) {
        const currentList = studentsData[currentDepartment] || [];
        const relatedTraineeDepts = getRelatedTraineeDepts(currentDepartment);
        const traineePool: Student[] = [];
        relatedTraineeDepts.forEach(rd => {
          (studentsData[rd] || []).forEach(st => {
            traineePool.push({ ...st, originalDepartment: st.originalDepartment || rd });
          });
        });

        const cleanP = (ph: string) => (ph || '').replace(/\D/g, '').slice(-9);
        const normK = (s: any) => `${(s.name || '').trim()}:::${cleanP(s.phone) || (s.idNumber || '').trim() || s.startDate || ''}`;
        const seen = new Set<string>();
        const merged: Student[] = [];

        currentList.forEach(s => {
          const k = normK(s);
          if (!seen.has(k)) {
            seen.add(k);
            merged.push(s);
          }
        });
        traineePool.forEach(s => {
          const k = normK(s);
          if (!seen.has(k)) {
            seen.add(k);
            merged.push(s);
          }
        });
        students = merged;
      } else {
        students = studentsData[currentDepartment] || [];
      }
    }
    
    return students.filter(student => 
      student.name.includes(searchTerm) || 
      student.phone.includes(searchTerm) ||
      (student.university && student.university.includes(searchTerm)) ||
      normalizeUniversityName(student.university).includes(searchTerm)
    );
  }, [currentDepartment, studentsData, searchTerm, allStudents]);

  const reportFilteredStudents = useMemo(() => {
    let pool = allStatisticalStudents;

    // 1. Department Filter
    if (reportDept !== 'All') {
      if (reportDept === 'المغادرين') {
        pool = pool.filter(s => s.folderKey === 'المغادرين' || s.isGraduated || s.computedStatus === 'completed');
      } else if (reportDept === 'الاستئناف') {
        pool = pool.filter(s => s.folderKey === 'الاستئناف' || s.isSuspended);
      } else if (reportDept.startsWith('CATEGORY_ALL_')) {
        const cat = reportDept.replace('CATEGORY_ALL_', '');
        let targetKeys: string[] = [];
        if (cat === 'medicine') targetKeys = ['جراحة', 'نسائية', 'الاطفال', 'طب تطوع', 'طب تدريب', 'الأطباء المتعاقدون'];
        else if (cat === 'nursing') targetKeys = ['التمريض', 'تمريض تدريب', 'تمريض امتياز', 'تدريب تمريض الجامعات', 'تمريض تطوع'];
        else if (cat === 'volunteer') targetKeys = ['طب تطوع', 'تمريض تطوع', 'العلاج الطبيعي', 'تغذية', 'الصحة النفسية', 'خدمة اجتماعية'];
        else if (cat === 'allied') targetKeys = ['العلاج الطبيعي', 'علاج طبيعي تدريب', 'علاج طبيعي امتياز', 'الصحة النفسية', 'أشعة', 'تغذية', 'مختبرات طبية', 'العلاج الوظيفي', 'خدمة اجتماعية', 'سكرتارية طبية', 'ضباط الإسعاف', 'هندسة طبية'];
        else if (cat === 'admin') targetKeys = ['إدارة', 'المحاسبة', 'المطبخ', 'العمل المجتمعي', 'خدمة اجتماعية', 'سكرتارية طبية'];
        else if (cat === 'health-trainers') targetKeys = ['مدربي أشعة', 'مدربي هندسة طبية', 'مدربي تغذية', 'مدربي صيدلية', 'مدربي مختبر', 'مدربي علاج طبيعي', 'مدربي علاج وظيفي'];
        
        pool = pool.filter(s => targetKeys.includes(s.department) || (s.originalDepartment && targetKeys.includes(s.originalDepartment)));
      } else {
        pool = pool.filter(s => 
          s.department === reportDept || 
          s.originalDepartment === reportDept || 
          s.folderKey === reportDept
        );
      }
    }

    // 2. Date Range Filter
    const startFilterMs = reportStartDate ? parseDateToMs(reportStartDate) : null;
    const endFilterMs = reportEndDate ? parseDateToMs(reportEndDate) : null;

    if (startFilterMs || endFilterMs) {
      pool = pool.filter(s => {
        const studentStartMs = parseDateToMs(s.startDate || s.globalStartDate);
        const studentEndMs = parseDateToMs(s.endDate || s.globalEndDate);

        if (startFilterMs && studentEndMs && studentEndMs < startFilterMs) return false;
        if (endFilterMs && studentStartMs && studentStartMs > endFilterMs) return false;
        if (startFilterMs && !studentEndMs && studentStartMs && studentStartMs < startFilterMs) return false;
        return true;
      });
    }

    // 3. Status Filter (active / completed / upcoming)
    if (reportStatus !== 'all') {
      pool = pool.filter(s => {
        if (reportStatus === 'active') return s.computedStatus === 'active';
        if (reportStatus === 'completed') return s.computedStatus === 'completed';
        if (reportStatus === 'upcoming') return s.computedStatus === 'upcoming';
        return true;
      });
    }

    // 4. Search Filter
    if (reportSearch.trim()) {
      const q = reportSearch.trim().toLowerCase();
      pool = pool.filter(s => {
        const normUni = normalizeUniversityName(s.university);
        if (normUni === reportSearch.trim()) return true;

        return (
          (s.name || '').toLowerCase().includes(q) ||
          (s.phone || '').includes(q) ||
          (s.university || '').toLowerCase().includes(q) ||
          normUni.toLowerCase().includes(q) ||
          (s.department || '').toLowerCase().includes(q) ||
          (s.originalDepartment || '').toLowerCase().includes(q) ||
          (s.specialty || '').toLowerCase().includes(q)
        );
      });
    }

    return pool;
  }, [allStatisticalStudents, reportDept, reportStartDate, reportEndDate, reportStatus, reportSearch]);

  // Helper to identify nursing trainers
  const isNursingTrainer = useCallback((s: any) => {
    if (
      s.department === 'تمريض تدريب' ||
      s.originalDepartment === 'تمريض تدريب' ||
      s.folderKey === 'تمريض تدريب' ||
      s.internshipYear === 'طالب متدرب' ||
      s.crescentJobNature === 'طالب تمريض متدرب' ||
      s.crescentJobNature === 'طالب متدرب' ||
      (typeof s.internshipYear === 'string' && s.internshipYear.includes('طالب'))
    ) {
      return false;
    }
    return Boolean(
      s.department === 'تدريب تمريض الجامعات' ||
      s.originalDepartment === 'تدريب تمريض الجامعات' ||
      s.folderKey === 'تدريب تمريض الجامعات' ||
      s.studySystem === 'تمريض جامعات' ||
      s.internshipYear === 'مدرب سريري' ||
      s.isUniversityTrainer
    );
  }, []);

  // Helper to identify contracted doctors
  const isContractedDoctorStudent = useCallback((s: any) => Boolean(
    s.department === 'الأطباء المتعاقدون' ||
    s.originalDepartment === 'الأطباء المتعاقدون' ||
    s.folderKey === 'الأطباء المتعاقدون' ||
    s.category === 'الأطباء المتعاقدون مع الجامعات'
  ), []);

  // Department metadata for currently selected department
  const currentDeptConfig = useMemo(() => {
    return getDeptConfig(reportDept);
  }, [reportDept]);

  // 1. All nursing trainers in the statistical pool
  const allTrainersInPool = useMemo(() => {
    return allStatisticalStudents.filter(s => isNursingTrainer(s));
  }, [allStatisticalStudents, isNursingTrainer]);

  // 2. Trainees strictly (students, interns, allied, volunteers - excluding clinical trainers)
  const reportTrainees = useMemo(() => {
    return reportFilteredStudents.filter(s => !isNursingTrainer(s));
  }, [reportFilteredStudents, isNursingTrainer]);

  // 3. Clinical Nursing Trainers matching current period and status
  const reportNursingTrainers = useMemo(() => {
    if (reportDept !== 'All' && reportDept !== 'تدريب تمريض الجامعات' && reportDept !== 'CATEGORY_ALL_nursing') {
      return [];
    }
    let list = reportFilteredStudents.filter(s => isNursingTrainer(s));
    if (trainerUniFilter) {
      list = list.filter(s => {
        const contracted = normalizeUniversityName(
          s.contractedUniversity ||
          (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
          s.previousContractedUniversity
        );
        return contracted === trainerUniFilter;
      });
    }
    return list;
  }, [reportFilteredStudents, isNursingTrainer, reportDept, trainerUniFilter]);

  // 4. Contracted Doctors matching current period and status
  const reportContractedDoctors = useMemo(() => {
    return reportFilteredStudents.filter(s => isContractedDoctorStudent(s));
  }, [reportFilteredStudents, isContractedDoctorStudent]);

  // 5. Dedicated KPI counts for CURRENT department view
  const currentDeptActiveCount = useMemo(() => {
    return reportFilteredStudents.filter(s => s.computedStatus === 'active').length;
  }, [reportFilteredStudents]);

  const currentDeptCompletedCount = useMemo(() => {
    return reportFilteredStudents.filter(s => s.computedStatus === 'completed').length;
  }, [reportFilteredStudents]);

  const currentDeptUpcomingCount = useMemo(() => {
    return reportFilteredStudents.filter(s => s.computedStatus === 'upcoming').length;
  }, [reportFilteredStudents]);

  // 6. University distribution tailored to current selected department
  const currentDeptUniversityStats = useMemo(() => {
    const map: { [uni: string]: { total: number; active: number; completed: number; upcoming: number } } = {};
    const isTrainer = currentDeptConfig.tableType === 'nursing_trainers' || currentDeptConfig.tableType === 'contracted_doctors';

    reportFilteredStudents.forEach(s => {
      const rawUni = isTrainer
        ? (s.contractedUniversity ||
           (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
           s.previousContractedUniversity ||
           s.university)
        : s.university;
      const uni = normalizeUniversityName(rawUni);
      if (!map[uni]) {
        map[uni] = { total: 0, active: 0, completed: 0, upcoming: 0 };
      }
      map[uni].total += 1;
      if (s.computedStatus === 'upcoming') map[uni].upcoming += 1;
      else if (s.computedStatus === 'completed') map[uni].completed += 1;
      else map[uni].active += 1;
    });

    const total = reportFilteredStudents.length;
    return Object.entries(map)
      .map(([name, data]) => ({
        name,
        ...data,
        percentage: total > 0 ? Math.round((data.total / total) * 100) : 0
      }))
      .sort((a, b) => b.total - a.total);
  }, [reportFilteredStudents, currentDeptConfig]);

  // 7. Medical Speciality / Study System breakdown (for medical departments)
  const currentDeptStudySystemStats = useMemo(() => {
    const map: { [sys: string]: number } = {};
    reportFilteredStudents.forEach(s => {
      const sys = s.studySystem || (s.internshipYear ? `سنة ${s.internshipYear}` : 'امتياز عام');
      map[sys] = (map[sys] || 0) + 1;
    });
    return Object.entries(map).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count);
  }, [reportFilteredStudents]);

  // 8. Contracted Doctor Specialties breakdown
  const currentDeptSpecialtyStats = useMemo(() => {
    const map: { [spec: string]: number } = {};
    reportFilteredStudents.forEach(s => {
      const spec = s.specialty || s.nursingSpecialty || s.studySystem || 'طب عام وتخصصي';
      map[spec] = (map[spec] || 0) + 1;
    });
    return Object.entries(map).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count);
  }, [reportFilteredStudents]);

  // Legacy counts for backward compatibility
  const reportTraineeActiveCount = useMemo(() => reportTrainees.filter(s => s.computedStatus === 'active').length, [reportTrainees]);
  const reportTraineeCompletedCount = useMemo(() => reportTrainees.filter(s => s.computedStatus === 'completed').length, [reportTrainees]);
  const reportTraineeUpcomingCount = useMemo(() => reportTrainees.filter(s => s.computedStatus === 'upcoming').length, [reportTrainees]);
  const reportTrainerActiveCount = useMemo(() => reportNursingTrainers.filter(s => s.computedStatus === 'active').length, [reportNursingTrainers]);
  const reportTrainerCompletedCount = useMemo(() => reportNursingTrainers.filter(s => s.computedStatus === 'completed').length, [reportNursingTrainers]);
  const reportTrainerUpcomingCount = useMemo(() => reportNursingTrainers.filter(s => s.computedStatus === 'upcoming').length, [reportNursingTrainers]);

  const reportTraineeUniversityStats = useMemo(() => {
    const map: { [uni: string]: { total: number; active: number; completed: number; upcoming: number } } = {};
    reportTrainees.forEach(s => {
      const uni = normalizeUniversityName(s.university);
      if (!map[uni]) map[uni] = { total: 0, active: 0, completed: 0, upcoming: 0 };
      map[uni].total += 1;
      if (s.computedStatus === 'upcoming') map[uni].upcoming += 1;
      else if (s.computedStatus === 'completed') map[uni].completed += 1;
      else map[uni].active += 1;
    });
    const total = reportTrainees.length;
    return Object.entries(map).map(([name, data]) => ({
      name,
      ...data,
      percentage: total > 0 ? Math.round((data.total / total) * 100) : 0
    })).sort((a, b) => b.total - a.total);
  }, [reportTrainees]);

  const reportTrainerUniversityStats = useMemo(() => {
    const map: { [uni: string]: { total: number; active: number; completed: number; upcoming: number } } = {};
    const baseTrainers = reportFilteredStudents.filter(s => isNursingTrainer(s));
    baseTrainers.forEach(s => {
      const contractedRaw = s.contractedUniversity ||
        (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
        s.previousContractedUniversity || s.university;
      const uni = normalizeUniversityName(contractedRaw);
      if (!map[uni]) map[uni] = { total: 0, active: 0, completed: 0, upcoming: 0 };
      map[uni].total += 1;
      if (s.computedStatus === 'upcoming') map[uni].upcoming += 1;
      else if (s.computedStatus === 'completed') map[uni].completed += 1;
      else map[uni].active += 1;
    });
    const total = baseTrainers.length;
    return Object.entries(map).map(([name, data]) => ({
      name,
      ...data,
      percentage: total > 0 ? Math.round((data.total / total) * 100) : 0
    })).sort((a, b) => b.total - a.total);
  }, [reportFilteredStudents, isNursingTrainer]);

  const reportActiveCount = currentDeptActiveCount;
  const reportCompletedCount = currentDeptCompletedCount;
  const reportUpcomingCount = currentDeptUpcomingCount;
  const reportUniversityStats = currentDeptUniversityStats;

    // ═════════════════════════════════════════════════════════════════════════════════
  // 🌟 DEDICATED REPORT GENERATOR: SPECIALIZED REPORT FOR EVERY HOSPITAL DEPARTMENT
  // ═════════════════════════════════════════════════════════════════════════════════
  const printDedicatedDepartmentReport = (targetDeptKey?: string) => {
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    const deptKey = targetDeptKey || reportDept || 'All';
    const cfg = getDeptConfig(deptKey);

    // Compute target students based on deptKey
    let targetStudents: Student[] = [];
    if (targetDeptKey && targetDeptKey !== reportDept) {
      if (deptKey === 'All') {
        targetStudents = allStatisticalStudents;
      } else if (deptKey.startsWith('CATEGORY_ALL_')) {
        const cat = deptKey.replace('CATEGORY_ALL_', '');
        targetStudents = allStatisticalStudents.filter(s => {
          const c = getDeptConfig(s.department || s.originalDepartment || '');
          return c.category === cat;
        });
      } else if (deptKey === 'الأطباء المتعاقدون' || deptKey === 'contracted_doctors') {
        targetStudents = allStatisticalStudents.filter(s => isContractedDoctor(s));
      } else if (deptKey === 'تدريب تمريض الجامعات' || deptKey === 'nursing_trainers') {
        targetStudents = allStatisticalStudents.filter(s => isNursingTrainer(s));
      } else if (deptKey === 'خريجون مكتملون' || deptKey === 'graduates' || deptKey === 'المغادرين') {
        targetStudents = allStatisticalStudents.filter(s => s.computedStatus === 'completed' || s.folderKey === 'المغادرين' || s.isGraduated);
      } else {
        targetStudents = allStatisticalStudents.filter(s => (s.department || s.originalDepartment || s.folderKey) === deptKey);
      }
    } else {
      targetStudents = reportFilteredStudents;
    }

    // Apply trainer university filter if active and applicable
    if (trainerUniFilter && (cfg.tableType === 'nursing_trainers' || cfg.tableType === 'contracted_doctors')) {
      targetStudents = targetStudents.filter(s => {
        const u = normalizeUniversityName(
          s.contractedUniversity ||
          (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
          s.previousContractedUniversity ||
          s.university
        );
        return u === trainerUniFilter;
      });
    }

    const activeList = targetStudents.filter(s => s.computedStatus === 'active');
    const completedList = targetStudents.filter(s => s.computedStatus === 'completed');
    const upcomingList = targetStudents.filter(s => s.computedStatus === 'upcoming');

    // Universities distribution
    const uniMap: { [key: string]: { total: number; active: number; completed: number; upcoming: number } } = {};
    targetStudents.forEach(s => {
      let uName = normalizeUniversityName(
        s.contractedUniversity ||
        (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
        s.university ||
        'غير محدد'
      );
      if (!uniMap[uName]) uniMap[uName] = { total: 0, active: 0, completed: 0, upcoming: 0 };
      uniMap[uName].total++;
      if (s.computedStatus === 'active') uniMap[uName].active++;
      else if (s.computedStatus === 'completed') uniMap[uName].completed++;
      else if (s.computedStatus === 'upcoming') uniMap[uName].upcoming++;
    });

    const uniStats = Object.keys(uniMap).map(name => ({
      name,
      ...uniMap[name],
      percentage: targetStudents.length > 0 ? ((uniMap[name].total / targetStudents.length) * 100).toFixed(1) : '0'
    })).sort((a, b) => b.total - a.total);

    // Specialty stats for contracted doctors
    const specMap: { [key: string]: number } = {};
    if (cfg.tableType === 'contracted_doctors') {
      targetStudents.forEach(s => {
        const sp = s.specialty || (s as any).academicDegree || 'طبيب استشاري / مشرف';
        specMap[sp] = (specMap[sp] || 0) + 1;
      });
    }

    // Study system stats for medical
    let sys5_2 = 0;
    let sys6_1 = 0;
    if (cfg.tableType === 'medical') {
      targetStudents.forEach(s => {
        const sys = (s.studySystem || '').trim();
        if (sys.includes('5')) sys5_2++;
        else if (sys.includes('6')) sys6_1++;
      });
    }

    const periodText = (reportStartDate || reportEndDate) 
      ? `الفترة من: ${reportStartDate || 'البداية'} إلى: ${reportEndDate || 'الآن'}` 
      : 'جميع الفترات الزمنية المعتمدة';

    // ══ BUILD SPECIALIZED TABLE ROWS BASED ON DEPARTMENT TABLE TYPE ══
    const tableRowsHtml = targetStudents.map((s, idx) => {
      const isUpcoming = s.computedStatus === 'upcoming';
      const isCompleted = s.computedStatus === 'completed';
      const statusText = isUpcoming ? 'مجدول (قادم)' : isCompleted ? 'أنهى التدريب / الإشراف' : 'على رأس العمل (نشط)';
      const statusColor = isUpcoming ? '#b45309' : isCompleted ? '#475569' : '#15803d';
      const statusBg = isUpcoming ? '#fef3c7' : isCompleted ? '#f1f5f9' : '#dcfce7';

      if (cfg.tableType === 'contracted_doctors') {
        const universities = Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0
          ? s.contractedUniversities.join('، ')
          : (s.contractedUniversity || s.university || '—');
        const worksAtCrescent = (s as any).workingAtCrescent !== false ? 'نعم (طاقم المستشفى)' : 'لا (مشرف خارجي)';
        const days = Array.isArray((s as any).workDays) && (s as any).workDays.length > 0
          ? (s as any).workDays.join('، ')
          : ((s as any).clinicSchedule || 'حسب جدول العيادات');

        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #4338ca;">${s.specialty || (s as any).academicDegree || 'طبيب استشاري/مشرف'}</td>
            <td style="color: #0f766e; font-size: 11.5px;">🤝 ${universities}</td>
            <td style="text-align: center; font-size: 11px;">${worksAtCrescent}</td>
            <td style="font-size: 11.5px;">${days}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td dir="ltr" style="text-align: center; font-size: 11px;">${s.nationalId || (s as any).idNumber || '—'}</td>
            <td style="text-align: center;">
              <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                ${statusText}
              </span>
            </td>
          </tr>
        `;
      }

      if (cfg.tableType === 'nursing_trainers') {
        const contractedUni = normalizeUniversityName(
          s.contractedUniversity ||
          (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
          s.previousContractedUniversity ||
          s.university
        );
        const gradUni = normalizeUniversityName(s.graduatedUniversity || (s.contractedUniversity !== s.university ? s.university : '') || '—');

        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #4c1d95;">🤝 ${contractedUni}</td>
            <td style="font-size: 11px; color: #0f766e;">🎓 ${gradUni}</td>
            <td>${s.department || s.originalDepartment || 'تدريب تمريض الجامعات'}</td>
            <td dir="ltr" style="text-align: center;">${s.startDate || s.globalStartDate || '—'}</td>
            <td dir="ltr" style="text-align: center;">${s.endDate || s.globalEndDate || '—'}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td style="text-align: center; font-size: 11px;">${s.internshipYear || s.studySystem || 'مدرب سريري'}</td>
            <td style="text-align: center;">
              <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                ${statusText}
              </span>
            </td>
          </tr>
        `;
      }

      if (cfg.tableType === 'medical') {
        const shiftGroup = (s as any).rotationGroup || (s as any).shiftSchedule || 'دوام سريري رسمي';
        const studySys = s.studySystem ? `نظام ${s.studySystem}` : 'نظام 5+2';
        const gradYear = (s as any).graduatedYear || (s as any).graduationYear || '—';

        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #8B1A2B;">${s.department || s.originalDepartment || cfg.name}</td>
            <td style="font-size: 11.5px; color: #475569;">${shiftGroup}</td>
            <td style="font-weight: 700; color: #1e3a8a;">${normalizeUniversityName(s.university)}</td>
            <td style="text-align: center; font-size: 11px;">${gradYear}</td>
            <td style="text-align: center; font-weight: 700; color: #0f766e; font-size: 11px;">${studySys}</td>
            <td dir="ltr" style="text-align: center;">${s.startDate || s.globalStartDate || '—'}</td>
            <td dir="ltr" style="text-align: center;">${s.endDate || s.globalEndDate || '—'}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td style="text-align: center;">
              <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                ${statusText}
              </span>
            </td>
          </tr>
        `;
      }

      if (cfg.tableType === 'nursing') {
        const supervisor = (s as any).supervisorName || (s as any).trainerName || 'مشرف القسم السريري';
        const rotation = s.internshipYear || s.studySystem || 'تدريب عملي سريري';

        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #0284c7;">${s.department || s.originalDepartment || cfg.name}</td>
            <td style="font-weight: 700; color: #0369a1;">${normalizeUniversityName(s.university)}</td>
            <td style="font-size: 11.5px; color: #475569;">${supervisor}</td>
            <td style="text-align: center; font-size: 11.5px;">${rotation}</td>
            <td dir="ltr" style="text-align: center;">${s.startDate || s.globalStartDate || '—'}</td>
            <td dir="ltr" style="text-align: center;">${s.endDate || s.globalEndDate || '—'}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td style="text-align: center;">
              <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                ${statusText}
              </span>
            </td>
          </tr>
        `;
      }

      if (cfg.tableType === 'allied') {
        const subUnit = s.specialty || s.department || cfg.name;
        const nature = s.studySystem || 'امتياز وتدريب عملي';

        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #0d9488;">${subUnit}</td>
            <td style="font-weight: 700; color: #115e59;">${normalizeUniversityName(s.university)}</td>
            <td style="font-size: 11.5px;">${nature}</td>
            <td style="font-size: 11.5px;">${(s as any).rotationGroup || 'دوام مساند مقرر'}</td>
            <td dir="ltr" style="text-align: center;">${s.startDate || s.globalStartDate || '—'}</td>
            <td dir="ltr" style="text-align: center;">${s.endDate || s.globalEndDate || '—'}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td style="text-align: center;">
              <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                ${statusText}
              </span>
            </td>
          </tr>
        `;
      }

      if (cfg.tableType === 'admin') {
        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #475569;">${s.department || s.originalDepartment || cfg.name}</td>
            <td style="font-weight: 700; color: #1e293b;">${normalizeUniversityName(s.university)}</td>
            <td style="font-size: 11.5px;">${s.specialty || 'إدارة مستشفيات وتطوير خدمات'}</td>
            <td style="font-size: 11.5px;">${(s as any).rotationGroup || 'دوام إداري رسمي'}</td>
            <td dir="ltr" style="text-align: center;">${s.startDate || s.globalStartDate || '—'}</td>
            <td dir="ltr" style="text-align: center;">${s.endDate || s.globalEndDate || '—'}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td style="text-align: center;">
              <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                ${statusText}
              </span>
            </td>
          </tr>
        `;
      }

      if (cfg.tableType === 'graduates') {
        return `
          <tr>
            <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
            <td><strong>${s.name}</strong></td>
            <td style="font-weight: 700; color: #15803d;">${s.department || s.originalDepartment || 'قسم سريري مكتمل'}</td>
            <td dir="ltr" style="text-align: center; font-weight: 700;">${s.endDate || s.globalEndDate || '—'}</td>
            <td style="font-weight: 700; color: #1e3a8a;">${normalizeUniversityName(s.university)}</td>
            <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
            <td dir="ltr" style="text-align: center; font-size: 11px;">${s.nationalId || (s as any).idNumber || '—'}</td>
            <td style="text-align: center;">
              <span style="background: #dcfce7; color: #15803d; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
                أنهى التدريب بنجاح ✓
              </span>
            </td>
          </tr>
        `;
      }

      // Default General Table Row
      return `
        <tr>
          <td style="text-align: center; font-weight: 700;">${idx + 1}</td>
          <td><strong>${s.name}</strong></td>
          <td style="font-weight: 700;">${s.department || s.originalDepartment || '—'}</td>
          <td style="color: #1e3a8a; font-weight: 700;">${normalizeUniversityName(s.university)}</td>
          <td style="font-size: 11.5px; color: #475569;">${cfg.category}</td>
          <td dir="ltr" style="text-align: center;">${s.startDate || s.globalStartDate || '—'}</td>
          <td dir="ltr" style="text-align: center;">${s.endDate || s.globalEndDate || '—'}</td>
          <td dir="ltr" style="text-align: center; font-family: monospace;">${s.phone || '—'}</td>
          <td style="text-align: center;">
            <span style="background: ${statusBg}; color: ${statusColor}; padding: 3px 8px; border-radius: 6px; font-weight: 700; font-size: 11px;">
              ${statusText}
            </span>
          </td>
        </tr>
      `;
    }).join('');

    // Table Header HTML based on table type
    let tableHeadersHtml = '';
    if (cfg.tableType === 'contracted_doctors') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم الطبيب المتعاقد / الاستشاري</th>
          <th>التخصص الطبي الدقيق</th>
          <th>المؤسسات والجامعات الشريكة</th>
          <th style="text-align: center;">طاقم الهلال الأحمر</th>
          <th>أيام الدوام والعيادات</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">رقم الهوية</th>
          <th style="text-align: center;">الحالة</th>
        </tr>
      `;
    } else if (cfg.tableType === 'nursing_trainers') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم المدرب السريري</th>
          <th style="color: #4c1d95;">🤝 الجامعة الشريكة (شراكة)</th>
          <th style="color: #0f766e;">🎓 الجامعة المتخرج منها (مؤهل)</th>
          <th>القسم المخصص للتدريب</th>
          <th style="text-align: center;">تاريخ البدء</th>
          <th style="text-align: center;">تاريخ الانتهاء</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">المسمى التدريبي</th>
          <th style="text-align: center;">الحالة</th>
        </tr>
      `;
    } else if (cfg.tableType === 'medical') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم طبيب الامتياز</th>
          <th>القسم السريري</th>
          <th>مجموعة ومناوبات الدوام</th>
          <th>الجامعة الطبية والدولة</th>
          <th style="text-align: center;">سنة التخرج</th>
          <th style="text-align: center;">نظام الدراسة</th>
          <th style="text-align: center;">تاريخ البدء</th>
          <th style="text-align: center;">تاريخ الانتهاء</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">الحالة السريرية</th>
        </tr>
      `;
    } else if (cfg.tableType === 'nursing') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم المتدرب / طالب التمريض</th>
          <th>القسم السريري</th>
          <th>كلية التمريض / الجامعة</th>
          <th>المشرف السريري المسؤول</th>
          <th style="text-align: center;">المرحلة / الروتيشن</th>
          <th style="text-align: center;">تاريخ البدء</th>
          <th style="text-align: center;">تاريخ الانتهاء</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">الحالة</th>
        </tr>
      `;
    } else if (cfg.tableType === 'allied') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم المتدرب / الأخصائي</th>
          <th>التخصص / الوحدة المخبرية</th>
          <th>الجامعة / الكلية</th>
          <th>طبيعة التدريب المساند</th>
          <th>أيام الحضور والدوام</th>
          <th style="text-align: center;">تاريخ البدء</th>
          <th style="text-align: center;">تاريخ الانتهاء</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">الحالة</th>
        </tr>
      `;
    } else if (cfg.tableType === 'admin') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم المتدرب الإداري</th>
          <th>الوحدة الإدارية</th>
          <th>المؤهل والجامعة</th>
          <th>طبيعة المهام والمسؤوليات</th>
          <th>أيام الدوام</th>
          <th style="text-align: center;">تاريخ البدء</th>
          <th style="text-align: center;">تاريخ الانتهاء</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">الحالة</th>
        </tr>
      `;
    } else if (cfg.tableType === 'graduates') {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>اسم الخريج المعتمد</th>
          <th>القسم التدريبي المكتمل</th>
          <th style="text-align: center;">تاريخ إتمام التدريب</th>
          <th>الجامعة / الكلية</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">رقم الهوية</th>
          <th style="text-align: center;">الحالة المعتمدة</th>
        </tr>
      `;
    } else {
      tableHeadersHtml = `
        <tr>
          <th style="width: 35px; text-align: center;">#</th>
          <th>الاسم الكامل</th>
          <th>القسم</th>
          <th>الجامعة / الكلية</th>
          <th>التصنيف والفئة</th>
          <th style="text-align: center;">تاريخ البدء</th>
          <th style="text-align: center;">تاريخ الانتهاء</th>
          <th style="text-align: center;">رقم الهاتف</th>
          <th style="text-align: center;">الحالة</th>
        </tr>
      `;
    }

    // Secondary distribution table (Universities)
    const uniRowsHtml = uniStats.map((u, i) => `
      <tr>
        <td style="text-align: center; font-weight: 700;">${i + 1}</td>
        <td><strong>${u.name}</strong></td>
        <td style="text-align: center; font-weight: 800; color: #1e3a8a; font-size: 13.5px;">${u.total}</td>
        <td style="text-align: center; color: #15803d; font-weight: 700;">${u.active}</td>
        <td style="text-align: center; color: #64748b;">${u.completed}</td>
        <td style="text-align: center; color: #b45309;">${u.upcoming}</td>
        <td style="text-align: center; font-weight: 700;">${u.percentage}%</td>
      </tr>
    `).join('');

    // Additional mini analytics (Medical study systems or Contracted specialties)
    let extraAnalyticsHtml = '';
    if (cfg.tableType === 'medical') {
      extraAnalyticsHtml = `
        <div style="margin-top: 18px; background: #f8fafc; border: 1.5px solid #cbd5e1; border-radius: 12px; padding: 14px 18px;">
          <h4 style="margin: 0 0 10px 0; color: #8B1A2B; font-size: 14px; font-weight: 800;">
            🩺 توزيع أطباء الامتياز حسب نظام الدراسة المعتمد
          </h4>
          <div style="display: flex; gap: 20px; font-size: 13px;">
            <div style="background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px 16px;">
              <strong>نظام 5+2 (دراسة 5 سنوات + سنتان تدريب):</strong> 
              <span style="color: #8B1A2B; font-weight: 800; font-size: 15px; margin-right: 6px;">${sys5_2} طبيب</span>
            </div>
            <div style="background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px 16px;">
              <strong>نظام 6+1 (دراسة 6 سنوات + سنة امتياز):</strong> 
              <span style="color: #0f766e; font-weight: 800; font-size: 15px; margin-right: 6px;">${sys6_1} طبيب</span>
            </div>
          </div>
        </div>
      `;
    } else if (cfg.tableType === 'contracted_doctors') {
      const specRows = Object.keys(specMap).map(sp => `
        <span style="background: white; border: 1px solid #c7d2fe; border-radius: 8px; padding: 5px 12px; font-size: 12px; font-weight: 700; color: #3730a3;">
          ${sp}: <strong>${specMap[sp]}</strong>
        </span>
      `).join(' ');
      extraAnalyticsHtml = `
        <div style="margin-top: 18px; background: #eef2ff; border: 1.5px solid #c7d2fe; border-radius: 12px; padding: 14px 18px;">
          <h4 style="margin: 0 0 10px 0; color: #3730a3; font-size: 14px; font-weight: 800;">
            🩺 التوزيع حسب التخصصات الطبية للأطباء المتعاقدين
          </h4>
          <div style="display: flex; gap: 10px; flex-wrap: wrap;">
            ${specRows}
          </div>
        </div>
      `;
    }

    const reportTitle = `التقرير الإحصائي التخصصي المعتمد — ${cfg.name}`;
    const primaryThemeColor = cfg.color || '#8B1A2B';

    printWindow.document.write(`
      <html dir="rtl">
      <head>
        <title>${reportTitle}</title>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700;800;900&display=swap');
          body { font-family: 'Tajawal', sans-serif; padding: 25px; direction: rtl; color: #1e293b; background: #fff; }
          .header { text-align: center; border-bottom: 3.5px solid ${primaryThemeColor}; padding-bottom: 16px; margin-bottom: 22px; position: relative; }
          .header h1 { color: #8B1A2B; margin: 0 0 6px 0; font-size: 24px; font-weight: 900; }
          .header h2 { color: ${primaryThemeColor}; margin: 0 0 8px 0; font-size: 20px; font-weight: 800; }
          .header .badge { display: inline-block; background: #f8fafc; color: ${primaryThemeColor}; padding: 5px 16px; border-radius: 20px; font-size: 13.5px; font-weight: 800; border: 1.5px solid ${primaryThemeColor}40; margin-bottom: 6px; }
          .header .meta { color: #64748b; font-size: 13px; font-weight: 700; margin-top: 4px; }
          .stats-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; margin-bottom: 22px; }
          .stat-box { background: #f8fafc; border: 1.5px solid #cbd5e1; border-radius: 12px; padding: 12px 10px; text-align: center; }
          .stat-num { font-size: 22px; font-weight: 900; color: ${primaryThemeColor}; }
          .stat-label { font-size: 11.5px; color: #475569; font-weight: 700; margin-top: 4px; }
          table { width: 100%; border-collapse: collapse; margin-top: 14px; font-size: 12px; }
          th, td { border: 1px solid #cbd5e1; padding: 7px 9px; text-align: right; }
          th { background: #f1f5f9; color: #0f172a; font-weight: 800; }
          .section-title { font-size: 15px; font-weight: 800; color: ${primaryThemeColor}; margin: 24px 0 10px 0; border-right: 5px solid ${primaryThemeColor}; padding-right: 10px; display: flex; align-items: center; gap: 6px; }
          .footer { margin-top: 40px; display: flex; justify-content: space-between; align-items: flex-end; border-top: 1.5px solid #cbd5e1; padding-top: 18px; }
          @media print {
            @page { margin: 1cm; size: A4 landscape; }
            body { padding: 0; }
            .no-print { display: none !important; }
          }
        </style>
      </head>
      <body>
        <div class="no-print" style="margin-bottom: 18px; display: flex; gap: 10px; justify-content: flex-end;">
          <button onclick="window.print()" style="background: ${primaryThemeColor}; color: white; border: none; padding: 9px 22px; border-radius: 8px; font-weight: 800; cursor: pointer; font-family: Tajawal; font-size: 14px;">
            🖨️ طباعة التقرير الرسمي المعتمد (A4)
          </button>
          <button onclick="window.close()" style="background: #e2e8f0; color: #334155; border: none; padding: 9px 18px; border-radius: 8px; font-weight: 700; cursor: pointer; font-family: Tajawal; font-size: 14px;">
            ✕ إغلاق
          </button>
        </div>

        <div class="header">
          <h1>مستشفى الهلال الأحمر التخصصي — الخليل</h1>
          <div class="badge">
            ${cfg.category} • ${cfg.description}
          </div>
          <h2>${reportTitle}</h2>
          <div class="meta">${periodText} • استخراج معتمد: ${new Date().toLocaleDateString('ar-EG')} • وحدة التطوير والتدريب والتعليم المستمر</div>
        </div>

        {/* Specialized KPI Box */}
        <div class="stats-grid">
          <div class="stat-box" style="border-color: ${primaryThemeColor}50;">
            <div class="stat-num" style="color: ${primaryThemeColor};">${targetStudents.length}</div>
            <div class="stat-label">إجمالي السجلات المقيدة</div>
          </div>
          <div class="stat-box" style="border-color: #86efac;">
            <div class="stat-num" style="color: #15803d;">${activeList.length}</div>
            <div class="stat-label">🟢 على رأس العمل (نشط)</div>
          </div>
          <div class="stat-box" style="border-color: #cbd5e1;">
            <div class="stat-num" style="color: #475569;">${completedList.length}</div>
            <div class="stat-label">⚪ أنهوا الفترة (مغادر)</div>
          </div>
          <div class="stat-box" style="border-color: #fde68a;">
            <div class="stat-num" style="color: #b45309;">${upcomingList.length}</div>
            <div class="stat-label">🟡 فترات قادمة (مجدول)</div>
          </div>
          <div class="stat-box" style="border-color: #93c5fd;">
            <div class="stat-num" style="color: #1d4ed8;">${uniStats.length}</div>
            <div class="stat-label">المؤسسات الأكاديمية الشريكة</div>
          </div>
        </div>

        ${extraAnalyticsHtml}

        <!-- Dedicated Section: Primary Student / Staff Table -->
        <div class="section-title">
          📋 الكشف التفصيلي للأسماء وبيانات التدريب والاتصال — ${cfg.name} (${targetStudents.length} سجل)
        </div>
        <table>
          <thead>
            ${tableHeadersHtml}
          </thead>
          <tbody>
            ${tableRowsHtml || '<tr><td colspan="11" style="text-align: center; padding: 22px; color: #64748b;">لا توجد سجلات مسجلة في هذا القسم للفترة المحددة</td></tr>'}
          </tbody>
        </table>

        <!-- Dedicated Section: Universities Distribution -->
        <div class="section-title">
          🏛️ التوزيع الإحصائي للكوادر والمتدربين حسب المؤسسات التعليمية والجامعات
        </div>
        <table>
          <thead>
            <tr>
              <th style="width: 35px; text-align: center;">#</th>
              <th>المؤسسة التعليمية / الجامعة الشريكة</th>
              <th style="text-align: center;">إجمالي الملتحقين</th>
              <th style="text-align: center;">🟢 نشط</th>
              <th style="text-align: center;">⚪ أنهى التدريب</th>
              <th style="text-align: center;">🟡 قادم</th>
              <th style="text-align: center;">النسبة المئوية</th>
            </tr>
          </thead>
          <tbody>
            ${uniRowsHtml || '<tr><td colspan="7" style="text-align: center; padding: 14px;">لا توجد بيانات للمؤسسات</td></tr>'}
          </tbody>
        </table>

        <!-- Official 3-Signature Approvals Block -->
        <div class="footer">
          <div style="font-weight: 700; color: #1b5e20; font-size: 13px; line-height: 1.6; text-align: center;">
            مسؤولة وحدة التدريب والتطوير<br/>
            <strong>أ. نسرين عابدين</strong>
          </div>
          <div style="font-weight: 700; color: #334155; font-size: 13px; line-height: 1.6; text-align: center;">
            المدير الطبي<br/>
            <strong>د. خالد سراحنة</strong>
          </div>
          <div style="font-weight: 700; color: #15803d; font-size: 13px; line-height: 1.6; text-align: center;">
            رئيس الجمعية<br/>
            <strong>د. طارق الجعبري</strong>
          </div>
        </div>

        <script>
          window.onload = function() {
            setTimeout(function() {
              window.focus();
              window.print();
            }, 400);
          };
        </script>
      </body>
      </html>
    `);
    printWindow.document.close();
  };

  // ═════════════════════════════════════════════════════════════════════════════════
  // 📥 DEDICATED CSV EXPORT: SPECIALIZED HEADERS & COLUMNS FOR EVERY DEPARTMENT
  // ═════════════════════════════════════════════════════════════════════════════════
  const exportDedicatedDepartmentCSV = (targetDeptKey?: string) => {
    const deptKey = targetDeptKey || reportDept || 'All';
    const cfg = getDeptConfig(deptKey);

    let targetStudents: Student[] = [];
    if (targetDeptKey && targetDeptKey !== reportDept) {
      if (deptKey === 'All') {
        targetStudents = allStatisticalStudents;
      } else if (deptKey.startsWith('CATEGORY_ALL_')) {
        const cat = deptKey.replace('CATEGORY_ALL_', '');
        targetStudents = allStatisticalStudents.filter(s => {
          const c = getDeptConfig(s.department || s.originalDepartment || '');
          return c.category === cat;
        });
      } else if (deptKey === 'الأطباء المتعاقدون' || deptKey === 'contracted_doctors') {
        targetStudents = allStatisticalStudents.filter(s => isContractedDoctor(s));
      } else if (deptKey === 'تدريب تمريض الجامعات' || deptKey === 'nursing_trainers') {
        targetStudents = allStatisticalStudents.filter(s => isNursingTrainer(s));
      } else if (deptKey === 'خريجون مكتملون' || deptKey === 'graduates' || deptKey === 'المغادرين') {
        targetStudents = allStatisticalStudents.filter(s => s.computedStatus === 'completed' || s.folderKey === 'المغادرين' || s.isGraduated);
      } else {
        targetStudents = allStatisticalStudents.filter(s => (s.department || s.originalDepartment || s.folderKey) === deptKey);
      }
    } else {
      targetStudents = reportFilteredStudents;
    }

    if (trainerUniFilter && (cfg.tableType === 'nursing_trainers' || cfg.tableType === 'contracted_doctors')) {
      targetStudents = targetStudents.filter(s => {
        const u = normalizeUniversityName(
          s.contractedUniversity ||
          (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
          s.previousContractedUniversity ||
          s.university
        );
        return u === trainerUniFilter;
      });
    }

    if (targetStudents.length === 0) {
      alert(`لا توجد بيانات مسجلة في قسم "${cfg.name}" لتصديرها`);
      return;
    }

    let headers: string[] = [];
    let rows: any[][] = [];

    if (cfg.tableType === 'contracted_doctors') {
      headers = ['#', 'اسم الطبيب المتعاقد / الاستشاري', 'التخصص الدقيق', 'المؤسسات والجامعات الشريكة', 'يعمل بمستشفى الهلال', 'أيام الدوام والعيادات', 'رقم الهاتف', 'رقم الهوية', 'الحالة'];
      rows = targetStudents.map((s, idx) => {
        const statusLabel = s.computedStatus === 'upcoming' ? 'قادم (مجدول)' : s.computedStatus === 'completed' ? 'أنهى التعاقد' : 'نشط (على رأس العمل)';
        const universities = Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0
          ? s.contractedUniversities.join('، ')
          : (s.contractedUniversity || s.university || '');
        const crescent = (s as any).workingAtCrescent !== false ? 'نعم' : 'لا';
        const days = Array.isArray((s as any).workDays) ? (s as any).workDays.join('، ') : ((s as any).clinicSchedule || '');
        return [
          idx + 1,
          `"${s.name || ''}"`,
          `"${s.specialty || (s as any).academicDegree || 'طبيب استشاري'}"`,
          `"${universities}"`,
          `"${crescent}"`,
          `"${days}"`,
          `"${s.phone || ''}"`,
          `"${s.nationalId || (s as any).idNumber || ''}"`,
          `"${statusLabel}"`
        ];
      });
    } else if (cfg.tableType === 'nursing_trainers') {
      headers = ['#', 'اسم المدرب السريري', 'الجامعة الشريكة (شراكة)', 'الجامعة المتخرج منها', 'القسم المخصص للتدريب', 'تاريخ البدء', 'تاريخ الانتهاء', 'رقم الهاتف', 'المسمى التدريبي', 'الحالة'];
      rows = targetStudents.map((s, idx) => {
        const statusLabel = s.computedStatus === 'upcoming' ? 'قادم (مجدول)' : s.computedStatus === 'completed' ? 'أنهى الإشراف' : 'نشط (على رأس العمل)';
        const contractedUni = normalizeUniversityName(s.contractedUniversity || (Array.isArray(s.contractedUniversities) ? s.contractedUniversities[0] : '') || s.university);
        const gradUni = normalizeUniversityName(s.graduatedUniversity || '');
        return [
          idx + 1,
          `"${s.name || ''}"`,
          `"${contractedUni}"`,
          `"${gradUni}"`,
          `"${s.department || s.originalDepartment || 'تدريب تمريض الجامعات'}"`,
          `"${s.startDate || s.globalStartDate || ''}"`,
          `"${s.endDate || s.globalEndDate || ''}"`,
          `"${s.phone || ''}"`,
          `"${s.internshipYear || s.studySystem || 'مدرب سريري'}"`,
          `"${statusLabel}"`
        ];
      });
    } else if (cfg.tableType === 'medical') {
      headers = ['#', 'اسم طبيب الامتياز', 'القسم السريري', 'مجموعة ومناوبات الدوام', 'الجامعة الطبية ودولة الدراسة', 'سنة التخرج', 'نظام الدراسة', 'تاريخ البدء', 'تاريخ الانتهاء', 'الهاتف', 'الحالة'];
      rows = targetStudents.map((s, idx) => {
        const statusLabel = s.computedStatus === 'upcoming' ? 'مجدول (قادم)' : s.computedStatus === 'completed' ? 'أنهى الدورة السريرية' : 'نشط (على رأس العمل)';
        return [
          idx + 1,
          `"${s.name || ''}"`,
          `"${s.department || s.originalDepartment || cfg.name}"`,
          `"${(s as any).rotationGroup || (s as any).shiftSchedule || 'دوام سريري'}"`,
          `"${normalizeUniversityName(s.university)}"`,
          `"${(s as any).graduatedYear || (s as any).graduationYear || ''}"`,
          `"${s.studySystem || '5+2'}"`,
          `"${s.startDate || s.globalStartDate || ''}"`,
          `"${s.endDate || s.globalEndDate || ''}"`,
          `"${s.phone || ''}"`,
          `"${statusLabel}"`
        ];
      });
    } else if (cfg.tableType === 'graduates') {
      headers = ['#', 'اسم الخريج المعتمد', 'القسم التدريبي المكتمل', 'تاريخ إتمام التدريب', 'الجامعة / الكلية', 'رقم الهاتف', 'رقم الهوية', 'الحالة'];
      rows = targetStudents.map((s, idx) => [
        idx + 1,
        `"${s.name || ''}"`,
        `"${s.department || s.originalDepartment || 'قسم سريري مكتمل'}"`,
        `"${s.endDate || s.globalEndDate || ''}"`,
        `"${normalizeUniversityName(s.university)}"`,
        `"${s.phone || ''}"`,
        `"${s.nationalId || (s as any).idNumber || ''}"`,
        `"أنهى التدريب بنجاح ✓"`
      ]);
    } else {
      headers = ['#', 'الاسم الكامل', 'القسم', 'الجامعة / الكلية', 'التصنيف', 'تاريخ البدء', 'تاريخ الانتهاء', 'الهاتف', 'الحالة'];
      rows = targetStudents.map((s, idx) => {
        const statusLabel = s.computedStatus === 'upcoming' ? 'مجدول (قادم)' : s.computedStatus === 'completed' ? 'أنهى التدريب' : 'نشط (على رأس العمل)';
        return [
          idx + 1,
          `"${s.name || ''}"`,
          `"${s.department || s.originalDepartment || ''}"`,
          `"${normalizeUniversityName(s.university)}"`,
          `"${cfg.category}"`,
          `"${s.startDate || s.globalStartDate || ''}"`,
          `"${s.endDate || s.globalEndDate || ''}"`,
          `"${s.phone || ''}"`,
          `"${statusLabel}"`
        ];
      });
    }

    const csvContent = '\uFEFF' + [headers.join(','), ...rows.map(e => e.join(','))].join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    const cleanDeptName = (cfg.shortName || cfg.name || deptKey).replace(/[/\\?%*:|"<>]/g, '_');
    link.setAttribute('download', `تقرير_إحصائي_خاص_${cleanDeptName}_${new Date().toISOString().split('T')[0]}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showToast(`تم تصدير تقرير قسم "${cfg.name}" بنجاح ✓`);
  };

  // ═══════════ Backward-Compatibility Wrappers ═══════════
  const printStatisticalReport = (mode?: 'all' | 'trainees' | 'trainers') => {
    if (mode === 'trainers') {
      printDedicatedDepartmentReport('تدريب تمريض الجامعات');
    } else {
      printDedicatedDepartmentReport();
    }
  };
  const printNursingTrainersReport = () => printDedicatedDepartmentReport('تدريب تمريض الجامعات');
  const exportStatisticalReportCSV = () => exportDedicatedDepartmentCSV();
  const exportNursingTrainersCSV = () => exportDedicatedDepartmentCSV('تدريب تمريض الجامعات');


  return (
    <div className="dashboard-container">
      {/* Header */}
      <div className="header" style={{ 
        background: 'linear-gradient(145deg, #1B1B2F 0%, #2D1F30 30%, #8B1A2B 70%, #6B0F1D 100%)',
        padding: '0',
        position: 'relative',
        overflow: 'hidden'
      }}>
        {/* Decorative Background Pattern */}
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, opacity: 0.06, pointerEvents: 'none' }}>
          <div style={{ position: 'absolute', top: '-30px', right: '-30px', width: '200px', height: '200px', border: '3px solid white', borderRadius: '50%' }}></div>
          <div style={{ position: 'absolute', bottom: '-50px', left: '-50px', width: '250px', height: '250px', border: '3px solid white', borderRadius: '50%' }}></div>
          <div style={{ position: 'absolute', top: '20px', left: '50%', width: '150px', height: '150px', border: '2px solid white', borderRadius: '50%' }}></div>
        </div>

        {/* Top Bar with Controls */}
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center', 
          flexWrap: 'wrap',
          gap: '12px',
          padding: '12px 25px', 
          borderBottom: '1px solid rgba(255,255,255,0.15)',
          position: 'relative',
          zIndex: 2
        }}>
          {/* Right side: User info + Logout */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
            {currentUser && (
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: '8px',
                  background: 'rgba(212,175,55,0.15)', padding: '6px 14px',
                  borderRadius: '10px', border: '1px solid rgba(212,175,55,0.3)'
                }}>
                  <i className="fas fa-user-circle" style={{ color: '#D4AF37', fontSize: '1rem' }}></i>
                  <span style={{ color: '#E8D5A8', fontSize: '0.85rem', fontWeight: '600' }}>{currentUser.displayName}</span>
                  {lastSynced && <span style={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.65rem', marginRight: '4px' }}>⚡ {lastSynced}</span>}
                </div>

                {/* Online Users Indicator */}
                {onlineUsers.length > 0 && (
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: '6px',
                    background: 'rgba(46,204,113,0.1)', padding: '6px 14px',
                    borderRadius: '10px', border: '1px solid rgba(46,204,113,0.3)'
                  }}>
                    <div style={{
                      width: '8px', height: '8px', borderRadius: '50%',
                      background: '#2ecc71', boxShadow: '0 0 8px #2ecc71',
                      animation: 'pulse 2s ease-in-out infinite'
                    }} />
                    <span style={{ color: 'rgba(46,204,113,0.9)', fontSize: '0.75rem', fontWeight: '600' }}>
                      {onlineUsers.map(u => u.displayName).join(' ، ')}
                    </span>
                    <span style={{ color: 'rgba(255,255,255,0.3)', fontSize: '0.65rem' }}>({onlineUsers.length} متصل)</span>
                  </div>
                )}

                <button onClick={handleLogout} style={{
                  background: 'rgba(231,76,60,0.2)', border: '1px solid rgba(231,76,60,0.4)',
                  color: '#e74c3c', padding: '6px 12px', borderRadius: '10px', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.8rem',
                  fontFamily: 'Tajawal, sans-serif', transition: 'all 0.3s'
                }}>
                  <i className="fas fa-sign-out-alt"></i>
                  <span>خروج</span>
                </button>
              </div>
            )}
          </div>

          {/* Left side: Controls & Reports */}
          <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
            {/* ══════ الزر الذهبي البارز — تقرير الجامعات الشريكة ══════ */}
            <button
              onClick={() => setShowUniStatsModal(true)}
              style={{
                background: 'linear-gradient(135deg, #78350f 0%, #b45309 45%, #d97706 80%, #f59e0b 100%)',
                border: '2px solid #ffd700',
                color: '#fff',
                padding: '8px 16px',
                borderRadius: '10px',
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                fontSize: '0.88rem',
                fontFamily: 'Tajawal, sans-serif',
                fontWeight: '900',
                cursor: 'pointer',
                boxShadow: '0 0 20px rgba(255,215,0,0.65), 0 4px 15px rgba(0,0,0,0.3)',
                transition: 'all 0.3s ease',
                letterSpacing: '0.3px',
                flexShrink: 0
              }}
              title="تقرير إحصائيات الجامعات الشريكة — الأطباء المتعاقدون وتمريض الجامعات"
            >
              <span style={{ fontSize: '1.2rem' }}>🏆</span>
              <span style={{ color: '#ffffff', fontWeight: '900' }}>تقرير الجامعات الشريكة</span>
              <span style={{
                background: '#ffd700',
                color: '#78350f',
                borderRadius: '12px',
                padding: '2px 8px',
                fontSize: '0.72rem',
                fontWeight: '900',
                boxShadow: '0 0 8px rgba(255,215,0,0.8)'
              }}>الذهبي ✨</span>
            </button>

            <button className="dark-mode-toggle" onClick={toggleDarkMode} style={{
              background: 'rgba(255,255,255,0.15)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255,255,255,0.2)',
              color: 'white',
              padding: '8px 14px',
              borderRadius: '10px',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              fontSize: '0.85rem',
              fontFamily: 'Tajawal, sans-serif',
              transition: 'all 0.3s ease'
            }}>
              <i className={`fas ${isDarkMode ? 'fa-sun' : 'fa-moon'}`}></i>
              <span style={{ color: '#E8D5A8' }}>{isDarkMode ? 'الوضع النهاري' : 'الوضع الليلي'}</span>
            </button>

            <button 
              onClick={() => setShowStatsReportModal(true)} 
              style={{
                background: 'rgba(255,255,255,0.12)',
                backdropFilter: 'blur(10px)',
                border: '1px solid rgba(255,255,255,0.25)',
                color: 'white',
                padding: '8px 14px',
                borderRadius: '10px',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                fontSize: '0.85rem',
                fontFamily: 'Tajawal, sans-serif',
                fontWeight: '700',
                transition: 'all 0.3s ease',
                boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
              }}
            >
              <i className="fas fa-chart-pie" style={{ color: '#ffd700' }}></i>
              <span>التقرير الإحصائي</span>
            </button>

            <Link href="/recruitment" style={{ 
              textDecoration: 'none', 
              background: 'linear-gradient(135deg, #059669 0%, #10B981 100%)',
              border: '1.5px solid rgba(255, 215, 0, 0.75)',
              color: 'white',
              padding: '8px 16px',
              borderRadius: '12px',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              fontSize: '0.9rem',
              fontWeight: '900',
              fontFamily: 'Tajawal, sans-serif',
              boxShadow: '0 0 15px rgba(16,185,129,0.4), 0 4px 15px rgba(0,0,0,0.2)',
              transition: 'all 0.3s ease'
            }}>
              <i className="fas fa-file-signature" style={{ color: '#ffd700', fontSize: '1rem' }}></i>
              <span>تقديم الطلبات</span>
            </Link>

            <Link href="/admin/applications" style={{ 
              textDecoration: 'none', 
              background: 'rgba(255,255,255,0.12)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255,255,255,0.25)',
              color: 'white',
              padding: '8px 14px',
              borderRadius: '10px',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              fontSize: '0.85rem',
              fontFamily: 'Tajawal, sans-serif',
              transition: 'all 0.3s ease'
            }}>
              <i className="fas fa-user-shield"></i>
              <span>إدارة الطلبات</span>
            </Link>

            {/* ══════ الزر المخصص لطلبات الجامعات والمتعاقدين ══════ */}
            <button 
              onClick={() => setShowUniversitiesModal(true)} 
              style={{ 
                background: 'linear-gradient(135deg, #1e1b4b 0%, #312e81 100%)',
                backdropFilter: 'blur(10px)',
                border: '1.5px solid rgba(168, 85, 247, 0.7)',
                color: 'white',
                padding: '8px 14px',
                borderRadius: '10px',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                fontSize: '0.85rem',
                fontFamily: 'Tajawal, sans-serif',
                fontWeight: '800',
                cursor: 'pointer',
                boxShadow: '0 0 15px rgba(168, 85, 247, 0.35), 0 4px 12px rgba(0,0,0,0.2)',
                transition: 'all 0.3s ease'
              }}
              title="عرض طلبات تدريب طلاب التمريض بالجامعات والأطباء المتعاقدون مع الجامعات"
            >
              <i className="fas fa-graduation-cap" style={{ color: '#c084fc', fontSize: '1rem' }}></i>
              <span>طلبات تدريب الجامعات</span>
              {universityApplications.length > 0 && (
                <span style={{
                  background: pendingUniCount > 0 ? '#ef4444' : '#10b981',
                  color: 'white',
                  borderRadius: '20px',
                  padding: '2px 8px',
                  fontSize: '0.75rem',
                  fontWeight: '900',
                  boxShadow: pendingUniCount > 0 ? '0 0 10px rgba(239, 68, 68, 0.7)' : 'none'
                }}>
                  {universityApplications.length}
                </span>
              )}
            </button>
          </div>
        </div>

        {/* ═══════════ Supervisor Badge - Prominent Top Left (Extra Large 110px & High-Res) ═══════════ */}
        <div style={{
          position: 'absolute',
          top: '75px',
          left: '25px',
          zIndex: 10,
          display: 'flex',
          alignItems: 'center',
          gap: '18px',
          background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.9) 0%, rgba(30, 41, 59, 0.88) 100%)',
          backdropFilter: 'blur(20px)',
          padding: '10px 26px 10px 14px',
          borderRadius: '70px',
          border: '2.5px solid rgba(255, 215, 0, 0.85)',
          boxShadow: '0 0 25px rgba(255,215,0,0.35), 0 15px 35px rgba(0,0,0,0.4)',
          transition: 'all 0.3s ease'
        }}>
          <img 
            src="/supervisor.png" 
            alt="أ. نسرين عابدين" 
            style={{
              width: '110px',
              height: '110px',
              borderRadius: '50%',
              objectFit: 'cover',
              objectPosition: 'center top',
              border: '4px solid #ffd700',
              boxShadow: '0 0 20px rgba(255,215,0,0.6), 0 8px 25px rgba(0,0,0,0.5)',
              background: '#ffffff'
            }} 
          />
          <div>
            <div style={{ fontSize: '0.95rem', color: '#ffd700', fontWeight: '800', letterSpacing: '0.6px', marginBottom: '4px' }}>
              وحدة التطوير والتدريب
            </div>
            <div style={{ fontSize: '1.45rem', color: '#ffffff', fontWeight: '900', display: 'flex', alignItems: 'center', gap: '8px', textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}>
              <i className="fas fa-star-and-crescent" style={{ fontSize: '1.1rem', color: '#ffd700' }}></i>
              بإشراف أ. نسرين عابدين
              <i className="fas fa-star-and-crescent" style={{ fontSize: '1.1rem', color: '#ffd700' }}></i>
            </div>
          </div>
        </div>

        {/* Main Header Content with Logo */}
        <div style={{ 
          display: 'flex', 
          flexDirection: 'column', 
          alignItems: 'center', 
          padding: '30px 20px 35px',
          position: 'relative',
          zIndex: 2
        }}>
          {/* Professional Logo */}
          <div style={{
            width: '120px',
            height: '120px',
            background: 'linear-gradient(145deg, #ffffff, #f5f0e8)',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: '0 12px 40px rgba(0,0,0,0.25), 0 0 0 3px rgba(200, 169, 110, 0.25), inset 0 2px 4px rgba(255,255,255,0.9)',
            marginBottom: '20px',
            position: 'relative'
          }}>
            {/* Rotating ring animation */}
            <div style={{
              position: 'absolute',
              top: '-6px', left: '-6px', right: '-6px', bottom: '-6px',
              borderRadius: '50%',
              border: '2px solid transparent',
              borderTopColor: 'rgba(200, 169, 110, 0.5)',
              borderBottomColor: 'rgba(200, 169, 110, 0.2)',
              animation: 'spin 8s linear infinite'
            }}></div>
            
            <img 
              src="/prcs-logo.png" 
              alt="جمعية الهلال الأحمر الفلسطيني" 
              style={{ 
                width: '90px', 
                height: '90px', 
                objectFit: 'contain',
                borderRadius: '50%'
              }} 
            />
          </div>

          {/* Hospital Name */}
          <h1 style={{ 
            color: 'white', 
            fontSize: '2rem', 
            fontWeight: '800', 
            marginBottom: '4px',
            textShadow: '0 2px 20px rgba(0,0,0,0.3)',
            letterSpacing: '1.5px'
          }}>
            مستشفى الهلال الأحمر
          </h1>
          
          <div style={{ 
            color: '#E8D5A8',
            fontSize: '1.1rem',
            letterSpacing: '2px',
            fontWeight: '600',
            marginBottom: '12px',
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}>
            <span style={{ width: '30px', height: '1px', background: 'rgba(255,255,255,0.5)', display: 'inline-block' }}></span>
            فلسطين
            <span style={{ width: '30px', height: '1px', background: 'rgba(255,255,255,0.5)', display: 'inline-block' }}></span>
          </div>

          {/* Dashboard Title */}
          <div style={{
            background: 'rgba(200, 169, 110, 0.12)',
            backdropFilter: 'blur(12px)',
            padding: '10px 30px',
            borderRadius: '30px',
            border: '1px solid rgba(200, 169, 110, 0.2)',
            marginTop: '5px'
          }}>
            <span style={{ color: 'white', fontSize: '1rem', fontWeight: '600' }}>
              <i className="fas fa-chart-bar" style={{ marginLeft: '8px' }}></i>
              قسم التطوير والتدريب
            </span>
          </div>
        </div>

        {/* Spin animation for logo ring */}
        <style jsx global>{`
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
          @keyframes fadeIn {
            from { opacity: 0; max-height: 0; }
            to { opacity: 1; max-height: 2000px; }
          }
        `}</style>
      </div>

      {/* Main View: Stats & Departments */}
      {!currentDepartment && (
        <>
          {/* ═══════════ CATEGORY-BASED DASHBOARD ═══════════ */}
          {!expandedCategory ? (
            <>
              {/* TOP STATS */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '16px', marginBottom: '24px' }}>
                <div onClick={() => setCurrentDepartment('All')} style={{
                  background: 'linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%)',
                  borderRadius: '20px', padding: '24px 20px', color: 'white', cursor: 'pointer',
                  position: 'relative', overflow: 'hidden', boxShadow: '0 10px 25px rgba(99, 102, 241, 0.3)',
                  transition: 'transform 0.3s ease, box-shadow 0.3s ease'
                }}
                onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 35px rgba(99, 102, 241, 0.45)'; }}
                onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(99, 102, 241, 0.3)'; }}
                >
                  <div style={{ position: 'absolute', top: '-20px', left: '-20px', width: '80px', height: '80px', background: 'rgba(255,255,255,0.15)', borderRadius: '50%' }}></div>
                  <i className="fas fa-users" style={{ fontSize: '1.5rem', marginBottom: '10px', display: 'block', position: 'relative', zIndex: 1 }}></i>
                  <div style={{ fontSize: '2.5rem', fontWeight: '900', lineHeight: 1, position: 'relative', zIndex: 1 }}>{totalCount}</div>
                  <div style={{ fontSize: '0.85rem', opacity: 0.9, marginTop: '6px', position: 'relative', zIndex: 1 }}>إجمالي المتدربين (جميع الأقسام)</div>
                </div>

                <div onClick={() => setCurrentDepartment('الجامعات')} style={{
                  background: 'linear-gradient(135deg, #D97706 0%, #B45309 100%)',
                  border: '1px solid rgba(255, 215, 0, 0.4)',
                  borderRadius: '20px', padding: '24px 20px', color: 'white', cursor: 'pointer',
                  position: 'relative', overflow: 'hidden', boxShadow: '0 10px 25px rgba(217, 119, 6, 0.25)',
                  transition: 'transform 0.3s ease, box-shadow 0.3s ease'
                }}
                onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 35px rgba(217, 119, 6, 0.4)'; }}
                onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(217, 119, 6, 0.25)'; }}
                >
                  <div style={{ position: 'absolute', top: '-20px', left: '-20px', width: '80px', height: '80px', background: 'rgba(255, 255, 255, 0.15)', borderRadius: '50%' }}></div>
                  <i className="fas fa-university" style={{ fontSize: '1.5rem', marginBottom: '10px', display: 'block', position: 'relative', zIndex: 1, color: '#ffffff' }}></i>
                  <div style={{ fontSize: '2.5rem', fontWeight: '900', lineHeight: 1, position: 'relative', zIndex: 1, color: '#FFFFFF' }}>{universityStats.length}</div>
                  <div style={{ fontSize: '0.95rem', fontWeight: 'bold', color: '#ffffff', marginTop: '6px', position: 'relative', zIndex: 1 }}>جامعة مختلفة</div>
                  <div style={{ fontSize: '0.75rem', opacity: 0.9, marginTop: '4px', position: 'relative', zIndex: 1 }}>تضم جميع المتدربين مسجلين بالجامعات</div>
                </div>

                {/* 🌟 الزر والبطاقة الذهبية البارزة — تقرير الجامعات الشريكة 🌟 */}
                <div 
                  onClick={() => {
                    setSelectedUniStatsName(null);
                    setShowUniStatsModal(true);
                  }} 
                  style={{
                    background: 'linear-gradient(135deg, #78350f 0%, #b45309 40%, #d97706 75%, #f59e0b 100%)',
                    border: '2.5px solid #ffd700',
                    borderRadius: '20px', 
                    padding: '22px 20px', 
                    color: 'white', 
                    cursor: 'pointer',
                    position: 'relative', 
                    overflow: 'hidden', 
                    boxShadow: '0 0 30px rgba(255, 215, 0, 0.45), 0 10px 25px rgba(0,0,0,0.3)',
                    transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between'
                  }}
                  onMouseOver={(e) => { 
                    e.currentTarget.style.transform = 'translateY(-5px) scale(1.02)'; 
                    e.currentTarget.style.boxShadow = '0 0 45px rgba(255, 215, 0, 0.75), 0 15px 35px rgba(0,0,0,0.4)'; 
                  }}
                  onMouseOut={(e) => { 
                    e.currentTarget.style.transform = 'translateY(0) scale(1)'; 
                    e.currentTarget.style.boxShadow = '0 0 30px rgba(255, 215, 0, 0.45), 0 10px 25px rgba(0,0,0,0.3)'; 
                  }}
                  title="اضغط لفتح التقرير الإحصائي الذهبي للجامعات الشريكة"
                >
                  <div style={{ position: 'absolute', top: '-20px', left: '-20px', width: '90px', height: '90px', background: 'rgba(255, 255, 255, 0.2)', borderRadius: '50%' }}></div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px', position: 'relative', zIndex: 1 }}>
                    <span style={{ fontSize: '2rem' }}>🏆</span>
                    <span style={{
                      background: 'rgba(0,0,0,0.35)',
                      border: '1.5px solid #ffd700',
                      borderRadius: '20px',
                      padding: '4px 12px',
                      fontSize: '0.8rem',
                      fontWeight: '900',
                      color: '#fef08a'
                    }}>
                      التقرير الذهبي ✨
                    </span>
                  </div>
                  <div>
                    <div style={{ fontSize: '1.45rem', fontWeight: '900', lineHeight: 1.25, position: 'relative', zIndex: 1, color: '#ffffff', textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}>
                      تقرير الجامعات الشريكة
                    </div>
                    <div style={{ fontSize: '0.88rem', fontWeight: '800', color: '#fef3c7', marginTop: '4px', position: 'relative', zIndex: 1 }}>
                      الأطباء المتعاقدون & تمريض الجامعات
                    </div>
                  </div>
                  {/* Selectable University Chips inside the Card */}
                  <div style={{ 
                    marginTop: '12px', 
                    position: 'relative', 
                    zIndex: 2,
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '6px'
                  }}>
                    <div style={{ fontSize: '0.78rem', color: '#fef08a', fontWeight: '800' }}>
                      اختر الجامعة لعرض أسمائها مباشرة:
                    </div>
                    <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                      <span 
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedUniStatsName('جامعة بوليتكنك فلسطين');
                          setShowUniStatsModal(true);
                        }}
                        style={{
                          background: 'rgba(37,99,235,0.5)',
                          border: '1px solid rgba(255,255,255,0.4)',
                          padding: '4px 10px',
                          borderRadius: '8px',
                          fontSize: '0.78rem',
                          fontWeight: '800',
                          color: '#fff',
                          cursor: 'pointer',
                          transition: 'all 0.2s',
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        onMouseOver={(e) => e.currentTarget.style.background = '#2563eb'}
                        onMouseOut={(e) => e.currentTarget.style.background = 'rgba(37,99,235,0.5)'}
                      >
                        🔬 البوليتكنك
                      </span>
                      <span 
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedUniStatsName('جامعة الخليل');
                          setShowUniStatsModal(true);
                        }}
                        style={{
                          background: 'rgba(220,38,38,0.5)',
                          border: '1px solid rgba(255,255,255,0.4)',
                          padding: '4px 10px',
                          borderRadius: '8px',
                          fontSize: '0.78rem',
                          fontWeight: '800',
                          color: '#fff',
                          cursor: 'pointer',
                          transition: 'all 0.2s',
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        onMouseOver={(e) => e.currentTarget.style.background = '#dc2626'}
                        onMouseOut={(e) => e.currentTarget.style.background = 'rgba(220,38,38,0.5)'}
                      >
                        🏛️ الخليل
                      </span>
                      <span 
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedUniStatsName('الكلية الذكية الجامعية للتعليم الحديث');
                          setShowUniStatsModal(true);
                        }}
                        style={{
                          background: 'rgba(124,58,237,0.5)',
                          border: '1px solid rgba(255,255,255,0.4)',
                          padding: '4px 10px',
                          borderRadius: '8px',
                          fontSize: '0.78rem',
                          fontWeight: '800',
                          color: '#fff',
                          cursor: 'pointer',
                          transition: 'all 0.2s',
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        onMouseOver={(e) => e.currentTarget.style.background = '#7c3aed'}
                        onMouseOut={(e) => e.currentTarget.style.background = 'rgba(124,58,237,0.5)'}
                      >
                        💡 الكلية الذكية
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Recruitment - Main Dashboard Only */}
              <Link href="/recruitment" style={{ textDecoration: 'none', display: 'block', marginBottom: '20px' }}>
                <div style={{
                  background: 'linear-gradient(135deg, #059669 0%, #047857 100%)',
                  borderRadius: '20px', padding: '24px 20px', color: 'white', cursor: 'pointer',
                  position: 'relative', overflow: 'hidden', boxShadow: '0 10px 25px rgba(5, 150, 105, 0.25)',
                  border: '1px solid rgba(255, 215, 0, 0.4)',
                  transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                  display: 'flex', alignItems: 'center', gap: '16px'
                }}
                onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 35px rgba(5, 150, 105, 0.4)'; }}
                onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(5, 150, 105, 0.25)'; }}
                >
                  <div style={{ position: 'absolute', top: '-20px', left: '-20px', width: '80px', height: '80px', background: 'rgba(255, 215, 0, 0.1)', borderRadius: '50%' }}></div>
                  <div style={{ background: 'rgba(255, 215, 0, 0.18)', borderRadius: '14px', padding: '12px', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', zIndex: 1 }}>
                    <i className="fas fa-file-signature" style={{ fontSize: '1.8rem', color: '#ffd700' }}></i>
                  </div>
                  <div style={{ position: 'relative', zIndex: 1 }}>
                    <div style={{ fontSize: '1.3rem', fontWeight: 800 }}>تقديم الطلبات</div>
                    <div style={{ fontSize: '0.85rem', opacity: 0.85, marginTop: '4px' }}>بوابة التدريب والتطوع — نماذج التقديم</div>
                  </div>
                  <i className="fas fa-arrow-left" style={{ marginRight: 'auto', fontSize: '1.2rem', opacity: 0.6, position: 'relative', zIndex: 1 }}></i>
                </div>
              </Link>

              {/* Documents & Certificates - Main Dashboard */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '20px' }}>
                <Link href="/certificate" style={{ textDecoration: 'none', display: 'block' }}>
                  <div style={{
                    background: 'linear-gradient(135deg, #4F46E5 0%, #6366F1 100%)',
                    borderRadius: '20px', padding: '22px 20px', color: 'white', cursor: 'pointer',
                    position: 'relative', overflow: 'hidden', boxShadow: '0 10px 25px rgba(79, 70, 229, 0.25)',
                    transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                    display: 'flex', alignItems: 'center', gap: '16px'
                  }}
                  onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 35px rgba(79, 70, 229, 0.35)'; }}
                  onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(79, 70, 229, 0.25)'; }}
                  >
                    <div style={{ position: 'absolute', top: '-20px', left: '-20px', width: '80px', height: '80px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }}></div>
                    <i className="fas fa-certificate" style={{ fontSize: '2rem', position: 'relative', zIndex: 1 }}></i>
                    <div style={{ position: 'relative', zIndex: 1 }}>
                      <div style={{ fontSize: '1.2rem', fontWeight: 800 }}>شهادات الخبرة</div>
                      <div style={{ fontSize: '0.8rem', opacity: 0.85, marginTop: '4px' }}>توليد وطباعة شهادات الخبرة</div>
                    </div>
                    <i className="fas fa-arrow-left" style={{ marginRight: 'auto', fontSize: '1rem', opacity: 0.5, position: 'relative', zIndex: 1 }}></i>
                  </div>
                </Link>

                <Link href="/idcard" style={{ textDecoration: 'none', display: 'block' }}>
                  <div style={{
                    background: 'linear-gradient(135deg, #059669 0%, #047857 100%)',
                    borderRadius: '20px', padding: '22px 20px', color: 'white', cursor: 'pointer',
                    position: 'relative', overflow: 'hidden', boxShadow: '0 10px 25px rgba(5, 150, 105, 0.25)',
                    transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                    display: 'flex', alignItems: 'center', gap: '16px'
                  }}
                  onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 35px rgba(5, 150, 105, 0.35)'; }}
                  onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(5, 150, 105, 0.25)'; }}
                  >
                    <div style={{ position: 'absolute', top: '-20px', left: '-20px', width: '80px', height: '80px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }}></div>
                    <i className="fas fa-id-badge" style={{ fontSize: '2rem', position: 'relative', zIndex: 1 }}></i>
                    <div style={{ position: 'relative', zIndex: 1 }}>
                      <div style={{ fontSize: '1.2rem', fontWeight: 800 }}>البطاقة الشخصية</div>
                      <div style={{ fontSize: '0.8rem', opacity: 0.85, marginTop: '4px' }}>طباعة بطاقات المتدربين</div>
                    </div>
                    <i className="fas fa-arrow-left" style={{ marginRight: 'auto', fontSize: '1rem', opacity: 0.5, position: 'relative', zIndex: 1 }}></i>
                  </div>
                </Link>
              </div>

              {/* ===== REDESIGNED END ALARM SYSTEM (DEPARTURE & TRAINING FINISH DASHBOARD) ===== */}
              {(() => {
                const today = new Date();
                today.setHours(0,0,0,0);

                // Robust Multi-format Date Parser
                const parseDateRobust = (raw?: string | null): Date | null => {
                  if (!raw || typeof raw !== 'string') return null;
                  const s = raw.trim();
                  if (!s) return null;

                  if (s.includes('/')) {
                    const parts = s.split('/').map(p => parseInt(p.trim(), 10));
                    if (parts.length === 3 && !parts.some(isNaN)) {
                      if (parts[0] > 1000) return new Date(parts[0], parts[1] - 1, parts[2]);
                      return new Date(parts[2], parts[1] - 1, parts[0]);
                    }
                  }

                  if (s.includes('-')) {
                    const parts = s.split('-').map(p => parseInt(p.trim(), 10));
                    if (parts.length === 3 && !parts.some(isNaN)) {
                      if (parts[0] > 1000) return new Date(parts[0], parts[1] - 1, parts[2]);
                      return new Date(parts[2], parts[1] - 1, parts[0]);
                    }
                  }

                  const dt = new Date(s);
                  return isNaN(dt.getTime()) ? null : dt;
                };

                interface LeaverItem {
                  student: Student;
                  originalIndex: number;
                  dept: string;
                  name: string;
                  endDate: string;
                  startDate: string;
                  daysLeft: number;
                  phone?: string;
                  university?: string;
                  idNumber?: string;
                }

                const allLeavers: LeaverItem[] = [];
                let totalOverdue = 0;
                let totalEndingToday = 0;
                let totalLeaving3 = 0;
                let totalLeaving7 = 0;
                let totalLeaving30 = 0;

                Object.entries(studentsData).forEach(([dept, students]) => {
                  if (dept === 'المغادرين' || dept === 'الاستئناف') return;
                  (students as Student[]).forEach((s: Student, studentIdx: number) => {
                    const rawEnd = (s as any).globalEndDate || (s as any).global_end_date || s.endDate || (s as any).end_date || '';
                    if (!rawEnd) return;
                    
                    const d = parseDateRobust(rawEnd);
                    if (!d) return;
                    d.setHours(0,0,0,0);

                    const diffDays = Math.ceil((d.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
                    
                    if (diffDays < 0) totalOverdue++;
                    if (diffDays === 0) totalEndingToday++;
                    if (diffDays <= 3) totalLeaving3++;
                    if (diffDays <= 7) totalLeaving7++;
                    if (diffDays <= 30) totalLeaving30++;

                    allLeavers.push({
                      student: s,
                      originalIndex: studentIdx,
                      dept: dept,
                      name: s.name,
                      endDate: rawEnd,
                      startDate: s.startDate || (s as any).globalStartDate || '',
                      daysLeft: diffDays,
                      phone: s.phone,
                      university: s.university,
                      idNumber: s.idNumber
                    });
                  });
                });

                // Filter by chosen days filter
                let filteredList = allLeavers.filter(item => {
                  if (departureFilterDays === -1) return item.daysLeft < 0;
                  if (departureFilterDays === 999) return true;
                  return item.daysLeft <= departureFilterDays;
                });

                // Filter by search query
                const q = (departureSearch || '').trim().toLowerCase();
                if (q) {
                  filteredList = filteredList.filter(item => {
                    const n = (item.name || '').toLowerCase();
                    const p = (item.phone || '').toLowerCase();
                    const d = (item.dept || '').toLowerCase();
                    const u = (item.university || '').toLowerCase();
                    const id = (item.idNumber || '').toLowerCase();
                    return n.includes(q) || p.includes(q) || d.includes(q) || u.includes(q) || id.includes(q);
                  });
                }

                // Sort by urgency ascending (most urgent first)
                filteredList.sort((a, b) => a.daysLeft - b.daysLeft);

                // Group by department
                const byDept: { [dept: string]: LeaverItem[] } = {};
                filteredList.forEach(item => {
                  if (!byDept[item.dept]) byDept[item.dept] = [];
                  byDept[item.dept].push(item);
                });

                const totalInSelectedFilter = filteredList.length;
                const activeDeptsCount = Object.keys(byDept).length;

                // Urgency badge generator
                const renderUrgencyBadge = (days: number) => {
                  if (days < 0) {
                    return (
                      <div style={{
                        background: 'linear-gradient(135deg, #b91c1c, #991b1b)',
                        color: '#fee2e2',
                        borderRadius: '20px',
                        padding: '4px 12px',
                        fontSize: '0.78rem',
                        fontWeight: 900,
                        border: '1px solid #ef4444',
                        boxShadow: '0 2px 10px rgba(239, 68, 68, 0.4)',
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '5px',
                        whiteSpace: 'nowrap'
                      }}>
                        <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#fca5a5', display: 'inline-block' }} />
                        متأخر {Math.abs(days)} يوم
                      </div>
                    );
                  }
                  if (days === 0) {
                    return (
                      <div style={{
                        background: 'linear-gradient(135deg, #d97706, #b45309)',
                        color: '#fef3c7',
                        borderRadius: '20px',
                        padding: '4px 12px',
                        fontSize: '0.78rem',
                        fontWeight: 900,
                        border: '1px solid #f59e0b',
                        boxShadow: '0 2px 10px rgba(245, 158, 11, 0.4)',
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '5px',
                        whiteSpace: 'nowrap'
                      }}>
                        <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#fef08a', display: 'inline-block' }} />
                        🔔 ينتهي اليوم!
                      </div>
                    );
                  }
                  if (days === 1) {
                    return (
                      <div style={{
                        background: 'linear-gradient(135deg, #ea580c, #c2410c)',
                        color: '#ffedd5',
                        borderRadius: '20px',
                        padding: '4px 12px',
                        fontSize: '0.78rem',
                        fontWeight: 800,
                        border: '1px solid #fb923c',
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '5px',
                        whiteSpace: 'nowrap'
                      }}>
                        ⚡ متبقي يوم واحد
                      </div>
                    );
                  }
                  if (days === 2) {
                    return (
                      <div style={{
                        background: 'linear-gradient(135deg, #ea580c, #c2410c)',
                        color: '#ffedd5',
                        borderRadius: '20px',
                        padding: '4px 12px',
                        fontSize: '0.78rem',
                        fontWeight: 800,
                        border: '1px solid #fb923c',
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '5px',
                        whiteSpace: 'nowrap'
                      }}>
                        ⚡ متبقي يومان
                      </div>
                    );
                  }
                  if (days <= 5) {
                    return (
                      <div style={{
                        background: 'rgba(234, 88, 12, 0.25)',
                        color: '#fdba74',
                        borderRadius: '20px',
                        padding: '4px 12px',
                        fontSize: '0.78rem',
                        fontWeight: 800,
                        border: '1px solid rgba(251, 146, 60, 0.5)',
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '5px',
                        whiteSpace: 'nowrap'
                      }}>
                        ⏳ متبقي {days} أيام
                      </div>
                    );
                  }
                  return (
                    <div style={{
                      background: 'rgba(255, 255, 255, 0.08)',
                      color: '#cbd5e1',
                      borderRadius: '20px',
                      padding: '4px 12px',
                      fontSize: '0.78rem',
                      fontWeight: 700,
                      border: '1px solid rgba(255, 255, 255, 0.15)',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '5px',
                      whiteSpace: 'nowrap'
                    }}>
                      📅 متبقي {days} يوم
                    </div>
                  );
                };

                return (
                  <div style={{ marginBottom: '30px' }}>
                    <div style={{
                      background: 'linear-gradient(145deg, #090d16 0%, #111827 50%, #0f172a 100%)',
                      borderRadius: '24px', 
                      padding: '26px 24px', 
                      color: 'white',
                      position: 'relative', 
                      overflow: 'hidden',
                      boxShadow: '0 20px 50px rgba(0,0,0,0.4)',
                      border: totalOverdue > 0 
                        ? '1.5px solid rgba(239, 68, 68, 0.45)' 
                        : '1.5px solid rgba(99, 102, 241, 0.35)',
                      backdropFilter: 'blur(20px)'
                    }}>
                      {/* Decorative ambient lights */}
                      <div style={{ position: 'absolute', top: '-50px', right: '-50px', width: '200px', height: '200px', background: totalOverdue > 0 ? 'rgba(239, 68, 68, 0.15)' : 'rgba(99, 102, 241, 0.15)', borderRadius: '50%', filter: 'blur(60px)', pointerEvents: 'none' }} />
                      {/* Ambient light & keyframe styles */}
                      <style>{`
                        @keyframes alarmPulse {
                          0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); }
                          70% { transform: scale(1.06); box-shadow: 0 0 0 12px rgba(239, 68, 68, 0); }
                          100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
                        }
                        @keyframes bellRing {
                          0%, 100% { transform: rotate(0); }
                          20%, 60% { transform: rotate(-14deg); }
                          40%, 80% { transform: rotate(14deg); }
                        }
                      `}</style>
                      <div style={{ position: 'absolute', top: '-50px', right: '-50px', width: '200px', height: '200px', background: totalOverdue > 0 ? 'rgba(239, 68, 68, 0.15)' : 'rgba(99, 102, 241, 0.15)', borderRadius: '50%', filter: 'blur(60px)', pointerEvents: 'none' }} />
                      <div style={{ position: 'absolute', bottom: '-40px', left: '-40px', width: '180px', height: '180px', background: 'rgba(245, 158, 11, 0.1)', borderRadius: '50%', filter: 'blur(60px)', pointerEvents: 'none' }} />

                      {/* ═══ 1. HEADER & SYSTEM TITLE ═══ */}
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '22px', flexWrap: 'wrap', gap: '16px', position: 'relative', zIndex: 1 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                          <div style={{ 
                            background: totalOverdue > 0 
                              ? 'linear-gradient(135deg, rgba(239,68,68,0.3), rgba(185,28,28,0.45))'
                              : 'linear-gradient(135deg, rgba(99,102,241,0.3), rgba(67,56,202,0.45))',
                            border: totalOverdue > 0 
                              ? '1.5px solid rgba(239,68,68,0.6)'
                              : '1.5px solid rgba(99,102,241,0.6)',
                            borderRadius: '16px', 
                            padding: '12px 16px', 
                            display: 'flex', 
                            alignItems: 'center', 
                            justifyContent: 'center',
                            boxShadow: '0 8px 20px rgba(0,0,0,0.3)',
                            animation: totalOverdue > 0 ? 'alarmPulse 2s infinite' : 'none'
                          }}>
                            <i className="fas fa-bell" style={{ fontSize: '1.6rem', color: totalOverdue > 0 ? '#fca5a5' : '#a5b4fc', animation: totalOverdue > 0 ? 'bellRing 2.5s infinite' : 'none' }}></i>
                          </div>
                          <div>
                            <div style={{ fontSize: '1.35rem', fontWeight: 900, display: 'flex', alignItems: 'center', gap: '10px', color: '#ffffff', flexWrap: 'wrap' }}>
                              نظام إنذارات وتنبيهات انتهاء التدريب والمغادرة
                              {totalOverdue > 0 && (
                                <span style={{ background: 'rgba(239, 68, 68, 0.25)', color: '#fca5a5', fontSize: '0.8rem', padding: '4px 12px', borderRadius: '20px', border: '1px solid #ef4444', fontWeight: 800 }}>
                                  🚨 {totalOverdue} متأخر
                                </span>
                              )}
                              {totalEndingToday > 0 && (
                                <span style={{ background: 'rgba(245, 158, 11, 0.25)', color: '#fef08a', fontSize: '0.8rem', padding: '4px 12px', borderRadius: '20px', border: '1px solid #f59e0b', fontWeight: 800 }}>
                                  🔔 {totalEndingToday} ينتهي اليوم
                                </span>
                              )}
                            </div>
                            <div style={{ fontSize: '0.85rem', color: '#94a3b8', marginTop: '4px' }}>
                              لوحة متابعة مركزية للمتدربين الموشكين على إنهاء تدريبهم أو المتأخرين عبر جميع الأقسام
                            </div>
                          </div>
                        </div>

                        {/* Top Action Controls & Alarm Toggle Button */}
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                          <button
                            type="button"
                            onClick={() => setShowDepartureNames(!showDepartureNames)}
                            style={{
                              background: showDepartureNames 
                                ? 'rgba(255,255,255,0.12)' 
                                : (totalOverdue > 0 ? 'linear-gradient(135deg, #ef4444, #dc2626)' : 'linear-gradient(135deg, #6366f1, #4f46e5)'),
                              color: '#ffffff',
                              border: showDepartureNames ? '1px solid rgba(255,255,255,0.2)' : '1px solid rgba(255,215,0,0.5)',
                              borderRadius: '12px',
                              padding: '9px 18px',
                              fontSize: '0.88rem',
                              fontWeight: 900,
                              cursor: 'pointer',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '8px',
                              fontFamily: 'Tajawal',
                              boxShadow: showDepartureNames ? 'none' : '0 4px 14px rgba(0,0,0,0.3)',
                              transition: 'all 0.2s ease'
                            }}
                            title={showDepartureNames ? 'إخفاء أسماء المتدربين والعودة لوضع التنبيه' : 'عرض أسماء المتدربين وكافة تفاصيلهم'}
                          >
                            <i className={`fas fa-${showDepartureNames ? 'eye-slash' : 'bell'}`}></i>
                            <span>{showDepartureNames ? 'إخفاء أسماء المتدربين 🔼' : `إظهار أسماء المغادرين (${totalInSelectedFilter}) 👈`}</span>
                          </button>

                          {/* View Mode Switcher (visible when names are expanded) */}
                          {showDepartureNames && (
                            <div style={{ display: 'flex', alignItems: 'center', gap: '6px', background: 'rgba(0,0,0,0.4)', padding: '5px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.1)' }}>
                              <button
                                type="button"
                                onClick={() => setDepartureViewMode('byDept')}
                                style={{
                                  background: departureViewMode === 'byDept' ? 'linear-gradient(135deg, #4f46e5, #6366f1)' : 'transparent',
                                  color: departureViewMode === 'byDept' ? 'white' : '#94a3b8',
                                  border: 'none',
                                  borderRadius: '8px',
                                  padding: '6px 12px',
                                  fontSize: '0.8rem',
                                  fontWeight: 800,
                                  cursor: 'pointer',
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '6px',
                                  fontFamily: 'Tajawal',
                                  boxShadow: departureViewMode === 'byDept' ? '0 2px 10px rgba(79,70,229,0.4)' : 'none'
                                }}
                              >
                                <i className="fas fa-sitemap"></i>
                                <span>أقسام</span>
                              </button>

                              <button
                                type="button"
                                onClick={() => setDepartureViewMode('timeline')}
                                style={{
                                  background: departureViewMode === 'timeline' ? 'linear-gradient(135deg, #d97706, #f59e0b)' : 'transparent',
                                  color: departureViewMode === 'timeline' ? 'white' : '#94a3b8',
                                  border: 'none',
                                  borderRadius: '8px',
                                  padding: '6px 12px',
                                  fontSize: '0.8rem',
                                  fontWeight: 800,
                                  cursor: 'pointer',
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '6px',
                                  fontFamily: 'Tajawal',
                                  boxShadow: departureViewMode === 'timeline' ? '0 2px 10px rgba(217,119,6,0.4)' : 'none'
                                }}
                              >
                                <i className="fas fa-hourglass-half"></i>
                                <span>زمني</span>
                              </button>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* ═══ 2. STATS COUNTERS CARDS (Clickable to reveal names & set filter) ═══ */}
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: '12px', marginBottom: '22px', position: 'relative', zIndex: 1 }}>
                        <div 
                          onClick={() => { setDepartureFilterDays(-1); setShowDepartureNames(true); }}
                          style={{ background: 'rgba(239, 68, 68, 0.12)', border: '1px solid rgba(239, 68, 68, 0.3)', borderRadius: '16px', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', transition: 'all 0.2s' }}
                          title="اضغط لعرض أسماء المتدربين المتأخرين فوراً"
                        >
                          <div style={{ width: '42px', height: '42px', borderRadius: '12px', background: 'rgba(239, 68, 68, 0.25)', color: '#fca5a5', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.2rem' }}>
                            <i className="fas fa-exclamation-triangle"></i>
                          </div>
                          <div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#fca5a5' }}>{totalOverdue}</div>
                            <div style={{ fontSize: '0.76rem', color: '#fda4af', fontWeight: 700 }}>انتهت فترتهم (متأخر)</div>
                          </div>
                        </div>

                        <div 
                          onClick={() => { setDepartureFilterDays(0); setShowDepartureNames(true); }}
                          style={{ background: 'rgba(245, 158, 11, 0.12)', border: '1px solid rgba(245, 158, 11, 0.3)', borderRadius: '16px', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', transition: 'all 0.2s' }}
                          title="اضغط لعرض أسماء المتدربين المنتهية فترتهم اليوم"
                        >
                          <div style={{ width: '42px', height: '42px', borderRadius: '12px', background: 'rgba(245, 158, 11, 0.25)', color: '#fef08a', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.2rem' }}>
                            <i className="fas fa-bell"></i>
                          </div>
                          <div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#fef08a' }}>{totalEndingToday}</div>
                            <div style={{ fontSize: '0.76rem', color: '#fef3c7', fontWeight: 700 }}>ينتهي اليوم</div>
                          </div>
                        </div>

                        <div 
                          onClick={() => { setDepartureFilterDays(3); setShowDepartureNames(true); }}
                          style={{ background: 'rgba(234, 88, 12, 0.12)', border: '1px solid rgba(234, 88, 12, 0.3)', borderRadius: '16px', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', transition: 'all 0.2s' }}
                          title="اضغط لعرض أسماء المتدربين المغادرين خلال 3 أيام"
                        >
                          <div style={{ width: '42px', height: '42px', borderRadius: '12px', background: 'rgba(234, 88, 12, 0.25)', color: '#fdba74', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.2rem' }}>
                            <i className="fas fa-bolt"></i>
                          </div>
                          <div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#fdba74' }}>{totalLeaving3}</div>
                            <div style={{ fontSize: '0.76rem', color: '#fed7aa', fontWeight: 700 }}>عاجل خلال 3 أيام</div>
                          </div>
                        </div>

                        <div 
                          onClick={() => { setDepartureFilterDays(7); setShowDepartureNames(true); }}
                          style={{ background: 'rgba(14, 165, 233, 0.12)', border: '1px solid rgba(14, 165, 233, 0.3)', borderRadius: '16px', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', transition: 'all 0.2s' }}
                          title="اضغط لعرض أسماء المتدربين المغادرين خلال 7 أيام"
                        >
                          <div style={{ width: '42px', height: '42px', borderRadius: '12px', background: 'rgba(14, 165, 233, 0.25)', color: '#7dd3fc', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.2rem' }}>
                            <i className="fas fa-calendar-week"></i>
                          </div>
                          <div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#7dd3fc' }}>{totalLeaving7}</div>
                            <div style={{ fontSize: '0.76rem', color: '#bae6fd', fontWeight: 700 }}>خلال 7 أيام</div>
                          </div>
                        </div>

                        <div 
                          onClick={() => { setShowDepartureNames(true); }}
                          style={{ background: 'rgba(99, 102, 241, 0.12)', border: '1px solid rgba(99, 102, 241, 0.3)', borderRadius: '16px', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', transition: 'all 0.2s' }}
                          title="اضغط لعرض كافة الأسماء في التصفية"
                        >
                          <div style={{ width: '42px', height: '42px', borderRadius: '12px', background: 'rgba(99, 102, 241, 0.25)', color: '#c7d2fe', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.2rem' }}>
                            <i className="fas fa-users"></i>
                          </div>
                          <div>
                            <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#c7d2fe' }}>{totalInSelectedFilter}</div>
                            <div style={{ fontSize: '0.76rem', color: '#e0e7ff', fontWeight: 700 }}>الإجمالي في التصفية</div>
                          </div>
                        </div>
                      </div>

                      {/* ═══ CONDITIONAL VIEW: ALARM ONLY vs FULL NAMES LISTING ═══ */}
                      {!showDepartureNames ? (
                        /* ═══ ALARM-ONLY VIEW: NAMES ARE HIDDEN, CLICK TO REVEAL ═══ */
                        <div 
                          onClick={() => setShowDepartureNames(true)}
                          style={{
                            background: totalOverdue > 0 
                              ? 'linear-gradient(135deg, rgba(239, 68, 68, 0.14) 0%, rgba(185, 28, 28, 0.22) 100%)' 
                              : 'linear-gradient(135deg, rgba(99, 102, 241, 0.14) 0%, rgba(67, 56, 202, 0.22) 100%)',
                            border: totalOverdue > 0 
                              ? '1.5px dashed rgba(239, 68, 68, 0.5)' 
                              : '1.5px dashed rgba(99, 102, 241, 0.5)',
                            borderRadius: '20px',
                            padding: '26px 20px',
                            textAlign: 'center',
                            cursor: 'pointer',
                            transition: 'all 0.25s ease',
                            position: 'relative',
                            zIndex: 1,
                            boxShadow: '0 10px 30px rgba(0,0,0,0.2)'
                          }}
                        >
                          <div style={{
                            width: '58px',
                            height: '58px',
                            borderRadius: '50%',
                            background: totalOverdue > 0 ? 'rgba(239, 68, 68, 0.25)' : 'rgba(99, 102, 241, 0.25)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginBottom: '12px',
                            boxShadow: totalOverdue > 0 ? '0 0 25px rgba(239, 68, 68, 0.45)' : '0 0 25px rgba(99, 102, 241, 0.45)'
                          }}>
                            <i className="fas fa-bell" style={{ fontSize: '1.8rem', color: totalOverdue > 0 ? '#fca5a5' : '#a5b4fc', animation: totalOverdue > 0 ? 'bellRing 2.5s infinite' : 'none' }}></i>
                          </div>

                          <div style={{ fontSize: '1.25rem', fontWeight: 900, color: '#ffffff', marginBottom: '8px' }}>
                            {totalOverdue > 0 
                              ? `🚨 تنبيه عاجل: يوجد ${totalOverdue} متدرب متأخر عن موعد انتهاء التدريب!`
                              : `🔔 تنبيه: يوجد ${totalInSelectedFilter} متدرب موشكون على انتهاء تدريبهم خلال هذه الفترة`}
                          </div>

                          <div style={{ fontSize: '0.88rem', color: '#cbd5e1', maxWidth: '620px', margin: '0 auto 18px', lineHeight: 1.6 }}>
                            تم إخفاء أسماء المتدربين من الواجهة الرئيسية للحفاظ على الخصوصية وترتيب الشاشة.
                            <br />
                            اضغط على زر التنبيه أدناه لإظهار كافة الأسماء والتفاصيل وتعديل الفترات أو إنهاء التدريب.
                          </div>

                          <button
                            type="button"
                            onClick={(e) => { e.stopPropagation(); setShowDepartureNames(true); }}
                            style={{
                              background: totalOverdue > 0 
                                ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 50%, #b91c1c 100%)' 
                                : 'linear-gradient(135deg, #6366f1 0%, #4f46e5 50%, #4338ca 100%)',
                              color: '#ffffff',
                              border: '1.5px solid rgba(255, 255, 255, 0.3)',
                              borderRadius: '14px',
                              padding: '12px 28px',
                              fontSize: '1.02rem',
                              fontWeight: 900,
                              cursor: 'pointer',
                              fontFamily: 'Tajawal',
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '10px',
                              boxShadow: totalOverdue > 0 
                                ? '0 6px 20px rgba(239,68,68,0.5)' 
                                : '0 6px 20px rgba(99,102,241,0.5)'
                            }}
                          >
                            <i className="fas fa-eye"></i>
                            <span>اضغط هنا لإظهار أسماء وتفاصيل المتدربين ({totalInSelectedFilter}) 👈</span>
                            <i className="fas fa-chevron-down"></i>
                          </button>
                        </div>
                      ) : (
                        <div>
                          {/* ═══ 3. SEARCH & TIME FILTER TOOLBAR (REVEALED) ═══ */}
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '14px', marginBottom: '20px', flexWrap: 'wrap', position: 'relative', zIndex: 1 }}>
                        {/* Search Input */}
                        <div style={{ flex: '1 1 300px', position: 'relative' }}>
                          <i className="fas fa-search" style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: '#94a3b8', fontSize: '0.9rem' }}></i>
                          <input
                            type="text"
                            value={departureSearch}
                            onChange={(e) => setDepartureSearch(e.target.value)}
                            placeholder="🔍 بحث سريع بالاسم، رقم الهاتف، القسم، أو الجامعة..."
                            style={{
                              width: '100%',
                              padding: '10px 40px 10px 35px',
                              background: 'rgba(0, 0, 0, 0.35)',
                              border: '1.5px solid rgba(255, 255, 255, 0.15)',
                              borderRadius: '12px',
                              color: '#ffffff',
                              fontSize: '0.9rem',
                              fontFamily: 'Tajawal',
                              outline: 'none',
                              transition: 'border 0.2s ease'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#6366f1'}
                            onBlur={(e) => e.target.style.borderColor = 'rgba(255, 255, 255, 0.15)'}
                          />
                          {departureSearch && (
                            <button
                              type="button"
                              onClick={() => setDepartureSearch('')}
                              style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: '0.9rem' }}
                            >
                              ✕
                            </button>
                          )}
                        </div>

                        {/* Filter Tabs */}
                        <div style={{ display: 'flex', gap: '6px', background: 'rgba(0,0,0,0.3)', padding: '5px', borderRadius: '14px', border: '1px solid rgba(255,255,255,0.08)', flexWrap: 'wrap' }}>
                          {[
                            { days: -1, label: '🚨 متأخر فقط' },
                            { days: 3, label: '⚡ 3 أيام' },
                            { days: 7, label: '🔔 7 أيام' },
                            { days: 15, label: '📅 15 يوم' },
                            { days: 30, label: '🗓️ 30 يوم' },
                            { days: 999, label: '🌐 الكل' }
                          ].map(tab => {
                            const isActive = departureFilterDays === tab.days;
                            return (
                              <button
                                key={tab.days}
                                type="button"
                                onClick={() => setDepartureFilterDays(tab.days)}
                                style={{
                                  background: isActive 
                                    ? 'linear-gradient(135deg, #4f46e5 0%, #6366f1 100%)' 
                                    : 'transparent',
                                  color: isActive ? '#ffffff' : '#94a3b8',
                                  border: isActive ? '1px solid rgba(255,215,0,0.4)' : '1px solid transparent',
                                  borderRadius: '9px',
                                  padding: '6px 12px',
                                  fontSize: '0.8rem',
                                  fontWeight: isActive ? 800 : 600,
                                  cursor: 'pointer',
                                  fontFamily: 'Tajawal',
                                  transition: 'all 0.2s ease',
                                  boxShadow: isActive ? '0 2px 10px rgba(79,70,229,0.4)' : 'none'
                                }}
                              >
                                {tab.label}
                              </button>
                            );
                          })}
                        </div>

                        {/* Expand / Collapse All in byDept mode */}
                        {departureViewMode === 'byDept' && activeDeptsCount > 0 && (
                          <div style={{ display: 'flex', gap: '6px' }}>
                            <button
                              type="button"
                              onClick={() => {
                                const allExpanded: {[k: string]: boolean} = {};
                                Object.keys(byDept).forEach(k => allExpanded[k] = false);
                                setCollapsedDepartureDepts(allExpanded);
                              }}
                              style={{ background: 'rgba(255,255,255,0.08)', color: '#cbd5e1', border: '1px solid rgba(255,255,255,0.15)', borderRadius: '9px', padding: '6px 12px', fontSize: '0.78rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                            >
                              <i className="fas fa-expand-alt" style={{ marginLeft: '4px' }}></i> فتح الكل
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                const allCollapsed: {[k: string]: boolean} = {};
                                Object.keys(byDept).forEach(k => allCollapsed[k] = true);
                                setCollapsedDepartureDepts(allCollapsed);
                              }}
                              style={{ background: 'rgba(255,255,255,0.08)', color: '#cbd5e1', border: '1px solid rgba(255,255,255,0.15)', borderRadius: '9px', padding: '6px 12px', fontSize: '0.78rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                            >
                              <i className="fas fa-compress-alt" style={{ marginLeft: '4px' }}></i> طي الكل
                            </button>
                          </div>
                        )}
                      </div>

                      {/* ═══ 4. CONTENT LISTING ═══ */}
                      {totalInSelectedFilter === 0 ? (
                        <div style={{ 
                          textAlign: 'center', 
                          padding: '36px 20px', 
                          position: 'relative', 
                          zIndex: 1, 
                          background: 'rgba(16, 185, 129, 0.05)', 
                          borderRadius: '16px',
                          border: '1.5px dashed rgba(16, 185, 129, 0.3)'
                        }}>
                          <div style={{
                            width: '56px',
                            height: '56px',
                            borderRadius: '50%',
                            background: 'rgba(16, 185, 129, 0.15)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            margin: '0 auto 12px'
                          }}>
                            <i className="fas fa-check-circle" style={{ fontSize: '2rem', color: '#10b981' }}></i>
                          </div>
                          <div style={{ fontSize: '1.15rem', fontWeight: 800, color: '#e2e8f0', marginBottom: '6px' }}>
                            {departureSearch ? 'لا توجد نتائج تطابق بحثك في قائمة الإنذارات' : 'جميع المتدربين ضمن الفترة الزمنية الطبيعية'}
                          </div>
                          <div style={{ fontSize: '0.85rem', color: '#94a3b8' }}>
                            {departureSearch ? 'جرب البحث باسم آخر أو تأكد من إلغاء فلاتر التصفية' : `لا يوجد متدربون تنتهي فترتهم خلال هذه الفترة الزمنية. يمكنك التبديل بين خيارات التصفية بالأعلى.`}
                          </div>
                        </div>
                      ) : departureViewMode === 'timeline' ? (
                        /* ═══ TIMELINE VIEW (URGENT FIRST) ═══ */
                        <div style={{ 
                          display: 'flex', 
                          flexDirection: 'column', 
                          gap: '10px', 
                          maxHeight: '680px', 
                          overflowY: 'auto', 
                          position: 'relative', 
                          zIndex: 1,
                          paddingLeft: '4px',
                          paddingRight: '4px'
                        }}>
                          {filteredList.map((p, i) => {
                            const isEditingThis = inlineEdit?.dept === p.dept && inlineEdit?.index === p.originalIndex;
                            return (
                              <div
                                key={`${p.dept}-${p.originalIndex}-${i}`}
                                style={{
                                  background: p.daysLeft < 0 ? 'rgba(239, 68, 68, 0.08)' : 'rgba(15, 23, 42, 0.75)',
                                  borderRadius: '14px',
                                  padding: '14px 18px',
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'space-between',
                                  gap: '16px',
                                  border: p.daysLeft < 0 ? '1px solid rgba(239, 68, 68, 0.35)' : '1px solid rgba(255, 255, 255, 0.1)',
                                  backdropFilter: 'blur(10px)',
                                  flexWrap: 'wrap',
                                  transition: 'all 0.2s ease'
                                }}
                              >
                                {/* Left/Info side */}
                                <div style={{ flex: '1 1 320px' }}>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                                    {renderUrgencyBadge(p.daysLeft)}
                                    <span
                                      onClick={() => setCurrentDepartment(p.dept)}
                                      style={{
                                        background: 'rgba(99, 102, 241, 0.2)',
                                        color: '#a5b4fc',
                                        border: '1px solid rgba(99, 102, 241, 0.4)',
                                        borderRadius: '10px',
                                        padding: '2px 10px',
                                        fontSize: '0.78rem',
                                        fontWeight: 800,
                                        cursor: 'pointer'
                                      }}
                                    >
                                      📁 {p.dept}
                                    </span>
                                  </div>

                                  {isEditingThis ? (
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px', flexWrap: 'wrap' }}>
                                      <input 
                                        type="text"
                                        value={inlineEdit.name}
                                        onChange={(e) => setInlineEdit({ ...inlineEdit, name: e.target.value })}
                                        onKeyDown={(e) => {
                                          if (e.key === 'Enter') handleSaveInlineName();
                                          if (e.key === 'Escape') setInlineEdit(null);
                                        }}
                                        autoFocus
                                        placeholder="الاسم الرباعي الجديد"
                                        style={{ background: 'rgba(0,0,0,0.5)', border: '2px solid #6366f1', borderRadius: '8px', color: '#fff', padding: '6px 12px', fontSize: '0.95rem', fontFamily: 'Tajawal', fontWeight: 700, minWidth: '220px', outline: 'none' }}
                                      />
                                      <button type="button" onClick={handleSaveInlineName} style={{ background: 'linear-gradient(135deg, #10b981, #059669)', color: 'white', border: 'none', borderRadius: '8px', padding: '6px 14px', fontSize: '0.82rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal' }}>
                                        <i className="fas fa-check"></i> حفظ
                                      </button>
                                      <button type="button" onClick={() => setInlineEdit(null)} style={{ background: 'rgba(255,255,255,0.1)', color: '#cbd5e1', border: '1px solid rgba(255,255,255,0.2)', borderRadius: '8px', padding: '6px 12px', fontSize: '0.82rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}>
                                        إلغاء
                                      </button>
                                    </div>
                                  ) : (
                                    <div style={{ marginTop: '6px', display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                                      <strong style={{ fontSize: '1.05rem', color: '#ffffff' }}>{p.name}</strong>
                                      {p.university && (
                                        <span style={{ fontSize: '0.82rem', color: '#94a3b8' }}>({p.university})</span>
                                      )}
                                      <button
                                        type="button"
                                        onClick={() => setInlineEdit({ dept: p.dept, index: p.originalIndex, name: p.name })}
                                        title="تعديل الاسم سريعاً"
                                        style={{ background: 'rgba(255, 215, 0, 0.12)', border: '1px solid rgba(255, 215, 0, 0.35)', color: '#ffd700', borderRadius: '6px', padding: '2px 8px', fontSize: '0.72rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                                      >
                                        <i className="fas fa-pen" style={{ fontSize: '0.65rem' }}></i> تعديل الاسم
                                      </button>
                                    </div>
                                  )}

                                  <div style={{ fontSize: '0.82rem', color: '#94a3b8', marginTop: '6px', display: 'flex', gap: '14px', flexWrap: 'wrap', alignItems: 'center' }}>
                                    <span>
                                      <i className="fas fa-calendar-times" style={{ marginLeft: '4px', color: '#f87171' }}></i>
                                      تاريخ الانتهاء: <strong style={{ color: '#f1f5f9' }}>{p.endDate}</strong>
                                    </span>
                                    {p.startDate && (
                                      <span>
                                        <i className="fas fa-calendar-check" style={{ marginLeft: '4px', color: '#38bdf8' }}></i>
                                        البدء: <span style={{ color: '#cbd5e1' }}>{p.startDate}</span>
                                      </span>
                                    )}
                                    {p.phone && (
                                      <a href={`tel:+970${p.phone}`} style={{ color: '#38bdf8', textDecoration: 'none', fontWeight: 600 }}>
                                        <i className="fas fa-phone" style={{ marginLeft: '4px' }}></i>{p.phone}
                                      </a>
                                    )}
                                  </div>
                                </div>

                                {/* Right/Actions side */}
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                                  {/* Edit Details */}
                                  <button
                                    type="button"
                                    onClick={() => {
                                      setEditTargetDept(p.dept);
                                      setSelectedStudentIndex(p.originalIndex);
                                      setFormData({
                                        ...p.student,
                                        department: p.dept,
                                        startDate: parseDateForInput(p.student.startDate || p.startDate || ''),
                                        endDate: parseDateForInput(p.student.endDate || p.endDate || ''),
                                        phone: p.student.phone || p.phone || '',
                                        name: p.student.name || p.name,
                                        university: p.student.university || p.university || '',
                                        address: p.student.address || '',
                                        shiftSystem: p.student.shiftSystem || '',
                                        idNumber: p.student.idNumber || '',
                                        graduationYear: p.student.graduationYear || '',
                                        attendanceDays: p.student.attendanceDays || '',
                                        studySystem: p.student.studySystem || '',
                                        internshipYear: p.student.internshipYear || '',
                                      });
                                      setActiveModal('edit');
                                    }}
                                    title="تعديل كامل البيانات وتاريخ الانتهاء"
                                    style={{ background: 'linear-gradient(135deg, #2563eb, #1d4ed8)', border: '1px solid rgba(255,255,255,0.2)', color: 'white', borderRadius: '9px', padding: '6px 14px', fontSize: '0.8rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal', display: 'flex', alignItems: 'center', gap: '5px', boxShadow: '0 2px 8px rgba(37,99,235,0.3)' }}
                                  >
                                    <i className="fas fa-edit"></i> تعديل وتمديد
                                  </button>

                                  {/* Quick Graduate */}
                                  <button
                                    type="button"
                                    onClick={() => handleQuickGraduateStudent(p.dept, p.originalIndex)}
                                    title="إنهاء التدريب ونقل المتدرب مباشرة لقائمة المغادرين"
                                    style={{ background: 'linear-gradient(135deg, #059669, #047857)', border: '1px solid rgba(16,185,129,0.4)', color: '#ecfdf5', borderRadius: '9px', padding: '6px 14px', fontSize: '0.8rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal', display: 'flex', alignItems: 'center', gap: '5px', boxShadow: '0 2px 8px rgba(5,150,105,0.3)' }}
                                  >
                                    <i className="fas fa-user-graduate"></i> إنهاء التدريب
                                  </button>

                                  {/* Certificate Link */}
                                  <Link
                                    href={`/certificate?student=${encodeURIComponent(p.name)}&dept=${encodeURIComponent(p.dept)}`}
                                    style={{ background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', border: '1px solid rgba(255,255,255,0.2)', color: 'white', borderRadius: '9px', padding: '6px 12px', fontSize: '0.8rem', fontWeight: 800, textDecoration: 'none', display: 'flex', alignItems: 'center', gap: '5px' }}
                                    title="إصدار شهادة الخبرة مباشرة"
                                  >
                                    <i className="fas fa-certificate"></i> الشهادة
                                  </Link>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      ) : (
                        /* ═══ DEPARTMENT GROUPED VIEW ═══ */
                        <div style={{ 
                          display: 'flex', 
                          flexDirection: 'column', 
                          gap: '14px', 
                          maxHeight: '680px', 
                          overflowY: 'auto', 
                          position: 'relative', 
                          zIndex: 1,
                          paddingLeft: '4px',
                          paddingRight: '4px'
                        }}>
                          {Object.entries(byDept).map(([dept, people]) => {
                            const isCollapsed = !!collapsedDepartureDepts[dept];
                            const deptOverdueCount = people.filter(p => p.daysLeft < 0).length;

                            return (
                              <div 
                                key={dept} 
                                style={{ 
                                  flexShrink: 0,
                                  background: 'rgba(15, 23, 42, 0.75)', 
                                  borderRadius: '16px', 
                                  overflow: 'hidden', 
                                  backdropFilter: 'blur(10px)', 
                                  border: deptOverdueCount > 0 ? '1px solid rgba(239, 68, 68, 0.35)' : '1px solid rgba(255,255,255,0.12)',
                                  boxShadow: '0 4px 15px rgba(0,0,0,0.2)'
                                }}
                              >
                                {/* Dept header row with collapse toggle */}
                                <div 
                                  onClick={() => setCollapsedDepartureDepts(prev => ({ ...prev, [dept]: !prev[dept] }))}
                                  style={{ 
                                    background: 'rgba(30, 41, 59, 0.85)', 
                                    padding: '12px 18px', 
                                    display: 'flex', 
                                    justifyContent: 'space-between', 
                                    alignItems: 'center', 
                                    borderBottom: isCollapsed ? 'none' : '1px solid rgba(255,255,255,0.08)',
                                    cursor: 'pointer',
                                    userSelect: 'none',
                                    transition: 'background 0.2s ease'
                                  }}
                                >
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
                                    <i className={`fas fa-chevron-${isCollapsed ? 'down' : 'up'}`} style={{ fontSize: '0.85rem', color: '#94a3b8', transition: 'transform 0.2s' }}></i>
                                    <span style={{ fontWeight: 900, fontSize: '1.08rem', color: '#f8fafc' }}>📁 {dept}</span>
                                    <span style={{ background: 'rgba(255,255,255,0.12)', color: '#cbd5e1', borderRadius: '20px', padding: '3px 12px', fontSize: '0.78rem', fontWeight: 800 }}>
                                      {people.length} متدرب
                                    </span>
                                    {deptOverdueCount > 0 && (
                                      <span style={{ background: 'rgba(239, 68, 68, 0.25)', color: '#fca5a5', borderRadius: '20px', padding: '2px 10px', fontSize: '0.75rem', fontWeight: 800, border: '1px solid #ef4444' }}>
                                        🚨 {deptOverdueCount} متأخر
                                      </span>
                                    )}
                                    {isCollapsed && (
                                      <span style={{ fontSize: '0.75rem', color: '#94a3b8', opacity: 0.8 }}>
                                        (اضغط لعرض المتدربين)
                                      </span>
                                    )}
                                  </div>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }} onClick={(e) => e.stopPropagation()}>
                                    <button
                                      type="button"
                                      onClick={() => setCurrentDepartment(dept)}
                                      style={{
                                        background: 'linear-gradient(135deg, #1e3a8a, #2563eb)',
                                        border: '1px solid rgba(255,255,255,0.25)',
                                        color: 'white',
                                        borderRadius: '10px',
                                        padding: '6px 14px',
                                        fontSize: '0.82rem',
                                        fontWeight: 800,
                                        cursor: 'pointer',
                                        fontFamily: 'Tajawal',
                                        boxShadow: '0 2px 8px rgba(37,99,235,0.35)',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '6px'
                                      }}
                                    >
                                      <span>فتح جدول القسم</span>
                                      <i className="fas fa-arrow-left"></i>
                                    </button>
                                  </div>
                                </div>

                                {/* Individual rows */}
                                {!isCollapsed && people.map((p, i) => {
                                  const isEditingThis = inlineEdit?.dept === p.dept && inlineEdit?.index === p.originalIndex;
                                  return (
                                    <div 
                                      key={`${dept}-${i}`} 
                                      style={{ 
                                        flexShrink: 0,
                                        padding: '14px 20px', 
                                        display: 'flex', 
                                        justifyContent: 'space-between', 
                                        alignItems: 'center', 
                                        borderTop: i > 0 ? '1px solid rgba(255,255,255,0.06)' : 'none', 
                                        flexWrap: 'wrap', 
                                        gap: '14px',
                                        background: isEditingThis ? 'rgba(99, 102, 241, 0.15)' : p.daysLeft < 0 ? 'rgba(239, 68, 68, 0.04)' : 'transparent',
                                        transition: 'all 0.2s ease'
                                      }}
                                    >
                                      {/* Info side */}
                                      <div style={{ flex: '1 1 320px' }}>
                                        {isEditingThis ? (
                                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                                            <input 
                                              type="text"
                                              value={inlineEdit.name}
                                              onChange={(e) => setInlineEdit({ ...inlineEdit, name: e.target.value })}
                                              onKeyDown={(e) => {
                                                if (e.key === 'Enter') handleSaveInlineName();
                                                if (e.key === 'Escape') setInlineEdit(null);
                                              }}
                                              autoFocus
                                              placeholder="الاسم الرباعي الجديد"
                                              style={{
                                                background: 'rgba(0,0,0,0.5)',
                                                border: '2px solid #6366f1',
                                                borderRadius: '8px',
                                                color: '#ffffff',
                                                padding: '6px 12px',
                                                fontSize: '0.95rem',
                                                fontFamily: 'Tajawal',
                                                fontWeight: 700,
                                                minWidth: '220px',
                                                outline: 'none'
                                              }}
                                            />
                                            <button 
                                              type="button" 
                                              onClick={handleSaveInlineName}
                                              style={{ background: 'linear-gradient(135deg, #10b981, #059669)', color: 'white', border: 'none', borderRadius: '8px', padding: '6px 14px', fontSize: '0.82rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal' }}
                                            >
                                              <i className="fas fa-check"></i> حفظ
                                            </button>
                                            <button 
                                              type="button" 
                                              onClick={() => setInlineEdit(null)}
                                              style={{ background: 'rgba(255,255,255,0.1)', color: '#cbd5e1', border: '1px solid rgba(255,255,255,0.15)', borderRadius: '8px', padding: '6px 12px', fontSize: '0.82rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                                            >
                                              إلغاء
                                            </button>
                                          </div>
                                        ) : (
                                          <div style={{ fontWeight: 800, fontSize: '1rem', display: 'flex', alignItems: 'center', gap: '8px', color: '#ffffff', flexWrap: 'wrap' }}>
                                            <i className="fas fa-user-circle" style={{ fontSize: '1rem', color: '#94a3b8' }}></i>
                                            <span>{p.name}</span>
                                            {p.university && (
                                              <span style={{ fontSize: '0.8rem', color: '#94a3b8', fontWeight: 500 }}>
                                                ({p.university})
                                              </span>
                                            )}
                                            <button
                                              type="button"
                                              onClick={() => setInlineEdit({ dept: p.dept, index: p.originalIndex, name: p.name })}
                                              title="تعديل الاسم سريعاً"
                                              style={{
                                                background: 'rgba(255, 215, 0, 0.12)',
                                                border: '1px solid rgba(255, 215, 0, 0.35)',
                                                color: '#ffd700',
                                                borderRadius: '6px',
                                                padding: '2px 8px',
                                                fontSize: '0.72rem',
                                                fontWeight: 700,
                                                cursor: 'pointer',
                                                fontFamily: 'Tajawal',
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                gap: '4px'
                                              }}
                                            >
                                              <i className="fas fa-pen" style={{ fontSize: '0.68rem' }}></i> تعديل الاسم
                                            </button>
                                          </div>
                                        )}

                                        <div style={{ fontSize: '0.82rem', color: '#94a3b8', marginTop: '6px', display: 'flex', gap: '14px', flexWrap: 'wrap', alignItems: 'center' }}>
                                          <span>
                                            <i className="fas fa-calendar-times" style={{ marginLeft: '4px', color: '#f87171' }}></i>
                                            تاريخ الانتهاء: <strong style={{ color: '#f1f5f9' }}>{p.endDate}</strong>
                                          </span>
                                          {p.startDate && (
                                            <span>
                                              <i className="fas fa-calendar-check" style={{ marginLeft: '4px', color: '#38bdf8' }}></i>
                                              البدء: <span style={{ color: '#cbd5e1' }}>{p.startDate}</span>
                                            </span>
                                          )}
                                          {p.phone && (
                                            <a href={`tel:+970${p.phone}`} style={{ color: '#38bdf8', textDecoration: 'none', fontWeight: 600 }}>
                                              <i className="fas fa-phone" style={{ marginLeft: '4px' }}></i>{p.phone}
                                            </a>
                                          )}
                                        </div>
                                      </div>

                                      {/* Action Buttons & Days Badge */}
                                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                                        {renderUrgencyBadge(p.daysLeft)}

                                        {/* Edit Details Button */}
                                        <button
                                          type="button"
                                          onClick={() => {
                                            setEditTargetDept(p.dept);
                                            setSelectedStudentIndex(p.originalIndex);
                                            setFormData({
                                              ...p.student,
                                              department: p.dept,
                                              startDate: parseDateForInput(p.student.startDate || p.startDate || ''),
                                              endDate: parseDateForInput(p.student.endDate || p.endDate || ''),
                                              phone: p.student.phone || p.phone || '',
                                              name: p.student.name || p.name,
                                              university: p.student.university || p.university || '',
                                              address: p.student.address || '',
                                              shiftSystem: p.student.shiftSystem || '',
                                              idNumber: p.student.idNumber || '',
                                              graduationYear: p.student.graduationYear || '',
                                              attendanceDays: p.student.attendanceDays || '',
                                              studySystem: p.student.studySystem || '',
                                              internshipYear: p.student.internshipYear || '',
                                            });
                                            setActiveModal('edit');
                                          }}
                                          title="تعديل كامل البيانات وتاريخ الانتهاء"
                                          style={{
                                            background: 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)',
                                            border: '1px solid rgba(255,255,255,0.2)',
                                            color: 'white',
                                            borderRadius: '9px',
                                            padding: '6px 14px',
                                            fontSize: '0.8rem',
                                            fontWeight: 800,
                                            cursor: 'pointer',
                                            fontFamily: 'Tajawal',
                                            display: 'flex',
                                            alignItems: 'center',
                                            gap: '5px',
                                            boxShadow: '0 2px 8px rgba(37,99,235,0.3)'
                                          }}
                                        >
                                          <i className="fas fa-edit"></i> تعديل وتمديد
                                        </button>

                                        {/* One-Click Finish & Move to Leavers */}
                                        <button
                                          type="button"
                                          onClick={() => handleQuickGraduateStudent(p.dept, p.originalIndex)}
                                          title="إنهاء التدريب ونقل المتدرب مباشرة لقائمة المغادرين"
                                          style={{
                                            background: 'linear-gradient(135deg, #059669 0%, #047857 100%)',
                                            border: '1px solid rgba(16, 185, 129, 0.4)',
                                            color: '#ecfdf5',
                                            borderRadius: '9px',
                                            padding: '6px 14px',
                                            fontSize: '0.8rem',
                                            fontWeight: 800,
                                            cursor: 'pointer',
                                            fontFamily: 'Tajawal',
                                            display: 'flex',
                                            alignItems: 'center',
                                            gap: '5px',
                                            boxShadow: '0 2px 8px rgba(5,150,105,0.3)'
                                          }}
                                        >
                                          <i className="fas fa-user-graduate"></i> إنهاء التدريب
                                        </button>

                                        {/* Certificate */}
                                        <Link
                                          href={`/certificate?student=${encodeURIComponent(p.name)}&dept=${encodeURIComponent(p.dept)}`}
                                          style={{ background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', border: '1px solid rgba(255,255,255,0.2)', color: 'white', borderRadius: '9px', padding: '6px 12px', fontSize: '0.8rem', fontWeight: 800, textDecoration: 'none', display: 'flex', alignItems: 'center', gap: '5px' }}
                                          title="إصدار شهادة الخبرة"
                                        >
                                          <i className="fas fa-certificate"></i> الشهادة
                                        </Link>
                                      </div>
                                    </div>
                                  );
                                })}
                              </div>
                            );
                          })}
                        </div>
                      )}

                          {/* Bottom Collapse Button */}
                          <div style={{ textAlign: 'center', marginTop: '22px' }}>
                            <button
                              type="button"
                              onClick={() => setShowDepartureNames(false)}
                              style={{
                                background: 'rgba(255,255,255,0.08)',
                                color: '#cbd5e1',
                                border: '1px solid rgba(255,255,255,0.18)',
                                borderRadius: '12px',
                                padding: '10px 24px',
                                fontSize: '0.88rem',
                                fontWeight: 800,
                                cursor: 'pointer',
                                fontFamily: 'Tajawal',
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '8px',
                                boxShadow: '0 2px 10px rgba(0,0,0,0.25)',
                                transition: 'all 0.2s ease'
                              }}
                            >
                              <i className="fas fa-chevron-up"></i>
                              <span>إخفاء أسماء المتدربين والرجوع لوضع التنبيه فقط 🔼</span>
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                );
              })()}

              {/* ===== STATISTICAL & PERIODIC REPORT CARD ===== */}
              <div 
                onClick={() => setShowStatsReportModal(true)} 
                style={{
                  background: 'linear-gradient(135deg, #0D9488 0%, #0F766E 100%)',
                  borderRadius: '20px', padding: '24px 20px', color: 'white', cursor: 'pointer',
                  position: 'relative', overflow: 'hidden', boxShadow: '0 10px 30px rgba(13, 148, 136, 0.25)',
                  transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                  display: 'flex', alignItems: 'center', gap: '16px', marginBottom: '20px'
                }}
                onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 40px rgba(13, 148, 136, 0.4)'; }}
                onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 30px rgba(13, 148, 136, 0.25)'; }}
              >
                <div style={{ position: 'absolute', top: '-30px', left: '-30px', width: '100px', height: '100px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }}></div>
                <div style={{ background: 'rgba(255,255,255,0.2)', borderRadius: '14px', padding: '12px', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', zIndex: 1 }}>
                  <i className="fas fa-chart-pie" style={{ fontSize: '2rem', color: '#ffd700' }}></i>
                </div>
                <div style={{ position: 'relative', zIndex: 1, flex: 1 }}>
                  <div style={{ fontSize: '1.3rem', fontWeight: 900, display: 'flex', alignItems: 'center', gap: '10px' }}>
                    التقرير الإحصائي وتوزيع الفترات
                    <span style={{ background: 'rgba(255, 215, 0, 0.25)', color: '#ffd700', fontSize: '0.75rem', padding: '2px 10px', borderRadius: '20px', border: '1px solid rgba(255, 215, 0, 0.4)' }}>
                      شامل الأقسام
                    </span>
                  </div>
                  <div style={{ fontSize: '0.85rem', opacity: 0.9, marginTop: '4px' }}>
                    تخصيص الفترات الزمنية والأقسام، حساب الأعداد، وطباعة التقارير الإحصائية الرسمية
                  </div>
                </div>
                <button style={{
                  marginRight: 'auto', background: 'rgba(255,255,255,0.2)', border: '1px solid rgba(255,255,255,0.3)',
                  color: 'white', padding: '8px 18px', borderRadius: '12px', fontWeight: 'bold', cursor: 'pointer',
                  fontFamily: 'Tajawal', display: 'flex', alignItems: 'center', gap: '8px', position: 'relative', zIndex: 1
                }}>
                  <i className="fas fa-sliders-h"></i> فتح التقرير
                </button>
              </div>

              {/* ===== PRINT ALL QR CODES CARD ===== */}
              <Link href="/print-qr" style={{ textDecoration: 'none', display: 'block', marginBottom: '20px' }}>
                <div style={{
                  background: 'linear-gradient(135deg, #6B21A8 0%, #9333EA 100%)',
                  borderRadius: '20px', padding: '24px 20px', color: 'white', cursor: 'pointer',
                  position: 'relative', overflow: 'hidden', boxShadow: '0 10px 30px rgba(147, 51, 234, 0.25)',
                  transition: 'transform 0.3s ease, box-shadow 0.3s ease',
                  display: 'flex', alignItems: 'center', gap: '16px'
                }}
                onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 15px 40px rgba(147, 51, 234, 0.4)'; }}
                onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 30px rgba(147, 51, 234, 0.25)'; }}
                >
                  <div style={{ position: 'absolute', top: '-30px', left: '-30px', width: '100px', height: '100px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }}></div>
                  <div style={{ position: 'absolute', bottom: '-20px', right: '-20px', width: '70px', height: '70px', background: 'rgba(255,255,255,0.07)', borderRadius: '50%' }}></div>
                  <div style={{ background: 'rgba(255,255,255,0.2)', borderRadius: '14px', padding: '12px', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', zIndex: 1 }}>
                    <i className="fas fa-qrcode" style={{ fontSize: '2rem' }}></i>
                  </div>
                  <div style={{ position: 'relative', zIndex: 1, flex: 1 }}>
                    <div style={{ fontSize: '1.3rem', fontWeight: 900 }}>طباعة جميع رموز QR</div>
                    <div style={{ fontSize: '0.85rem', opacity: 0.88, marginTop: '4px' }}>جميع أقسام التقديم في صفحة واحدة قابلة للطباعة</div>
                  </div>
                  <i className="fas fa-print" style={{ marginRight: 'auto', fontSize: '1.4rem', opacity: 0.7, position: 'relative', zIndex: 1 }}></i>
                </div>
              </Link>

              {/* ══════════════════════════════════════════════════════════════════
                  DEDICATED SECTION: كادر تدريب تمريض الجامعات والأطباء المتعاقدون (مستقل)
              ══════════════════════════════════════════════════════════════════ */}
              <div style={{ marginBottom: '35px' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', flexWrap: 'wrap', gap: '10px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <div style={{ width: '44px', height: '44px', borderRadius: '14px', background: 'linear-gradient(135deg, #7c3aed, #4338ca)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 4px 15px rgba(124, 58, 237, 0.35)' }}>
                      <i className="fas fa-graduation-cap" style={{ fontSize: '1.4rem' }}></i>
                    </div>
                    <div>
                      <h2 style={{ fontSize: '1.45rem', fontWeight: 900, color: 'var(--text)', margin: 0, display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                        كادر تدريب تمريض الجامعات والأطباء المتعاقدون
                        <span style={{ fontSize: '0.78rem', background: '#ede9fe', color: '#6d28d9', padding: '3px 12px', borderRadius: '14px', fontWeight: 800, border: '1px solid #ddd6fe' }}>
                          قسم مستقل ومفصول تماماً
                        </span>
                      </h2>
                      <div style={{ fontSize: '0.84rem', color: 'var(--text-muted)', marginTop: '3px' }}>
                        إدارة ومتابعة طلبات المشرفين والمدربين الجامعيين والأطباء المتعاقدين المعتمدين في المستشفى
                      </div>
                    </div>
                  </div>

                  <Link
                    href="/admin/applications?tab=universities"
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '8px',
                      padding: '9px 18px',
                      borderRadius: '12px',
                      background: 'linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)',
                      color: 'white',
                      textDecoration: 'none',
                      fontSize: '0.88rem',
                      fontWeight: 800,
                      boxShadow: '0 4px 12px rgba(109, 40, 217, 0.3)',
                      transition: 'all 0.2s'
                    }}
                  >
                    <i className="fas fa-tasks"></i>
                    إدارة طلبات التعاقد والجامعات
                  </Link>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '18px' }}>
                  {/* Card 1: تدريب تمريض الجامعات */}
                  <div
                    onClick={() => setCurrentDepartment('تدريب تمريض الجامعات')}
                    style={{
                      background: 'linear-gradient(135deg, #0284c7 0%, #0369a1 100%)',
                      borderRadius: '22px',
                      padding: '24px 22px',
                      color: 'white',
                      position: 'relative',
                      overflow: 'hidden',
                      cursor: 'pointer',
                      boxShadow: '0 10px 25px rgba(2, 132, 199, 0.25)',
                      transition: 'all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)'
                    }}
                    onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px) scale(1.01)'; e.currentTarget.style.boxShadow = '0 16px 35px rgba(2, 132, 199, 0.35)'; }}
                    onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0) scale(1)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(2, 132, 199, 0.25)'; }}
                  >
                    <div style={{ position: 'absolute', top: '-25px', left: '-25px', width: '100px', height: '100px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }} />
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '14px', position: 'relative', zIndex: 1 }}>
                      <div style={{ width: '52px', height: '52px', borderRadius: '14px', background: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <i className="fas fa-user-nurse" style={{ fontSize: '1.7rem' }}></i>
                      </div>
                      <div style={{ background: 'rgba(255,255,255,0.25)', padding: '6px 16px', borderRadius: '20px', fontSize: '1.15rem', fontWeight: 900 }}>
                        {studentsData['تدريب تمريض الجامعات']?.length || 0} مدرب معتمد
                      </div>
                    </div>
                    <div style={{ position: 'relative', zIndex: 1 }}>
                      <h3 style={{ fontSize: '1.35rem', fontWeight: 900, marginBottom: '6px' }}>تدريب تمريض الجامعات</h3>
                      <p style={{ fontSize: '0.85rem', opacity: 0.9, margin: '0 0 14px 0', lineHeight: 1.4 }}>
                        كادر مشرفي ومدربي التمريض المنتدبين من الجامعات الشريكة
                      </p>
                      <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
                        <div style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', fontSize: '0.84rem', fontWeight: 800, background: 'rgba(0,0,0,0.18)', padding: '6px 14px', borderRadius: '10px' }}>
                          <span>فتح الجدول المخصص للكادر</span>
                          <i className="fas fa-arrow-left"></i>
                        </div>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            setReportDept('تدريب تمريض الجامعات');
                            setShowStatsReportModal(true);
                          }}
                          style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '6px',
                            fontSize: '0.84rem',
                            fontWeight: 800,
                            background: 'rgba(255,255,255,0.25)',
                            color: 'white',
                            padding: '6px 12px',
                            borderRadius: '10px',
                            border: 'none',
                            cursor: 'pointer',
                            fontFamily: 'Tajawal'
                          }}
                        >
                          <i className="fas fa-chart-pie"></i>
                          <span>التقرير الإحصائي للكادر</span>
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* Card 2: الأطباء المتعاقدون مع الجامعات */}
                  <div
                    onClick={() => setCurrentDepartment('الأطباء المتعاقدون')}
                    style={{
                      background: 'linear-gradient(135deg, #4338ca 0%, #3730a3 100%)',
                      borderRadius: '22px',
                      padding: '24px 22px',
                      color: 'white',
                      position: 'relative',
                      overflow: 'hidden',
                      cursor: 'pointer',
                      boxShadow: '0 10px 25px rgba(67, 56, 202, 0.25)',
                      transition: 'all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)'
                    }}
                    onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-4px) scale(1.01)'; e.currentTarget.style.boxShadow = '0 16px 35px rgba(67, 56, 202, 0.35)'; }}
                    onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0) scale(1)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(67, 56, 202, 0.25)'; }}
                  >
                    <div style={{ position: 'absolute', top: '-25px', left: '-25px', width: '100px', height: '100px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }} />
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '14px', position: 'relative', zIndex: 1 }}>
                      <div style={{ width: '52px', height: '52px', borderRadius: '14px', background: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <i className="fas fa-user-md" style={{ fontSize: '1.7rem' }}></i>
                      </div>
                      <div style={{ background: 'rgba(255,255,255,0.25)', padding: '6px 16px', borderRadius: '20px', fontSize: '1.15rem', fontWeight: 900 }}>
                        {studentsData['الأطباء المتعاقدون']?.length || 0} طبيب متعاقد
                      </div>
                    </div>
                    <div style={{ position: 'relative', zIndex: 1 }}>
                      <h3 style={{ fontSize: '1.35rem', fontWeight: 900, marginBottom: '6px' }}>الأطباء المتعاقدون مع الجامعات</h3>
                      <p style={{ fontSize: '0.85rem', opacity: 0.9, margin: '0 0 14px 0', lineHeight: 1.4 }}>
                        الأطباء والاستشاريون المتعاقدون للإشراف والتدريب في الأقسام
                      </p>
                      <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
                        <div style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', fontSize: '0.84rem', fontWeight: 800, background: 'rgba(0,0,0,0.18)', padding: '6px 14px', borderRadius: '10px' }}>
                          <span>فتح الجدول المخصص للكادر</span>
                          <i className="fas fa-arrow-left"></i>
                        </div>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            setReportDept('الأطباء المتعاقدون');
                            setShowStatsReportModal(true);
                          }}
                          style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '6px',
                            fontSize: '0.84rem',
                            fontWeight: 800,
                            background: 'rgba(255,255,255,0.25)',
                            color: 'white',
                            padding: '6px 12px',
                            borderRadius: '10px',
                            border: 'none',
                            cursor: 'pointer',
                            fontFamily: 'Tajawal'
                          }}
                        >
                          <i className="fas fa-chart-pie"></i>
                          <span>التقرير الإحصائي للكادر</span>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* ══════════════════════════════════════════════════════════════════
                  DEDICATED SECTION: مدربين الأقسام الصحية المساندة
              ══════════════════════════════════════════════════════════════════ */}
              {(() => {
                const healthDepts = [
                  { key: 'مدربي أشعة',        label: 'مدربو الأشعة',         sub: 'التصوير الطبي والأشعة التشخيصية',   icon: 'fas fa-radiation',        color: '#7C3AED', shadow: 'rgba(124,58,237,0.3)' },
                  { key: 'مدربي علاج طبيعي',  label: 'مدربو العلاج الطبيعي', sub: 'إعادة التأهيل والعلاج الحركي',      icon: 'fas fa-walking',          color: '#059669', shadow: 'rgba(5,150,105,0.3)'  },
                  { key: 'مدربي صيدلية',      label: 'مدربو الصيدلة',         sub: 'الصيدلة السريرية وإدارة الأدوية',   icon: 'fas fa-pills',            color: '#b45309', shadow: 'rgba(180,83,9,0.3)'   },
                  { key: 'مدربي تغذية',       label: 'مدربو التغذية',         sub: 'التغذية السريرية والعلاجية',         icon: 'fas fa-apple-alt',        color: '#16a34a', shadow: 'rgba(22,163,74,0.3)'  },
                  { key: 'مدربي مختبر',       label: 'مدربو المختبرات',       sub: 'المختبرات الطبية والتحاليل',         icon: 'fas fa-flask',            color: '#0284c7', shadow: 'rgba(2,132,199,0.3)'  },
                  { key: 'مدربي هندسة طبية',  label: 'مدربو الهندسة الطبية',  sub: 'الأجهزة والتقنيات الطبية',           icon: 'fas fa-microchip',        color: '#1d4ed8', shadow: 'rgba(29,78,216,0.3)'  },
                  { key: 'مدربي علاج وظيفي',  label: 'مدربو العلاج الوظيفي',  sub: 'العلاج الوظيفي والتكامل الحسي',      icon: 'fas fa-hands',            color: '#0f766e', shadow: 'rgba(15,118,110,0.3)' },
                ];
                const healthTotal = healthDepts.reduce((s, d) => s + (studentsData[d.key]?.length || 0), 0);

                return (
                  <div style={{ marginBottom: '35px' }}>

                    {/* ── Main Banner Card ── */}
                    <div
                      onClick={() => setShowHealthTrainersPanel(p => !p)}
                      style={{
                        background: showHealthTrainersPanel
                          ? 'linear-gradient(135deg, #0c4a6e 0%, #0369a1 50%, #0891b2 100%)'
                          : 'linear-gradient(135deg, #0891b2 0%, #0e7490 50%, #155e75 100%)',
                        borderRadius: showHealthTrainersPanel ? '22px 22px 0 0' : '22px',
                        padding: '26px 28px',
                        color: 'white',
                        position: 'relative',
                        overflow: 'hidden',
                        cursor: 'pointer',
                        boxShadow: showHealthTrainersPanel
                          ? '0 6px 20px rgba(8,145,178,0.35)'
                          : '0 12px 30px rgba(8,145,178,0.28)',
                        transition: 'all 0.3s ease',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '22px',
                        marginBottom: 0,
                      }}
                    >
                      {/* bg circles */}
                      <div style={{ position:'absolute', top:'-35px', left:'-35px', width:'130px', height:'130px', background:'rgba(255,255,255,0.08)', borderRadius:'50%' }} />
                      <div style={{ position:'absolute', bottom:'-20px', right:'-20px', width:'90px',  height:'90px',  background:'rgba(255,255,255,0.06)', borderRadius:'50%' }} />

                      {/* icon */}
                      <div style={{ width:'68px', height:'68px', borderRadius:'18px', background:'rgba(255,255,255,0.18)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, position:'relative', zIndex:1, boxShadow:'0 4px 14px rgba(0,0,0,0.15)' }}>
                        <i className="fas fa-chalkboard-teacher" style={{ fontSize:'2rem' }} />
                      </div>

                      {/* text */}
                      <div style={{ flex:1, position:'relative', zIndex:1 }}>
                        <div style={{ display:'flex', alignItems:'center', gap:'12px', marginBottom:'5px', flexWrap:'wrap' }}>
                          <span style={{ fontSize:'1.4rem', fontWeight:900 }}>مدربين الأقسام الصحية المساندة</span>
                          <span style={{ background:'rgba(255,255,255,0.22)', padding:'3px 14px', borderRadius:'20px', fontSize:'0.9rem', fontWeight:900 }}>
                            {healthTotal} مدرب
                          </span>
                          <span style={{ background:'rgba(255,255,255,0.15)', border:'1px solid rgba(255,255,255,0.3)', padding:'2px 11px', borderRadius:'12px', fontSize:'0.75rem', fontWeight:700 }}>
                            قسم مستقل
                          </span>
                        </div>
                        <div style={{ fontSize:'0.86rem', opacity:0.88, lineHeight:1.5, marginBottom:'10px' }}>
                          مدربو قسم الأشعة · العلاج الطبيعي · الصيدلة · التغذية · المختبرات · الهندسة الطبية · العلاج الوظيفي
                        </div>
                        {/* mini pills row */}
                        <div style={{ display:'flex', gap:'8px', flexWrap:'wrap' }}>
                          {healthDepts.map(d => (
                            <div key={d.key} style={{ background:'rgba(255,255,255,0.16)', borderRadius:'10px', padding:'3px 11px', fontSize:'0.78rem', fontWeight:700, display:'flex', alignItems:'center', gap:'5px' }}>
                              <i className={d.icon} style={{ fontSize:'0.72rem' }} />
                              <span>{d.label.replace('مدربو ','')}</span>
                              {(studentsData[d.key]?.length || 0) > 0 && (
                                <span style={{ background:'rgba(255,255,255,0.28)', borderRadius:'7px', padding:'0px 6px', fontSize:'0.73rem', fontWeight:900 }}>
                                  {studentsData[d.key]?.length}
                                </span>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>

                      {/* chevron */}
                      <div style={{ position:'relative', zIndex:1, flexShrink:0, transition:'transform 0.3s ease', transform: showHealthTrainersPanel ? 'rotate(90deg)' : 'rotate(0deg)' }}>
                        <div style={{ background:'rgba(255,255,255,0.2)', borderRadius:'12px', padding:'10px 14px', display:'flex', alignItems:'center', gap:'8px', fontSize:'0.88rem', fontWeight:800 }}>
                          <span>{showHealthTrainersPanel ? 'إغلاق' : 'فتح الأقسام'}</span>
                          <i className="fas fa-chevron-left" />
                        </div>
                      </div>
                    </div>

                    {/* ── Inline Sub-Cards Panel ── */}
                    {showHealthTrainersPanel && (
                      <div style={{
                        background: 'var(--card-bg, #f8fafc)',
                        border: '2px solid #bae6fd',
                        borderTop: '3px solid #0891b2',
                        borderRadius: '0 0 22px 22px',
                        padding: '24px 22px 22px',
                        boxShadow: '0 10px 30px rgba(8,145,178,0.12)',
                        animation: 'fadeIn 0.25s ease',
                      }}>
                        {/* panel header */}
                        <div style={{ display:'flex', alignItems:'center', gap:'10px', marginBottom:'18px' }}>
                          <div style={{ width:'36px', height:'36px', borderRadius:'10px', background:'linear-gradient(135deg,#0891b2,#0e7490)', color:'white', display:'flex', alignItems:'center', justifyContent:'center' }}>
                            <i className="fas fa-th" style={{ fontSize:'0.95rem' }} />
                          </div>
                          <div>
                            <div style={{ fontWeight:900, fontSize:'1.05rem', color:'var(--text,#0f172a)' }}>اختر القسم لعرض المدربين</div>
                            <div style={{ fontSize:'0.78rem', color:'var(--text-muted,#64748b)' }}>انقر على أي قسم لفتح جدول المدربين المخصص</div>
                          </div>
                        </div>

                        {/* individual sub-department cards grid */}
                        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px, 1fr))', gap:'16px' }}>
                          {healthDepts.map(dept => {
                            const count = studentsData[dept.key]?.length || 0;
                            return (
                              <div
                                key={dept.key}
                                onClick={() => { setCurrentDepartment(dept.key); setShowHealthTrainersPanel(false); }}
                                style={{
                                  background: `linear-gradient(145deg, ${dept.color}f0, ${dept.color}c0)`,
                                  borderRadius: '18px',
                                  padding: '22px 20px',
                                  color: 'white',
                                  cursor: 'pointer',
                                  position: 'relative',
                                  overflow: 'hidden',
                                  boxShadow: `0 8px 22px ${dept.shadow}`,
                                  transition: 'all 0.3s cubic-bezier(0.175,0.885,0.32,1.275)',
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '16px',
                                }}
                                onMouseOver={e => { e.currentTarget.style.transform='translateY(-5px) scale(1.02)'; e.currentTarget.style.boxShadow=`0 16px 35px ${dept.shadow.replace('0.3)','0.45)')}`; }}
                                onMouseOut={e  => { e.currentTarget.style.transform='translateY(0) scale(1)';   e.currentTarget.style.boxShadow=`0 8px 22px ${dept.shadow}`; }}
                              >
                                {/* bg bubble */}
                                <div style={{ position:'absolute', top:'-20px', left:'-20px', width:'80px', height:'80px', background:'rgba(255,255,255,0.1)', borderRadius:'50%' }} />

                                {/* icon box */}
                                <div style={{ width:'56px', height:'56px', borderRadius:'14px', background:'rgba(255,255,255,0.22)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, position:'relative', zIndex:1, boxShadow:'0 3px 10px rgba(0,0,0,0.12)' }}>
                                  <i className={dept.icon} style={{ fontSize:'1.6rem' }} />
                                </div>

                                {/* info */}
                                <div style={{ flex:1, position:'relative', zIndex:1 }}>
                                  <div style={{ fontSize:'1.05rem', fontWeight:900, marginBottom:'3px' }}>{dept.label}</div>
                                  <div style={{ fontSize:'0.78rem', opacity:0.88, marginBottom:'8px', lineHeight:1.3 }}>{dept.sub}</div>
                                  <div style={{ display:'inline-flex', alignItems:'center', gap:'6px', background:'rgba(0,0,0,0.18)', padding:'4px 12px', borderRadius:'10px' }}>
                                    <span style={{ fontSize:'1.1rem', fontWeight:900 }}>{count}</span>
                                    <span style={{ fontSize:'0.77rem', opacity:0.9 }}>مدرب مسجل</span>
                                  </div>
                                </div>

                                {/* arrow */}
                                <div style={{ position:'relative', zIndex:1, flexShrink:0 }}>
                                  <i className="fas fa-arrow-left" style={{ fontSize:'1.1rem', opacity:0.8 }} />
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })()}

              {/* MAIN CATEGORIES */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '20px' }}>
                <i className="fas fa-layer-group" style={{ fontSize: '1.6rem', color: 'var(--primary)' }}></i>
                <h2 style={{ fontSize: '1.5rem', fontWeight: 800, color: 'var(--text)', margin: 0 }}>الأقسام الرئيسية</h2>
              </div>
              
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '20px', marginBottom: '40px' }}>
                {[
                  { id: 'medicine', title: 'أطباء الامتياز', desc: 'الجراحة، الأطفال، النسائية', icon: 'fas fa-stethoscope', gradient: 'linear-gradient(135deg, #4F46E5 0%, #6366F1 100%)' },
                  { id: 'nursing', title: 'التمريض', desc: 'التمريض، تمريض تدريب، تمريض امتياز', icon: 'fas fa-user-nurse', gradient: 'linear-gradient(135deg, #0D9488 0%, #14B8A6 100%)' },
                  { id: 'volunteer', title: 'التطوع', desc: 'طب تطوع، تمريض تطوع، علاج طبيعي، تغذية، صحة نفسية، خدمة اجتماعية', icon: 'fas fa-hands-helping', gradient: 'linear-gradient(135deg, #059669 0%, #10B981 100%)' },
                  { id: 'allied', title: 'المهن الطبية المساندة', desc: 'علاج طبيعي تدريب، علاج طبيعي امتياز، علاج وظيفي، تغذية، أشعة', icon: 'fas fa-x-ray', gradient: 'linear-gradient(135deg, #D97706 0%, #F59E0B 100%)' },
                  { id: 'admin', title: 'الإدارة والخدمات', desc: 'الإدارة، المحاسبة، المطبخ، ضباط الإسعاف', icon: 'fas fa-briefcase', gradient: 'linear-gradient(135deg, #3F3F46 0%, #52525B 100%)' },
                ].map(cat => {
                  let total = 0;
                  if (cat.id === 'medicine') total = (studentsData['جراحة']?.length||0) + (studentsData['نسائية']?.length||0) + (studentsData['الاطفال']?.length||0);
                  if (cat.id === 'nursing') total = (studentsData['التمريض']?.length||0) + (studentsData['تمريض تدريب']?.length||0) + (studentsData['تمريض امتياز']?.length||0);
                  if (cat.id === 'volunteer') total = (studentsData['طب تطوع']?.length||0) + (studentsData['تمريض تطوع']?.length||0) + (studentsData['العلاج الطبيعي']?.length||0) + (studentsData['تغذية']?.length||0) + (studentsData['الصحة النفسية']?.length||0) + (studentsData['خدمة اجتماعية']?.length||0);
                  if (cat.id === 'allied') total = (studentsData['علاج طبيعي تدريب']?.length||0) + (studentsData['علاج طبيعي امتياز']?.length||0) + (studentsData['العلاج الطبيعي']?.length||0) + (studentsData['الصحة النفسية']?.length||0) + (studentsData['أشعة']?.length||0) + (studentsData['تغذية']?.length||0);
                  if (cat.id === 'admin') total = (studentsData['إدارة']?.length||0) + (studentsData['المحاسبة']?.length||0) + (studentsData['المطبخ']?.length||0) + (studentsData['ضباط الإسعاف']?.length||0);

                  return (
                    <div key={cat.id} onClick={() => setExpandedCategory(cat.id)} style={{
                      background: cat.gradient,
                      borderRadius: '24px', padding: '32px 24px', color: 'white',
                      position: 'relative', overflow: 'hidden', cursor: 'pointer',
                      boxShadow: '0 10px 25px rgba(0,0,0,0.15)',
                      transition: 'transform 0.3s ease, box-shadow 0.3s ease'
                    }}
                    onMouseOver={(e) => { e.currentTarget.style.transform = 'translateY(-6px)'; e.currentTarget.style.boxShadow = '0 20px 40px rgba(0,0,0,0.25)'; }}
                    onMouseOut={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 10px 25px rgba(0,0,0,0.15)'; }}
                    >
                      <div style={{ position: 'absolute', top: '-40px', left: '-40px', width: '130px', height: '130px', background: 'rgba(255,255,255,0.1)', borderRadius: '50%' }}></div>
                      <div style={{ position: 'absolute', bottom: '-20px', right: '-20px', width: '80px', height: '80px', background: 'rgba(255,255,255,0.08)', borderRadius: '50%' }}></div>
                      
                      <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', height: '100%' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '20px' }}>
                          <i className={cat.icon} style={{ fontSize: '2.5rem', opacity: 1 }}></i>
                          <div style={{ background: 'rgba(255,255,255,0.2)', padding: '6px 16px', borderRadius: '30px', fontSize: '1rem', fontWeight: 800 }}>
                            {total} طالب
                          </div>
                        </div>
                        
                        <div style={{ marginTop: 'auto' }}>
                          <h3 style={{ fontSize: '1.6rem', fontWeight: 900, marginBottom: '8px' }}>{cat.title}</h3>
                          <p style={{ fontSize: '0.9rem', opacity: 0.9, margin: 0, lineHeight: 1.4 }}>{cat.desc}</p>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          ) : (
            <>
              {/* EXPANDED CATEGORY VIEW */}
              <div style={{ marginBottom: '40px', animation: 'fadeIn 0.3s ease' }}>
                <button className="back-btn" onClick={() => setExpandedCategory(null)} style={{ marginBottom: '25px', padding: '10px 20px', fontSize: '1rem' }}>
                  <i className="fas fa-arrow-right"></i>
                  رجوع للتصنيفات الرئيسية
                </button>
                
                {(() => {
                  let depts: any[] = [];
                  let catTitle = '';
                  let catIcon = '';
                  if (expandedCategory === 'medicine') {
                    catTitle = 'أطباء الامتياز';
                    catIcon = 'fas fa-stethoscope';
                    depts = [
                      { key: 'CATEGORY_ALL_medicine', icon: 'fas fa-users', color: '#4F46E5', label: 'الكل' },
                      { key: 'جراحة', icon: 'fas fa-procedures', color: '#4F46E5', label: 'الجراحة العامة' },
                      { key: 'نسائية', icon: 'fas fa-female', color: '#7C3AED', label: 'النسائية والتوليد' },
                      { key: 'الاطفال', icon: 'fas fa-baby', color: '#D97706', label: 'طب الأطفال' },
                      { key: 'الأطباء المتعاقدون', icon: 'fas fa-user-md', color: '#4338ca', label: 'الأطباء المتعاقدون' },
                      { key: 'طب تدريب', icon: 'fas fa-hospital-user', color: '#c2185b', label: 'طب تدريب' }
                    ];
                  } else if (expandedCategory === 'nursing') {
                    catTitle = 'التمريض';
                    catIcon = 'fas fa-user-nurse';
                    depts = [
                      { key: 'CATEGORY_ALL_nursing', icon: 'fas fa-users', color: '#0D9488', label: 'الكل' },
                      { key: 'التمريض', icon: 'fas fa-heartbeat', color: '#0D9488', label: 'التمريض العام' },
                      { key: 'تدريب تمريض الجامعات', icon: 'fas fa-graduation-cap', color: '#0284c7', label: 'تدريب تمريض الجامعات' },
                      { key: 'تمريض تدريب', icon: 'fas fa-syringe', color: '#0891B2', label: 'تمريض تدريب' },
                      { key: 'تمريض امتياز', icon: 'fas fa-stethoscope', color: '#7C3AED', label: 'تمريض امتياز' },
                      { key: 'تمريض تطوع', icon: 'fas fa-hand-holding-medical', color: '#00bcd4', label: 'تمريض تطوع' }
                    ];
                  } else if (expandedCategory === 'allied') {
                    catTitle = 'المهن الطبية المساندة';
                    catIcon = 'fas fa-x-ray';
                    depts = [
                      { key: 'CATEGORY_ALL_allied', icon: 'fas fa-users', color: '#D97706', label: 'الكل' },
                      { key: 'علاج طبيعي تدريب', icon: 'fas fa-walking', color: '#16a34a', label: 'علاج طبيعي تدريب' },
                      { key: 'علاج طبيعي امتياز', icon: 'fas fa-user-graduate', color: '#059669', label: 'علاج طبيعي امتياز' },
                      { key: 'مختبرات طبية', icon: 'fas fa-vial', color: '#0284c7', label: 'المختبرات الطبية' },
                      { key: 'أشعة', icon: 'fas fa-radiation', color: '#7C3AED', label: 'الأشعة والتصوير الطبي' },
                      { key: 'العلاج الوظيفي', icon: 'fas fa-hands', color: '#16a085', label: 'العلاج الوظيفي' },
                      { key: 'تغذية', icon: 'fas fa-apple-alt', color: '#10B981', label: 'التغذية السريرية' },
                      { key: 'الصحة النفسية', icon: 'fas fa-brain', color: '#059669', label: 'الصحة النفسية' },
                      { key: 'ضباط الإسعاف', icon: 'fas fa-ambulance', color: '#EA580C', label: 'ضباط الإسعاف' }
                    ];
                  } else if (expandedCategory === 'admin') {
                    catTitle = 'الإدارة والخدمات';
                    catIcon = 'fas fa-briefcase';
                    depts = [
                      { key: 'CATEGORY_ALL_admin', icon: 'fas fa-users', color: '#3F3F46', label: 'الكل' },
                      { key: 'إدارة', icon: 'fas fa-building', color: '#52525B', label: 'إدارة' },
                      { key: 'المحاسبة', icon: 'fas fa-calculator', color: '#78716C', label: 'المحاسبة والمالية' },
                      { key: 'سكرتارية طبية', icon: 'fas fa-file-invoice', color: '#00838f', label: 'سكرتارية طبية' },
                      { key: 'المطبخ', icon: 'fas fa-utensils', color: '#B45309', label: 'المطبخ والإعاشة' },
                      { key: 'العمل المجتمعي', icon: 'fas fa-handshake', color: '#00695c', label: 'العمل المجتمعي' }
                    ];
                  } else if (expandedCategory === 'volunteer') {
                    catTitle = 'التطوع';
                    catIcon = 'fas fa-hands-helping';
                    depts = [
                      { key: 'CATEGORY_ALL_volunteer', icon: 'fas fa-users', color: '#059669', label: 'الكل' },
                      { key: 'طب تطوع', icon: 'fas fa-hands-helping', color: '#4F46E5', label: 'طب تطوع' },
                      { key: 'تمريض تطوع', icon: 'fas fa-user-nurse', color: '#0D9488', label: 'تمريض تطوع' },
                      { key: 'العلاج الطبيعي', icon: 'fas fa-walking', color: '#D97706', label: 'علاج طبيعي تطوع' },
                      { key: 'تغذية', icon: 'fas fa-apple-alt', color: '#059669', label: 'تغذية تطوع' },
                      { key: 'الصحة النفسية', icon: 'fas fa-brain', color: '#0D9488', label: 'الصحة النفسية تطوع' },
                      { key: 'خدمة اجتماعية', icon: 'fas fa-users', color: '#854D0E', label: 'خدمة اجتماعية' }
                    ];
                  } else if (expandedCategory === 'health-trainers') {
                    catTitle = 'مدربين الأقسام الصحية المساندة';
                    catIcon = 'fas fa-chalkboard-teacher';
                    depts = [
                      { key: 'CATEGORY_ALL_health-trainers', icon: 'fas fa-users', color: '#0891b2', label: 'الكل' },
                      { key: 'مدربي أشعة', icon: 'fas fa-radiation', color: '#7C3AED', label: 'مدربو الأشعة والتصوير الطبي' },
                      { key: 'مدربي هندسة طبية', icon: 'fas fa-microchip', color: '#1d4ed8', label: 'مدربو الهندسة الطبية' },
                      { key: 'مدربي تغذية', icon: 'fas fa-apple-alt', color: '#16a34a', label: 'مدربو التغذية السريرية' },
                      { key: 'مدربي صيدلية', icon: 'fas fa-pills', color: '#b45309', label: 'مدربو الصيدلة' },
                      { key: 'مدربي مختبر', icon: 'fas fa-flask', color: '#0284c7', label: 'مدربو المختبرات الطبية' },
                      { key: 'مدربي علاج طبيعي', icon: 'fas fa-walking', color: '#059669', label: 'مدربو العلاج الطبيعي' },
                      { key: 'مدربي علاج وظيفي', icon: 'fas fa-hands', color: '#0f766e', label: 'مدربو العلاج الوظيفي' },
                    ];
                  }

                  return (
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '15px', marginBottom: '30px', paddingRight: '10px' }}>
                        <div style={{ width: '50px', height: '50px', borderRadius: '14px', background: 'var(--primary)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <i className={catIcon} style={{ fontSize: '1.5rem' }}></i>
                        </div>
                        <h2 style={{ fontSize: '1.8rem', fontWeight: 800, color: 'var(--text)', margin: 0 }}>
                          أقسام {catTitle}
                        </h2>
                      </div>
                      
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '20px' }}>
                        {depts.map(dept => {
                          let count = 0;
                          if (dept.key.startsWith('CATEGORY_ALL_')) {
                            count = depts.reduce((acc, d) => acc + (d.key !== dept.key ? (studentsData[d.key]?.length || 0) : 0), 0);
                          } else {
                            count = studentsData[dept.key]?.length || 0;
                          }
                          return (
                            <div key={dept.key} onClick={() => setCurrentDepartment(dept.key)} style={{
                              background: `linear-gradient(145deg, ${dept.color}fa, ${dept.color}d5)`,
                              borderRadius: '20px', padding: '30px 25px', color: 'white',
                              position: 'relative', overflow: 'hidden', cursor: 'pointer',
                              boxShadow: `0 12px 30px ${dept.color}30`,
                              transition: 'all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)'
                            }}
                            onMouseOver={(e) => { 
                              e.currentTarget.style.transform = 'translateY(-6px) scale(1.02)'; 
                              e.currentTarget.style.boxShadow = `0 18px 40px ${dept.color}45`; 
                            }}
                            onMouseOut={(e) => { 
                              e.currentTarget.style.transform = 'translateY(0) scale(1)'; 
                              e.currentTarget.style.boxShadow = `0 12px 30px ${dept.color}30`; 
                            }}
                            >
                              <div style={{ position: 'absolute', top: '-25px', left: '-25px', width: '100px', height: '100px', background: 'rgba(255,255,255,0.08)', borderRadius: '50%', transition: 'all 0.3s ease' }}></div>
                              
                              <div style={{ display: 'flex', alignItems: 'center', gap: '20px', position: 'relative', zIndex: 1 }}>
                                <div style={{ width: '60px', height: '60px', background: 'rgba(255,255,255,0.2)', borderRadius: '16px', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                                  <i className={dept.icon} style={{ fontSize: '1.8rem' }}></i>
                                </div>
                                <div style={{ flex: 1 }}>
                                  <div style={{ fontSize: '1.3rem', fontWeight: 800, marginBottom: '5px' }}>{dept.label}</div>
                                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', background: 'rgba(0,0,0,0.15)', padding: '4px 12px', borderRadius: '12px' }}>
                                    <span style={{ fontSize: '1.1rem', fontWeight: 900 }}>{count}</span>
                                    <span style={{ fontSize: '0.8rem', opacity: 0.9 }}>طالب/متدرب</span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })()}
              </div>
            </>
          )}

          {/* ═══════════ QUICK LINKS ROW ═══════════ */}
          {expandedCategory && (
            <div style={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
              gap: '16px', 
              marginBottom: '30px',
              marginTop: '10px'
            }}>
              {/* Schedule Generator - For ALL Specialties */}
              <Link href="/schedule" className="department-card schedule-generator" style={{ textDecoration: 'none' }}>
                <div className="card-header" style={{ 
                  background: 'linear-gradient(135deg, #4F46E5 0%, #6366F1 100%)',
                  position: 'relative', overflow: 'hidden'
                }}>
                  <i className="fas fa-calendar-alt icon"></i>
                  <h3>توزيع جدول الدوام ✨</h3>
                  <div className="count-label" style={{ fontSize: '1rem', marginTop: '10px' }}>إنشاء وتوزيع جداول المناوبات</div>
                </div>
              </Link>

              {/* Experience Certificate - For ALL Specialties */}
              <Link href="/certificate" className="department-card certificate-card" style={{ textDecoration: 'none' }}>
                <div className="card-header" style={{ 
                  background: 'linear-gradient(135deg, #8B1A2B 0%, #B91C1C 100%)',
                  position: 'relative', overflow: 'hidden'
                }}>
                  <i className="fas fa-certificate icon"></i>
                  <h3>شهادات الخبرة ✨</h3>
                  <div className="count-label" style={{ fontSize: '1rem', marginTop: '10px' }}>إصدار وطباعة شهادات الخبرة</div>
                </div>
              </Link>

              {/* Graduates */}
              <div className="department-card graduates" onClick={() => setCurrentDepartment('المغادرين')}>
                <div className="card-header">
                  <i className="fas fa-user-graduate icon"></i>
                  <h3>المغادرين</h3>
                  <div className="count">{studentsData['المغادرين']?.length || 0}</div>
                  <div className="count-label">أنهوا التدريب</div>
                </div>
              </div>

              {/* Suspended */}
              <div className="department-card suspended" onClick={() => setCurrentDepartment('الاستئناف')}>
                <div className="card-header">
                  <i className="fas fa-pause-circle icon"></i>
                  <h3>الاستئناف</h3>
                  <div className="count">{studentsData['الاستئناف']?.length || 0}</div>
                  <div className="count-label">إجازة مؤقتة</div>
                </div>
              </div>

            </div>
          )}
        </>
      )}

      {/* University Chart View */}
      {currentDepartment === 'الجامعات' && (
        <div style={{ padding: '0 10px' }}>
          <div style={{ marginBottom: '20px' }}>
            <button className="back-btn" onClick={() => { setCurrentDepartment(null); }}>
              <i className="fas fa-arrow-right"></i>
              رجوع للأقسام
            </button>
          </div>

          {/* Faculty Filter Tabs */}
          {(() => {
            const facultyFilters = [
              { key: 'all', label: 'الكل (جميع المتدربين والمغادرين)', unitLabel: 'متدرب', icon: 'fas fa-globe', color: '#6366f1', depts: null },
              { key: 'medicine', label: 'طب بشري', unitLabel: 'طبيب', icon: 'fas fa-stethoscope', color: '#8B1A2B', depts: ['جراحة', 'نسائية', 'الاطفال', 'طب تدريب', 'طب تطوع', 'الأطباء المتعاقدون'] },
              { key: 'nursing', label: 'تمريض وقبالة', unitLabel: 'ممرض/ة', icon: 'fas fa-heartbeat', color: '#7b1fa2', depts: ['التمريض', 'تمريض تدريب', 'تمريض امتياز', 'تدريب تمريض الجامعات', 'أطفال', 'طوارئ', 'كلى', 'عمليات', 'قبل الولادة', 'بعد الولادة', 'ICU', 'NICU', 'PICU'] },
              { key: 'allied', label: 'مهن مساندة ومختبرات', unitLabel: 'أخصائي', icon: 'fas fa-briefcase-medical', color: '#27ae60', depts: ['العلاج الطبيعي', 'العلاج الوظيفي', 'الصحة النفسية', 'الصحة النفسية تطوع', 'أشعة', 'تغذية', 'خدمة اجتماعية', 'مختبرات طبية', 'سكرتارية طبية', 'ضباط الإسعاف'] },
              { key: 'admin', label: 'إداري وخدمات', unitLabel: 'متدرب', icon: 'fas fa-building', color: '#2c3e50', depts: ['إدارة', 'المحاسبة', 'المطبخ', 'العمل المجتمعي'] },
              { key: 'health-trainers', label: 'مدربين الأقسام الصحية المساندة', unitLabel: 'مدرب', icon: 'fas fa-chalkboard-teacher', color: '#0891b2', depts: ['مدربي أشعة', 'مدربي هندسة طبية', 'مدربي تغذية', 'مدربي صيدلية', 'مدربي مختبر', 'مدربي علاج طبيعي', 'مدربي علاج وظيفي'] },
              { key: 'graduates', label: 'المغادرين (أنهوا التدريب)', unitLabel: 'خريج', icon: 'fas fa-user-graduate', color: '#78909c', depts: ['المغادرين'] }
            ];

            const activeFilter = universityFilter || 'all';
            const currentFilter = facultyFilters.find(f => f.key === activeFilter) || facultyFilters[0];

            // Filter students based on selected faculty from allStatisticalStudents
            const filteredForUni = currentFilter.key === 'graduates'
              ? (studentsData['المغادرين'] || [])
              : currentFilter.depts 
                ? allStatisticalStudents.filter(s => currentFilter.depts!.includes(s.department) || (s.originalDepartment && currentFilter.depts!.includes(s.originalDepartment)))
                : allStatisticalStudents;

            // Build university stats for filtered students
            // For trainers: use contractedUniversity 🤝 (not graduation university 🎓)
            const filteredUniStats: { name: string; value: number }[] = [];
            const uniMap: { [key: string]: number } = {};
            let noUni = 0;
            filteredForUni.forEach(s => {
              // Determine whether this person is a trainer (uses contracted uni) or regular student (uses graduation uni)
              const isTrainerRow = (
                s.department === 'تدريب تمريض الجامعات' ||
                s.originalDepartment === 'تدريب تمريض الجامعات' ||
                s.department === 'الأطباء المتعاقدون' ||
                s.originalDepartment === 'الأطباء المتعاقدون' ||
                (s.department || '').startsWith('مدربي ') ||
                (s.originalDepartment || '').startsWith('مدربي ') ||
                s.studySystem === 'تمريض جامعات' ||
                s.internshipYear === 'مدرب سريري' ||
                s.isUniversityTrainer
              );
              const rawUni = isTrainerRow
                ? (s.contractedUniversity ||
                   (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
                   s.previousContractedUniversity ||
                   s.university)
                : s.university;
              const u = normalizeUniversityName(rawUni);
              if (u === 'جامعات أخرى / غير محدد') {
                noUni++;
              } else {
                uniMap[u] = (uniMap[u] || 0) + 1;
              }
            });
            Object.entries(uniMap).sort((a, b) => b[1] - a[1]).forEach(([name, value]) => {
              filteredUniStats.push({ name, value });
            });
            if (noUni > 0) filteredUniStats.push({ name: 'بدون جامعة / أخرى', value: noUni });

            const totalFiltered = filteredForUni.length;

            return (
              <>
                {/* Filter Tabs */}
                <div style={{ 
                  display: 'flex', gap: '8px', marginBottom: '20px', flexWrap: 'wrap',
                  background: 'var(--card-bg)', padding: '12px 16px', borderRadius: '16px',
                  boxShadow: '0 2px 12px rgba(0,0,0,0.06)', border: '1px solid var(--border)'
                }}>
                  {facultyFilters.map(f => (
                    <button
                      key={f.key}
                      onClick={() => setUniversityFilter(f.key)}
                      style={{
                        padding: '10px 20px',
                        borderRadius: '12px',
                        border: activeFilter === f.key ? `2px solid ${f.color}` : '2px solid transparent',
                        background: activeFilter === f.key ? `${f.color}15` : 'var(--bg-light)',
                        color: activeFilter === f.key ? f.color : 'var(--text-secondary)',
                        fontWeight: activeFilter === f.key ? '800' : '600',
                        cursor: 'pointer',
                        display: 'flex', alignItems: 'center', gap: '8px',
                        fontFamily: 'Tajawal, sans-serif',
                        fontSize: '0.95rem',
                        transition: 'all 0.3s',
                        boxShadow: activeFilter === f.key ? `0 4px 15px ${f.color}20` : 'none'
                      }}
                    >
                      <i className={f.icon} style={{ fontSize: '0.9rem' }}></i>
                      {f.label}
                      <span style={{
                        background: activeFilter === f.key ? f.color : 'var(--text-secondary)',
                        color: 'white',
                        padding: '2px 8px',
                        borderRadius: '20px',
                        fontSize: '0.75rem',
                        fontWeight: '700',
                        minWidth: '24px',
                        textAlign: 'center'
                      }}>
                        {f.key === 'graduates' 
                          ? (studentsData['المغادرين']?.length || 0)
                          : f.depts 
                            ? allStatisticalStudents.filter(s => f.depts!.includes(s.department) || (s.originalDepartment && f.depts!.includes(s.originalDepartment))).length 
                            : allStatisticalStudents.length}
                      </span>
                    </button>
                  ))}
                </div>

                {/* University Chart Section */}
                <div style={{ 
                  marginBottom: '30px', 
                  background: 'var(--card-bg)', 
                  padding: '30px', 
                  borderRadius: '20px', 
                  boxShadow: '0 8px 32px rgba(0,0,0,0.08)', 
                  border: `2px solid ${currentFilter.color}30`,
                  position: 'relative',
                  overflow: 'hidden'
                }}>
                  <div style={{ position: 'absolute', top: '-40px', left: '-40px', width: '120px', height: '120px', background: `${currentFilter.color}08`, borderRadius: '50%' }}></div>
                  <div style={{ position: 'absolute', bottom: '-30px', right: '-30px', width: '100px', height: '100px', background: `${currentFilter.color}08`, borderRadius: '50%' }}></div>
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '25px', position: 'relative', zIndex: 1 }}>
                    <h3 style={{ color: currentFilter.color, fontSize: '1.2rem', fontWeight: '700', display: 'flex', alignItems: 'center', gap: '10px' }}>
                      <i className="fas fa-chart-pie" style={{ fontSize: '1.1rem' }}></i>
                      توزيع الطلاب حسب الجامعات — {currentFilter.label}
                    </h3>
                    <span style={{ 
                      background: `${currentFilter.color}15`, 
                      color: currentFilter.color, 
                      padding: '6px 16px', 
                      borderRadius: '20px', 
                      fontWeight: '700',
                      fontSize: '0.9rem'
                    }}>
                      {totalFiltered} متدرب
                    </span>
                  </div>

                  {filteredUniStats.length === 0 ? (
                    <div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--text-secondary)' }}>
                      <i className="fas fa-inbox" style={{ fontSize: '3rem', marginBottom: '15px', opacity: 0.3 }}></i>
                      <p style={{ fontSize: '1.1rem' }}>لا يوجد متدربين في هذا القسم</p>
                    </div>
                  ) : (
                    <div style={{ 
                      display: 'grid',
                      gridTemplateColumns: 'minmax(250px, 400px) 1fr',
                      gap: '40px',
                      alignItems: 'start'
                    }}>
                      {/* Left Side: Chart */}
                      <div style={{ height: '350px', position: 'relative' }}>
                        <ResponsiveContainer width="100%" height="100%">
                          <PieChart>
                            <Pie
                              data={filteredUniStats}
                              cx="50%"
                              cy="50%"
                              innerRadius={80}
                              outerRadius={120}
                              paddingAngle={5}
                              dataKey="value"
                              stroke="none"
                            >
                              {filteredUniStats.map((entry, index) => (
                                <Cell key={index} fill={COLORS[index % COLORS.length]} />
                              ))}
                            </Pie>
                            <Tooltip 
                              contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 15px rgba(0,0,0,0.1)' }}
                              itemStyle={{ color: '#fff' }}
                            />
                          </PieChart>
                        </ResponsiveContainer>
                        <div style={{
                          position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
                          textAlign: 'center', pointerEvents: 'none'
                        }}>
                          <div style={{ fontSize: '2.5rem', fontWeight: '800', lineHeight: 1, color: 'var(--text)' }}>
                            {totalFiltered}
                          </div>
                          <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>{currentFilter.label}</div>
                        </div>
                      </div>

                      {/* Right Side: Faculty List nested cards */}
                      <div style={{ 
                        display: 'grid', 
                        gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', 
                        gap: '15px' 
                      }}>
                        {filteredUniStats.map((stat, index) => {
                          const percentage = totalFiltered > 0 ? ((stat.value / totalFiltered) * 100).toFixed(1) : '0';
                          const isExpanded = expandedUniversity === stat.name;
                          const color = COLORS[index % COLORS.length];

                          return (
                            <div key={index} style={{ gridColumn: isExpanded ? '1 / -1' : undefined }}>
                              <div 
                                onClick={() => setExpandedUniversity(isExpanded ? null : stat.name)}
                                style={{ 
                                  background: isExpanded ? `linear-gradient(135deg, ${color}20, ${color}08)` : 'var(--card-bg)',
                                  border: `2px solid ${isExpanded ? color : 'var(--border)'}`,
                                  borderRadius: isExpanded ? '16px 16px 0 0' : '16px',
                                  padding: '20px',
                                  cursor: 'pointer',
                                  transition: 'all 0.3s ease',
                                  position: 'relative',
                                  overflow: 'hidden',
                                  boxShadow: isExpanded ? `0 8px 25px ${color}25` : '0 2px 8px rgba(0,0,0,0.05)',
                                }}
                              >
                                {isExpanded && (
                                  <div style={{
                                    position: 'absolute', top: 0, right: 0, bottom: 0, width: '4px', background: color
                                  }}></div>
                                )}
                                <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
                                  <div style={{ width: '40px', height: '40px', borderRadius: '12px', background: `${color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: color }}>
                                    <i className="fas fa-university" style={{ fontSize: '1.2rem' }}></i>
                                  </div>
                                  <div style={{ flex: 1 }}>
                                    <div style={{ fontSize: '1rem', fontWeight: 'bold', color: 'var(--text)', marginBottom: '4px', lineHeight: 1.3 }}>{stat.name}</div>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                      <span style={{ fontSize: '1.2rem', fontWeight: '800', color }}>{stat.value}</span>
                                      <span style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>{currentFilter.unitLabel} ({percentage}%)</span>
                                    </div>
                                  </div>
                                  <div style={{ color: 'var(--text-secondary)' }}>
                                    <i className={`fas fa-chevron-${isExpanded ? 'up' : 'down'}`} style={{ transition: 'transform 0.3s' }}></i>
                                  </div>
                                </div>
                              </div>

                              {isExpanded && (
                                <div style={{ background: 'var(--card-bg)', border: `2px solid ${color}`, borderTop: 'none', borderRadius: '0 0 16px 16px', padding: '20px', animation: 'slideDown 0.3s ease-out' }}>
                                  <table className="students-table" style={{ margin: 0, width: '100%' }}>
                                    <thead>
                                      <tr>
                                        <th>الاسم</th>
                                        <th>القسم</th>
                                        <th>رقم الهاتف</th>
                                      </tr>
                                    </thead>
                                    <tbody>
                                      {filteredForUni.filter(s => {
                                        const u = normalizeUniversityName(s.university);
                                        return stat.name === 'بدون جامعة / أخرى'
                                          ? (u === 'جامعات أخرى / غير محدد')
                                          : u === stat.name;
                                      }).map((student, i) => (
                                        <tr key={i}>
                                          <td>
                                            <div className="doctor-badge">
                                              <i className="fas fa-user-md" style={{ color: color }}></i>
                                              <span>{student.name}</span>
                                            </div>
                                          </td>
                                          <td><span className="badge">{student.department || 'غير محدد'}</span></td>
                                          <td>{student.phone || '—'}</td>
                                        </tr>
                                      ))}
                                    </tbody>
                                  </table>
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              </>
            );
          })()}
        </div>
      )}

      {/* Students List View */}
      {currentDepartment && currentDepartment !== 'الجامعات' && (
        <div className="students-section visible">
          <div className="section-header">
            <div className="title-group">
              <button className="back-btn" onClick={() => { setCurrentDepartment(null); setSearchTerm(""); }}>
                <i className="fas fa-arrow-right"></i>
                رجوع للأقسام
              </button>
              <h2>
                <i className="fas fa-list-ul"></i>
                قائمة أطباء
                <span className={`dept-badge ${
                  currentDepartment === 'جراحة' ? 'surgery' :
                  currentDepartment === 'نسائية' ? 'gynecology' :
                  currentDepartment === 'الاطفال' ? 'pediatrics' :
                  currentDepartment === 'المغادرين' ? 'graduates' : 
                  (currentDepartment === 'All' || currentDepartment?.startsWith('CATEGORY_ALL_')) ? 'all-badge' : 'suspended'
                }`} style={(currentDepartment === 'All' || currentDepartment?.startsWith('CATEGORY_ALL_')) ? { background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', color: 'white' } : {}}>
                  {(currentDepartment === 'All' || currentDepartment?.startsWith('CATEGORY_ALL_')) ? 'الكل' : currentDepartment}
                </span>
              </h2>
            </div>
            <div className="controls-group">
              <div className="search-box">
                <i className="fas fa-search"></i>
                <input 
                  type="text" 
                  placeholder="ابحث عن طبيب..." 
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <button className="action-btn add" onClick={() => {
                const defaultDept = (currentDepartment && !currentDepartment.startsWith('CATEGORY_ALL_') && currentDepartment !== 'All') ? currentDepartment : '';
                setFormData({ name: '', startDate: '', endDate: '', phone: '', university: '', department: defaultDept });
                setActiveModal('add');
              }}>
                <i className="fas fa-plus"></i>
                إضافة متدرب
              </button>
              {isTrainerDepartment(currentDepartment) && (
                <button
                  type="button"
                  className="action-btn"
                  onClick={() => openQuickAddTrainerModal(currentDepartment)}
                  style={{
                    background: 'linear-gradient(135deg, #0891b2, #0e7490)',
                    color: 'white',
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '8px',
                    padding: '10px 18px',
                    borderRadius: '10px',
                    fontWeight: 800,
                    fontSize: '0.9rem',
                    cursor: 'pointer',
                    border: 'none',
                    boxShadow: '0 4px 12px rgba(8, 145, 178, 0.25)'
                  }}
                  title={`إضافة مدرب سريري جديد في قسم ${currentDepartment}`}
                >
                  <i className="fas fa-chalkboard-teacher" />
                  إضافة مدرب سريري جديد
                </button>
              )}
              <Link 
                href={`/certificate?dept=${encodeURIComponent(currentDepartment)}`} 
                className="action-btn"
                style={{
                  background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)',
                  color: 'white',
                  textDecoration: 'none',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '8px',
                  padding: '10px 18px',
                  borderRadius: '10px',
                  fontWeight: 800,
                  fontSize: '0.9rem',
                  boxShadow: '0 4px 12px rgba(139, 26, 43, 0.25)'
                }}
              >
                <i className="fas fa-certificate"></i>
                شهادة الخبرة للقسم
              </Link>
              <button 
                type="button"
                className="action-btn"
                onClick={() => {
                  setReportDept(currentDepartment || 'All');
                  setShowStatsReportModal(true);
                }}
                style={{
                  background: 'linear-gradient(135deg, #f59e0b, #d97706)',
                  color: 'white',
                  border: 'none',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '8px',
                  padding: '10px 18px',
                  borderRadius: '10px',
                  fontWeight: 800,
                  fontSize: '0.9rem',
                  cursor: 'pointer',
                  boxShadow: '0 4px 12px rgba(217, 119, 6, 0.25)',
                  fontFamily: 'Tajawal'
                }}
              >
                <i className="fas fa-chart-pie"></i>
                تقرير إحصائي خاص بهذا القسم
              </button>
              <button className="action-btn print" onClick={() => window.print()}>
                <i className="fas fa-print"></i>
                طباعة
              </button>
              <button className="action-btn export" onClick={() => exportToExcel(false)}>
                <i className="fas fa-file-excel"></i>
                تصدير Excel
              </button>
            </div>
          </div>
          {/* ═══════════ SCHEDULE CARD ═══════════ */}
          {(() => {
            const deptScheduleMap: Record<string, Department> = {
              'جراحة': 'surgery',
              'نسائية': 'gynecology',
              'الاطفال': 'pediatrics'
            };
            const scheduleDept = currentDepartment ? deptScheduleMap[currentDepartment] : undefined;
            if (!scheduleDept) {
              return (
                <div style={{
                  background: 'white',
                  borderRadius: '20px',
                  padding: '20px 25px',
                  marginBottom: '25px',
                  boxShadow: '0 8px 30px rgba(0,0,0,0.06)',
                  border: '2px solid #e0e7ff',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  flexWrap: 'wrap',
                  gap: '16px'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                    <div style={{ width: '48px', height: '48px', borderRadius: '12px', background: 'linear-gradient(135deg, #4F46E5, #6366F1)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.4rem' }}>
                      <i className="fas fa-calendar-alt"></i>
                    </div>
                    <div>
                      <h3 style={{ margin: 0, fontSize: '1.2rem', fontWeight: 800, color: 'var(--text)' }}>
                        توزيع جدول ومناوبات قسم {currentDepartment}
                      </h3>
                      <p style={{ margin: '4px 0 0', fontSize: '0.85rem', color: 'var(--text-light)' }}>
                        إنشاء وتوزيع ومتابعة جداول الدوام والشفتات لمتدربي وكادر القسم
                      </p>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                    <Link href={`/schedule/editor?dept=${encodeURIComponent(currentDepartment)}`} style={{
                      background: 'linear-gradient(135deg, #4F46E5, #6366F1)',
                      color: 'white',
                      textDecoration: 'none',
                      padding: '10px 18px',
                      borderRadius: '10px',
                      fontWeight: 800,
                      fontSize: '0.9rem',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '8px',
                      boxShadow: '0 4px 14px rgba(79, 70, 229, 0.3)'
                    }}>
                      <i className="fas fa-calendar-check"></i>
                      توزيع ومولد جدول المناوبات
                    </Link>
                    <Link href={`/certificate?dept=${encodeURIComponent(currentDepartment)}`} style={{
                      background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)',
                      color: 'white',
                      textDecoration: 'none',
                      padding: '10px 18px',
                      borderRadius: '10px',
                      fontWeight: 800,
                      fontSize: '0.9rem',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '8px',
                      boxShadow: '0 4px 14px rgba(139, 26, 43, 0.25)'
                    }}>
                      <i className="fas fa-certificate"></i>
                      شهادة الخبرة للقسم
                    </Link>
                  </div>
                </div>
              );
            }

            const schedInfo = getScheduleInfo(scheduleDept);
            const schedule = schedInfo.exists ? getSchedule(scheduleDept) : null;
            const sectionNames = getDepartmentSectionNames(scheduleDept);
            const sectionColors = getDepartmentSectionColors(scheduleDept);

            // Find current week
            const today = new Date();
            const currentWeek = schedule?.weeks.find(w => {
              const ws = new Date(w.startDate.split('/').reverse().join('-'));
              const we = new Date(w.endDate.split('/').reverse().join('-'));
              return today >= ws && today <= we;
            });

            const deptColorMap: Record<string, string> = {
              'surgery': '#e74c3c',
              'gynecology': '#9b59b6',
              'pediatrics': '#3498db'
            };
            const cardColor = deptColorMap[scheduleDept] || '#667eea';

            const dayOrder: DayOfWeek[] = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'];
            const dayNamesAr: Record<string, string> = {
              'Saturday': 'السبت', 'Sunday': 'الأحد', 'Monday': 'الاثنين',
              'Tuesday': 'الثلاثاء', 'Wednesday': 'الأربعاء', 'Thursday': 'الخميس', 'Friday': 'الجمعة'
            };

            return (
              <div style={{
                background: 'white',
                borderRadius: '20px',
                padding: '0',
                marginBottom: '25px',
                boxShadow: '0 10px 40px rgba(0,0,0,0.08)',
                overflow: 'hidden',
                border: `2px solid ${cardColor}20`
              }}>
                {/* Card Header */}
                <div style={{
                  background: `linear-gradient(135deg, ${cardColor} 0%, ${cardColor}cc 100%)`,
                  padding: '20px 25px',
                  color: 'white',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  flexWrap: 'wrap',
                  gap: '12px'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <i className="fas fa-calendar-alt" style={{ fontSize: '1.5rem' }}></i>
                    <div>
                      <h3 style={{ margin: 0, fontSize: '1.3rem', fontWeight: 800 }}>جدول المناوبات</h3>
                      {schedInfo.exists && (
                        <small style={{ opacity: 0.9 }}>{schedInfo.weeksCount} أسبوع • {schedInfo.studentsCount} طبيب</small>
                      )}
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '10px' }}>
                    {schedInfo.exists && (
                      <button onClick={() => setShowScheduleCard(!showScheduleCard)} style={{
                        background: 'rgba(255,255,255,0.2)', color: 'white', border: '2px solid rgba(255,255,255,0.4)',
                        padding: '8px 18px', borderRadius: '10px', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem',
                        fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: '6px'
                      }}>
                        <i className={`fas fa-${showScheduleCard ? 'eye-slash' : 'eye'}`}></i>
                        {showScheduleCard ? 'إخفاء الجدول' : 'إظهار الجدول'}
                      </button>
                    )}
                    {schedInfo.exists && (
                      <button onClick={() => router.push(`/schedule/editor?dept=${scheduleDept}`)} style={{
                        background: 'rgba(255,255,255,0.2)', color: 'white', border: '2px solid rgba(255,255,255,0.4)',
                        padding: '8px 18px', borderRadius: '10px', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem',
                        fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: '6px'
                      }}>
                        <i className="fas fa-edit"></i> تعديل الجدول
                      </button>
                    )}
                    <button onClick={() => router.push(`/schedule/${scheduleDept}`)} style={{
                      background: 'white', color: cardColor, border: 'none',
                      padding: '8px 18px', borderRadius: '10px', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem',
                      fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: '6px'
                    }}>
                      <i className="fas fa-magic"></i> {schedInfo.exists ? 'إنشاء جديد' : 'إنشاء جدول'}
                    </button>
                  </div>
                </div>

                {/* Card Body - only visible when toggled */}
                {showScheduleCard && (
                <div style={{ padding: '20px 25px' }}>
                  {!schedInfo.exists ? (
                    <div style={{ textAlign: 'center', padding: '30px 0', color: '#94a3b8' }}>
                      <i className="fas fa-calendar-times" style={{ fontSize: '3rem', marginBottom: '15px', display: 'block', opacity: 0.4 }}></i>
                      <p style={{ fontSize: '1.1rem', fontWeight: 600 }}>لا يوجد جدول مناوبات حالياً</p>
                      <p style={{ fontSize: '0.85rem' }}>اضغط "إنشاء جدول" لإنشاء جدول تلقائي</p>
                    </div>
                  ) : currentWeek ? (
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '15px' }}>
                        <span style={{
                          background: `${cardColor}15`, color: cardColor, padding: '6px 14px',
                          borderRadius: '20px', fontSize: '0.85rem', fontWeight: 700
                        }}>
                          📅 الأسبوع {currentWeek.weekNumber} — {currentWeek.startDate} → {currentWeek.endDate}
                        </span>
                      </div>
                      <div style={{ overflowX: 'auto' }}>
                        <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: '4px', fontSize: '0.8rem' }}>
                          <thead>
                            <tr>
                              <th style={{ padding: '8px', background: '#f8fafc', borderRadius: '8px', fontWeight: 700, minWidth: '80px' }}>الطبيب</th>
                              {dayOrder.map(day => (
                                <th key={day} style={{ padding: '8px', background: '#f8fafc', borderRadius: '8px', fontWeight: 600, minWidth: '70px' }}>
                                  {dayNamesAr[day]}
                                </th>
                              ))}
                            </tr>
                          </thead>
                          <tbody>
                            {schedule?.config.students.map((student, si) => (
                              <tr key={si}>
                                <td style={{ padding: '6px 8px', fontWeight: 600, fontSize: '0.78rem', whiteSpace: 'nowrap' }}>
                                  {student.name.split(' ').slice(0, 2).join(' ')}
                                </td>
                                {dayOrder.map(day => {
                                  const dayAssignments = currentWeek.days[day] || [];
                                  const assignment = dayAssignments.find(a => a.studentId === student.id);
                                  if (!assignment) return <td key={day} style={{ padding: '4px', textAlign: 'center' }}>—</td>;
                                  const secColor = sectionColors[assignment.section];
                                  return (
                                    <td key={day} style={{ padding: '3px' }}>
                                      <div style={{
                                        background: secColor?.bg || '#e2e8f0',
                                        color: secColor?.text || '#333',
                                        padding: '5px 6px', borderRadius: '8px', textAlign: 'center',
                                        fontSize: '0.72rem', fontWeight: 700, lineHeight: 1.2
                                      }}>
                                        {sectionNames[assignment.section] || assignment.section}
                                      </div>
                                    </td>
                                  );
                                })}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  ) : (
                    <div style={{ textAlign: 'center', padding: '20px 0', color: '#94a3b8' }}>
                      <p style={{ fontSize: '0.95rem', fontWeight: 600 }}>✅ جدول محفوظ — لا يوجد أسبوع حالي</p>
                      <p style={{ fontSize: '0.8rem' }}>فتح المحرر لعرض الجدول الكامل</p>
                    </div>
                  )}
                </div>
                )}
              </div>
            );
          })()}

          <div className="table-container">
            
            {(currentDepartment === 'All' || currentDepartment?.startsWith('CATEGORY_ALL_')) ? (
              <div style={{ paddingBottom: '20px' }}>
                {(() => {
                  // Group filtered students by department
                  const grouped: Record<string, typeof filteredStudents> = {};
                  filteredStudents.forEach(s => {
                    const dept = s.department || s.originalDepartment || s.deptLabel || 'غير مصنف';
                    if (!grouped[dept]) grouped[dept] = [];
                    grouped[dept].push(s);
                  });
                  const deptColors: Record<string,string> = {
                    'جراحة': '#8B1A2B', 'نسائية': '#6B3A7D', 'الاطفال': '#2B5F8B',
                    'أطفال': '#2196F3', 'طوارئ': '#f44336', 'كلى': '#009688',
                    'عمليات': '#795548', 'قبل الولادة': '#E91E63', 'بعد الولادة': '#9C27B0',
                    'ICU': '#FF5722', 'NICU': '#FF9800', 'PICU': '#4CAF50',
                    'التمريض': '#e74c3c', 'العلاج الطبيعي': '#27ae60', 'علاج طبيعي تدريب': '#16a34a', 'علاج طبيعي امتياز': '#059669', 'الصحة النفسية': '#16a085',
                    'المطبخ': '#d35400', 'إدارة': '#2c3e50', 'المحاسبة': '#8e44ad',
                    'طب تطوع': '#f39c12', 'تمريض تدريب': '#c2185b', 'تمريض امتياز': '#7b1fa2',
                    'تغذية': '#689f38', 'أشعة': '#455a64', 'خدمة اجتماعية': '#5d4037',
                    'تمريض تطوع': '#e91e63', 'علاج طبيعي تطوع': '#4caf50', 'تغذية تطوع': '#8bc34a',
                    'الصحة النفسية تطوع': '#009688', 'المغادرين': '#78909c', 'الاستئناف': '#546e7a',
                    'مدربي أشعة': '#7C3AED', 'مدربي هندسة طبية': '#1d4ed8', 'مدربي تغذية': '#16a34a',
                    'مدربي صيدلية': '#b45309', 'مدربي مختبر': '#0284c7', 'مدربي علاج طبيعي': '#059669', 'مدربي علاج وظيفي': '#0f766e'
                  };
                  return Object.entries(grouped).map(([dept, students]) => (
                    <div key={dept} style={{ marginBottom: '30px' }}>
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px',
                        padding: '14px 20px', borderRadius: '14px',
                        background: `linear-gradient(135deg, ${deptColors[dept] || '#667eea'}dd, ${deptColors[dept] || '#764ba2'}99)`,
                        color: 'white', boxShadow: '0 4px 15px rgba(0,0,0,0.15)'
                      }}>
                        <i className="fas fa-hospital-alt" style={{ fontSize: '1.2rem' }}></i>
                        <h3 style={{ margin: 0, fontWeight: 800, fontSize: '1.1rem' }}>{dept}</h3>
                        <span style={{
                          background: 'rgba(255,255,255,0.25)', padding: '4px 14px',
                          borderRadius: '20px', fontSize: '0.85rem', fontWeight: 700, marginRight: 'auto'
                        }}>{students.length} متدرب</span>

                        {/* Quick actions for تمريض تدريب and nursing */}
                        {(dept === 'تمريض تدريب' || dept === 'التمريض' || dept === 'تمريض امتياز') && (
                          <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                            <button
                              type="button"
                              onClick={() => {
                                setSelectedStudentIndex(null);
                                setFormData({
                                  department: dept,
                                  name: '',
                                  phone: '',
                                  university: '',
                                  startDate: new Date().toISOString().split('T')[0],
                                  endDate: '',
                                  shiftSystem: '',
                                  address: '',
                                  idNumber: '',
                                  graduationYear: ''
                                } as any);
                                setActiveModal('add');
                              }}
                              style={{
                                background: 'rgba(255,255,255,0.25)',
                                border: '1px solid rgba(255,255,255,0.5)',
                                color: 'white',
                                borderRadius: '8px',
                                padding: '5px 12px',
                                fontSize: '0.8rem',
                                fontWeight: 800,
                                cursor: 'pointer',
                                fontFamily: 'Tajawal',
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '6px'
                              }}
                              title={`إضافة متدرب جديد مباشرة لقسم ${dept}`}
                            >
                              <i className="fas fa-plus"></i>
                              <span>إضافة متدرب {dept}</span>
                            </button>
                            <button
                              type="button"
                              onClick={() => setCurrentDepartment(dept)}
                              style={{
                                background: 'white',
                                border: 'none',
                                color: deptColors[dept] || '#c2185b',
                                borderRadius: '8px',
                                padding: '5px 12px',
                                fontSize: '0.8rem',
                                fontWeight: 800,
                                cursor: 'pointer',
                                fontFamily: 'Tajawal',
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '6px',
                                boxShadow: '0 2px 6px rgba(0,0,0,0.15)'
                              }}
                              title={`فتح جدول ومناوبات قسم ${dept} الكامل`}
                            >
                              <span>فتح جدول القسم</span>
                              <i className="fas fa-arrow-left"></i>
                            </button>
                          </div>
                        )}
                      </div>
                      <div style={{ overflowX: 'auto' }}>
                        <table style={{ width: '100%' }}>
                          <thead>
                            <tr>
                              <th>#</th>
                              <th>الإسم</th>
                              <th>رقم الهوية</th>
                              <th>رقم الهاتف</th>
                              <th>تاريخ البدأ</th>
                              <th>تاريخ الانتهاء</th>
                              <th>الجامعة</th>
                              <th>مكان السكن</th>
                              <th>القسم الحالي</th>
                              <th>الإجراءات</th>
                            </tr>
                          </thead>
                          <tbody>
                            {students.map((student, index) => (
                              <tr key={index}>
                                <td style={{ fontWeight: 700, color: deptColors[dept] || 'var(--primary)' }}>{index + 1}</td>
                                <td style={{ fontWeight: 600 }}>{hideNames ? '—' : student.name}</td>
                                <td>{student.idNumber || '—'}</td>
                                <td dir="ltr" style={{ textAlign: 'right' }}>{student.phone}</td>
                                <td>{student.globalStartDate || student.startDate || '—'}</td>
                                <td>{student.globalEndDate || student.endDate || '—'}</td>
                                <td>
                                  {student.university && <><i className="fas fa-university"></i> {normalizeUniversityName(student.university)}</>}
                                  {student.graduationYear && <><br/><small style={{ color: 'var(--text-light)' }}>عام: {student.graduationYear}</small></>}
                                  {!student.university && '—'}
                                </td>
                                <td>{student.address || '—'}</td>
                                <td>
                                  {(() => {
                                    const today = new Date();
                                    let currentRot: any = null;
                                    if (student.allRotations && student.allRotations.length > 0) {
                                      for (const rot of student.allRotations) {
                                        const rs = new Date(rot.start);
                                        const re = new Date(rot.end);
                                        if (today >= rs && today <= re) { currentRot = rot; break; }
                                      }
                                    }
                                    if (currentRot) {
                                      return <span style={{ fontWeight: 700, color: deptColors[currentRot.dept] || '#333' }}>{currentRot.dept}</span>;
                                    }
                                    return <span className="badge" style={{ background: '#94a3b8', color: 'white' }}>{dept}</span>;
                                  })()}
                                </td>
                                <td>
                                  <div className="row-actions">
                                    <button
                                      className="btn-icon"
                                      onClick={() => openIdCardModal(student, dept)}
                                      title="تعديل وطباعة بطاقة الهوية"
                                      style={{ background: '#16a34a', color: 'white' }}
                                    >
                                      <i className="fas fa-id-card"></i>
                                    </button>
                            {/* ══════ زر شهادة الخبرة ══════ */}
                            <Link
                              href={`/certificate?student=${encodeURIComponent(student.name)}&dept=${encodeURIComponent(dept || currentDepartment || student.department || '')}`}
                              className="btn-icon cert"
                              title={`إصدار شهادة الخبرة - ${student.name}`}
                              style={{ background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', color: 'white', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none' }}
                            >
                              <i className="fas fa-certificate"></i>
                            </Link>
                            {student.unionPaperBase64 && student.unionPaperBase64 !== (student as any).photoBase64 && student.unionPaperBase64 !== (student as any).doctorPhotoBase64 && (
                              <button className="btn-icon" onClick={() => {
                                const link = document.createElement('a');
                                link.href = student.unionPaperBase64!;
                                link.download = student.unionPaperFileName || 'وثيقة_التسجيل';
                                link.click();
                              }} title="تحميل وثائق التسجيل" style={{ background: '#2980b9' }}>
                                <i className="fas fa-file-download"></i>
                              </button>
                            )}
                            <button
                              className="btn-icon edit"
                              onClick={() => {
                                const studentDept = (dept || student.department || student.originalDepartment || 'جراحة') as string;
                                const realIdx = (studentsData[studentDept] || []).findIndex(s => s.name === student.name && (s.phone === student.phone || s.startDate === student.startDate));
                                const targetIdx = realIdx !== -1 ? realIdx : index;
                                setEditTargetDept(studentDept);
                                setSelectedStudentIndex(targetIdx);
                                setFormData({
                                  ...student,
                                  department: studentDept,
                                  name: student.name,
                                  startDate: parseDateForInput(student.globalStartDate || student.startDate || ''),
                                  endDate: parseDateForInput(student.globalEndDate || student.endDate || ''),
                                  phone: student.phone || '',
                                  university: student.university || '',
                                  address: student.address || '',
                                  shiftSystem: student.shiftSystem || '',
                                  idNumber: student.idNumber || '',
                                  graduationYear: student.graduationYear || '',
                                  attendanceDays: student.attendanceDays || '',
                                  studySystem: student.studySystem || '',
                                  internshipYear: student.internshipYear || '',
                                } as any);
                                setActiveModal('edit');
                              }}
                              title="تعديل بيانات المتدرب مباشرة"
                              style={{ background: '#2563eb', color: 'white' }}
                            >
                              <i className="fas fa-edit"></i>
                            </button>
                            {/* ══════ زر النقل لقسم آخر ══════ */}
                            <button
                              className="btn-icon move"
                              onClick={() => {
                                const studentDept = (dept || student.department || student.originalDepartment || 'جراحة') as string;
                                const realIdx = (studentsData[studentDept] || []).findIndex(s => s.name === student.name && (s.phone === student.phone || s.startDate === student.startDate));
                                const targetIdx = realIdx !== -1 ? realIdx : index;
                                openMoveModal(studentDept, targetIdx, student);
                              }}
                              title="نقل المتدرب لقسم آخر"
                              style={{ background: 'linear-gradient(135deg, #6B3A7D, #4E2A5E)', color: 'white' }}
                            >
                              <i className="fas fa-exchange-alt"></i>
                            </button>
                            {/* ══════ زر تعيين لمدرب سريري (الأشعة، التمريض، المختبر، وكافة الأقسام) ══════ */}
                            {isEligibleForTrainerAssignment(dept, student) && (
                              <button
                                className="btn-icon"
                                onClick={() => {
                                  const studentDept = (dept || student.department || student.originalDepartment || 'تمريض تدريب') as string;
                                  openAssignModal(student, studentDept);
                                }}
                                style={{
                                  background: 'linear-gradient(135deg, #0891b2, #0e7490)',
                                  color: 'white',
                                  boxShadow: '0 2px 6px rgba(8,145,178,0.35)'
                                }}
                                title={(student as any).assignedTrainer 
                                  ? `تغيير المدرب السريري (حالياً: ${(student as any).assignedTrainer})` 
                                  : "تعيين لمدرب سريري ونقله تحت إشراف المدرب"}
                              >
                                <i className="fas fa-chalkboard-teacher"></i>
                              </button>
                            )}
                            {dept !== 'المغادرين' && (
                              <button
                                className="btn-icon"
                                onClick={() => {
                                  const studentDept = (dept || student.department || student.originalDepartment || 'جراحة') as string;
                                  const realIdx = (studentsData[studentDept] || []).findIndex(s => s.name === student.name && (s.phone === student.phone || s.startDate === student.startDate));
                                  handleQuickGraduateStudent(studentDept, realIdx !== -1 ? realIdx : index);
                                }}
                                title="إنهاء التدريب ونقل للمغادرين مباشرة"
                                style={{ background: '#059669', color: 'white' }}
                              >
                                <i className="fas fa-user-graduate"></i>
                              </button>
                            )}
                            <button 
                              className="btn-icon delete" 
                              onClick={() => {
                                const studentDept = (dept || student.department || student.originalDepartment || 'جراحة') as string;
                                const realIdx = (studentsData[studentDept] || []).findIndex(s => s.name === student.name && (s.phone === student.phone || s.startDate === student.startDate));
                                handleDeleteStudent(realIdx !== -1 ? realIdx : index, studentDept);
                              }} 
                              title="حذف الطالب"
                            >
                              <i className="fas fa-trash"></i>
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
                    </div>
                  ));
                })()}
              </div>
            ) : (
              <div style={{ overflowX: 'auto', paddingBottom: '20px' }}>
                {(() => {
                  const isUniSpecialDept = currentDepartment === 'تدريب تمريض الجامعات' || currentDepartment === 'الأطباء المتعاقدون';
                  const isDoctorSpecial = currentDepartment === 'الأطباء المتعاقدون';

                  return (
                    <table className="dept-table" style={{ width: '100%' }}>
                      <thead>
                        <tr>
                          <th>#</th>
                          <th>{isTrainerDepartment(currentDepartment) ? 'اسم الطالب / المتدرب' : (isUniSpecialDept ? (isDoctorSpecial ? 'اسم الطبيب المتعاقد' : 'اسم مدرب التمريض') : 'اسم الطبيب / المتدرب')}</th>
                          <th>رقم الهاتف</th>
                          <th>{isTrainerDepartment(currentDepartment) ? 'الجامعة' : (isUniSpecialDept ? 'الجامعات المتعاقد معها' : 'الجامعة')}</th>
                          <th>{isTrainerDepartment(currentDepartment) ? 'طبيعة التدريب / التخصص' : (isUniSpecialDept ? 'طبيعة الوظيفة / المساقات' : 'سنة التخرج')}</th>
                          <th>{isTrainerDepartment(currentDepartment) ? 'تاريخ البداية' : (isUniSpecialDept ? 'تاريخ بدء التعاقد' : 'تاريخ البداية (القسم)')}</th>
                          <th>{isTrainerDepartment(currentDepartment) ? 'تاريخ الانتهاء' : (isUniSpecialDept ? 'تاريخ انتهاء التعاقد' : 'تاريخ الانتهاء (القسم)')}</th>
                          <th>مكان السكن</th>
                          <th>{isTrainerDepartment(currentDepartment) ? 'أيام الدوام' : (isUniSpecialDept ? 'أيام الدوام الأسبوعية' : 'نظام الدوام')}</th>
                          <th>الإجراءات</th>
                        </tr>
                      </thead>
                   <tbody>
                    {isTrainerDepartment(currentDepartment) ? (() => {
                      const UNASSIGNED = '⚠️ طلاب بانتظار التعيين لمدرب';
                      
                      // Arabic normalization helper
                      const normArKey = (str: string) => (str || '')
                        .trim()
                        .replace(/[\u064B-\u065F\u0670\u0640]/g, '')
                        .replace(/[أإآءئؤ]/g, 'ا')
                        .replace(/ة/g, 'ه')
                        .replace(/ى/g, 'ي')
                        .replace(/\s+/g, '');

                      // 1. Identify all registered trainers in the department
                      const fullDeptStudents = studentsData[currentDepartment || ''] || [];
                      const trainerCanonicalNames: string[] = [];
                      const trainerKeyToCanonical: Record<string, string> = {};
                      const trainerFirstLastToCanonical: Record<string, string> = {};

                      const isTrainerRow = (s: any) => {
                        if (s.assignedTrainer) return false;
                        return (
                          s.internshipYear === 'مدرب سريري' ||
                          s.isUniversityTrainer ||
                          s.crescentJobNature === 'مدرب سريري' ||
                          s.crescentJobNature === 'على كادر الهلال الاحمر' ||
                          s.crescentJobNature === 'عقد سنوي'
                        );
                      };

                      fullDeptStudents.forEach((s: any) => {
                        if (isTrainerRow(s)) {
                          const tName = (s.name || '').trim();
                          if (tName) {
                            if (!trainerCanonicalNames.includes(tName)) {
                              trainerCanonicalNames.push(tName);
                            }
                            const k = normArKey(tName);
                            trainerKeyToCanonical[k] = tName;
                            
                            const parts = tName.split(/\s+/).filter(Boolean);
                            if (parts.length >= 2) {
                              const fl = normArKey(parts[0] + parts[parts.length - 1]);
                              trainerFirstLastToCanonical[fl] = tName;
                            }
                          }
                        }
                      });

                      // Also include trainers from availableTrainersList matching this department
                      availableTrainersList.forEach((t: any) => {
                        const matchesDept = t.department === currentDepartment || 
                          (currentDepartment === 'تدريب تمريض الجامعات' && (t.specialtyGroup === 'nursing' || t.isNursingTrainer)) ||
                          (currentDepartment === 'مدربي أشعة' && t.specialtyGroup === 'radiology') ||
                          (currentDepartment === 'مدربي مختبر' && t.specialtyGroup === 'lab') ||
                          (currentDepartment === 'مدربي علاج طبيعي' && t.specialtyGroup === 'pt') ||
                          (currentDepartment === 'مدربي صيدلية' && t.specialtyGroup === 'pharmacy') ||
                          (currentDepartment === 'مدربي تغذية' && t.specialtyGroup === 'nutrition') ||
                          (currentDepartment === 'مدربي هندسة طبية' && t.specialtyGroup === 'biomedical') ||
                          (currentDepartment === 'مدربي علاج وظيفي' && t.specialtyGroup === 'ot');

                        if (!matchesDept) return;
                        const tName = (t.name || '').trim();
                        if (tName) {
                          const k = normArKey(tName);
                          if (!trainerKeyToCanonical[k]) {
                            trainerCanonicalNames.push(tName);
                            trainerKeyToCanonical[k] = tName;
                            const parts = tName.split(/\s+/).filter(Boolean);
                            if (parts.length >= 2) {
                              const fl = normArKey(parts[0] + parts[parts.length - 1]);
                              trainerFirstLastToCanonical[fl] = tName;
                            }
                          }
                        }
                      });

                      // Canonical resolver to match any variations in spelling or parts
                      const resolveTrainerName = (rawName: string): string => {
                        if (!rawName || !rawName.trim()) return '';
                        const clean = rawName.trim();
                        const k = normArKey(clean);
                        if (trainerKeyToCanonical[k]) return trainerKeyToCanonical[k];

                        const parts = clean.split(/\s+/).filter(Boolean);
                        if (parts.length >= 2) {
                          const fl = normArKey(parts[0] + parts[parts.length - 1]);
                          if (trainerFirstLastToCanonical[fl]) return trainerFirstLastToCanonical[fl];
                        }

                        // Substring or fuzzy check
                        for (const canName of trainerCanonicalNames) {
                          const canKey = normArKey(canName);
                          if (k.length >= 5 && (canKey.includes(k) || k.includes(canKey))) {
                            return canName;
                          }
                          const canParts = canName.split(/\s+/).filter(Boolean);
                          if (parts.length >= 2 && canParts.length >= 2) {
                            if (normArKey(parts[0]) === normArKey(canParts[0]) && 
                                normArKey(parts[parts.length - 1]) === normArKey(canParts[canParts.length - 1])) {
                              return canName;
                            }
                          }
                        }
                        return clean;
                      };

                      // Initialize groups for all canonical trainers
                      const groups: { [trainer: string]: typeof filteredStudents } = {};
                      trainerCanonicalNames.forEach(tn => {
                        groups[tn] = [];
                      });

                      // Distribute students under their assigned trainer with deduplication
                      const seenInTrainerSection = new Set<string>();

                      filteredStudents.forEach(s => {
                        const sName = (s.name || '').trim();
                        const sKey = normArKey(sName);

                        // If this row is one of the trainers themselves without assignedTrainer, don't display as a student
                        if (trainerKeyToCanonical[sKey] && !(s as any).assignedTrainer) return;

                        const sPhone = (s.phone || '').trim();
                        const sId = (s.idNumber || '').trim();
                        const dedupKey = (sPhone || sId) ? `${sKey}:::${sPhone || sId}` : `${sKey}:::${(s as any).id || (s as any).startDate || ''}`;
                        if (seenInTrainerSection.has(dedupKey)) return;
                        seenInTrainerSection.add(dedupKey);

                        const rawTrainer = (s as any).assignedTrainer?.trim();
                        if (rawTrainer) {
                          const resolved = resolveTrainerName(rawTrainer);
                          if (!groups[resolved]) groups[resolved] = [];
                          groups[resolved].push(s);
                        } else {
                          if (!groups[UNASSIGNED]) groups[UNASSIGNED] = [];
                          groups[UNASSIGNED].push(s);
                        }
                      });

                      const trainerKeys = Object.keys(groups).filter(k => {
                        if (k === UNASSIGNED) return false;
                        return groups[k].length > 0 || fullDeptStudents.some((s: any) => s.name === k);
                      }).sort((a, b) => a.localeCompare(b, 'ar'));

                      if (groups[UNASSIGNED] && groups[UNASSIGNED].length > 0) {
                        trainerKeys.push(UNASSIGNED);
                      }
                      const trainerColors = ['#0369a1','#7c3aed','#059669','#b45309','#c2185b','#1d4ed8','#0f766e','#6b21a8','#065f46','#92400e'];
                      let colorIdx = 0;
                      const rows: React.ReactNode[] = [];

                      const actualTrainersCount = trainerKeys.filter(k => k !== UNASSIGNED).length;
                      if (actualTrainersCount === 0) {
                        rows.push(
                          <tr key="no-trainers-empty-state">
                            <td colSpan={10} style={{ textAlign: 'center', padding: '36px 20px', background: 'var(--card-bg, #fff)' }}>
                              <div style={{ maxWidth: '480px', margin: '0 auto', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '12px' }}>
                                <div style={{ width: '56px', height: '56px', borderRadius: '50%', background: '#ede9fe', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#7c3aed', fontSize: '1.6rem' }}>
                                  <i className="fas fa-chalkboard-teacher" />
                                </div>
                                <div style={{ fontWeight: 800, fontSize: '1.05rem', color: 'var(--text, #1e293b)' }}>
                                  لم يتم إضافة مدربين سريريين في قسم ({currentDepartment}) بعد
                                </div>
                                <div style={{ fontSize: '0.85rem', color: '#64748b', lineHeight: 1.6 }}>
                                  يمكنك إضافة أول مدرب سريري الآن، والبدء بإضافة وتعيين الطلاب المتدربين تحت إشرافه بكل سهولة
                                </div>
                                <button
                                  type="button"
                                  onClick={() => openQuickAddTrainerModal(currentDepartment)}
                                  style={{
                                    display: 'inline-flex', alignItems: 'center', gap: '8px',
                                    background: 'linear-gradient(135deg, #7c3aed, #6d28d9)',
                                    color: 'white', border: 'none', padding: '9px 20px',
                                    borderRadius: '10px', fontWeight: 800, fontSize: '0.92rem',
                                    cursor: 'pointer', fontFamily: 'Tajawal',
                                    boxShadow: '0 4px 14px rgba(124, 58, 237, 0.35)'
                                  }}
                                >
                                  <i className="fas fa-plus" />
                                  إضافة أول مدرب سريري في {currentDepartment}
                                </button>
                              </div>
                            </td>
                          </tr>
                        );
                      }

                      trainerKeys.forEach((trainerName) => {
                        const groupStudents = groups[trainerName] || [];
                        const isUnassigned = trainerName === UNASSIGNED;
                        const color = isUnassigned ? '#64748b' : trainerColors[colorIdx++ % trainerColors.length];
                        rows.push(
                          <tr key={`hdr-${trainerName}`} style={{ background: `${color}14` }}>
                            <td colSpan={10} style={{ padding: '10px 16px', fontWeight: 800, fontSize: '0.92rem', color, borderRight: `4px solid ${color}`, borderBottom: `2px solid ${color}30` }}>
                              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '10px' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                  {isUnassigned
                                    ? <><i className="fas fa-user-clock" style={{ marginLeft: '8px' }} />{trainerName} — ({groupStudents.length} متدرب)</>
                                    : <><i className="fas fa-chalkboard-teacher" style={{ marginLeft: '8px' }} />👤 المدرب: {trainerName} — ({groupStudents.length} طالب متدرب)</>
                                  }
                                </div>
                                {!isUnassigned && (
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                                    <button
                                      type="button"
                                      onClick={() => openQuickTrainerStudentModal(trainerName, currentDepartment || 'تدريب تمريض الجامعات')}
                                      style={{
                                        display: 'inline-flex', alignItems: 'center', gap: '6px',
                                        background: color, color: '#fff', border: 'none',
                                        padding: '5px 12px', borderRadius: '8px', fontSize: '0.8rem',
                                        fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal',
                                        boxShadow: `0 2px 6px ${color}44`, transition: 'all 0.15s ease'
                                      }}
                                      title={`إضافة طالب متدرب جديد مباشرة تحت إشراف المدرب ${trainerName}`}
                                    >
                                      <i className="fas fa-plus" />
                                      إضافة طالب تحت هذا المدرب
                                    </button>
                                    <button
                                      type="button"
                                      onClick={() => openQuickAssignModal(trainerName, currentDepartment || 'تدريب تمريض الجامعات')}
                                      style={{
                                        display: 'inline-flex', alignItems: 'center', gap: '6px',
                                        background: 'var(--card-bg, #fff)', color, border: `1.5px solid ${color}`,
                                        padding: '4px 10px', borderRadius: '8px', fontSize: '0.8rem',
                                        fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal',
                                        transition: 'all 0.15s ease'
                                      }}
                                      title={`تعيين طالب مسجل في النظام تحت إشراف المدرب ${trainerName}`}
                                    >
                                      <i className="fas fa-link" />
                                      تعيين طالب مسجل
                                    </button>
                                  </div>
                                )}
                              </div>
                            </td>
                          </tr>
                        );

                        if (groupStudents.length === 0) {
                          rows.push(
                            <tr key={`empty-${trainerName}`}>
                              <td colSpan={10} style={{ textAlign: 'center', padding: '14px 16px', color: '#64748b', fontSize: '0.84rem', background: 'var(--bg, #f8fafc)' }}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '10px', flexWrap: 'wrap' }}>
                                  <span>لا يوجد طلاب متدربون معيّنون لهذا المدرب حالياً</span>
                                  <button
                                    type="button"
                                    onClick={() => openQuickTrainerStudentModal(trainerName, currentDepartment || 'تدريب تمريض الجامعات')}
                                    style={{
                                      background: '#0891b2', color: '#fff', border: 'none',
                                      padding: '4px 12px', borderRadius: '6px', fontSize: '0.78rem',
                                      fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal'
                                    }}
                                  >
                                    <i className="fas fa-plus" style={{ marginLeft: '4px' }} />
                                    إضافة طالب له الآن
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => openQuickAssignModal(trainerName, currentDepartment || 'تدريب تمريض الجامعات')}
                                    style={{
                                      background: '#ede9fe', color: '#6d28d9', border: '1px solid #c4b5fd',
                                      padding: '4px 12px', borderRadius: '6px', fontSize: '0.78rem',
                                      fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal'
                                    }}
                                  >
                                    <i className="fas fa-link" style={{ marginLeft: '4px' }} />
                                    تعيين طالب مسجل
                                  </button>
                                </div>
                              </td>
                            </tr>
                          );
                        } else {
                          groupStudents.forEach((student, rowIdx) => {
                            const deptList = studentsData[currentDepartment || ''] || [];
                            const realIdx = deptList.findIndex((s: any) => 
                              (student.id && s.id === student.id) ||
                              (s.name === student.name && (s.phone === student.phone || s.idNumber === student.idNumber)) ||
                              (normArKey(s.name) === normArKey(student.name) && (s.phone === student.phone || s.idNumber === student.idNumber))
                            );
                            const safeIdx = realIdx !== -1 ? realIdx : (deptList.findIndex((s: any) => normArKey(s.name) === normArKey(student.name)) !== -1 ? deptList.findIndex((s: any) => normArKey(s.name) === normArKey(student.name)) : rowIdx);
                            rows.push(
                              <tr key={`${trainerName}-${rowIdx}`} style={{ borderRight: `3px solid ${color}30` }}>
                                <td style={{ fontWeight: 700, color }}>{rowIdx + 1}</td>
                                <td>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                    {((student as any).photoBase64 || (student as any).doctorPhotoBase64) && (
                                      <img src={(student as any).photoBase64 || (student as any).doctorPhotoBase64} alt="" style={{ width: '32px', height: '32px', borderRadius: '50%', objectFit: 'cover', border: `1.5px solid ${color}` }} />
                                    )}
                                    <div>
                                      <strong>{hideNames ? '—' : student.name}</strong>
                                      <div style={{ fontSize: '0.72rem', color: (student as any).assignedTrainer ? '#0891b2' : '#7c3aed', fontWeight: 700, marginTop: '2px' }}>
                                        {(student as any).assignedTrainer 
                                          ? `🩺 متدرب — المدرب: ${(student as any).assignedTrainer}`
                                          : `🎓 كادر ${currentDepartment}`}
                                      </div>
                                    </div>
                                  </div>
                                </td>
                                <td dir="ltr" style={{ textAlign: 'right' }}><a href={`tel:+970${student.phone}`} className="phone-link"><i className="fas fa-phone"></i> {student.phone}</a></td>
                                <td style={{ fontSize: '0.85rem' }}>
                                  {(student as any).contractedUniversities && (student as any).contractedUniversities.length > 0 ? (
                                    <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                                      {(Array.isArray((student as any).contractedUniversities) ? (student as any).contractedUniversities : [(student as any).contractedUniversities]).map((u: string, uIdx: number) => (
                                        <span key={uIdx} style={{ background: '#ede9fe', color: '#5b21b6', padding: '2px 8px', borderRadius: '8px', fontSize: '0.76rem', fontWeight: 700 }}>{u}</span>
                                      ))}
                                    </div>
                                  ) : normalizeUniversityName(student.university) || '—'}
                                </td>
                                <td style={{ fontSize: '0.85rem', fontWeight: 600 }}>{(student as any).crescentJobNature || student.graduationYear || '—'}</td>
                                <td>{student.startDate || '—'}</td>
                                <td>{student.endDate || '—'}</td>
                                <td>{student.address || '—'}</td>
                                <td>
                                  {(student as any).workDays && (student as any).workDays.length > 0 ? (
                                    <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                                      {(Array.isArray((student as any).workDays) ? (student as any).workDays : [(student as any).workDays]).map((d: string, dIdx: number) => (
                                        <span key={dIdx} style={{ background: '#ecfdf5', color: '#065f46', padding: '2px 6px', borderRadius: '6px', fontSize: '0.72rem', fontWeight: 700 }}>{d}</span>
                                      ))}
                                    </div>
                                  ) : <span style={{ background: student.shiftSystem ? '#f1f2f6' : 'transparent', padding: student.shiftSystem ? '4px 10px' : '0', borderRadius: '20px', fontSize: '0.85rem', fontWeight: 700 }}>{student.shiftSystem || '—'}</span>}
                                </td>
                                <td>
                                  <div className="row-actions">
                                    <button 
                                      className="btn-icon" 
                                      onClick={() => openAssignModal(student, currentDepartment || 'تدريب تمريض الجامعات')} 
                                      style={{ background: 'linear-gradient(135deg, #0891b2, #0e7490)', color: 'white' }} 
                                      title={(student as any).assignedTrainer ? `تغيير المدرب السريري (حالياً: ${(student as any).assignedTrainer})` : "تعيين لمدرب سريري"}
                                    >
                                      <i className="fas fa-chalkboard-teacher"></i>
                                    </button>
                                    <button className="btn-icon edit" onClick={() => { setSelectedStudentIndex(safeIdx); setFormData({ ...formData, name: student.name, startDate: parseDateForInput(student.startDate || ''), endDate: parseDateForInput(student.endDate || ''), phone: student.phone, university: student.university || '', address: student.address || '', shiftSystem: student.shiftSystem || '', idNumber: student.idNumber || '', graduationYear: student.graduationYear || '', attendanceDays: student.attendanceDays || '', studySystem: student.studySystem || '', internshipYear: student.internshipYear || '' } as any); setActiveModal('edit'); }} title="تعديل"><i className="fas fa-edit"></i></button>
                                    <button className="btn-icon move" onClick={() => { setSelectedStudentIndex(safeIdx); setActiveModal('move'); }} title="نقل لقسم آخر"><i className="fas fa-exchange-alt"></i></button>
                                    <button className="btn-icon" onClick={() => handleQuickGraduateStudent(currentDepartment, safeIdx)} title="إنهاء التدريب" style={{ background: '#059669', color: 'white' }}><i className="fas fa-user-graduate"></i></button>
                                    <button className="btn-icon delete" onClick={() => handleDeleteStudent(safeIdx)} title="حذف"><i className="fas fa-trash"></i></button>
                                  </div>
                                </td>
                              </tr>
                            );
                          });
                        }
                      });
                      return rows;
                    })() : (
                    filteredStudents.map((student, index) => (
                      <tr key={index}>
                        <td style={{ fontWeight: 700, color: 'var(--primary)' }}>{index + 1}</td>
                        <td>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            {((student as any).photoBase64 || (student as any).doctorPhotoBase64) && (
                              <img 
                                src={(student as any).photoBase64 || (student as any).doctorPhotoBase64} 
                                alt="" 
                                style={{ width: '32px', height: '32px', borderRadius: '50%', objectFit: 'cover', border: '1.5px solid #6366f1' }}
                              />
                            )}
                            <div>
                              <strong>{hideNames ? '—' : student.name}</strong>
                              {currentDepartment === 'الأطباء المتعاقدون' && (
                                <div style={{ fontSize: '0.72rem', color: '#6b21a8', fontWeight: 700, marginTop: '2px' }}>
                                  🩺 طبيب متعاقد
                                </div>
                              )}
                              {currentDepartment === 'الاستئناف' && student.originalDepartment && (
                                <><br/><small style={{ color: 'var(--warning)' }}>القسم الأصلي: {student.originalDepartment}</small></>
                              )}
                            </div>
                          </div>
                        </td>
                        <td dir="ltr" style={{ textAlign: 'right' }}>
                          <a href={`tel:+970${student.phone}`} className="phone-link">
                            <i className="fas fa-phone"></i> {student.phone}
                          </a>
                        </td>
                        <td style={{ fontSize: '0.85rem' }}>
                          {currentDepartment === 'الأطباء المتعاقدون' && (student as any).contractedUniversities && (student as any).contractedUniversities.length > 0 ? (
                            <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                              {(Array.isArray((student as any).contractedUniversities) ? (student as any).contractedUniversities : [(student as any).contractedUniversities]).map((u: string, uIdx: number) => (
                                <span key={uIdx} style={{ background: '#ede9fe', color: '#5b21b6', padding: '2px 8px', borderRadius: '8px', fontSize: '0.76rem', fontWeight: 700 }}>
                                  {u}
                                </span>
                              ))}
                            </div>
                          ) : (
                            normalizeUniversityName(student.university) || '—'
                          )}
                        </td>
                        <td style={{ fontSize: '0.85rem', fontWeight: 600 }}>
                          {currentDepartment === 'الأطباء المتعاقدون' ? (
                            (student as any).crescentJobNature || ((student as any).teachingCourses && (student as any).teachingCourses.length > 0 ? (Array.isArray((student as any).teachingCourses) ? (student as any).teachingCourses.join('، ') : (student as any).teachingCourses) : student.graduationYear || '—')
                          ) : (
                            student.graduationYear || '—'
                          )}
                        </td>
                        <td>{student.suspendDate || student.startDate || '—'}</td>
                        <td>{student.endDate || '—'}</td>
                        <td>{student.address || '—'}</td>
                        <td>
                          {currentDepartment === 'الأطباء المتعاقدون' && (student as any).workDays && (student as any).workDays.length > 0 ? (
                            <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                              {(Array.isArray((student as any).workDays) ? (student as any).workDays : [(student as any).workDays]).map((d: string, dIdx: number) => (
                                <span key={dIdx} style={{ background: '#ecfdf5', color: '#065f46', padding: '2px 6px', borderRadius: '6px', fontSize: '0.72rem', fontWeight: 700 }}>
                                  {d}
                                </span>
                              ))}
                            </div>
                          ) : (
                            <span style={{ 
                              background: student.shiftSystem ? '#f1f2f6' : 'transparent', 
                              padding: student.shiftSystem ? '4px 10px' : '0', 
                              borderRadius: '20px', fontSize: '0.85rem', fontWeight: 700, color: '#333'
                            }}>
                              {student.shiftSystem || '—'}
                            </span>
                          )}
                        </td>
                        <td>
                          <div className="row-actions">
                            {currentDepartment === 'الاستئناف' ? (
                              <>
                                <button className="btn-icon return" onClick={() => handleReturnFromSuspension(index)} title="إرجاع للقسم الأصلي" style={{ background: 'var(--success)' }}>
                                  <i className="fas fa-undo"></i>
                                </button>
                                <button className="btn-icon edit" onClick={() => {
                                  setSelectedStudentIndex(index);
                                  setFormData({ ...formData, name: student.name, startDate: parseDateForInput(student.startDate), endDate: parseDateForInput(student.endDate), phone: student.phone, university: student.university || '', address: student.address || '', shiftSystem: student.shiftSystem || '' } as any);
                                  setActiveModal('edit');
                                }} title="تعديل"><i className="fas fa-edit"></i></button>
                                <button className="btn-icon delete" onClick={() => handleDeleteStudent(index)} title="حذف"><i className="fas fa-trash"></i></button>
                              </>
                            ) : (
                              <>
                                <button className="btn-icon edit" onClick={() => {
                                  setSelectedStudentIndex(index);
                                  setFormData({ ...formData, name: student.name, startDate: parseDateForInput(student.startDate || ''), endDate: parseDateForInput(student.endDate || ''), phone: student.phone, university: student.university || '', address: student.address || '', shiftSystem: student.shiftSystem || '', idNumber: student.idNumber || '', graduationYear: student.graduationYear || '', attendanceDays: student.attendanceDays || '', studySystem: student.studySystem || '', internshipYear: student.internshipYear || '' } as any);
                                  setActiveModal('edit');
                                }} title="تعديل"><i className="fas fa-edit"></i></button>
                                <button className="btn-icon move" onClick={() => {
                                  setSelectedStudentIndex(index);
                                  setActiveModal('move');
                                }} title="نقل لقسم آخر"><i className="fas fa-exchange-alt"></i></button>
                                {(currentDepartment === 'تمريض تدريب' || currentDepartment === 'التمريض' || currentDepartment === 'تمريض امتياز' || currentDepartment === 'تمريض تطوع') && (
                                  <button
                                    className="btn-icon"
                                    onClick={() => openAssignModal(student, currentDepartment)}
                                    style={{
                                      background: 'linear-gradient(135deg, #0891b2, #0e7490)',
                                      color: 'white',
                                      boxShadow: '0 2px 6px rgba(8,145,178,0.35)'
                                    }}
                                    title="تعيين لمدرب سريري (نقل تمريض تدريب إلى مدربهم في تدريب الجامعات)"
                                  >
                                    <i className="fas fa-chalkboard-teacher"></i>
                                  </button>
                                )}
                                {currentDepartment !== 'المغادرين' && (
                                  <button
                                    className="btn-icon"
                                    onClick={() => handleQuickGraduateStudent(currentDepartment, index)}
                                    title="إنهاء التدريب ونقل للمغادرين مباشرة"
                                    style={{ background: '#059669', color: 'white' }}
                                  >
                                    <i className="fas fa-user-graduate"></i>
                                  </button>
                                )}
                                <button className="btn-icon delete" onClick={() => handleDeleteStudent(index)} title="حذف"><i className="fas fa-trash"></i></button>
                              </>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))
                    )}
                  </tbody>
                </table>
                  );
                })()}
              </div>
            )}

          </div>
        </div>
      )}

      {/* Footer */}
      <div className="footer">
        <div className="footer-logo">
          <div className="crescent-icon">
            <svg viewBox="0 0 200 200" width="50" height="50">
              <circle cx="100" cy="100" r="96" fill="white" stroke="#CE1126" strokeWidth="4"/>
              <g transform="translate(100, 100)">
                <circle cx="0" cy="0" r="45" fill="#CE1126"/>
                <circle cx="16" cy="0" r="35" fill="white"/>
              </g>
            </svg>
          </div>
          <span>الهلال الأحمر الفلسطيني</span>
        </div>
        <p>© 2025 جميع الحقوق محفوظة - قسم التدريب الطبي</p>
      </div>

      {/* Modals */}
      {activeModal === 'idcard' && (
        <div className="modal-overlay active" onClick={(e) => e.target === e.currentTarget && setActiveModal(null)}>
          <div className="modal" style={{ maxWidth: '900px', width: '95%', maxHeight: '92vh', overflowY: 'auto' }}>
            <div className="modal-header" style={{ borderBottom: '2px solid #059669', paddingBottom: '12px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: '#ecfdf5', color: '#059669', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.2rem' }}>
                  <i className="fas fa-id-card"></i>
                </div>
                <div>
                  <h3 style={{ margin: 0, fontSize: '1.2rem', color: '#0f172a', fontWeight: 800 }}>تعديل وطباعة بطاقة المتدرب</h3>
                  <span style={{ fontSize: '0.8rem', color: '#64748b' }}>يمكنك تعديل القسم والمسمى الوظيفي وبيانات البطاقة بالكامل قبل الطباعة</span>
                </div>
              </div>
              <button className="modal-close" onClick={() => setActiveModal(null)}>&times;</button>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '24px', padding: '20px 0' }}>
              {/* Form Controls */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
                {/* الاسم */}
                <div className="form-group" style={{ margin: 0 }}>
                  <label style={{ fontSize: '0.85rem', fontWeight: 700, marginBottom: '5px' }}>الاسم الكامل:</label>
                  <input
                    type="text"
                    value={idCardData.name}
                    onChange={e => setIdCardData({ ...idCardData, name: e.target.value })}
                    style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontWeight: 700, color: '#CE1126' }}
                  />
                </div>

                {/* القسم - EDITABLE 100% */}
                <div style={{ background: '#f0fdf4', border: '2px solid #86efac', borderRadius: '12px', padding: '14px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                    <label style={{ fontSize: '0.9rem', fontWeight: 800, color: '#166534', display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <i className="fas fa-hospital-alt"></i> القسم : (قابل للتعديل 100%)
                    </label>
                    <span style={{ fontSize: '0.72rem', background: '#16a34a', color: 'white', padding: '2px 8px', borderRadius: '12px', fontWeight: 700 }}>
                      ✏️ تعديل القسم
                    </span>
                  </div>
                  
                  {/* Direct Text input */}
                  <input
                    type="text"
                    value={idCardData.dept}
                    onChange={e => setIdCardData({ ...idCardData, dept: e.target.value })}
                    placeholder="اكتب القسم المطلوب..."
                    style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '2px solid #16a34a', background: 'white', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.95rem', color: '#0f172a', marginBottom: '8px' }}
                  />

                  {/* Quick Department Dropdown */}
                  <select
                    value={['طب الأطفال', 'الجراحة العامة', 'النسائية والتوليد', 'الباطني', 'الطوارئ', 'العناية المركزة ICU', 'الحضانة وحديثي الولادة NICU', 'العمليات الجراحية', 'التمريض العام', 'المختبرات الطبية وبنك الدم', 'الأشعة والتصوير الطبي', 'العلاج الطبيعي والتأهيل', 'التغذية السريرية والحميات'].includes(idCardData.dept) ? idCardData.dept : ''}
                    onChange={e => { if (e.target.value) setIdCardData({ ...idCardData, dept: e.target.value }); }}
                    style={{ width: '100%', padding: '8px 10px', borderRadius: '8px', border: '1px solid #cbd5e1', background: 'white', fontFamily: 'Tajawal', fontSize: '0.85rem', fontWeight: 600, color: '#334155', marginBottom: '8px' }}
                  >
                    <option value="">-- أو اختر من قائمة أقسام المستشفى --</option>
                    <option value="طب الأطفال">طب الأطفال</option>
                    <option value="الجراحة العامة">الجراحة العامة</option>
                    <option value="النسائية والتوليد">النسائية والتوليد</option>
                    <option value="الباطني">الباطني</option>
                    <option value="الطوارئ">الطوارئ</option>
                    <option value="العناية المركزة ICU">العناية المركزة ICU</option>
                    <option value="الحضانة وحديثي الولادة NICU">الحضانة وحديثي الولادة NICU</option>
                    <option value="العمليات الجراحية">العمليات الجراحية</option>
                    <option value="التمريض العام">التمريض العام</option>
                    <option value="المختبرات الطبية وبنك الدم">المختبرات الطبية وبنك الدم</option>
                    <option value="الأشعة والتصوير الطبي">الأشعة والتصوير الطبي</option>
                    <option value="العلاج الطبيعي والتأهيل">العلاج الطبيعي والتأهيل</option>
                    <option value="التغذية السريرية والحميات">التغذية السريرية والحميات</option>
                    <option value="الخدمة الاجتماعية">الخدمة الاجتماعية</option>
                    <option value="ضباط الإسعاف والطوارئ">ضباط الإسعاف والطوارئ</option>
                  </select>

                  {/* Quick Pills */}
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                    {['طب الأطفال', 'الجراحة العامة', 'النسائية والتوليد', 'الطوارئ', 'ICU', 'NICU', 'التمريض'].map((p, pi) => (
                      <button
                        key={pi}
                        type="button"
                        onClick={() => setIdCardData({ ...idCardData, dept: p === 'ICU' ? 'العناية المركزة ICU' : (p === 'NICU' ? 'الحضانة وحديثي الولادة NICU' : (p === 'التمريض' ? 'التمريض العام' : p)) })}
                        style={{
                          fontSize: '0.72rem', padding: '3px 8px', borderRadius: '6px', cursor: 'pointer', fontFamily: 'Tajawal',
                          border: idCardData.dept.includes(p) ? '1.5px solid #16a34a' : '1px solid #cbd5e1',
                          background: idCardData.dept.includes(p) ? '#16a34a' : 'white',
                          color: idCardData.dept.includes(p) ? 'white' : '#334155',
                          fontWeight: idCardData.dept.includes(p) ? 800 : 600
                        }}
                      >
                        {p}
                      </button>
                    ))}
                  </div>
                </div>

                {/* المسمى */}
                <div className="form-group" style={{ margin: 0 }}>
                  <label style={{ fontSize: '0.85rem', fontWeight: 700, marginBottom: '5px' }}>المسمى الوظيفي:</label>
                  <div style={{ display: 'flex', gap: '8px' }}>
                    <input
                      type="text"
                      value={idCardData.title}
                      onChange={e => setIdCardData({ ...idCardData, title: e.target.value })}
                      style={{ flex: 1, padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal' }}
                    />
                    <select
                      onChange={e => { if (e.target.value) setIdCardData({ ...idCardData, title: e.target.value }); }}
                      style={{ padding: '8px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.85rem' }}
                    >
                      <option value="">اقتراحات</option>
                      <option value="طبيب امتياز">طبيب امتياز</option>
                      <option value="ممرض/ة">ممرض/ة</option>
                      <option value="متدرب/ة تمريض">متدرب/ة تمريض</option>
                      <option value="أخصائي/ة">أخصائي/ة</option>
                      <option value="طبيب متطوع">طبيب متطوع</option>
                      <option value="متدرب/ة">متدرب/ة</option>
                    </select>
                  </div>
                </div>

                {/* تاريخ الانتهاء والهوية */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
                  <div className="form-group" style={{ margin: 0 }}>
                    <label style={{ fontSize: '0.85rem', fontWeight: 700, marginBottom: '5px' }}>تاريخ الإنتهاء :</label>
                    <input
                      type="text"
                      value={idCardData.endDate}
                      onChange={e => setIdCardData({ ...idCardData, endDate: e.target.value })}
                      dir="ltr"
                      style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', textAlign: 'right' }}
                    />
                  </div>
                  <div className="form-group" style={{ margin: 0 }}>
                    <label style={{ fontSize: '0.85rem', fontWeight: 700, marginBottom: '5px' }}>رقم الهوية:</label>
                    <input
                      type="text"
                      value={idCardData.idNumber}
                      onChange={e => setIdCardData({ ...idCardData, idNumber: e.target.value })}
                      style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal' }}
                    />
                  </div>
                </div>
              </div>

              {/* Live Card Preview Column */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: '#f8fafc', padding: '20px', borderRadius: '16px', border: '1px dashed #cbd5e1' }}>
                <div style={{ fontSize: '0.85rem', fontWeight: 700, color: '#475569', marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                  <i className="fas fa-eye" style={{ color: '#059669' }}></i> معاينة البطاقة الحية
                </div>

                <div style={{ transform: 'scale(1.15)', transformOrigin: 'center center', margin: '15px 0' }}
                  dangerouslySetInnerHTML={{ __html: `
                    <div style="width:85mm;height:54mm;border:1px solid #bbb;overflow:hidden;display:flex;flex-direction:column;font-family:'Tajawal',sans-serif;background:white;position:relative;box-sizing:border-box;box-shadow:0 4px 15px rgba(0,0,0,0.08);">
                      <div style="display:flex;align-items:center;justify-content:space-between;padding:5px 7px;border-bottom:2.5px solid #CE1126;background:#f9f9f9;">
                        <div style="text-align:right;flex:1;direction:rtl;">
                          <div style="font-size:7px;font-weight:800;color:#CE1126;">جمعية الهلال الأحمر الفلسطيني - الخليل</div>
                          <div style="font-size:6px;font-weight:700;color:#333;">مستشفى الهلال الأحمر التخصصي - الخليل</div>
                        </div>
                        <div style="margin:0 5px;flex-shrink:0;width:30px;height:30px;border-radius:50%;border:1px solid #CE1126;overflow:hidden;display:flex;align-items:center;justify-content:center;background:white;">
                          <img src="/prcs-logo.png" style="width:24px;height:24px;object-fit:contain;" alt="Logo" />
                        </div>
                        <div style="text-align:left;flex:1;">
                          <div style="font-size:6px;font-weight:800;color:#CE1126;">Palestine Red Crescent Society- Hebron</div>
                          <div style="font-size:5px;font-weight:600;color:#555;">Red Crescent Specilized Hospital - Hebron</div>
                        </div>
                      </div>
                      <div style="flex:1;padding:5px 10px;direction:rtl;display:flex;flex-direction:column;justify-content:center;gap:4px;">
                        <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
                          <span style="font-size:9px;font-weight:800;min-width:60px;color:#222;">الاسم :</span>
                          <span style="font-size:10px;font-weight:800;color:#CE1126;">${idCardData.name}</span>
                        </div>
                        <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
                          <span style="font-size:9px;font-weight:800;min-width:60px;color:#222;">المسمى:</span>
                          <span style="font-size:9px;font-weight:700;color:#333;">${idCardData.title}</span>
                        </div>
                        <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
                          <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">القسم :</span>
                          <span style="font-size:9px;font-weight:700;color:#333;background:#eff6ff;padding:1px 4px;border-radius:3px;">${idCardData.dept}</span>
                        </div>
                        <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
                          <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">تاريخ الإنتهاء :</span>
                          <span style="font-size:9px;font-weight:700;color:#333;">${idCardData.endDate}</span>
                        </div>
                        ${(idCardData.idNumber || idCardData.bloodType) ? `
                          <div style="display:flex;align-items:center;justify-content:center;gap:12px;margin-top:1px;">
                            ${idCardData.idNumber ? `<div style="background:#f1f5f9;border:1px solid #cbd5e1;border-radius:3px;padding:1px 5px;display:flex;align-items:center;"><span style="font-size:7px;font-weight:800;color:#334155;margin-left:3px;">الهوية:</span><span style="font-size:8px;font-weight:700;color:#0f172a;">${idCardData.idNumber}</span></div>` : ''}
                            ${idCardData.bloodType ? `<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:3px;padding:1px 5px;display:flex;align-items:center;"><span style="font-size:7px;font-weight:800;color:#ef4444;margin-left:3px;">فصيلة الدم:</span><span style="font-size:8px;font-weight:800;color:#b91c1c;" dir="ltr">${idCardData.bloodType}</span></div>` : ''}
                          </div>` : ''}
                      </div>
                      <div style="padding:3px 10px;direction:rtl;display:flex;justify-content:flex-end;">
                        <span style="font-size:8px;font-weight:700;color:#555;">المدير الطبي</span>
                      </div>
                      <div style="height:6px;background:linear-gradient(to bottom,#CE1126,#8B0000);position:absolute;bottom:0;width:100%;"></div>
                    </div>`
                  }}
                />

                <span style={{ fontSize: '0.75rem', color: '#64748b', marginTop: '12px' }}>
                  💡 الحجم القياسي للطباعة: 85mm × 54mm (بطاقة هوية رسمية)
                </span>
              </div>
            </div>

            {/* Modal Actions */}
            <div className="modal-actions" style={{ borderTop: '1px solid #e2e8f0', paddingTop: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '10px' }}>
              <Link
                href={`/idcard?student=${encodeURIComponent(idCardData.name)}&dept=${encodeURIComponent(idCardData.dept)}`}
                className="btn-secondary"
                style={{ textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: '6px' }}
              >
                <i className="fas fa-external-link-alt"></i> فتح في محرر البطاقات المتقدم
              </Link>

              <div style={{ display: 'flex', gap: '10px' }}>
                <button type="button" className="btn-secondary" onClick={() => setActiveModal(null)}>إلغاء</button>
                <button
                  type="button"
                  className="btn-primary"
                  onClick={handlePrintIdCardFromModal}
                  style={{ background: 'linear-gradient(135deg, #059669, #047857)', display: 'inline-flex', alignItems: 'center', gap: '8px' }}
                >
                  <i className="fas fa-print"></i> طباعة البطاقة بالقسم المعدل
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeModal === 'add' && (
        <div className="modal-overlay active" onClick={(e) => e.target === e.currentTarget && setActiveModal(null)}>
          <div className="modal">
            <div className="modal-header">
              <h3><i className="fas fa-user-plus"></i> إضافة طبيب جديد</h3>
              <button className="modal-close" onClick={() => setActiveModal(null)}>&times;</button>
            </div>
            <form onSubmit={handleAddStudent}>
              <div className="form-group">
                <label>اسم الطبيب</label>
                <input type="text" required value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />
              </div>
              <div className="form-group">
                <label>رقم الهوية</label>
                <input type="text" value={formData.idNumber || ''} onChange={e => setFormData({...formData, idNumber: e.target.value})} placeholder="رقم الهوية الفلسطينية" />
              </div>
              <div className="form-group">
                <label>تاريخ البدء</label>
                <input type="date" required value={formData.startDate} onChange={e => setFormData({...formData, startDate: e.target.value})} />
              </div>
              <div className="form-group">
                <label>تاريخ الانتهاء</label>
                <input type="date" required value={formData.endDate} onChange={e => setFormData({...formData, endDate: e.target.value})} />
              </div>
              <div className="form-group">
                <label>رقم الهاتف</label>
                <input type="tel" required value={formData.phone} onChange={e => setFormData({...formData, phone: e.target.value})} />
              </div>
              <div className="form-group">
                <label>الجامعة</label>
                <input type="text" value={formData.university || ''} onChange={e => setFormData({...formData, university: e.target.value})} placeholder="الجامعة" />
              </div>
              <div className="form-group">
                <label>سنة التخرج</label>
                <input type="text" required value={formData.graduationYear || ''} onChange={e => setFormData({...formData, graduationYear: e.target.value})} placeholder="سنة التخرج" />
              </div>
              <div className="form-actions">
                <button type="button" className="btn-secondary" onClick={() => setActiveModal(null)}>إلغاء</button>
                <button type="submit" className="btn-primary">إضافة الطبيب</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {activeModal === 'addDirect' && (
        <div className="modal-overlay active" onClick={(e) => e.target === e.currentTarget && setActiveModal(null)}>
          <div className="modal">
            <div className="modal-header">
              <h3><i className="fas fa-user-plus"></i> إضافة طبيب جديد</h3>
              <button className="modal-close" onClick={() => setActiveModal(null)}>&times;</button>
            </div>
            <form onSubmit={handleAddStudentDirect}>
              <div className="form-group">
                <label>القسم</label>
                <select required value={formData.department || ''} onChange={e => setFormData({...formData, department: e.target.value})} style={{ width: '100%', padding: '10px 14px', border: '2px solid var(--border)', borderRadius: '10px', fontSize: '1rem', background: 'var(--card-bg)', color: 'var(--text)', outline: 'none' }}>
                  <optgroup label="الطب والامتياز">
                    <option value="جراحة">الجراحة العامة</option>
                    <option value="نسائية">النسائية والتوليد</option>
                    <option value="الاطفال">طب الأطفال</option>
                    <option value="الأطباء المتعاقدون">الأطباء المتعاقدون</option>
                    <option value="طب تدريب">طب تدريب</option>
                    <option value="طب تطوع">طب تطوع</option>
                  </optgroup>
                  <optgroup label="التمريض">
                    <option value="التمريض">التمريض العام</option>
                    <option value="تدريب تمريض الجامعات">تدريب تمريض الجامعات</option>
                    <option value="تمريض تدريب">تمريض تدريب</option>
                    <option value="تمريض امتياز">تمريض امتياز</option>
                    <option value="تمريض تطوع">تمريض تطوع</option>
                  </optgroup>
                  <optgroup label="المهن الطبية والمساندة">
                    <option value="العلاج الطبيعي">العلاج الطبيعي</option>
                    <option value="مختبرات طبية">المختبرات الطبية</option>
                    <option value="أشعة">الأشعة والتصوير الطبي</option>
                    <option value="العلاج الوظيفي">العلاج الوظيفي</option>
                    <option value="تغذية">التغذية السريرية</option>
                    <option value="الصحة النفسية">الصحة النفسية</option>
                    <option value="خدمة اجتماعية">خدمة اجتماعية</option>
                    <option value="ضباط الإسعاف">ضباط الإسعاف</option>
                  </optgroup>
                  <optgroup label="مدربين الأقسام الصحية المساندة">
                    <option value="مدربي أشعة">مدربو الأشعة والتصوير الطبي</option>
                    <option value="مدربي هندسة طبية">مدربو الهندسة الطبية</option>
                    <option value="مدربي تغذية">مدربو التغذية السريرية</option>
                    <option value="مدربي صيدلية">مدربو الصيدلة</option>
                    <option value="مدربي مختبر">مدربو المختبرات الطبية</option>
                    <option value="مدربي علاج طبيعي">مدربو العلاج الطبيعي</option>
                    <option value="مدربي علاج وظيفي">مدربو العلاج الوظيفي</option>
                  </optgroup>
                  <optgroup label="الإدارة والخدمات والتطوع">
                    <option value="إدارة">إدارة</option>
                    <option value="المحاسبة">المحاسبة والمالية</option>
                    <option value="سكرتارية طبية">سكرتارية طبية</option>
                    <option value="المطبخ">المطبخ والإعاشة</option>
                    <option value="العمل المجتمعي">العمل المجتمعي</option>
                  </optgroup>
                  <optgroup label="حالات خاصة">
                    <option value="المغادرين">المغادرين (أنهوا فترة التدريب)</option>
                    <option value="الاستئناف">الاستئناف (إجازة مؤقتة)</option>
                  </optgroup>
                </select>
              </div>
              <div className="form-group">
                <label>اسم الطبيب</label>
                <input type="text" required value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />
              </div>
              <div className="form-group">
                <label>رقم الهوية</label>
                <input type="text" value={formData.idNumber || ''} onChange={e => setFormData({...formData, idNumber: e.target.value})} placeholder="رقم الهوية الفلسطينية" />
              </div>
              <div className="form-group">
                <label>رقم الهاتف</label>
                <input type="tel" value={formData.phone} onChange={e => setFormData({...formData, phone: e.target.value})} placeholder="5XXXXXXXX" />
              </div>
              <div className="form-group">
                <label>الجامعة</label>
                <input type="text" value={formData.university || ''} onChange={e => setFormData({...formData, university: e.target.value})} placeholder="الجامعة" />
              </div>
              <div className="form-group">
                <label>سنة التخرج</label>
                <input type="text" required value={formData.graduationYear || ''} onChange={e => setFormData({...formData, graduationYear: e.target.value})} placeholder="سنة التخرج" />
              </div>
              <div className="form-group">
                <label>تاريخ البدء</label>
                <input type="date" value={formData.startDate} onChange={e => setFormData({...formData, startDate: e.target.value})} />
              </div>
              <div className="form-group">
                <label>تاريخ الانتهاء</label>
                <input type="date" value={formData.endDate} onChange={e => setFormData({...formData, endDate: e.target.value})} />
              </div>
              <div className="form-actions">
                <button type="button" className="btn-secondary" onClick={() => setActiveModal(null)}>إلغاء</button>
                <button type="submit" className="btn-primary">إضافة الطبيب</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {activeModal === 'edit' && (
        <div className="modal-overlay active" onClick={(e) => e.target === e.currentTarget && setActiveModal(null)}>
          <div className="modal" style={{ maxWidth: '600px', maxHeight: '90vh', overflowY: 'auto' }}>
            <div className="modal-header">
              <h3><i className="fas fa-edit"></i> تعديل بيانات الطبيب</h3>
              <button className="modal-close" onClick={() => setActiveModal(null)}>&times;</button>
            </div>
            <form onSubmit={handleEditStudent}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', padding: '0 4px' }}>
                <div className="form-group" style={{ gridColumn: 'span 2' }}>
                  <label>القسم / الحالة الحالية</label>
                  <select 
                    value={formData.department || editTargetDept || currentDepartment || ''} 
                    onChange={e => setFormData({...formData, department: e.target.value})}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '8px', border: '1px solid var(--border)', fontSize: '0.95rem', fontFamily: 'Tajawal', background: 'var(--card-bg)', color: 'var(--text)' }}
                  >
                  <optgroup label="الطب والامتياز">
                    <option value="جراحة">الجراحة العامة</option>
                    <option value="نسائية">النسائية والتوليد</option>
                    <option value="الاطفال">طب الأطفال</option>
                    <option value="الأطباء المتعاقدون">الأطباء المتعاقدون</option>
                    <option value="طب تدريب">طب تدريب</option>
                    <option value="طب تطوع">طب تطوع</option>
                  </optgroup>
                  <optgroup label="التمريض">
                    <option value="التمريض">التمريض العام</option>
                    <option value="تدريب تمريض الجامعات">تدريب تمريض الجامعات</option>
                    <option value="تمريض تدريب">تمريض تدريب</option>
                    <option value="تمريض امتياز">تمريض امتياز</option>
                    <option value="تمريض تطوع">تمريض تطوع</option>
                  </optgroup>
                  <optgroup label="المهن الطبية والمساندة">
                    <option value="العلاج الطبيعي">العلاج الطبيعي</option>
                    <option value="مختبرات طبية">المختبرات الطبية</option>
                    <option value="أشعة">الأشعة والتصوير الطبي</option>
                    <option value="العلاج الوظيفي">العلاج الوظيفي</option>
                    <option value="تغذية">التغذية السريرية</option>
                    <option value="الصحة النفسية">الصحة النفسية</option>
                    <option value="خدمة اجتماعية">خدمة اجتماعية</option>
                    <option value="ضباط الإسعاف">ضباط الإسعاف</option>
                  </optgroup>
                  <optgroup label="مدربين الأقسام الصحية المساندة">
                    <option value="مدربي أشعة">مدربو الأشعة والتصوير الطبي</option>
                    <option value="مدربي هندسة طبية">مدربو الهندسة الطبية</option>
                    <option value="مدربي تغذية">مدربو التغذية السريرية</option>
                    <option value="مدربي صيدلية">مدربو الصيدلة</option>
                    <option value="مدربي مختبر">مدربو المختبرات الطبية</option>
                    <option value="مدربي علاج طبيعي">مدربو العلاج الطبيعي</option>
                    <option value="مدربي علاج وظيفي">مدربو العلاج الوظيفي</option>
                  </optgroup>
                  <optgroup label="الإدارة والخدمات والتطوع">
                    <option value="إدارة">إدارة</option>
                    <option value="المحاسبة">المحاسبة والمالية</option>
                    <option value="سكرتارية طبية">سكرتارية طبية</option>
                    <option value="المطبخ">المطبخ والإعاشة</option>
                    <option value="العمل المجتمعي">العمل المجتمعي</option>
                  </optgroup>
                  <optgroup label="حالات خاصة">
                    <option value="المغادرين">المغادرين (أنهوا فترة التدريب)</option>
                    <option value="الاستئناف">الاستئناف (إجازة مؤقتة)</option>
                  </optgroup>
                  </select>
                </div>
                <div className="form-group" style={{ gridColumn: 'span 2' }}>
                  <label>اسم الطبيب الرباعي *</label>
                  <input type="text" required value={formData.name || ''} onChange={e => setFormData({...formData, name: e.target.value})} placeholder="الاسم الرباعي" />
                </div>
                <div className="form-group">
                  <label>رقم الهوية</label>
                  <input type="text" value={formData.idNumber || ''} onChange={e => setFormData({...formData, idNumber: e.target.value})} placeholder="رقم الهوية" />
                </div>
                <div className="form-group">
                  <label>رقم الهاتف *</label>
                  <input type="tel" required value={formData.phone || ''} onChange={e => setFormData({...formData, phone: e.target.value})} placeholder="رقم الهاتف" />
                </div>
                <div className="form-group">
                  <label>تاريخ البدء *</label>
                  <input type="date" required value={formData.startDate || ''} onChange={e => setFormData({...formData, startDate: e.target.value})} />
                </div>
                <div className="form-group">
                  <label>تاريخ الانتهاء *</label>
                  <input type="date" required value={formData.endDate || ''} onChange={e => setFormData({...formData, endDate: e.target.value})} />
                </div>
                <div className="form-group">
                  <label>الجامعة</label>
                  <input type="text" value={formData.university || ''} onChange={e => setFormData({...formData, university: e.target.value})} placeholder="اسم الجامعة" />
                </div>
                <div className="form-group">
                  <label>سنة التخرج</label>
                  <input type="text" value={formData.graduationYear || ''} onChange={e => setFormData({...formData, graduationYear: e.target.value})} placeholder="مثال: 2024" />
                </div>
                <div className="form-group" style={{ gridColumn: 'span 2' }}>
                  <label>مكان السكن</label>
                  <input type="text" value={formData.address || ''} onChange={e => setFormData({...formData, address: e.target.value})} placeholder="مدينة / قرية السكن" />
                </div>
                <div className="form-group" style={{ gridColumn: 'span 2' }}>
                  <label>أيام الحضور</label>
                  <input type="text" value={formData.attendanceDays || ''} onChange={e => setFormData({...formData, attendanceDays: e.target.value})} placeholder="مثال: سبت / اتنين / اربعاء" />
                </div>
                <div className="form-group">
                  <label>نظام الدراسة</label>
                  <input type="text" value={formData.studySystem || ''} onChange={e => setFormData({...formData, studySystem: e.target.value})} placeholder="مثال: انتظام" />
                </div>
                <div className="form-group">
                  <label>مستوى الامتياز</label>
                  <input type="text" value={formData.internshipYear || ''} onChange={e => setFormData({...formData, internshipYear: e.target.value})} placeholder="مثال: طبيب امتياز" />
                </div>
                <div className="form-group" style={{ gridColumn: 'span 2' }}>
                  <label>نظام الشيفت</label>
                  <select value={formData.shiftSystem || ''} onChange={e => setFormData({...formData, shiftSystem: e.target.value})} style={{ width: '100%', padding: '10px 14px', borderRadius: '8px', border: '1px solid var(--border)', fontSize: '0.95rem', fontFamily: 'inherit' }}>
                    <option value="">-- اختر نظام الشيفت --</option>
                    <option value="سبت / اتنين / اربعاء">سبت / اتنين / اربعاء</option>
                    <option value="احد / ثلاثاء / خميس">احد / ثلاثاء / خميس</option>
                    <option value="يومي">يومي</option>
                    <option value="مرن">مرن</option>
                  </select>
                </div>
              </div>
              <div className="form-actions" style={{ marginTop: '20px' }}>
                <button type="button" className="btn-secondary" onClick={() => setActiveModal(null)}>إلغاء</button>
                <button type="submit" className="btn-primary"><i className="fas fa-save"></i> حفظ التعديلات</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {activeModal === 'move' && (() => {
        const sourceDept = editTargetDept || currentDepartment || 'جراحة';
        const targetStudent = sourceDept && selectedStudentIndex !== null ? (studentsData[sourceDept]?.[selectedStudentIndex]) : null;

        // Structured departments list
        const predefinedDepts = [
          // أقسام الامتياز والطب
          { key: 'جراحة', label: 'الجراحة العامة', category: 'الطب والامتياز', icon: 'fa-procedures', color: '#8B1A2B' },
          { key: 'نسائية', label: 'النسائية والتوليد', category: 'الطب والامتياز', icon: 'fa-female', color: '#6B3A7D' },
          { key: 'الاطفال', label: 'طب الأطفال', category: 'الطب والامتياز', icon: 'fa-baby', color: '#2B5F8B' },
          { key: 'طب تدريب', label: 'طب تدريب', category: 'الطب والامتياز', icon: 'fa-user-md', color: '#c2185b' },
          { key: 'طب تطوع', label: 'طب تطوع', category: 'الطب والامتياز', icon: 'fa-hand-holding-heart', color: '#f39c12' },
          
          // أقسام التمريض
          { key: 'التمريض', label: 'التمريض العام', category: 'التمريض', icon: 'fa-heartbeat', color: '#e74c3c' },
          { key: 'تمريض تدريب', label: 'تمريض تدريب', category: 'التمريض', icon: 'fa-stethoscope', color: '#e91e63' },
          { key: 'تمريض امتياز', label: 'تمريض امتياز', category: 'التمريض', icon: 'fa-user-nurse', color: '#9c27b0' },
          { key: 'تمريض تطوع', label: 'تمريض تطوع', category: 'التمريض', icon: 'fa-hand-holding-medical', color: '#00bcd4' },
          { key: 'تدريب تمريض الجامعات', label: 'تدريب تمريض الجامعات', category: 'التمريض', icon: 'fa-graduation-cap', color: '#0284c7' },

          // المهن الطبية والمساندة
          { key: 'مختبرات طبية', label: 'مختبرات طبية', category: 'المهن الطبية والمساندة', icon: 'fa-vial', color: '#0284c7' },
          { key: 'أشعة', label: 'أشعة وتصوير طبي', category: 'المهن الطبية والمساندة', icon: 'fa-x-ray', color: '#455a64' },
          { key: 'علاج طبيعي تدريب', label: 'علاج طبيعي تدريب', category: 'المهن الطبية والمساندة', icon: 'fa-walking', color: '#16a34a' },
          { key: 'علاج طبيعي امتياز', label: 'علاج طبيعي امتياز', category: 'المهن الطبية والمساندة', icon: 'fa-user-graduate', color: '#059669' },
          { key: 'العلاج الطبيعي', label: 'العلاج الطبيعي (عام)', category: 'المهن الطبية والمساندة', icon: 'fa-running', color: '#27ae60' },
          { key: 'العلاج الوظيفي', label: 'العلاج الوظيفي', category: 'المهن الطبية والمساندة', icon: 'fa-hands', color: '#16a085' },
          { key: 'تغذية', label: 'التغذية السريرية', category: 'المهن الطبية والمساندة', icon: 'fa-apple-alt', color: '#689f38' },
          { key: 'الصحة النفسية', label: 'الصحة النفسية', category: 'المهن الطبية والمساندة', icon: 'fa-brain', color: '#009688' },
          { key: 'خدمة اجتماعية', label: 'خدمة اجتماعية', category: 'المهن الطبية والمساندة', icon: 'fa-users', color: '#5d4037' },
          { key: 'ضباط الإسعاف', label: 'ضباط الإسعاف', category: 'المهن الطبية والمساندة', icon: 'fa-ambulance', color: '#FF5722' },

          // مدربين الأقسام الصحية المساندة
          { key: 'مدربي أشعة', label: 'مدربو الأشعة والتصوير الطبي', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-radiation', color: '#7C3AED' },
          { key: 'مدربي هندسة طبية', label: 'مدربو الهندسة الطبية', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-microchip', color: '#1d4ed8' },
          { key: 'مدربي تغذية', label: 'مدربو التغذية السريرية', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-apple-alt', color: '#16a34a' },
          { key: 'مدربي صيدلية', label: 'مدربو الصيدلة', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-pills', color: '#b45309' },
          { key: 'مدربي مختبر', label: 'مدربو المختبرات الطبية', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-flask', color: '#0284c7' },
          { key: 'مدربي علاج طبيعي', label: 'مدربو العلاج الطبيعي', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-walking', color: '#059669' },
          { key: 'مدربي علاج وظيفي', label: 'مدربو العلاج الوظيفي', category: 'مدربين الأقسام الصحية المساندة', icon: 'fa-hands', color: '#0f766e' },

          // الإدارة والخدمات
          { key: 'إدارة', label: 'إدارة', category: 'الإدارة والخدمات', icon: 'fa-briefcase', color: '#2c3e50' },
          { key: 'المحاسبة', label: 'المحاسبة والمالية', category: 'الإدارة والخدمات', icon: 'fa-calculator', color: '#8e44ad' },
          { key: 'سكرتارية طبية', label: 'سكرتارية طبية', category: 'الإدارة والخدمات', icon: 'fa-file-invoice', color: '#00838f' },
          { key: 'المطبخ', label: 'المطبخ والإعاشة', category: 'الإدارة والخدمات', icon: 'fa-utensils', color: '#d35400' },
          { key: 'العمل المجتمعي', label: 'العمل المجتمعي', category: 'الإدارة والخدمات', icon: 'fa-handshake', color: '#00695c' },

          // حالات خاصة
          { key: 'المغادرين', label: 'قسم المغادرين', category: 'حالات خاصة', icon: 'fa-user-graduate', color: '#78909c' },
          { key: 'الاستئناف', label: 'قائمة الاستئناف', category: 'حالات خاصة', icon: 'fa-pause-circle', color: '#546e7a' }
        ];

        // Include any additional dynamic departments from studentsData
        Object.keys(studentsData).forEach(k => {
          if (!predefinedDepts.some(d => d.key === k)) {
            predefinedDepts.push({ key: k, label: k, category: 'أقسام أخرى', icon: 'fa-folder', color: '#475569' });
          }
        });

        // Filter departments based on search term
        const filteredDepts = moveDeptSearch.trim()
          ? predefinedDepts.filter(d => d.label.toLowerCase().includes(moveDeptSearch.trim().toLowerCase()) || d.key.toLowerCase().includes(moveDeptSearch.trim().toLowerCase()) || d.category.toLowerCase().includes(moveDeptSearch.trim().toLowerCase()))
          : predefinedDepts;

        // Group by category
        const categories = Array.from(new Set(filteredDepts.map(d => d.category)));

        return (
          <div className="modal-overlay active" onClick={(e) => e.target === e.currentTarget && setActiveModal(null)}>
            <div className="modal" style={{ maxWidth: '780px', width: '95%', maxHeight: '90vh', overflowY: 'auto', borderRadius: '24px', padding: '24px' }}>
              
              {/* Header */}
              <div className="modal-header" style={{ borderBottom: '2px solid var(--border)', paddingBottom: '16px', marginBottom: '20px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                  <div style={{
                    width: '46px', height: '46px', borderRadius: '12px',
                    background: 'linear-gradient(135deg, #f59e0b, #d97706)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    boxShadow: '0 4px 12px rgba(245, 158, 11, 0.35)', color: 'white'
                  }}>
                    <i className="fas fa-exchange-alt" style={{ fontSize: '1.25rem' }}></i>
                  </div>
                  <div>
                    <h3 style={{ margin: 0, fontSize: '1.3rem', fontWeight: 900 }}>نقل المتدرب إلى قسم آخر</h3>
                    <p style={{ margin: '3px 0 0 0', color: 'var(--text-light)', fontSize: '0.85rem' }}>
                      اختر القسم الجديد لنقل المتدرب وتحديث فترة تدريبه وقيده فورياً
                    </p>
                  </div>
                </div>
                <button className="modal-close" onClick={() => setActiveModal(null)}>&times;</button>
              </div>

              {/* Student Card Summary */}
              {targetStudent && (
                <div style={{
                  background: 'linear-gradient(135deg, rgba(245, 158, 11, 0.08) 0%, rgba(217, 119, 6, 0.12) 100%)',
                  border: '1.5px solid rgba(245, 158, 11, 0.35)',
                  borderRadius: '16px',
                  padding: '16px 20px',
                  marginBottom: '20px'
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                      <i className="fas fa-user-circle" style={{ fontSize: '2.2rem', color: '#f59e0b' }}></i>
                      <div>
                        <div style={{ fontSize: '1.15rem', fontWeight: 900, color: 'var(--text)' }}>
                          {targetStudent.name}
                        </div>
                        <div style={{ fontSize: '0.85rem', color: 'var(--text-light)', marginTop: '2px' }}>
                          {targetStudent.university && <span>🎓 {targetStudent.university} &bull; </span>}
                          {targetStudent.phone && <span>📞 {targetStudent.phone}</span>}
                        </div>
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <span style={{ fontSize: '0.82rem', color: 'var(--text-light)', fontWeight: 600 }}>القسم الحالي:</span>
                      <span style={{
                        background: 'linear-gradient(135deg, #1e3a8a, #2563eb)',
                        color: 'white',
                        padding: '4px 14px',
                        borderRadius: '20px',
                        fontWeight: 800,
                        fontSize: '0.88rem',
                        boxShadow: '0 2px 8px rgba(37, 99, 235, 0.3)'
                      }}>
                        {sourceDept}
                      </span>
                    </div>
                  </div>

                  <div style={{ display: 'flex', gap: '16px', marginTop: '12px', paddingTop: '10px', borderTop: '1px dashed rgba(245, 158, 11, 0.25)', fontSize: '0.82rem', color: 'var(--text-light)' }}>
                    <div>📅 البدء الحالي: <strong style={{ color: 'var(--text)' }}>{targetStudent.startDate || '—'}</strong></div>
                    <div>⏳ الانتهاء الحالي: <strong style={{ color: 'var(--text)' }}>{targetStudent.endDate || '—'}</strong></div>
                  </div>
                </div>
              )}

              {/* ⚡ Quick Move / Assign Shortcuts ⚡ */}
              <div style={{
                background: 'linear-gradient(135deg, rgba(8,145,178,0.08) 0%, rgba(233,30,99,0.08) 100%)',
                border: '1.5px solid #0891b2',
                borderRadius: '16px',
                padding: '14px 18px',
                marginBottom: '20px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                gap: '10px'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <div style={{ width: '34px', height: '34px', borderRadius: '10px', background: '#0891b2', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '0.95rem' }}>
                    <i className="fas fa-bolt"></i>
                  </div>
                  <div>
                    <div style={{ fontWeight: 800, fontSize: '0.92rem', color: 'var(--text)' }}>نقل سريع ومباشر للتمريض:</div>
                    <div style={{ fontSize: '0.78rem', color: 'var(--text-light)' }}>تسريع النقل إلى تمريض تدريب أو التعيين لمدربهم مباشرة</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                  <button
                    type="button"
                    onClick={() => handleMoveStudent('تمريض تدريب')}
                    disabled={sourceDept === 'تمريض تدريب'}
                    style={{
                      background: sourceDept === 'تمريض تدريب' ? '#cbd5e1' : 'linear-gradient(135deg, #e91e63, #c2185b)',
                      color: 'white',
                      border: 'none',
                      borderRadius: '10px',
                      padding: '8px 14px',
                      fontSize: '0.85rem',
                      fontWeight: 800,
                      cursor: sourceDept === 'تمريض تدريب' ? 'not-allowed' : 'pointer',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '6px',
                      fontFamily: 'Tajawal',
                      boxShadow: '0 2px 8px rgba(233,30,99,0.3)'
                    }}
                    title="نقل الطالب فوراً إلى قسم تمريض تدريب"
                  >
                    <i className="fas fa-syringe"></i>
                    <span>نقل فوري إلى تمريض تدريب</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const st = targetStudent;
                      const src = sourceDept;
                      setActiveModal(null);
                      if (st) openAssignModal(st, src);
                    }}
                    style={{
                      background: 'linear-gradient(135deg, #0891b2, #0e7490)',
                      color: 'white',
                      border: 'none',
                      borderRadius: '10px',
                      padding: '8px 14px',
                      fontSize: '0.85rem',
                      fontWeight: 800,
                      cursor: 'pointer',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '6px',
                      fontFamily: 'Tajawal',
                      boxShadow: '0 2px 8px rgba(8,145,178,0.3)'
                    }}
                    title="تعيين الطالب لمدرب سريري ونقله لتدريب تمريض الجامعات"
                  >
                    <i className="fas fa-chalkboard-teacher"></i>
                    <span>تعيين لمدرب سريري (نقل لمدربهم)</span>
                  </button>
                </div>
              </div>

              {/* Dates Setting Options */}
              <div style={{
                background: 'var(--card-bg)',
                border: '1px solid var(--border)',
                borderRadius: '16px',
                padding: '16px 20px',
                marginBottom: '20px',
                boxShadow: 'var(--shadow)'
              }}>
                <div style={{ fontSize: '0.9rem', fontWeight: 800, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--text)' }}>
                  <i className="fas fa-calendar-alt" style={{ color: '#6366f1' }}></i>
                  <span>إعدادات تواريخ الدوام في القسم الجديد:</span>
                </div>

                <div style={{ display: 'flex', gap: '18px', flexWrap: 'wrap', alignItems: 'center', marginBottom: keepExistingDates ? '0' : '14px' }}>
                  <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', fontSize: '0.88rem', fontWeight: 700 }}>
                    <input 
                      type="radio" 
                      name="dateMode" 
                      checked={!keepExistingDates} 
                      onChange={() => setKeepExistingDates(false)} 
                    />
                    <span>تحديث التواريخ للقسم الجديد (البدء اليوم والانتهاء بعد شهرين)</span>
                  </label>
                  <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', fontSize: '0.88rem', fontWeight: 700 }}>
                    <input 
                      type="radio" 
                      name="dateMode" 
                      checked={keepExistingDates} 
                      onChange={() => setKeepExistingDates(true)} 
                    />
                    <span>الاحتفاظ بالتواريخ الحالية دون تعديل</span>
                  </label>
                </div>

                {!keepExistingDates && (
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '12px', paddingTop: '10px', borderTop: '1px solid var(--border)' }}>
                    <div>
                      <label style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-light)', display: 'block', marginBottom: '4px' }}>
                        تاريخ البدء في القسم الجديد:
                      </label>
                      <input 
                        type="date" 
                        value={moveCustomStartDate} 
                        onChange={(e) => setMoveCustomStartDate(e.target.value)}
                        style={{ width: '100%', padding: '8px 12px', borderRadius: '8px', border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontFamily: 'Tajawal', fontWeight: 700 }}
                      />
                    </div>
                    <div>
                      <label style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-light)', display: 'block', marginBottom: '4px' }}>
                        تاريخ الانتهاء في القسم الجديد:
                      </label>
                      <input 
                        type="date" 
                        value={moveCustomEndDate} 
                        onChange={(e) => setMoveCustomEndDate(e.target.value)}
                        style={{ width: '100%', padding: '8px 12px', borderRadius: '8px', border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontFamily: 'Tajawal', fontWeight: 700 }}
                      />
                    </div>
                  </div>
                )}
              </div>

              {/* Department Fast Search */}
              <div style={{ position: 'relative', marginBottom: '16px' }}>
                <i className="fas fa-search" style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-light)' }}></i>
                <input 
                  type="text" 
                  placeholder="ابحث بالاسم عن القسم المطلوب نقله إليه (مثال: جراحة، نسائية، مختبرات، تمريض)..."
                  value={moveDeptSearch}
                  onChange={(e) => setMoveDeptSearch(e.target.value)}
                  style={{
                    width: '100%',
                    padding: '12px 42px 12px 14px',
                    borderRadius: '12px',
                    border: '1.5px solid var(--border)',
                    background: 'var(--bg)',
                    color: 'var(--text)',
                    fontFamily: 'Tajawal',
                    fontSize: '0.95rem',
                    fontWeight: 600,
                    outline: 'none'
                  }}
                />
              </div>

              {/* Departments Grid Grouped by Category */}
              <div style={{ maxHeight: '380px', overflowY: 'auto', paddingRight: '4px' }}>
                {categories.map(cat => {
                  const deptsInCat = filteredDepts.filter(d => d.category === cat);
                  if (deptsInCat.length === 0) return null;
                  return (
                    <div key={cat} style={{ marginBottom: '18px' }}>
                      <div style={{ fontSize: '0.88rem', fontWeight: 800, color: 'var(--text-light)', marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                        <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: '#f59e0b' }}></span>
                        {cat}
                      </div>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))', gap: '10px' }}>
                        {deptsInCat.map(dept => {
                          const isCurrent = sourceDept === dept.key;
                          const studentCount = studentsData[dept.key]?.length || 0;
                          return (
                            <button
                              key={dept.key}
                              type="button"
                              onClick={() => {
                                if (dept.key === 'الاستئناف') {
                                  handleMoveToSuspended();
                                } else {
                                  handleMoveStudent(dept.key);
                                }
                              }}
                              disabled={isCurrent}
                              style={{
                                background: isCurrent 
                                  ? 'rgba(0,0,0,0.06)' 
                                  : 'var(--card-bg)',
                                border: isCurrent 
                                  ? '1.5px dashed rgba(0,0,0,0.2)' 
                                  : '1.5px solid var(--border)',
                                color: isCurrent ? '#94a3b8' : 'var(--text)',
                                borderRadius: '12px',
                                padding: '12px 14px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                                gap: '10px',
                                cursor: isCurrent ? 'not-allowed' : 'pointer',
                                transition: 'all 0.2s ease',
                                boxShadow: isCurrent ? 'none' : '0 2px 6px rgba(0,0,0,0.05)',
                                fontFamily: 'Tajawal',
                                opacity: isCurrent ? 0.6 : 1
                              }}
                              onMouseEnter={(e) => {
                                if (!isCurrent) {
                                  e.currentTarget.style.borderColor = '#f59e0b';
                                  e.currentTarget.style.transform = 'translateY(-2px)';
                                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(245, 158, 11, 0.2)';
                                }
                              }}
                              onMouseLeave={(e) => {
                                if (!isCurrent) {
                                  e.currentTarget.style.borderColor = 'var(--border)';
                                  e.currentTarget.style.transform = 'translateY(0)';
                                  e.currentTarget.style.boxShadow = '0 2px 6px rgba(0,0,0,0.05)';
                                }
                              }}
                            >
                              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                <div style={{
                                  width: '32px', height: '32px', borderRadius: '8px',
                                  background: isCurrent ? '#cbd5e1' : (dept.color + '20'),
                                  color: isCurrent ? '#64748b' : dept.color,
                                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                                  fontSize: '0.9rem'
                                }}>
                                  <i className={'fas ' + dept.icon}></i>
                                </div>
                                <div style={{ textAlign: 'right' }}>
                                  <div style={{ fontWeight: 800, fontSize: '0.92rem' }}>{dept.label}</div>
                                  {isCurrent && (
                                    <div style={{ fontSize: '0.72rem', color: '#ef4444', fontWeight: 700 }}>
                                      (القسم الحالي للمتدرب)
                                    </div>
                                  )}
                                </div>
                              </div>
                              <span style={{
                                background: isCurrent ? '#cbd5e1' : 'rgba(0,0,0,0.06)',
                                color: isCurrent ? '#64748b' : 'var(--text-light)',
                                fontSize: '0.75rem',
                                fontWeight: 700,
                                padding: '2px 8px',
                                borderRadius: '12px'
                              }}>
                                {studentCount}
                              </span>
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Footer */}
              <div style={{ marginTop: '20px', paddingTop: '16px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  onClick={() => setActiveModal(null)}
                  style={{
                    padding: '10px 24px',
                    borderRadius: '10px',
                    border: '1px solid var(--border)',
                    background: 'var(--bg)',
                    color: 'var(--text)',
                    fontFamily: 'Tajawal',
                    fontWeight: 700,
                    cursor: 'pointer'
                  }}
                >
                  إلغاء
                </button>
              </div>

            </div>
          </div>
        );
      })()}

      {/* ═══════════════════════════════════════════════════════════════ */}
      {/* ═══════ STATISTICAL & PERIODIC REPORT MODAL ═════════════════ */}
      {/* ═══════════════════════════════════════════════════════════════ */}
      {showStatsReportModal && (
        <div 
          className="modal-overlay active" 
          onClick={(e) => e.target === e.currentTarget && setShowStatsReportModal(false)}
          style={{
            position: 'fixed',
            inset: 0,
            background: 'rgba(0, 0, 0, 0.75)',
            backdropFilter: 'blur(8px)',
            zIndex: 9999,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '16px'
          }}
        >
          <div 
            className="modal" 
            style={{ 
              maxWidth: '1280px', 
              width: '97vw', 
              maxHeight: '94vh', 
              overflowY: 'auto', 
              borderRadius: '24px',
              border: `1.5px solid ${currentDeptConfig.badgeColor || 'var(--primary)'}40`,
              boxShadow: '0 25px 65px rgba(0,0,0,0.4)',
              background: 'var(--card-bg)',
              color: 'var(--text)'
            }}
          >
            {/* Modal Header */}
            <div 
              className="modal-header" 
              style={{ 
                borderBottom: '2px solid var(--border)', 
                paddingBottom: '16px', 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                flexWrap: 'wrap',
                gap: '12px'
              }}
            >
              <div>
                <h3 style={{ fontSize: '1.35rem', fontWeight: 900, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: '10px', margin: 0 }}>
                  <i className="fas fa-chart-pie" style={{ color: '#ffd700', fontSize: '1.4rem' }}></i>
                  التقرير الإحصائي التخصصي المعتمد للأقسام وبرامج التدريب
                </h3>
                <div style={{ fontSize: '0.85rem', color: 'var(--text-light)', marginTop: '4px', fontWeight: 600 }}>
                  وحدة التطوير والتدريب والتعليم المستمر — مستشفى الهلال الأحمر الفلسطيني (بإشراف أ. نسرين عابدين)
                </div>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <button
                  type="button"
                  onClick={() => printDedicatedDepartmentReport()}
                  style={{
                    padding: '8px 16px',
                    borderRadius: '10px',
                    border: 'none',
                    background: 'linear-gradient(135deg, #f59e0b, #d97706)',
                    color: 'white',
                    fontFamily: 'Tajawal',
                    fontWeight: 800,
                    fontSize: '0.85rem',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    boxShadow: '0 4px 12px rgba(217, 119, 6, 0.3)'
                  }}
                >
                  <i className="fas fa-print"></i>
                  طباعة التقرير (A4)
                </button>
                <button 
                  className="modal-close" 
                  onClick={() => setShowStatsReportModal(false)} 
                  style={{ fontSize: '1.8rem', background: 'none', border: 'none', color: 'var(--text-light)', cursor: 'pointer', lineHeight: 1 }}
                >
                  &times;
                </button>
              </div>
            </div>

            {/* ═══════════ Quick Category Filter Switcher Pills ═══════════ */}
            <div style={{ marginTop: '16px', display: 'flex', gap: '6px', flexWrap: 'wrap', alignItems: 'center' }}>
              <span style={{ fontSize: '0.8rem', fontWeight: 800, color: 'var(--text-light)', marginLeft: '6px' }}>
                <i className="fas fa-layer-group" style={{ marginLeft: '4px' }}></i> فئات الأقسام:
              </span>
              {[
                { key: 'All', label: '🌟 كل الأقسام', color: '#2563eb' },
                { key: 'CATEGORY_ALL_medicine', label: '🏥 الأقسام الطبية السريرية', color: '#8B1A2B' },
                { key: 'الأطباء المتعاقدون', label: '🩺 كادر الأطباء المتعاقدون', color: '#4338ca' },
                { key: 'CATEGORY_ALL_nursing', label: '💉 أقسام التمريض والقبالة', color: '#0d9488' },
                { key: 'تدريب تمريض الجامعات', label: '👨‍🏫 كادر مدربي التمريض', color: '#7c3aed' },
                { key: 'CATEGORY_ALL_allied', label: '🔬 المهن المساندة والمختبرات', color: '#0891b2' },
                { key: 'CATEGORY_ALL_health-trainers', label: '🧑‍🏫 مدربو الأقسام المساندة', color: '#6d28d9' },
                { key: 'CATEGORY_ALL_admin', label: '📊 التدريب الإداري', color: '#475569' },
                { key: 'المغادرين', label: '🎓 المغادرين (أنهوا التدريب)', color: '#15803d' },
              ].map((pill) => {
                const isActive = reportDept === pill.key;
                return (
                  <button
                    key={pill.key}
                    type="button"
                    onClick={() => {
                      setReportDept(pill.key);
                      setTrainerUniFilter('');
                    }}
                    style={{
                      padding: '5px 12px',
                      borderRadius: '12px',
                      border: isActive ? `1.5px solid ${pill.color}` : '1px solid var(--border)',
                      background: isActive ? `${pill.color}18` : 'var(--bg-light)',
                      color: isActive ? pill.color : 'var(--text)',
                      fontSize: '0.8rem',
                      fontWeight: isActive ? 900 : 700,
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      transition: 'all 0.2s ease',
                      boxShadow: isActive ? `0 2px 8px ${pill.color}25` : 'none'
                    }}
                  >
                    {pill.label}
                  </button>
                );
              })}
            </div>

            {/* Filter Controls Box */}
            <div style={{ background: 'var(--bg-light)', padding: '18px 20px', borderRadius: '18px', margin: '16px 0', border: '1px solid var(--border)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(210px, 1fr))', gap: '14px', marginBottom: '14px' }}>
                {/* Department Selector with Rich Optgroups */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 800, marginBottom: '6px', color: 'var(--text)' }}>
                    <i className="fas fa-hospital-alt" style={{ marginLeft: '6px', color: 'var(--primary)' }}></i>
                    القسم أو التخصص المطلوب:
                  </label>
                  <select 
                    value={reportDept} 
                    onChange={e => {
                      setReportDept(e.target.value);
                      setTrainerUniFilter('');
                    }}
                    style={{ 
                      width: '100%', 
                      padding: '10px 14px', 
                      borderRadius: '10px', 
                      border: '1.5px solid var(--border)', 
                      fontFamily: 'Tajawal', 
                      fontWeight: 700, 
                      fontSize: '0.88rem',
                      background: 'var(--card-bg)', 
                      color: 'var(--text)' 
                    }}
                  >
                    <optgroup label="🌟 التقارير الشاملة والفئات الرئيسية">
                      <option value="All">🌟 كل الأقسام (تقرير إحصائي شامل لجميع البرامج) ({allStatisticalStudents.length})</option>
                      <option value="CATEGORY_ALL_medicine">🏥 كافة الأقسام الطبية السريرية (امتياز الطب البشري)</option>
                      <option value="CATEGORY_ALL_nursing">💉 كافة أقسام التمريض والمشرفين</option>
                      <option value="CATEGORY_ALL_allied">🔬 كافة المهن الطبية المساندة والمختبرات</option>
                      <option value="CATEGORY_ALL_health-trainers">🧑‍🏫 كافة مدربي الأقسام الصحية المساندة</option>
                      <option value="CATEGORY_ALL_admin">📊 كافة وحدات التدريب الإداري وتطوير الخدمات</option>
                    </optgroup>

                    <optgroup label="🩺 كادر الأطباء المتعاقدون مع الجامعات (تقرير تخصصي)">
                      <option value="الأطباء المتعاقدون">
                        🩺 كادر الأطباء المتعاقدون مع الجامعات ({allStatisticalStudents.filter(s => isContractedDoctor(s)).length} طبيب)
                      </option>
                    </optgroup>

                    <optgroup label="🎓 كادر تدريب تمريض الجامعات الشريكة (تقرير مستقل)">
                      <option value="تدريب تمريض الجامعات">
                        🎓 كادر مدربي تمريض الجامعات الشريكة ({allStatisticalStudents.filter(s => isNursingTrainer(s)).length} مدرب)
                      </option>
                    </optgroup>

                    <optgroup label="🏥 الأقسام الطبية السريرية (امتياز وتدريب الطب البشري)">
                      {[
                        { k: 'باطني', l: '🩺 قسم الباطني العام' },
                        { k: 'جراحة', l: '🔪 قسم الجراحة العامة والعمليات' },
                        { k: 'جراحة العظام', l: '🦴 قسم جراحة العظام والكسور' },
                        { k: 'تخدير', l: '💉 قسم التخدير والإنعاش' },
                        { k: 'نسائية', l: '🤰 قسم أمراض النسائية والتوليد' },
                        { k: 'الاطفال', l: '👶 قسم طب الأطفال وحضانات الخداج' },
                        { k: 'عيون', l: '👁️ قسم طب وجراحة العيون' },
                        { k: 'طوارئ', l: '🚑 قسم الطوارئ والحوادث' },
                        { k: 'عناية مكثفة', l: '🫀 قسم العناية الحثيثة والمركزة (ICU)' },
                        { k: 'اشعة', l: '☢️ قسم الأشعة والتصوير الطبي' },
                        { k: 'طب تدريب', l: '👨‍⚕️ قسم طب تدريب وتأهيل سريري' },
                        { k: 'طب تطوع', l: '🤝 قسم طب بشري تطوع' },
                      ].map(d => {
                        const cnt = allStatisticalStudents.filter(s => (s.department || s.originalDepartment) === d.k).length;
                        return (
                          <option key={d.k} value={d.k}>
                            {d.l} ({cnt} طبيب)
                          </option>
                        );
                      })}
                    </optgroup>

                    <optgroup label="💉 أقسام التمريض والقبالة">
                      {[
                        { k: 'تمريض تدريب', l: '💉 قسم تمريض تدريب سريري' },
                        { k: 'تمريض امتياز', l: '🩺 قسم تمريض امتياز' },
                        { k: 'تمريض باطني وجراحة', l: '🏥 تمريض الباطني والجراحة' },
                        { k: 'تمريض نسائية وولادة', l: '🤰 تمريض النسائية والولادة' },
                        { k: 'تمريض أطفال وخداج', l: '👶 تمريض الأطفال والحضانة' },
                        { k: 'تمريض عناية مكثفة', l: '🫀 تمريض العناية المركزة (ICU)' },
                        { k: 'تمريض عمليات', l: '🔪 تمريض العمليات والتعقيم' },
                        { k: 'تمريض طوارئ', l: '🚑 تمريض الطوارئ' },
                        { k: 'تمريض تطوع', l: '🤝 قسم تمريض تطوع' },
                      ].map(d => {
                        const cnt = allStatisticalStudents.filter(s => (s.department || s.originalDepartment) === d.k).length;
                        return (
                          <option key={d.k} value={d.k}>
                            {d.l} ({cnt} ممرض/ة)
                          </option>
                        );
                      })}
                    </optgroup>

                    <optgroup label="🔬 المهن الطبية المساندة والمختبرات والصيدلة">
                      {[
                        { k: 'مختبر', l: '🔬 قسم المختبرات الطبية وبنك الدم' },
                        { k: 'صيدلة', l: '💊 قسم الصيدلة والصيدلة السريرية' },
                        { k: 'علاج طبيعي', l: '🏃‍♂️ قسم العلاج الطبيعي والتأهيل' },
                        { k: 'تخدير تدريب', l: '💉 تدريب فنيي التخدير' },
                        { k: 'اشعة تدريب', l: '☢️ تدريب فنيي الأشعة' },
                      ].map(d => {
                        const cnt = allStatisticalStudents.filter(s => (s.department || s.originalDepartment) === d.k).length;
                        return (
                          <option key={d.k} value={d.k}>
                            {d.l} ({cnt} متدرب)
                          </option>
                        );
                      })}
                    </optgroup>

                    <optgroup label="🧑‍🏫 مدربو الأقسام الصحية المساندة">
                      {[
                        { k: 'مدربي أشعة', l: '☢️ مدربو الأشعة' },
                        { k: 'مدربي مختبر', l: '🔬 مدربو المختبر وبنك الدم' },
                        { k: 'مدربي تخدير', l: '💉 مدربو التخدير' },
                        { k: 'مدربي علاج طبيعي', l: '🏃‍♂️ مدربو العلاج الطبيعي' },
                        { k: 'مدربي صحة عامة', l: '🩺 مدربو الصحة العامة' },
                      ].map(d => {
                        const cnt = allStatisticalStudents.filter(s => (s.department || s.originalDepartment) === d.k).length;
                        return (
                          <option key={d.k} value={d.k}>
                            {d.l} ({cnt} مدرب)
                          </option>
                        );
                      })}
                    </optgroup>

                    <optgroup label="📊 التدريب الإداري وتطوير الخدمات">
                      {[
                        { k: 'تدريب إداري', l: '📊 قسم التدريب الإداري وإدارة المستشفيات' },
                        { k: 'إدارة مستشفيات', l: '🏢 قسم نظم المعلومات والإدارة الصحية' },
                      ].map(d => {
                        const cnt = allStatisticalStudents.filter(s => (s.department || s.originalDepartment) === d.k).length;
                        return (
                          <option key={d.k} value={d.k}>
                            {d.l} ({cnt} متدرب)
                          </option>
                        );
                      })}
                    </optgroup>

                    <optgroup label="🎓 خريجو البرامج المنتهية والحالات الخاصة">
                      <option value="المغادرين">
                        ⚪ المغادرون (الذين أنهوا التدريب بنجاح) ({allStatisticalStudents.filter(s => s.folderKey === 'المغادرين' || s.isGraduated || s.computedStatus === 'completed').length})
                      </option>
                      <option value="خريجون مكتملون">
                        🎓 خريجون مكتملون معتمدون
                      </option>
                      {studentsData['الاستئناف'] && studentsData['الاستئناف'].length > 0 && (
                        <option value="الاستئناف">
                          ⏸️ الاستئناف (إجازة مؤقتة) ({studentsData['الاستئناف'].length})
                        </option>
                      )}
                    </optgroup>

                    {/* Any dynamically detected department not covered above */}
                    {(() => {
                      const covered = new Set([
                        'All', 'CATEGORY_ALL_medicine', 'CATEGORY_ALL_nursing', 'CATEGORY_ALL_allied', 'CATEGORY_ALL_health-trainers', 'CATEGORY_ALL_admin',
                        'الأطباء المتعاقدون', 'تدريب تمريض الجامعات', 'المغادرين', 'خريجون مكتملون', 'الاستئناف',
                        'باطني', 'جراحة', 'جراحة العظام', 'تخدير', 'نسائية', 'الاطفال', 'عيون', 'طوارئ', 'عناية مكثفة', 'اشعة', 'طب تدريب', 'طب تطوع',
                        'تمريض تدريب', 'تمريض امتياز', 'تمريض باطني وجراحة', 'تمريض نسائية وولادة', 'تمريض أطفال وخداج', 'تمريض عناية مكثفة', 'تمريض عمليات', 'تمريض طوارئ', 'تمريض تطوع',
                        'مختبر', 'صيدلة', 'علاج طبيعي', 'تخدير تدريب', 'اشعة تدريب',
                        'مدربي أشعة', 'مدربي مختبر', 'مدربي تخدير', 'مدربي علاج طبيعي', 'مدربي صحة عامة',
                        'تدريب إداري', 'إدارة مستشفيات'
                      ]);
                      const others = allStatisticalDepartments.filter(d => !covered.has(d));
                      if (others.length === 0) return null;
                      return (
                        <optgroup label="أقسام إضافية مسجلة">
                          {others.map(dept => {
                            const count = allStatisticalStudents.filter(s => s.department === dept || s.originalDepartment === dept || s.folderKey === dept).length;
                            return (
                              <option key={dept} value={dept}>
                                📁 {dept} ({count} متدرب)
                              </option>
                            );
                          })}
                        </optgroup>
                      );
                    })()}
                  </select>
                </div>

                {/* Start Date Picker */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 800, marginBottom: '6px', color: 'var(--text)' }}>
                    <i className="fas fa-calendar-alt" style={{ marginLeft: '6px', color: '#3498db' }}></i>
                    من تاريخ (بداية الفترة):
                  </label>
                  <input 
                    type="date" 
                    value={reportStartDate} 
                    onChange={e => setReportStartDate(e.target.value)}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border)', fontFamily: 'Tajawal', background: 'var(--card-bg)', color: 'var(--text)' }}
                  />
                </div>

                {/* End Date Picker */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 800, marginBottom: '6px', color: 'var(--text)' }}>
                    <i className="fas fa-calendar-check" style={{ marginLeft: '6px', color: '#2ecc71' }}></i>
                    إلى تاريخ (نهاية الفترة):
                  </label>
                  <input 
                    type="date" 
                    value={reportEndDate} 
                    onChange={e => setReportEndDate(e.target.value)}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border)', fontFamily: 'Tajawal', background: 'var(--card-bg)', color: 'var(--text)' }}
                  />
                </div>

                {/* Status Filter */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 800, marginBottom: '6px', color: 'var(--text)' }}>
                    <i className="fas fa-filter" style={{ marginLeft: '6px', color: '#e67e22' }}></i>
                    حالة التدريب / العمل:
                  </label>
                  <select 
                    value={reportStatus} 
                    onChange={e => setReportStatus(e.target.value)}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border)', fontFamily: 'Tajawal', fontWeight: 700, background: 'var(--card-bg)', color: 'var(--text)' }}
                  >
                    <option value="all">كل الحالات المسجلة</option>
                    <option value="active">🟢 على رأس العمل (نشط)</option>
                    <option value="completed">⚪ أنهوا فترة التدريب / الإشراف</option>
                    <option value="upcoming">🟡 فترات قادمة (مجدول)</option>
                  </select>
                </div>
              </div>

              {/* Quick Presets & Search */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px', borderTop: '1px solid var(--border)', paddingTop: '14px' }}>
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', alignItems: 'center' }}>
                  <span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-light)', marginLeft: '6px' }}>فترات سريعة:</span>
                  <button 
                    type="button" 
                    onClick={() => { setReportStartDate(''); setReportEndDate(''); }}
                    style={{ padding: '5px 12px', borderRadius: '14px', border: 'none', background: (!reportStartDate && !reportEndDate) ? 'var(--primary)' : 'var(--card-bg)', color: (!reportStartDate && !reportEndDate) ? 'white' : 'var(--text)', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                  >
                    كل الأوقات
                  </button>
                  <button 
                    type="button" 
                    onClick={() => {
                      const now = new Date();
                      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0];
                      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString().split('T')[0];
                      setReportStartDate(firstDay); setReportEndDate(lastDay);
                    }}
                    style={{ padding: '5px 12px', borderRadius: '14px', border: 'none', background: 'var(--card-bg)', color: 'var(--text)', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                  >
                    هذا الشهر
                  </button>
                  <button 
                    type="button" 
                    onClick={() => {
                      const now = new Date();
                      const start = now.toISOString().split('T')[0];
                      const next3m = new Date(now); next3m.setMonth(next3m.getMonth() + 3);
                      setReportStartDate(start); setReportEndDate(next3m.toISOString().split('T')[0]);
                    }}
                    style={{ padding: '5px 12px', borderRadius: '14px', border: 'none', background: 'var(--card-bg)', color: 'var(--text)', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                  >
                    الـ 3 أشهر القادمة
                  </button>
                  <button 
                    type="button" 
                    onClick={() => { setReportStartDate('2026-01-01'); setReportEndDate('2026-12-31'); }}
                    style={{ padding: '5px 12px', borderRadius: '14px', border: 'none', background: 'var(--card-bg)', color: 'var(--text)', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}
                  >
                    سنة 2026
                  </button>
                </div>

                <div style={{ minWidth: '240px', flex: '1 1 220px' }}>
                  <input 
                    type="text" 
                    placeholder="بحث سريع: اسم الطبيب، التخصص، الجامعة، الهاتف..."
                    value={reportSearch} 
                    onChange={e => setReportSearch(e.target.value)}
                    style={{ width: '100%', padding: '9px 14px', borderRadius: '10px', border: '1.5px solid var(--border)', fontFamily: 'Tajawal', fontSize: '0.85rem', background: 'var(--card-bg)', color: 'var(--text)' }}
                  />
                </div>
              </div>
            </div>

            {/* ═══════════ DEDICATED DEPARTMENT HERO BANNER ═══════════ */}
            <div style={{
              background: `linear-gradient(135deg, ${currentDeptConfig.badgeColor}18 0%, ${currentDeptConfig.badgeColor}06 100%)`,
              border: `2px solid ${currentDeptConfig.badgeColor}35`,
              borderRadius: '20px',
              padding: '18px 22px',
              marginBottom: '20px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: '14px',
              boxShadow: `0 8px 24px ${currentDeptConfig.badgeColor}12`
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                <div style={{
                  width: '52px',
                  height: '52px',
                  borderRadius: '16px',
                  background: `linear-gradient(135deg, ${currentDeptConfig.badgeColor}, ${currentDeptConfig.badgeColor}cc)`,
                  color: 'white',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '1.5rem',
                  boxShadow: `0 6px 16px ${currentDeptConfig.badgeColor}35`,
                  flexShrink: 0
                }}>
                  <i className={currentDeptConfig.icon}></i>
                </div>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                    <h4 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 900, color: 'var(--text)' }}>
                      {currentDeptConfig.name}
                    </h4>
                    <span style={{
                      background: currentDeptConfig.badgeBg,
                      color: currentDeptConfig.badgeColor,
                      padding: '3px 10px',
                      borderRadius: '12px',
                      fontSize: '0.78rem',
                      fontWeight: 800,
                      border: `1px solid ${currentDeptConfig.badgeColor}40`
                    }}>
                      {currentDeptConfig.categoryLabel}
                    </span>
                    <span style={{
                      background: 'rgba(16, 185, 129, 0.12)',
                      color: '#059669',
                      padding: '3px 10px',
                      borderRadius: '12px',
                      fontSize: '0.76rem',
                      fontWeight: 800
                    }}>
                      تقرير تخصصي مستقل ومفصول
                    </span>
                  </div>
                  <div style={{ fontSize: '0.84rem', color: 'var(--text-light)', marginTop: '4px', fontWeight: 600 }}>
                    {currentDeptConfig.description}
                  </div>
                </div>
              </div>

              <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                <button
                  type="button"
                  onClick={() => printDedicatedDepartmentReport()}
                  style={{
                    padding: '9px 18px',
                    borderRadius: '12px',
                    border: 'none',
                    background: `linear-gradient(135deg, ${currentDeptConfig.badgeColor}, #8B1A2B)`,
                    color: 'white',
                    fontFamily: 'Tajawal',
                    fontWeight: 800,
                    fontSize: '0.88rem',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    boxShadow: `0 4px 12px ${currentDeptConfig.badgeColor}35`
                  }}
                >
                  <i className="fas fa-print"></i>
                  طباعة التقرير (A4)
                </button>
                <button
                  type="button"
                  onClick={() => exportDedicatedDepartmentCSV()}
                  style={{
                    padding: '9px 16px',
                    borderRadius: '12px',
                    border: '1.5px solid var(--border)',
                    background: 'var(--card-bg)',
                    color: 'var(--text)',
                    fontFamily: 'Tajawal',
                    fontWeight: 800,
                    fontSize: '0.88rem',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px'
                  }}
                >
                  <i className="fas fa-file-excel" style={{ color: '#10b981' }}></i>
                  تصدير CSV
                </button>
              </div>
            </div>

            {/* ═══════════ SPECIALIZED KPI CARDS ═══════════ */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: '12px', marginBottom: '22px' }}>
              <div style={{ background: `linear-gradient(135deg, ${currentDeptConfig.badgeColor}, #1e293b)`, borderRadius: '16px', padding: '14px', color: 'white', textAlign: 'center', boxShadow: '0 6px 16px rgba(0,0,0,0.12)' }}>
                <div style={{ fontSize: '0.78rem', opacity: 0.9 }}>إجمالي المقيدين بالقسم</div>
                <div style={{ fontSize: '1.9rem', fontWeight: 900, marginTop: '4px' }}>{reportFilteredStudents.length}</div>
              </div>
              <div style={{ background: 'linear-gradient(135deg, #15803d, #16a34a)', borderRadius: '16px', padding: '14px', color: 'white', textAlign: 'center', boxShadow: '0 6px 16px rgba(22, 163, 74, 0.25)' }}>
                <div style={{ fontSize: '0.78rem', opacity: 0.9 }}>🟢 على رأس العمل (نشط)</div>
                <div style={{ fontSize: '1.9rem', fontWeight: 900, marginTop: '4px' }}>{currentDeptActiveCount}</div>
              </div>
              <div style={{ background: 'linear-gradient(135deg, #475569, #64748b)', borderRadius: '16px', padding: '14px', color: 'white', textAlign: 'center', boxShadow: '0 6px 16px rgba(100, 116, 139, 0.25)' }}>
                <div style={{ fontSize: '0.78rem', opacity: 0.9 }}>⚪ أنهوا الفترة (مغادر)</div>
                <div style={{ fontSize: '1.9rem', fontWeight: 900, marginTop: '4px' }}>{currentDeptCompletedCount}</div>
              </div>
              <div style={{ background: 'linear-gradient(135deg, #d97706, #f59e0b)', borderRadius: '16px', padding: '14px', color: 'white', textAlign: 'center', boxShadow: '0 6px 16px rgba(245, 158, 11, 0.25)' }}>
                <div style={{ fontSize: '0.78rem', opacity: 0.9 }}>🟡 فترات قادمة (مجدول)</div>
                <div style={{ fontSize: '1.9rem', fontWeight: 900, marginTop: '4px' }}>{currentDeptUpcomingCount}</div>
              </div>
              <div style={{ background: 'linear-gradient(135deg, #0d9488, #0f766e)', borderRadius: '16px', padding: '14px', color: 'white', textAlign: 'center', boxShadow: '0 6px 16px rgba(13, 148, 136, 0.25)' }}>
                <div style={{ fontSize: '0.78rem', opacity: 0.9 }}>المؤسسات الأكاديمية</div>
                <div style={{ fontSize: '1.9rem', fontWeight: 900, marginTop: '4px' }}>
                  {currentDeptUniversityStats.length}
                </div>
              </div>
            </div>

            {/* ═══════════ SECONDARY ANALYTICS (UNIVERSITIES & SPECIALTIES) ═══════════ */}
            <div style={{ background: 'var(--bg-light)', borderRadius: '18px', padding: '16px 18px', border: '1.5px solid var(--border)', marginBottom: '22px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px', flexWrap: 'wrap', gap: '8px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fas fa-university" style={{ color: currentDeptConfig.badgeColor, fontSize: '1.1rem' }}></i>
                  <h5 style={{ margin: 0, fontSize: '1rem', fontWeight: 800, color: 'var(--text)' }}>
                    🏛️ توزيع الكوادر والمتدربين حسب المؤسسات التعليمية والجامعات ({currentDeptUniversityStats.length} جامعة ومؤسسة)
                  </h5>
                </div>
                {trainerUniFilter && (
                  <button 
                    onClick={() => setTrainerUniFilter('')}
                    style={{ background: '#ede9fe', color: '#6d28d9', border: '1px solid #c4b5fd', padding: '3px 10px', borderRadius: '8px', fontSize: '0.75rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal' }}
                  >
                    إلغاء فلترة الجامعة ({trainerUniFilter}) ✕
                  </button>
                )}
              </div>

              {/* University Cards Grid */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(210px, 1fr))', gap: '10px' }}>
                {currentDeptUniversityStats.map((uni, idx) => {
                  const isSelected = trainerUniFilter === uni.name;
                  return (
                    <div 
                      key={idx}
                      onClick={() => setTrainerUniFilter(isSelected ? '' : uni.name)}
                      style={{
                        background: isSelected ? 'rgba(139, 26, 43, 0.1)' : 'var(--card-bg)',
                        border: isSelected ? '2px solid var(--primary)' : '1px solid var(--border)',
                        borderRadius: '12px',
                        padding: '10px 12px',
                        cursor: 'pointer',
                        transition: 'all 0.2s ease',
                        boxShadow: isSelected ? '0 4px 14px rgba(139, 26, 43, 0.2)' : 'none'
                      }}
                    >
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                        <div style={{ fontWeight: 800, fontSize: '0.85rem', color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '150px' }}>
                          {uni.name}
                        </div>
                        <div style={{ background: currentDeptConfig.badgeColor, color: 'white', padding: '2px 8px', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 900 }}>
                          {uni.total}
                        </div>
                      </div>

                      <div style={{ display: 'flex', gap: '5px', fontSize: '0.68rem', fontWeight: 700, marginBottom: '6px' }}>
                        <span style={{ background: 'rgba(21, 128, 61, 0.1)', color: '#15803d', padding: '1px 5px', borderRadius: '4px' }}>
                          🟢 {uni.active} نشط
                        </span>
                        <span style={{ background: 'rgba(100, 116, 139, 0.1)', color: '#64748b', padding: '1px 5px', borderRadius: '4px' }}>
                          ⚪ {uni.completed} مغادر
                        </span>
                        {uni.upcoming > 0 && (
                          <span style={{ background: 'rgba(217, 119, 6, 0.1)', color: '#b45309', padding: '1px 5px', borderRadius: '4px' }}>
                            🟡 {uni.upcoming} قادم
                          </span>
                        )}
                      </div>

                      <div style={{ width: '100%', height: '5px', background: 'var(--border)', borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${uni.percentage}%`, height: '100%', background: currentDeptConfig.badgeColor, borderRadius: '3px' }}></div>
                      </div>
                      <div style={{ fontSize: '0.68rem', color: 'var(--text-light)', textAlign: 'left', marginTop: '2px', fontWeight: 700 }}>
                        {uni.percentage}% من القسم
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Extra Medical Study Systems breakdown */}
              {currentDeptConfig.tableType === 'medical' && currentDeptStudySystemStats.length > 0 && (
                <div style={{ marginTop: '14px', paddingTop: '12px', borderTop: '1px solid var(--border)', display: 'flex', gap: '10px', flexWrap: 'wrap', alignItems: 'center' }}>
                  <span style={{ fontSize: '0.82rem', fontWeight: 800, color: 'var(--text)' }}>
                    🩺 توزيع أطباء الامتياز حسب نظام الدراسة والمرحلة:
                  </span>
                  {currentDeptStudySystemStats.map((sys, idx) => (
                    <span key={idx} style={{ background: 'var(--card-bg)', border: '1px solid var(--border)', borderRadius: '10px', padding: '4px 12px', fontSize: '0.8rem', fontWeight: 700 }}>
                      {sys.name}: <strong style={{ color: '#8B1A2B' }}>{sys.count} طبيب</strong>
                    </span>
                  ))}
                </div>
              )}

              {/* Extra Contracted Specialties breakdown */}
              {currentDeptConfig.tableType === 'contracted_doctors' && currentDeptSpecialtyStats.length > 0 && (
                <div style={{ marginTop: '14px', paddingTop: '12px', borderTop: '1px solid var(--border)', display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
                  <span style={{ fontSize: '0.82rem', fontWeight: 800, color: '#3730a3' }}>
                    🩺 التخصصات الطبية للأطباء المتعاقدين:
                  </span>
                  {currentDeptSpecialtyStats.map((sp, idx) => (
                    <span key={idx} style={{ background: '#eef2ff', color: '#3730a3', border: '1px solid #c7d2fe', borderRadius: '8px', padding: '3px 10px', fontSize: '0.78rem', fontWeight: 700 }}>
                      {sp.name}: <strong>{sp.count}</strong>
                    </span>
                  ))}
                </div>
              )}
            </div>

            {/* ═══════════ MAIN DATA TABLE (SPECIALIZED PER TABLE TYPE) ═══════════ */}
            <div style={{ marginBottom: '22px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                <h4 style={{ margin: 0, fontSize: '1.05rem', fontWeight: 800, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fas fa-list-alt" style={{ color: currentDeptConfig.badgeColor }}></i>
                  الكشف التفصيلي للأسماء وبيانات التدريب — {currentDeptConfig.name} ({reportFilteredStudents.length} سجل)
                </h4>
              </div>

              <div className="table-container" style={{ maxHeight: '420px', overflowY: 'auto', border: '1.5px solid var(--border)', borderRadius: '16px', background: 'var(--card-bg)' }}>
                <table style={{ width: '100%', fontSize: '0.86rem' }}>
                  <thead>
                    <tr style={{ background: 'var(--bg-light)', position: 'sticky', top: 0, zIndex: 2 }}>
                      {currentDeptConfig.tableType === 'contracted_doctors' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم الطبيب المتعاقد / الاستشاري</th>
                          <th>التخصص الدقيق</th>
                          <th>المؤسسات والجامعات الشريكة</th>
                          <th style={{ textAlign: 'center' }}>طاقم الهلال</th>
                          <th>أيام الدوام والعيادات</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>رقم الهوية</th>
                          <th style={{ textAlign: 'center' }}>الحالة</th>
                        </>
                      ) : currentDeptConfig.tableType === 'nursing_trainers' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم المدرب السريري</th>
                          <th style={{ color: '#4c1d95' }}>🤝 الجامعة الشريكة (شراكة)</th>
                          <th style={{ color: '#0f766e' }}>🎓 الجامعة المتخرج منها (مؤهل)</th>
                          <th>القسم المخصص للتدريب</th>
                          <th style={{ textAlign: 'center' }}>تاريخ البدء</th>
                          <th style={{ textAlign: 'center' }}>تاريخ الانتهاء</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>المسمى التدريبي</th>
                          <th style={{ textAlign: 'center' }}>الحالة</th>
                        </>
                      ) : currentDeptConfig.tableType === 'medical' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم طبيب الامتياز</th>
                          <th>القسم السريري</th>
                          <th>مجموعة ومناوبات الدوام</th>
                          <th>الجامعة الطبية والدولة</th>
                          <th style={{ textAlign: 'center' }}>سنة التخرج</th>
                          <th style={{ textAlign: 'center' }}>نظام الدراسة</th>
                          <th style={{ textAlign: 'center' }}>تاريخ البدء</th>
                          <th style={{ textAlign: 'center' }}>تاريخ الانتهاء</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>الحالة السريرية</th>
                        </>
                      ) : currentDeptConfig.tableType === 'nursing' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم المتدرب / طالب التمريض</th>
                          <th>القسم السريري</th>
                          <th>كلية التمريض / الجامعة</th>
                          <th>المشرف السريري المسؤول</th>
                          <th style={{ textAlign: 'center' }}>المرحلة / الروتيشن</th>
                          <th style={{ textAlign: 'center' }}>تاريخ البدء</th>
                          <th style={{ textAlign: 'center' }}>تاريخ الانتهاء</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>الحالة</th>
                        </>
                      ) : currentDeptConfig.tableType === 'allied' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم المتدرب / الأخصائي</th>
                          <th>التخصص / الوحدة المخبرية</th>
                          <th>الجامعة / الكلية</th>
                          <th>طبيعة التدريب المساند</th>
                          <th>أيام الحضور والدوام</th>
                          <th style={{ textAlign: 'center' }}>تاريخ البدء</th>
                          <th style={{ textAlign: 'center' }}>تاريخ الانتهاء</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>الحالة</th>
                        </>
                      ) : currentDeptConfig.tableType === 'admin' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم المتدرب الإداري</th>
                          <th>الوحدة الإدارية</th>
                          <th>المؤهل والجامعة</th>
                          <th>طبيعة المهام والمسؤوليات</th>
                          <th>أيام الدوام</th>
                          <th style={{ textAlign: 'center' }}>تاريخ البدء</th>
                          <th style={{ textAlign: 'center' }}>تاريخ الانتهاء</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>الحالة</th>
                        </>
                      ) : currentDeptConfig.tableType === 'graduates' ? (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>اسم الخريج المعتمد</th>
                          <th>القسم التدريبي المكتمل</th>
                          <th style={{ textAlign: 'center' }}>تاريخ إتمام التدريب</th>
                          <th>الجامعة / الكلية</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>رقم الهوية</th>
                          <th style={{ textAlign: 'center' }}>الحالة المعتمدة</th>
                        </>
                      ) : (
                        <>
                          <th style={{ width: '35px', textAlign: 'center' }}>#</th>
                          <th>الاسم الكامل</th>
                          <th>القسم</th>
                          <th>الجامعة / الكلية</th>
                          <th>الفئة والتصنيف</th>
                          <th style={{ textAlign: 'center' }}>تاريخ البدء</th>
                          <th style={{ textAlign: 'center' }}>تاريخ الانتهاء</th>
                          <th style={{ textAlign: 'center' }}>الهاتف</th>
                          <th style={{ textAlign: 'center' }}>الحالة</th>
                        </>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {reportFilteredStudents.length === 0 ? (
                      <tr>
                        <td colSpan={11} style={{ textAlign: 'center', padding: '35px', color: 'var(--text-muted)' }}>
                          <i className="fas fa-inbox" style={{ fontSize: '2rem', display: 'block', marginBottom: '8px' }}></i>
                          لا توجد سجلات تطابق الفلاتر المحددة لقسم "{currentDeptConfig.name}" في هذه الفترة
                        </td>
                      </tr>
                    ) : (
                      reportFilteredStudents.map((s, idx) => {
                        const isUpcoming = s.computedStatus === 'upcoming';
                        const isCompleted = s.computedStatus === 'completed';
                        const statusText = isUpcoming ? 'مجدول (قادم)' : isCompleted ? 'أنهى التدريب / الإشراف' : 'على رأس العمل (نشط)';
                        const statusColor = isUpcoming ? '#b45309' : isCompleted ? '#475569' : '#15803d';
                        const statusBg = isUpcoming ? '#fef3c7' : isCompleted ? 'rgba(100, 116, 139, 0.15)' : 'rgba(21, 128, 61, 0.12)';

                        if (currentDeptConfig.tableType === 'contracted_doctors') {
                          const universities = Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0
                            ? s.contractedUniversities.join('، ')
                            : (s.contractedUniversity || s.university || '—');
                          const worksAtCrescent = (s as any).workingAtCrescent !== false ? 'نعم (طاقم المستشفى)' : 'لا (مشرف خارجي)';
                          const days = Array.isArray((s as any).workDays) && (s as any).workDays.length > 0
                            ? (s as any).workDays.join('، ')
                            : ((s as any).clinicSchedule || 'حسب جدول العيادات');

                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#4338ca', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#4338ca' }}>{s.specialty || (s as any).academicDegree || 'طبيب استشاري/مشرف'}</td>
                              <td style={{ color: '#0f766e', fontSize: '0.8rem' }}>🤝 {universities}</td>
                              <td style={{ textAlign: 'center', fontSize: '0.78rem' }}>{worksAtCrescent}</td>
                              <td style={{ fontSize: '0.8rem' }}>{days}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontSize: '0.8rem' }}>{s.nationalId || (s as any).idNumber || '—'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: statusBg, color: statusColor, padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  {statusText}
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        if (currentDeptConfig.tableType === 'nursing_trainers') {
                          const contractedUni = normalizeUniversityName(
                            s.contractedUniversity ||
                            (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0 ? s.contractedUniversities[0] : '') ||
                            s.previousContractedUniversity ||
                            s.university
                          );
                          const gradUni = normalizeUniversityName(s.graduatedUniversity || (s.contractedUniversity !== s.university ? s.university : '') || '—');

                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#7c3aed', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#4c1d95' }}>🤝 {contractedUni}</td>
                              <td style={{ fontSize: '0.78rem', color: '#0f766e' }}>🎓 {gradUni}</td>
                              <td>{s.department || s.originalDepartment || 'تدريب تمريض الجامعات'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.startDate || s.globalStartDate || '—'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.endDate || s.globalEndDate || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td style={{ textAlign: 'center', fontSize: '0.78rem', fontWeight: 700, color: '#4c1d95' }}>{s.internshipYear || s.studySystem || 'مدرب سريري'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: statusBg, color: statusColor, padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  {statusText}
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        if (currentDeptConfig.tableType === 'medical') {
                          const shiftGroup = (s as any).rotationGroup || (s as any).shiftSchedule || 'دوام سريري رسمي';
                          const studySys = s.studySystem ? `نظام ${s.studySystem}` : 'نظام 5+2';
                          const gradYear = (s as any).graduatedYear || (s as any).graduationYear || '—';

                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#8B1A2B', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#8B1A2B' }}>{s.department || s.originalDepartment || currentDeptConfig.name}</td>
                              <td style={{ fontSize: '0.8rem', color: 'var(--text-light)' }}>{shiftGroup}</td>
                              <td style={{ fontWeight: 700, color: '#1e3a8a' }}>{normalizeUniversityName(s.university)}</td>
                              <td style={{ textAlign: 'center', fontSize: '0.78rem' }}>{gradYear}</td>
                              <td style={{ textAlign: 'center', fontWeight: 700, color: '#0f766e', fontSize: '0.78rem' }}>{studySys}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.startDate || s.globalStartDate || '—'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.endDate || s.globalEndDate || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: statusBg, color: statusColor, padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  {statusText}
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        if (currentDeptConfig.tableType === 'nursing') {
                          const supervisor = (s as any).supervisorName || (s as any).trainerName || 'مشرف القسم السريري';
                          const rotation = s.internshipYear || s.studySystem || 'تدريب عملي سريري';

                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#0d9488', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#0d9488' }}>{s.department || s.originalDepartment || currentDeptConfig.name}</td>
                              <td style={{ fontWeight: 700, color: '#0369a1' }}>{normalizeUniversityName(s.university)}</td>
                              <td style={{ fontSize: '0.8rem', color: 'var(--text-light)' }}>{supervisor}</td>
                              <td style={{ textAlign: 'center', fontSize: '0.8rem' }}>{rotation}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.startDate || s.globalStartDate || '—'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.endDate || s.globalEndDate || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: statusBg, color: statusColor, padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  {statusText}
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        if (currentDeptConfig.tableType === 'allied') {
                          const subUnit = s.specialty || s.department || currentDeptConfig.name;
                          const nature = s.studySystem || 'امتياز وتدريب عملي';

                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#0891b2', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#0891b2' }}>{subUnit}</td>
                              <td style={{ fontWeight: 700, color: '#115e59' }}>{normalizeUniversityName(s.university)}</td>
                              <td style={{ fontSize: '0.8rem' }}>{nature}</td>
                              <td style={{ fontSize: '0.8rem' }}>{(s as any).rotationGroup || 'دوام مساند مقرر'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.startDate || s.globalStartDate || '—'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.endDate || s.globalEndDate || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: statusBg, color: statusColor, padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  {statusText}
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        if (currentDeptConfig.tableType === 'admin') {
                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#475569', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#475569' }}>{s.department || s.originalDepartment || currentDeptConfig.name}</td>
                              <td style={{ fontWeight: 700, color: '#1e293b' }}>{normalizeUniversityName(s.university)}</td>
                              <td style={{ fontSize: '0.8rem' }}>{s.specialty || 'إدارة مستشفيات وتطوير خدمات'}</td>
                              <td style={{ fontSize: '0.8rem' }}>{(s as any).rotationGroup || 'دوام إداري رسمي'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.startDate || s.globalStartDate || '—'}</td>
                              <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.endDate || s.globalEndDate || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: statusBg, color: statusColor, padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  {statusText}
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        if (currentDeptConfig.tableType === 'graduates') {
                          return (
                            <tr key={idx}>
                              <td style={{ fontWeight: 800, color: '#15803d', textAlign: 'center' }}>{idx + 1}</td>
                              <td><strong style={{ color: 'var(--text)' }}>{s.name}</strong></td>
                              <td style={{ fontWeight: 700, color: '#15803d' }}>{s.department || s.originalDepartment || 'قسم سريري مكتمل'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontWeight: 700 }}>{s.endDate || s.globalEndDate || '—'}</td>
                              <td style={{ fontWeight: 700, color: '#1e3a8a' }}>{normalizeUniversityName(s.university)}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                              <td dir="ltr" style={{ textAlign: 'center', fontSize: '0.8rem' }}>{s.nationalId || (s as any).idNumber || '—'}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ background: '#dcfce7', color: '#15803d', padding: '3px 8px', borderRadius: '10px', fontSize: '0.76rem', fontWeight: 800 }}>
                                  أنهى التدريب بنجاح ✓
                                </span>
                              </td>
                            </tr>
                          );
                        }

                        // Default General Table Row
                        return (
                          <tr key={idx}>
                            <td style={{ fontWeight: 700, color: 'var(--primary)', textAlign: 'center' }}>{idx + 1}</td>
                            <td>
                              <strong>{s.name}</strong>
                              {s.folderKey === 'المغادرين' && (
                                <span style={{ marginRight: '6px', fontSize: '0.72rem', color: '#64748b', fontWeight: 700 }}>
                                  (مغادر)
                                </span>
                              )}
                            </td>
                            <td>
                              <span style={{ background: 'rgba(139, 26, 43, 0.12)', color: 'var(--primary)', padding: '3px 10px', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 700 }}>
                                {s.department || s.originalDepartment || '—'}
                              </span>
                            </td>
                            <td>{normalizeUniversityName(s.university)}</td>
                            <td style={{ fontSize: '0.8rem', color: 'var(--text-light)' }}>{currentDeptConfig.categoryLabel}</td>
                            <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.startDate || s.globalStartDate || '—'}</td>
                            <td dir="ltr" style={{ fontSize: '0.82rem', textAlign: 'center' }}>{s.endDate || s.globalEndDate || '—'}</td>
                            <td dir="ltr" style={{ textAlign: 'center', fontFamily: 'monospace' }}>{s.phone || '—'}</td>
                            <td style={{ textAlign: 'center' }}>
                              <span style={{ background: statusBg, color: statusColor, padding: '4px 10px', borderRadius: '12px', fontSize: '0.78rem', fontWeight: 800, whiteSpace: 'nowrap' }}>
                                {statusText}
                              </span>
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            {/* ═══════════ MODAL ACTIONS FOOTER ═══════════ */}
            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', borderTop: '2px solid var(--border)', paddingTop: '18px' }}>
              <button 
                onClick={() => printDedicatedDepartmentReport()}
                style={{
                  flex: '2 1 240px', 
                  padding: '13px 20px', 
                  borderRadius: '12px', 
                  border: 'none',
                  background: `linear-gradient(135deg, ${currentDeptConfig.badgeColor}, #8B1A2B)`,
                  color: 'white', 
                  fontFamily: 'Tajawal', 
                  fontWeight: 900, 
                  fontSize: '0.96rem',
                  cursor: 'pointer', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center', 
                  gap: '8px',
                  boxShadow: `0 6px 18px ${currentDeptConfig.badgeColor}35`, 
                  transition: 'all 0.3s'
                }}
              >
                <i className="fas fa-print"></i>
                🖨️ طباعة تقرير إحصائي خاص بقسم ({currentDeptConfig.shortName || currentDeptConfig.name}) (A4 رسمي)
              </button>

              <button 
                onClick={() => exportDedicatedDepartmentCSV()}
                style={{
                  flex: '1.2 1 180px', 
                  padding: '13px 16px', 
                  borderRadius: '12px', 
                  border: 'none',
                  background: 'linear-gradient(135deg, #10b981, #047857)',
                  color: 'white', 
                  fontFamily: 'Tajawal', 
                  fontWeight: 800, 
                  fontSize: '0.9rem',
                  cursor: 'pointer', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center', 
                  gap: '6px',
                  boxShadow: '0 6px 18px rgba(16, 185, 129, 0.3)', 
                  transition: 'all 0.3s'
                }}
              >
                <i className="fas fa-file-excel"></i>
                تصدير كشف ({currentDeptConfig.shortName || currentDeptConfig.name}) (CSV)
              </button>

              {reportDept !== 'All' && (
                <button 
                  onClick={() => printDedicatedDepartmentReport('All')}
                  style={{
                    flex: '1.5 1 200px', 
                    padding: '13px 18px', 
                    borderRadius: '12px', 
                    border: '1.5px solid var(--border)',
                    background: 'var(--card-bg)',
                    color: 'var(--text)', 
                    fontFamily: 'Tajawal', 
                    fontWeight: 800, 
                    fontSize: '0.9rem',
                    cursor: 'pointer', 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'center', 
                    gap: '8px',
                    transition: 'all 0.3s'
                  }}
                >
                  <i className="fas fa-layer-group" style={{ color: 'var(--primary)' }}></i>
                  طباعة التقرير الشامل لكافة الأقسام
                </button>
              )}

              <button 
                onClick={() => setShowStatsReportModal(false)}
                style={{
                  padding: '13px 24px', 
                  borderRadius: '12px', 
                  border: '1px solid var(--border)',
                  background: 'var(--bg-light)', 
                  color: 'var(--text)', 
                  fontFamily: 'Tajawal',
                  fontWeight: 800, 
                  fontSize: '0.95rem', 
                  cursor: 'pointer'
                }}
              >
                إغلاق
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════
          MODAL: طلبات الجامعات والأطباء المتعاقدون (SEPARATE MANAGER)
      ══════════════════════════════════════════════════════════ */}
      {showUniversitiesModal && (
        <div 
          className="modal-overlay active" 
          onClick={(e) => e.target === e.currentTarget && setShowUniversitiesModal(false)}
          style={{
            position: 'fixed',
            inset: 0,
            background: 'rgba(0, 0, 0, 0.75)',
            backdropFilter: 'blur(10px)',
            zIndex: 9999,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '20px',
            animation: 'fadeIn 0.25s ease'
          }}
        >
          <div 
            style={{
              background: isDarkMode ? '#111827' : '#ffffff',
              color: isDarkMode ? '#f8fafc' : '#0f172a',
              borderRadius: '24px',
              border: '1.5px solid rgba(168, 85, 247, 0.4)',
              boxShadow: '0 25px 60px -15px rgba(0,0,0,0.6), 0 0 35px rgba(168, 85, 247, 0.2)',
              width: '96vw',
              maxWidth: '1440px',
              maxHeight: '90vh',
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
              fontFamily: 'Tajawal, sans-serif'
            }}
          >
            {/* Modal Header */}
            <div style={{
              padding: '24px 28px',
              background: 'linear-gradient(135deg, #1e1b4b 0%, #312e81 60%, #4338ca 100%)',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: '15px',
              flexWrap: 'wrap',
              borderBottom: '2px solid rgba(255,215,0,0.3)'
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                <div style={{
                  width: '50px',
                  height: '50px',
                  borderRadius: '16px',
                  background: 'rgba(255,255,255,0.18)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  border: '1.5px solid rgba(255,255,255,0.35)',
                  boxShadow: '0 6px 15px rgba(0,0,0,0.25)'
                }}>
                  <i className="fas fa-graduation-cap" style={{ fontSize: '1.6rem', color: '#ffd700' }}></i>
                </div>
                <div>
                  <h2 style={{ fontSize: '1.4rem', fontWeight: 900, margin: 0, textShadow: '0 2px 4px rgba(0,0,0,0.3)' }}>
                    إدارة طلبات تدريب تمريض الجامعات والأطباء المتعاقدون
                  </h2>
                  <div style={{ fontSize: '0.85rem', color: '#cbd5e1', marginTop: '4px' }}>
                    متابعة واعتماد الطلبات المقدمة عبر نماذج تدريب تمريض الجامعات ونماذج الأطباء المتعاقدين
                  </div>
                </div>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <Link
                  href="/admin/applications"
                  onClick={() => setShowUniversitiesModal(false)}
                  style={{
                    padding: '8px 16px',
                    borderRadius: '12px',
                    background: 'rgba(255,255,255,0.15)',
                    color: '#ffffff',
                    textDecoration: 'none',
                    fontSize: '0.85rem',
                    fontWeight: 700,
                    border: '1px solid rgba(255,255,255,0.25)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px'
                  }}
                >
                  <i className="fas fa-external-link-alt"></i>
                  <span>لوحة الأرشيف الكاملة</span>
                </Link>

                <button 
                  onClick={() => setShowUniversitiesModal(false)}
                  style={{
                    background: 'rgba(255,255,255,0.15)',
                    border: 'none',
                    color: 'white',
                    width: '38px',
                    height: '38px',
                    borderRadius: '50%',
                    fontSize: '1.4rem',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                  }}
                >
                  &times;
                </button>
              </div>
            </div>

            {/* Statistics Banner */}
            <div style={{
              padding: '16px 24px',
              background: isDarkMode ? 'rgba(30, 41, 59, 0.7)' : '#f8fafc',
              borderBottom: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0',
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
              gap: '12px'
            }}>
              <div style={{
                background: isDarkMode ? 'rgba(15, 23, 42, 0.6)' : '#ffffff',
                padding: '12px 16px',
                borderRadius: '14px',
                border: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
              }}>
                <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(99, 102, 241, 0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i className="fas fa-users" style={{ color: '#6366f1' }}></i>
                </div>
                <div>
                  <div style={{ fontSize: '0.75rem', color: '#94a3b8', fontWeight: 600 }}>إجمالي الطلبات المستلمة</div>
                  <div style={{ fontSize: '1.25rem', fontWeight: 900, color: isDarkMode ? '#ffffff' : '#0f172a' }}>{universityApplications.length}</div>
                </div>
              </div>

              <div style={{
                background: isDarkMode ? 'rgba(15, 23, 42, 0.6)' : '#ffffff',
                padding: '12px 16px',
                borderRadius: '14px',
                border: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
              }}>
                <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(2, 132, 199, 0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i className="fas fa-heartbeat" style={{ color: '#0284c7' }}></i>
                </div>
                <div>
                  <div style={{ fontSize: '0.75rem', color: '#94a3b8', fontWeight: 600 }}>تدريب تمريض الجامعات</div>
                  <div style={{ fontSize: '1.25rem', fontWeight: 900, color: '#0284c7' }}>{nursingTrainersCount}</div>
                </div>
              </div>

              <div style={{
                background: isDarkMode ? 'rgba(15, 23, 42, 0.6)' : '#ffffff',
                padding: '12px 16px',
                borderRadius: '14px',
                border: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
              }}>
                <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(67, 56, 202, 0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i className="fas fa-stethoscope" style={{ color: '#4338ca' }}></i>
                </div>
                <div>
                  <div style={{ fontSize: '0.75rem', color: '#94a3b8', fontWeight: 600 }}>الأطباء المتعاقدون</div>
                  <div style={{ fontSize: '1.25rem', fontWeight: 900, color: '#6366f1' }}>{contractedDoctorsCount}</div>
                </div>
              </div>

              <div style={{
                background: isDarkMode ? 'rgba(15, 23, 42, 0.6)' : '#ffffff',
                padding: '12px 16px',
                borderRadius: '14px',
                border: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
              }}>
                <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(239, 68, 68, 0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i className="fas fa-clock" style={{ color: '#ef4444' }}></i>
                </div>
                <div>
                  <div style={{ fontSize: '0.75rem', color: '#94a3b8', fontWeight: 600 }}>طلبات جديدة قيد الانتظار</div>
                  <div style={{ fontSize: '1.25rem', fontWeight: 900, color: '#ef4444' }}>{pendingUniCount}</div>
                </div>
              </div>
            </div>

            {/* Filter Tabs & Search Bar */}
            <div style={{
              padding: '16px 24px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: '14px',
              borderBottom: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0'
            }}>
              <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                <button
                  onClick={() => setUniFilterTab('all')}
                  style={{
                    padding: '8px 16px',
                    borderRadius: '10px',
                    border: uniFilterTab === 'all' ? '1px solid #4338ca' : '1px solid rgba(255,255,255,0.1)',
                    background: uniFilterTab === 'all' ? 'linear-gradient(135deg, #4338ca, #312e81)' : (isDarkMode ? 'rgba(255,255,255,0.05)' : '#f1f5f9'),
                    color: uniFilterTab === 'all' ? '#ffffff' : (isDarkMode ? '#cbd5e1' : '#475569'),
                    fontWeight: 700,
                    fontSize: '0.88rem',
                    cursor: 'pointer',
                    fontFamily: 'Tajawal'
                  }}
                >
                  🌟 كافة الطلبات ({universityApplications.length})
                </button>

                <button
                  onClick={() => setUniFilterTab('nursing')}
                  style={{
                    padding: '8px 16px',
                    borderRadius: '10px',
                    border: uniFilterTab === 'nursing' ? '1px solid #0284c7' : '1px solid rgba(255,255,255,0.1)',
                    background: uniFilterTab === 'nursing' ? 'linear-gradient(135deg, #0284c7, #0369a1)' : (isDarkMode ? 'rgba(255,255,255,0.05)' : '#f1f5f9'),
                    color: uniFilterTab === 'nursing' ? '#ffffff' : (isDarkMode ? '#cbd5e1' : '#475569'),
                    fontWeight: 700,
                    fontSize: '0.88rem',
                    cursor: 'pointer',
                    fontFamily: 'Tajawal'
                  }}
                >
                  🩺 تدريب تمريض الجامعات ({nursingTrainersCount})
                </button>

                <button
                  onClick={() => setUniFilterTab('doctors')}
                  style={{
                    padding: '8px 16px',
                    borderRadius: '10px',
                    border: uniFilterTab === 'doctors' ? '1px solid #7c3aed' : '1px solid rgba(255,255,255,0.1)',
                    background: uniFilterTab === 'doctors' ? 'linear-gradient(135deg, #7c3aed, #5b21b6)' : (isDarkMode ? 'rgba(255,255,255,0.05)' : '#f1f5f9'),
                    color: uniFilterTab === 'doctors' ? '#ffffff' : (isDarkMode ? '#cbd5e1' : '#475569'),
                    fontWeight: 700,
                    fontSize: '0.88rem',
                    cursor: 'pointer',
                    fontFamily: 'Tajawal'
                  }}
                >
                  👨‍⚕️ الأطباء المتعاقدون مع الجامعات ({contractedDoctorsCount})
                </button>
              </div>

              {/* Search */}
              <div style={{ position: 'relative', minWidth: '260px' }}>
                <i className="fas fa-search" style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)', color: '#94a3b8' }}></i>
                <input
                  type="text"
                  placeholder="بحث باسم الطبيب، الجامعة، الهاتف..."
                  value={uniSearch}
                  onChange={(e) => setUniSearch(e.target.value)}
                  style={{
                    width: '100%',
                    padding: '9px 38px 9px 12px',
                    borderRadius: '10px',
                    border: isDarkMode ? '1px solid rgba(255,255,255,0.15)' : '1px solid #cbd5e1',
                    background: isDarkMode ? 'rgba(15, 23, 42, 0.8)' : '#ffffff',
                    color: isDarkMode ? '#ffffff' : '#0f172a',
                    fontSize: '0.88rem',
                    fontFamily: 'Tajawal',
                    outline: 'none'
                  }}
                />
              </div>
            </div>

            {/* Applications List Area */}
            <div style={{
              padding: '20px 24px',
              overflowY: 'auto',
              flex: 1
            }}>
              {filteredUniApps.length === 0 ? (
                <div style={{
                  textAlign: 'center',
                  padding: '50px 20px',
                  background: isDarkMode ? 'rgba(255,255,255,0.02)' : '#f8fafc',
                  borderRadius: '16px',
                  border: isDarkMode ? '1px dashed rgba(255,255,255,0.15)' : '1px dashed #cbd5e1'
                }}>
                  <i className="fas fa-inbox" style={{ fontSize: '40px', color: '#94a3b8', marginBottom: '14px' }}></i>
                  <h3 style={{ fontSize: '1.2rem', fontWeight: 800, marginBottom: '6px' }}>لا توجد طلبات تطابق هذا التحديد</h3>
                  <p style={{ color: '#94a3b8', fontSize: '0.9rem', maxWidth: '500px', margin: '0 auto 16px' }}>
                    عندما يقوم أي متدرب أو طبيب بتعبئة نموذج تدريب تمريض الجامعات أو الأطباء المتعاقدون، ستظهر طلباتهم هنا فوراً.
                  </p>
                  <Link
                    href="/recruitment"
                    onClick={() => setShowUniversitiesModal(false)}
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '8px',
                      padding: '10px 20px',
                      borderRadius: '10px',
                      background: 'linear-gradient(135deg, #059669 0%, #10B981 100%)',
                      color: 'white',
                      textDecoration: 'none',
                      fontWeight: 800,
                      fontSize: '0.88rem'
                    }}
                  >
                    <i className="fas fa-external-link-alt"></i>
                    <span>فتح صفحة التقديم والباركودات (QR)</span>
                  </Link>
                </div>
              ) : (
                <div>
                  <style>{`
                    .uni-table-scroll-container::-webkit-scrollbar {
                      height: 14px !important;
                    }
                    .uni-table-scroll-container::-webkit-scrollbar-track {
                      background: ${isDarkMode ? '#0f172a' : '#f1f5f9'} !important;
                      border-radius: 8px !important;
                    }
                    .uni-table-scroll-container::-webkit-scrollbar-thumb {
                      background: linear-gradient(135deg, #7c3aed, #4338ca) !important;
                      border-radius: 8px !important;
                      border: 2px solid ${isDarkMode ? '#0f172a' : '#f1f5f9'} !important;
                    }
                    .uni-table-scroll-container::-webkit-scrollbar-thumb:hover {
                      background: #6d28d9 !important;
                    }
                  `}</style>

                  {/* ═══════════ TOP MOUSE SCROLLBAR & QUICK NAVIGATION ═══════════ */}
                  <div style={{
                    background: isDarkMode ? 'rgba(30, 41, 59, 0.9)' : '#f8fafc',
                    padding: '10px 16px',
                    borderRadius: '14px',
                    marginBottom: '12px',
                    border: isDarkMode ? '1.5px solid #4338ca' : '1.5px solid #c4b5fd',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    flexWrap: 'wrap',
                    gap: '12px',
                    boxShadow: '0 3px 12px rgba(0,0,0,0.06)'
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <button
                        type="button"
                        onClick={scrollTableLeft}
                        style={{
                          padding: '8px 16px',
                          borderRadius: '10px',
                          background: 'linear-gradient(135deg, #7c3aed, #4338ca)',
                          color: 'white',
                          border: 'none',
                          fontWeight: 900,
                          fontSize: '0.88rem',
                          cursor: 'pointer',
                          fontFamily: 'Tajawal',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '6px',
                          boxShadow: '0 2px 8px rgba(124, 58, 237, 0.35)'
                        }}
                        title="انقر للتمرير لليسار لرؤية أزرار الإجراءات والتفاصيل"
                      >
                        <i className="fas fa-arrow-left"></i>
                        <span>الذهاب لليسار (الإجراءات) 👈</span>
                      </button>

                      <button
                        type="button"
                        onClick={scrollTableRight}
                        style={{
                          padding: '8px 16px',
                          borderRadius: '10px',
                          background: isDarkMode ? '#334155' : '#e2e8f0',
                          color: isDarkMode ? '#f8fafc' : '#1e293b',
                          border: 'none',
                          fontWeight: 800,
                          fontSize: '0.88rem',
                          cursor: 'pointer',
                          fontFamily: 'Tajawal',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '6px'
                        }}
                        title="انقر للرجوع إلى بداية الجدول جهة اليمين"
                      >
                        <span>👉 بداية الجدول (اليمين)</span>
                        <i className="fas fa-arrow-right"></i>
                      </button>
                    </div>

                    {/* Draggable Mouse Range Slider Bar */}
                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: 1, minWidth: '260px', maxWidth: '420px' }}>
                      <span style={{ fontSize: '0.82rem', color: isDarkMode ? '#cbd5e1' : '#475569', fontWeight: 800, whiteSpace: 'nowrap' }}>
                        🖱️ شريط التمرير بالماوس:
                      </span>
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={tableScrollPercent}
                        onChange={(e) => handleSliderScroll(Number(e.target.value))}
                        style={{
                          width: '100%',
                          cursor: 'ew-resize',
                          accentColor: '#7c3aed',
                          height: '10px'
                        }}
                        title="اسحب هذا الشريط بالماوس للتحرك يميناً ويساراً في الجدول"
                      />
                      <span style={{ fontSize: '0.78rem', color: '#7c3aed', fontWeight: 800, minWidth: '36px', textAlign: 'left' }}>
                        {tableScrollPercent}%
                      </span>
                    </div>

                    <div style={{ fontSize: '0.8rem', color: isDarkMode ? '#a78bfa' : '#6d28d9', fontWeight: 800 }}>
                      ✓ تم تثبيت عمود الإجراءات باليسار، ويمكنك سحب الشريط لرؤية كافة تفاصيل الطلاب
                    </div>
                  </div>

                  {/* ═══════════ TABLE SCROLL CONTAINER ═══════════ */}
                  <div 
                    ref={uniTableRef}
                    onScroll={handleTableScroll}
                    className="uni-table-scroll-container"
                    style={{ 
                      overflowX: 'auto',
                      position: 'relative',
                      borderRadius: '16px',
                      border: isDarkMode ? '1.5px solid rgba(255,255,255,0.1)' : '1.5px solid #cbd5e1',
                      scrollbarWidth: 'auto',
                      scrollbarColor: '#7c3aed #f1f5f9'
                    }}
                  >
                    <table style={{
                      width: '100%',
                      minWidth: '1200px',
                      borderCollapse: 'collapse',
                      textAlign: 'right',
                      fontSize: '0.88rem'
                    }}>
                      <thead>
                        <tr style={{
                          background: isDarkMode ? 'rgba(30, 41, 59, 0.95)' : '#f1f5f9',
                          color: isDarkMode ? '#cbd5e1' : '#475569',
                          borderBottom: isDarkMode ? '2px solid rgba(255,255,255,0.1)' : '2px solid #cbd5e1'
                        }}>
                          <th style={{ padding: '12px 14px', fontWeight: 800, width: '45px' }}>#</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>الاسم والمعلومات</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>نوع الطلب</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>الجامعة / الجامعات</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>رقم الهاتف</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>طبيعة العمل / المساقات</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>تاريخ التقديم</th>
                          <th style={{ padding: '12px 14px', fontWeight: 800 }}>الحالة</th>
                          <th style={{ 
                            padding: '12px 14px', 
                            fontWeight: 800, 
                            textAlign: 'center',
                            position: 'sticky',
                            left: 0,
                            background: isDarkMode ? '#1e293b' : '#f1f5f9',
                            boxShadow: '-4px 0 10px rgba(0,0,0,0.15)',
                            zIndex: 3,
                            minWidth: '210px'
                          }}>
                            الإجراءات
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredUniApps.map((app: any, idx: number) => {
                          const isNursing = isUniversityNursingTrainer(app);
                          const photoSrc = app.doctorPhotoBase64 || (app.unionPaperBase64?.startsWith('data:image') ? app.unionPaperBase64 : '');
                          const uniText = app.contractedUniversities && app.contractedUniversities.length > 0
                            ? (Array.isArray(app.contractedUniversities) ? app.contractedUniversities.join('، ') : app.contractedUniversities)
                            : (app.university || '—');
                          const status = (app.status || 'pending').toLowerCase();
                          const statusBadge = status === 'accepted' || status === 'مقبول' ? (
                            <span style={{ background: '#dcfce7', color: '#15803d', border: '1px solid #86efac', padding: '3px 10px', borderRadius: '15px', fontSize: '0.78rem', fontWeight: 800 }}>مقبول ومعتمد ✓</span>
                          ) : status === 'rejected' || status === 'مرفوض' ? (
                            <span style={{ background: '#fee2e2', color: '#b91c1c', border: '1px solid #fca5a5', padding: '3px 10px', borderRadius: '15px', fontSize: '0.78rem', fontWeight: 800 }}>مرفوض ✕</span>
                          ) : (
                            <span style={{ background: '#fef3c7', color: '#b45309', border: '1px solid #fde68a', padding: '3px 10px', borderRadius: '15px', fontSize: '0.78rem', fontWeight: 800 }}>قيد الانتظار ⏳</span>
                          );

                          return (
                            <tr 
                              key={app.id || app._supabaseId || idx}
                              style={{
                                borderBottom: isDarkMode ? '1px solid rgba(255,255,255,0.06)' : '1px solid #e2e8f0',
                                transition: 'all 0.2s',
                                background: idx % 2 === 0 ? 'transparent' : (isDarkMode ? 'rgba(255,255,255,0.02)' : '#fafafa')
                              }}
                            >
                              <td style={{ padding: '12px 14px', fontWeight: 800, color: '#a855f7' }}>{idx + 1}</td>
                              
                              <td style={{ padding: '12px 14px' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                  {photoSrc ? (
                                    <img 
                                      src={photoSrc} 
                                      alt={app.name} 
                                      style={{ width: '40px', height: '40px', borderRadius: '50%', objectFit: 'cover', border: '2px solid #a855f7' }} 
                                    />
                                  ) : (
                                    <div style={{ width: '40px', height: '40px', borderRadius: '50%', background: isNursing ? 'rgba(2, 132, 199, 0.2)' : 'rgba(124, 58, 237, 0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: isNursing ? '#0284c7' : '#7c3aed', fontWeight: 800 }}>
                                      {isNursing ? 'ن' : 'ط'}
                                    </div>
                                  )}
                                  <div>
                                    <div style={{ fontWeight: 800, fontSize: '0.92rem' }}>{app.name || '—'}</div>
                                    <div style={{ fontSize: '0.75rem', color: '#94a3b8' }}>هوية: {app.idNumber || '—'}</div>
                                  </div>
                                </div>
                              </td>

                              <td style={{ padding: '12px 14px' }}>
                                <span style={{
                                  padding: '4px 10px',
                                  borderRadius: '12px',
                                  fontSize: '0.75rem',
                                  fontWeight: 800,
                                  background: isNursing ? 'rgba(2, 132, 199, 0.15)' : 'rgba(67, 56, 202, 0.15)',
                                  color: isNursing ? '#38bdf8' : '#a78bfa',
                                  border: isNursing ? '1px solid rgba(2, 132, 199, 0.3)' : '1px solid rgba(67, 56, 202, 0.3)'
                                }}>
                                  {isNursing ? 'تدريب تمريض الجامعات' : 'الأطباء المتعاقدون'}
                                </span>
                              </td>

                              <td style={{ padding: '12px 14px', fontWeight: 700 }}>
                                {uniText}
                              </td>

                              <td style={{ padding: '12px 14px', direction: 'ltr', textAlign: 'right' }}>
                                {app.phone ? (
                                  <a 
                                    href={`tel:${app.phone}`} 
                                    style={{ color: '#38bdf8', textDecoration: 'none', fontWeight: 700 }}
                                  >
                                    {app.phone}
                                  </a>
                                ) : '—'}
                              </td>

                              <td style={{ padding: '12px 14px', fontSize: '0.8rem', color: '#94a3b8' }}>
                                {app.crescentJobNature || app.employmentType || (app.teachingCourses && Array.isArray(app.teachingCourses) ? app.teachingCourses.join('، ') : '—')}
                              </td>

                              <td style={{ padding: '12px 14px', fontSize: '0.8rem' }}>
                                {app.date || app.createdAt || app.created_at || '—'}
                              </td>

                              <td style={{ padding: '12px 14px' }}>
                                {statusBadge}
                              </td>

                              {/* STICKY ACTIONS COLUMN */}
                              <td style={{ 
                                padding: '12px 14px', 
                                textAlign: 'center',
                                position: 'sticky',
                                left: 0,
                                background: isDarkMode 
                                  ? (idx % 2 === 0 ? '#111827' : '#1e293b') 
                                  : (idx % 2 === 0 ? '#ffffff' : '#f8fafc'),
                                boxShadow: '-4px 0 10px rgba(0,0,0,0.08)',
                                zIndex: 2
                              }}>
                                <div style={{ display: 'flex', gap: '6px', justifyContent: 'center' }}>
                                  <button
                                    onClick={() => printUniApplication(app)}
                                    style={{
                                      padding: '6px 10px',
                                      borderRadius: '8px',
                                      border: '1px solid rgba(255, 215, 0, 0.4)',
                                      background: 'rgba(255, 215, 0, 0.15)',
                                      color: '#ffd700',
                                      cursor: 'pointer',
                                      fontSize: '0.78rem',
                                      fontWeight: 700,
                                      fontFamily: 'Tajawal',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      gap: '4px'
                                    }}
                                    title="طباعة استمارة الاعتماد الرسمية A4"
                                  >
                                    <i className="fas fa-print"></i>
                                    <span>طباعة</span>
                                  </button>

                                  <button
                                    onClick={() => openUniAppModal(app, false)}
                                    style={{
                                      padding: '6px 10px',
                                      borderRadius: '8px',
                                      border: '1px solid rgba(56, 189, 248, 0.4)',
                                      background: 'rgba(56, 189, 248, 0.15)',
                                      color: '#38bdf8',
                                      cursor: 'pointer',
                                      fontSize: '0.78rem',
                                      fontWeight: 700,
                                      fontFamily: 'Tajawal',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      gap: '4px'
                                    }}
                                    title="عرض كامل تفاصيل الطلب"
                                  >
                                    <i className="fas fa-eye"></i>
                                    <span>تفاصيل</span>
                                  </button>

                                  <button
                                    onClick={() => openUniAppModal(app, true)}
                                    style={{
                                      padding: '6px 10px',
                                      borderRadius: '8px',
                                      border: '1px solid rgba(168, 85, 247, 0.4)',
                                      background: 'rgba(168, 85, 247, 0.15)',
                                      color: '#c084fc',
                                      cursor: 'pointer',
                                      fontSize: '0.78rem',
                                      fontWeight: 700,
                                      fontFamily: 'Tajawal',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      gap: '4px'
                                    }}
                                    title="تعديل كامل للطلب وإدارة أقسام التدريب"
                                  >
                                    <i className="fas fa-edit"></i>
                                    <span>تعديل</span>
                                  </button>

                                  {(!app.status || app.status === 'pending' || app.status === 'new') && (
                                    <button
                                      onClick={() => handleAcceptUniApp(app)}
                                      disabled={isProcessingUniApp}
                                      style={{
                                        padding: '6px 10px',
                                        borderRadius: '8px',
                                        border: '1px solid rgba(16, 185, 129, 0.4)',
                                        background: 'rgba(16, 185, 129, 0.15)',
                                        color: '#10b981',
                                        cursor: 'pointer',
                                        fontSize: '0.78rem',
                                        fontWeight: 700,
                                        fontFamily: 'Tajawal',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        gap: '4px'
                                      }}
                                      title="اعتماد وإضافة للقسم بالمستشفى"
                                    >
                                      <i className="fas fa-check"></i>
                                      <span>اعتماد</span>
                                    </button>
                                  )}
                                </div>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>

                  {/* ═══════════ BOTTOM MOUSE SCROLLBAR & CONTROLS ═══════════ */}
                  <div style={{
                    marginTop: '10px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    flexWrap: 'wrap',
                    gap: '10px',
                    padding: '8px 14px',
                    background: isDarkMode ? 'rgba(30, 41, 59, 0.6)' : '#f8fafc',
                    borderRadius: '12px',
                    border: isDarkMode ? '1px solid rgba(255,255,255,0.06)' : '1px solid #e2e8f0'
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <button
                        type="button"
                        onClick={scrollTableLeft}
                        style={{
                          padding: '6px 14px',
                          borderRadius: '8px',
                          background: '#7c3aed',
                          color: 'white',
                          border: 'none',
                          fontWeight: 800,
                          fontSize: '0.82rem',
                          cursor: 'pointer',
                          fontFamily: 'Tajawal',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '6px'
                        }}
                      >
                        <i className="fas fa-arrow-left"></i>
                        <span>الذهاب لليسار 👈</span>
                      </button>

                      <button
                        type="button"
                        onClick={scrollTableRight}
                        style={{
                          padding: '6px 14px',
                          borderRadius: '8px',
                          background: isDarkMode ? '#334155' : '#e2e8f0',
                          color: isDarkMode ? '#f8fafc' : '#1e293b',
                          border: 'none',
                          fontWeight: 700,
                          fontSize: '0.82rem',
                          cursor: 'pointer',
                          fontFamily: 'Tajawal',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '6px'
                        }}
                      >
                        <span>👉 البداية (اليمين)</span>
                        <i className="fas fa-arrow-right"></i>
                      </button>
                    </div>

                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1, maxWidth: '350px' }}>
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={tableScrollPercent}
                        onChange={(e) => handleSliderScroll(Number(e.target.value))}
                        style={{
                          width: '100%',
                          cursor: 'ew-resize',
                          accentColor: '#7c3aed',
                          height: '8px'
                        }}
                        title="اسحب بالماوس للتنقل"
                      />
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* Modal Footer */}
            <div style={{
              padding: '16px 24px',
              borderTop: isDarkMode ? '1px solid rgba(255,255,255,0.08)' : '1px solid #e2e8f0',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: '10px'
            }}>
              <div style={{ fontSize: '0.85rem', color: '#94a3b8' }}>
                💡 يمكنك مراجعة وأرشفة كافة الطلبات بالتفصيل من خلال صفحة إدارة وأرشيف الطلبات.
              </div>

              <div style={{ display: 'flex', gap: '10px' }}>
                <Link
                  href="/admin/applications"
                  onClick={() => setShowUniversitiesModal(false)}
                  style={{
                    padding: '10px 18px',
                    borderRadius: '10px',
                    background: 'linear-gradient(135deg, #4338ca, #312e81)',
                    color: 'white',
                    textDecoration: 'none',
                    fontWeight: 700,
                    fontSize: '0.88rem'
                  }}
                >
                  فتح الأرشيف المتقدم
                </Link>

                <button
                  onClick={() => setShowUniversitiesModal(false)}
                  style={{
                    padding: '10px 20px',
                    borderRadius: '10px',
                    border: '1px solid #94a3b8',
                    background: 'transparent',
                    color: isDarkMode ? '#cbd5e1' : '#475569',
                    fontWeight: 700,
                    fontSize: '0.88rem',
                    cursor: 'pointer',
                    fontFamily: 'Tajawal'
                  }}
                >
                  إغلاق
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════
          SUB-MODAL: DETAILS OF SPECIFIC APPLICANT
      ══════════════════════════════════════════════════════════ */}
      {selectedUniApp && (
        <div 
          className="modal-overlay active"
          onClick={(e) => e.target === e.currentTarget && setSelectedUniApp(null)}
          style={{
            position: 'fixed',
            inset: 0,
            background: 'rgba(0,0,0,0.82)',
            backdropFilter: 'blur(10px)',
            zIndex: 10000,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '20px'
          }}
        >
          <div style={{
            background: isDarkMode ? '#1e293b' : '#ffffff',
            color: isDarkMode ? '#f8fafc' : '#0f172a',
            borderRadius: '22px',
            maxWidth: '780px',
            width: '100%',
            maxHeight: '90vh',
            overflowY: 'auto',
            padding: '26px',
            fontFamily: 'Tajawal, sans-serif',
            border: isDarkMode ? '1.5px solid rgba(255,255,255,0.15)' : '1.5px solid #e2e8f0',
            boxShadow: '0 25px 60px rgba(0,0,0,0.5)'
          }}>
            {/* Modal Header */}
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '18px',
              borderBottom: isDarkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid #e2e8f0',
              paddingBottom: '14px',
              flexWrap: 'wrap',
              gap: '10px'
            }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <h3 style={{ fontSize: '1.3rem', fontWeight: 900, margin: 0 }}>
                    {isEditingUniApp ? '✏️ تعديل كامل لبيانات الطلب والأقسام' : `تفاصيل طلب: ${selectedUniApp.name}`}
                  </h3>
                  <span style={{
                    padding: '3px 10px',
                    borderRadius: '12px',
                    fontSize: '0.75rem',
                    fontWeight: 800,
                    background: isUniversityNursingTrainer(selectedUniApp) ? 'rgba(124, 58, 237, 0.15)' : 'rgba(56, 189, 248, 0.15)',
                    color: isUniversityNursingTrainer(selectedUniApp) ? '#a78bfa' : '#38bdf8',
                    border: isUniversityNursingTrainer(selectedUniApp) ? '1px solid rgba(124, 58, 237, 0.3)' : '1px solid rgba(56, 189, 248, 0.3)'
                  }}>
                    {isUniversityNursingTrainer(selectedUniApp) ? 'تدريب تمريض الجامعات' : 'الأطباء المتعاقدون'}
                  </span>
                </div>
                <div style={{ fontSize: '0.82rem', color: '#94a3b8', marginTop: '3px' }}>
                  {isEditingUniApp ? 'يمكنك إضافة أقسام تدريب متعددة (مثل: أطفال، جراحة، نسائية) وتعديل أو حذف أي حقل' : 'استعراض بيانات الطلب والطباعة الرسمية وإدارة الاعتماد'}
                </div>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <button
                  type="button"
                  onClick={() => setIsEditingUniApp(!isEditingUniApp)}
                  style={{
                    padding: '7px 14px',
                    borderRadius: '10px',
                    border: isEditingUniApp ? '1px solid #7c3aed' : '1px solid #f59e0b',
                    background: isEditingUniApp ? 'rgba(124, 58, 237, 0.15)' : 'rgba(245, 158, 11, 0.15)',
                    color: isEditingUniApp ? '#c084fc' : '#f59e0b',
                    cursor: 'pointer',
                    fontWeight: 800,
                    fontSize: '0.82rem',
                    fontFamily: 'Tajawal',
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '6px'
                  }}
                >
                  <i className={`fas ${isEditingUniApp ? 'fa-eye' : 'fa-edit'}`}></i>
                  <span>{isEditingUniApp ? 'وضع العرض 👁️' : 'تعديل كامل للطلب ✏️'}</span>
                </button>

                <button
                  onClick={() => { setSelectedUniApp(null); setIsEditingUniApp(false); }}
                  style={{
                    background: 'none',
                    border: 'none',
                    fontSize: '1.6rem',
                    cursor: 'pointer',
                    color: '#94a3b8',
                    padding: '0 4px',
                    lineHeight: 1
                  }}
                  title="إغلاق"
                >
                  &times;
                </button>
              </div>
            </div>

            {/* ═══════════════ EDIT MODE ═══════════════ */}
            {isEditingUniApp ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                {/* 1. TRAINING DEPARTMENTS MANAGER */}
                <div style={{
                  background: isDarkMode ? '#0f172a' : '#f8fafc',
                  borderRadius: '14px',
                  padding: '16px',
                  border: isDarkMode ? '1.5px solid #334155' : '1.5px solid #cbd5e1'
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px', flexWrap: 'wrap', gap: '6px' }}>
                    <div style={{ fontWeight: 800, fontSize: '0.98rem', color: isDarkMode ? '#f8fafc' : '#1e293b', display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <span style={{ fontSize: '1.2rem' }}>🏥</span>
                      <span>أقسام التدريب المعتمدة ({uniAppEditForm.trainingDepartments?.length || 0})</span>
                    </div>
                    <span style={{ fontSize: '0.78rem', color: '#7c3aed', fontWeight: 700 }}>
                      ✓ يمكن إضافة أكثر من قسم (مثل: الأطفال، جراحة، نسائية...)
                    </span>
                  </div>

                  {/* List of current departments */}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '12px' }}>
                    {(!uniAppEditForm.trainingDepartments || uniAppEditForm.trainingDepartments.length === 0) ? (
                      <div style={{
                        padding: '12px',
                        textAlign: 'center',
                        color: '#94a3b8',
                        fontSize: '0.85rem',
                        border: '1px dashed #cbd5e1',
                        borderRadius: '10px'
                      }}>
                        لم يتم تعيين أقسام بعد. اختر قسماً من القائمة بالأسفل لإضافته.
                      </div>
                    ) : (
                      uniAppEditForm.trainingDepartments.map((deptName: string, idx: number) => (
                        <div key={idx} style={{
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'space-between',
                          background: isDarkMode ? '#1e293b' : '#ffffff',
                          padding: '8px 12px',
                          borderRadius: '10px',
                          border: isDarkMode ? '1px solid #334155' : '1px solid #e2e8f0',
                          gap: '10px'
                        }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
                            <span style={{
                              background: '#7c3aed',
                              color: 'white',
                              borderRadius: '50%',
                              width: '24px',
                              height: '24px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: '0.75rem',
                              fontWeight: 800,
                              flexShrink: 0
                            }}>
                              {idx + 1}
                            </span>
                            <span style={{ fontSize: '0.85rem', fontWeight: 700, color: '#64748b' }}>
                              قسم {idx + 1}:
                            </span>
                            <input
                              type="text"
                              value={deptName}
                              onChange={(e) => {
                                const updated = [...(uniAppEditForm.trainingDepartments || [])];
                                updated[idx] = e.target.value;
                                setUniAppEditForm({ ...uniAppEditForm, trainingDepartments: updated });
                              }}
                              style={{
                                flex: 1,
                                padding: '6px 12px',
                                borderRadius: '8px',
                                border: '1px solid #cbd5e1',
                                background: isDarkMode ? '#0f172a' : '#ffffff',
                                color: isDarkMode ? '#f8fafc' : '#0f172a',
                                fontWeight: 700,
                                fontSize: '0.9rem',
                                fontFamily: 'Tajawal'
                              }}
                              placeholder="اسم القسم التدريبي..."
                            />
                          </div>

                          <button
                            type="button"
                            onClick={() => handleRemoveDeptFromForm(idx)}
                            style={{
                              padding: '6px 12px',
                              borderRadius: '8px',
                              border: '1px solid rgba(239, 68, 68, 0.4)',
                              background: 'rgba(239, 68, 68, 0.12)',
                              color: '#ef4444',
                              cursor: 'pointer',
                              fontWeight: 700,
                              fontSize: '0.8rem',
                              fontFamily: 'Tajawal',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '4px',
                              flexShrink: 0
                            }}
                            title="حذف هذا القسم"
                          >
                            <i className="fas fa-trash-alt"></i>
                            <span>حذف</span>
                          </button>
                        </div>
                      ))
                    )}
                  </div>

                  {/* Add Department Controls */}
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '10px' }}>
                    {/* Quick Select */}
                    <div>
                      <select
                        onChange={(e) => {
                          const val = e.target.value;
                          if (val) {
                            handleAddDeptToForm(val);
                            e.target.value = '';
                          }
                        }}
                        style={{
                          width: '100%',
                          padding: '9px 12px',
                          borderRadius: '8px',
                          border: '1.5px solid #7c3aed',
                          background: isDarkMode ? '#1e293b' : '#ffffff',
                          color: isDarkMode ? '#f8fafc' : '#0f172a',
                          fontWeight: 700,
                          fontFamily: 'Tajawal',
                          fontSize: '0.86rem',
                          cursor: 'pointer'
                        }}
                      >
                        <option value="">➕ اختر قسماً مستشفوياً للإضافة...</option>
                        {HOSPITAL_TRAINING_DEPTS.map((d: string, i: number) => (
                          <option key={i} value={d}>
                            {d === 'الاطفال' ? 'طب الأطفال (Pediatrics)' :
                             d === 'جراحة' ? 'الجراحة العامة (Surgery)' :
                             d === 'نسائية' ? 'النسائية والتوليد (Gynecology)' :
                             d === 'التمريض' ? 'التمريض العام (Nursing)' :
                             d === 'طوارئ' ? 'الطوارئ (Emergency)' :
                             d === 'باطني' ? 'الباطني (Internal Medicine)' :
                             d === 'عناية مكثفة' ? 'العناية المكثفة (ICU)' :
                             d === 'عمليات' ? 'العمليات (OR)' :
                             d === 'العلاج الطبيعي' ? 'العلاج الطبيعي (PT)' :
                             d === 'مختبرات طبية' ? 'المختبرات الطبية (Labs)' :
                             d === 'أشعة' ? 'الأشعة (Radiology)' : d}
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* Custom Add */}
                    <div style={{ display: 'flex', gap: '6px' }}>
                      <input
                        type="text"
                        placeholder="أو اكتب اسم قسم واضغط إضافة..."
                        value={customDeptInput}
                        onChange={(e) => setCustomDeptInput(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            e.preventDefault();
                            if (customDeptInput.trim()) {
                              handleAddDeptToForm(customDeptInput.trim());
                              setCustomDeptInput('');
                            }
                          }
                        }}
                        style={{
                          flex: 1,
                          padding: '9px 12px',
                          borderRadius: '8px',
                          border: '1px solid #cbd5e1',
                          background: isDarkMode ? '#1e293b' : '#ffffff',
                          color: isDarkMode ? '#f8fafc' : '#0f172a',
                          fontSize: '0.85rem',
                          fontFamily: 'Tajawal'
                        }}
                      />
                      <button
                        type="button"
                        onClick={() => {
                          if (customDeptInput.trim()) {
                            handleAddDeptToForm(customDeptInput.trim());
                            setCustomDeptInput('');
                          }
                        }}
                        style={{
                          padding: '9px 16px',
                          borderRadius: '8px',
                          background: '#7c3aed',
                          color: 'white',
                          border: 'none',
                          fontWeight: 700,
                          cursor: 'pointer',
                          fontFamily: 'Tajawal',
                          fontSize: '0.82rem',
                          whiteSpace: 'nowrap'
                        }}
                      >
                        ➕ إضافة
                      </button>
                    </div>
                  </div>
                </div>

                {/* 2. BASIC PERSONAL & PROFESSIONAL FIELDS */}
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
                  gap: '12px'
                }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      الاسم الرباعي <span style={{ color: '#ef4444' }}>*</span>
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.name || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, name: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      رقم الهوية
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.idNumber || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, idNumber: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      رقم الهاتف
                    </label>
                    <input
                      type="text"
                      dir="ltr"
                      value={uniAppEditForm.phone || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, phone: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal',
                        textAlign: 'right'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      مكان السكن
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.address || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, address: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      سنة التخرج
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.graduationYear || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, graduationYear: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      طبيعة الوظيفة بمستشفى الهلال
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.crescentJobNature || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, crescentJobNature: e.target.value })}
                      placeholder="مثال: مدرب سريري، مدرب تمريض، طبيب متعاقد"
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      التخصص
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.specialty || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, specialty: e.target.value })}
                      placeholder="مثال: تمريض عام، تمريض أطفال، باطني"
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      حالة الطلب
                    </label>
                    <select
                      value={uniAppEditForm.status || 'pending'}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, status: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1.5px solid #10b981',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 800,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    >
                      <option value="pending">⏳ قيد المعالجة (Pending)</option>
                      <option value="accepted">✓ معتمد ومقبول (Accepted)</option>
                      <option value="rejected">🚫 مرفوض ومؤرشف (Rejected)</option>
                    </select>
                  </div>
                </div>

                {/* 3. CONTRACTED UNIVERSITIES */}
                <div style={{
                  background: isDarkMode ? '#0f172a' : '#f8fafc',
                  borderRadius: '12px',
                  padding: '14px',
                  border: isDarkMode ? '1px solid #334155' : '1px solid #e2e8f0'
                }}>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 800, marginBottom: '8px', color: '#7c3aed' }}>
                    🎓 الجامعات الشريكة المتعاقد معها:
                  </label>
                  <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '8px' }}>
                    {PARTNER_UNIVERSITIES_LIST.map((u: string, idx: number) => {
                      const isSelected = (uniAppEditForm.contractedUniversities || []).includes(u);
                      return (
                        <button
                          key={idx}
                          type="button"
                          onClick={() => handleToggleUniInForm(u)}
                          style={{
                            padding: '5px 12px',
                            borderRadius: '16px',
                            border: isSelected ? '1.5px solid #7c3aed' : '1px solid #cbd5e1',
                            background: isSelected ? 'rgba(124, 58, 237, 0.2)' : 'transparent',
                            color: isSelected ? '#a78bfa' : (isDarkMode ? '#cbd5e1' : '#475569'),
                            fontWeight: 700,
                            fontSize: '0.8rem',
                            cursor: 'pointer',
                            fontFamily: 'Tajawal'
                          }}
                        >
                          {isSelected ? '✓ ' : '+ '}{u}
                        </button>
                      );
                    })}
                  </div>

                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input
                      type="text"
                      placeholder="أو اكتب اسم جامعة أخرى واضغط إضافة..."
                      value={customUniInput}
                      onChange={(e) => setCustomUniInput(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          e.preventDefault();
                          if (customUniInput.trim()) {
                            handleToggleUniInForm(customUniInput.trim());
                            setCustomUniInput('');
                          }
                        }
                      }}
                      style={{
                        flex: 1,
                        padding: '7px 10px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#1e293b' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontSize: '0.85rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                    <button
                      type="button"
                      onClick={() => {
                        if (customUniInput.trim()) {
                          handleToggleUniInForm(customUniInput.trim());
                          setCustomUniInput('');
                        }
                      }}
                      style={{
                        padding: '7px 14px',
                        borderRadius: '8px',
                        background: '#4338ca',
                        color: 'white',
                        border: 'none',
                        fontWeight: 700,
                        cursor: 'pointer',
                        fontFamily: 'Tajawal',
                        fontSize: '0.82rem'
                      }}
                    >
                      إضافة جامعة
                    </button>
                  </div>
                </div>

                {/* 4. DATES & WORK SCHEDULE */}
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
                  gap: '12px',
                  background: isDarkMode ? '#0f172a' : '#f8fafc',
                  padding: '14px',
                  borderRadius: '12px',
                  border: isDarkMode ? '1px solid #334155' : '1px solid #e2e8f0'
                }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      تاريخ بدء التدريب (من)
                    </label>
                    <input
                      type="date"
                      value={uniAppEditForm.startDate || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, startDate: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#1e293b' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      تاريخ انتهاء التدريب (إلى)
                    </label>
                    <input
                      type="date"
                      value={uniAppEditForm.endDate || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, endDate: e.target.value })}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#1e293b' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div style={{ gridColumn: '1 / -1' }}>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '6px', color: '#64748b' }}>
                      أيام الدوام الأسبوعية:
                    </label>
                    <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                      {WEEK_DAYS_LIST.map((day: string, idx: number) => {
                        const isDaySelected = (uniAppEditForm.workDays || []).includes(day);
                        return (
                          <button
                            key={idx}
                            type="button"
                            onClick={() => handleToggleWorkDayInForm(day)}
                            style={{
                              padding: '5px 12px',
                              borderRadius: '16px',
                              border: isDaySelected ? '1.5px solid #10b981' : '1px solid #cbd5e1',
                              background: isDaySelected ? 'rgba(16, 185, 129, 0.2)' : 'transparent',
                              color: isDaySelected ? '#10b981' : (isDarkMode ? '#cbd5e1' : '#475569'),
                              fontWeight: 700,
                              fontSize: '0.8rem',
                              cursor: 'pointer',
                              fontFamily: 'Tajawal'
                            }}
                          >
                            {isDaySelected ? '✓ ' : '+ '}{day}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                </div>

                {/* 5. COURSES & NOTES */}
                <div style={{ display: 'grid', gap: '12px' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      المساقات التدريسية (مفصولة بفواصل)
                    </label>
                    <input
                      type="text"
                      value={uniAppEditForm.teachingCoursesText || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, teachingCoursesText: e.target.value })}
                      placeholder="مثال: تمريض أطفال سريري، تمريض جراحي، أساسيات التمريض"
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontWeight: 700,
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, marginBottom: '4px', color: '#64748b' }}>
                      ملاحظات إضافية
                    </label>
                    <textarea
                      rows={2}
                      value={uniAppEditForm.notes || ''}
                      onChange={(e) => setUniAppEditForm({ ...uniAppEditForm, notes: e.target.value })}
                      placeholder="أي ملاحظات خاصة بالمدرب أو الشعب أو التنسيق..."
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        border: '1px solid #cbd5e1',
                        background: isDarkMode ? '#0f172a' : '#ffffff',
                        color: isDarkMode ? '#f8fafc' : '#0f172a',
                        fontSize: '0.9rem',
                        fontFamily: 'Tajawal'
                      }}
                    />
                  </div>
                </div>

                {/* EDIT MODE ACTION BUTTONS */}
                <div style={{
                  display: 'flex',
                  gap: '10px',
                  marginTop: '10px',
                  borderTop: isDarkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid #e2e8f0',
                  paddingTop: '16px',
                  flexWrap: 'wrap'
                }}>
                  <button
                    type="button"
                    onClick={handleSaveUniAppEdit}
                    disabled={isProcessingUniApp}
                    style={{
                      flex: 2,
                      minWidth: '180px',
                      padding: '12px 18px',
                      borderRadius: '12px',
                      background: 'linear-gradient(135deg, #059669 0%, #10b981 100%)',
                      color: 'white',
                      border: 'none',
                      fontWeight: 900,
                      fontSize: '0.95rem',
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      gap: '8px',
                      boxShadow: '0 4px 14px rgba(16, 185, 129, 0.4)'
                    }}
                  >
                    <i className="fas fa-save"></i>
                    <span>{isProcessingUniApp ? 'جاري الحفظ...' : '💾 حفظ التعديلات وتحديث القيد'}</span>
                  </button>

                  <button
                    type="button"
                    onClick={() => handleDeleteUniApp(selectedUniApp)}
                    disabled={isProcessingUniApp}
                    style={{
                      padding: '12px 16px',
                      borderRadius: '12px',
                      background: 'rgba(239, 68, 68, 0.15)',
                      color: '#ef4444',
                      border: '1px solid rgba(239, 68, 68, 0.4)',
                      fontWeight: 800,
                      fontSize: '0.88rem',
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '6px'
                    }}
                    title="حذف هذا الطلب نهائياً من قاعدة البيانات"
                  >
                    <i className="fas fa-trash-alt"></i>
                    <span>حذف الطلب نهائياً</span>
                  </button>

                  <button
                    type="button"
                    onClick={() => setIsEditingUniApp(false)}
                    style={{
                      padding: '12px 18px',
                      borderRadius: '12px',
                      background: '#64748b',
                      color: 'white',
                      border: 'none',
                      fontWeight: 700,
                      fontSize: '0.88rem',
                      cursor: 'pointer',
                      fontFamily: 'Tajawal'
                    }}
                  >
                    إلغاء
                  </button>
                </div>
              </div>
            ) : (
              /* ═══════════════ VIEW MODE ═══════════════ */
              <div>
                <div style={{ display: 'grid', gap: '12px', fontSize: '0.92rem' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '10px' }}>
                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>رقم الهوية:</span>
                      <strong>{selectedUniApp.idNumber || '—'}</strong>
                    </div>

                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>رقم الهاتف:</span>
                      {selectedUniApp.phone ? (
                        <a href={`tel:${selectedUniApp.phone}`} style={{ color: '#38bdf8', textDecoration: 'none', fontWeight: 800 }}>
                          {selectedUniApp.phone}
                        </a>
                      ) : '—'}
                    </div>

                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>مكان السكن:</span>
                      <strong>{selectedUniApp.address || '—'}</strong>
                    </div>

                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>سنة التخرج:</span>
                      <strong>{selectedUniApp.graduationYear || '—'}</strong>
                    </div>

                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>الوظيفة بمستشفى الهلال:</span>
                      <strong style={{ color: '#a78bfa' }}>{selectedUniApp.crescentJobNature || selectedUniApp.employmentType || '—'}</strong>
                    </div>

                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>التخصص:</span>
                      <strong>{selectedUniApp.specialty || '—'}</strong>
                    </div>
                  </div>

                  <div>
                    <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block', marginBottom: '4px' }}>الجامعات الشريكة المتعاقد معها:</span>
                    <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                      {selectedUniApp.contractedUniversities && selectedUniApp.contractedUniversities.length > 0 ? (
                        (Array.isArray(selectedUniApp.contractedUniversities) ? selectedUniApp.contractedUniversities : [selectedUniApp.contractedUniversities]).map((u: string, idx: number) => (
                          <span key={idx} style={{
                            background: 'rgba(124, 58, 237, 0.15)',
                            color: '#a78bfa',
                            border: '1px solid rgba(124, 58, 237, 0.3)',
                            padding: '3px 10px',
                            borderRadius: '12px',
                            fontWeight: 700,
                            fontSize: '0.82rem'
                          }}>
                            🎓 {u}
                          </span>
                        ))
                      ) : (
                        <strong>{selectedUniApp.university || '—'}</strong>
                      )}
                    </div>
                  </div>

                  {/* Highlighted Training Departments */}
                  <div style={{
                    background: isDarkMode ? '#0f172a' : '#f8fafc',
                    padding: '14px',
                    borderRadius: '12px',
                    border: isDarkMode ? '1px solid #334155' : '1px solid #e2e8f0'
                  }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                      <span style={{ color: '#7c3aed', fontSize: '0.85rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '6px' }}>
                        <span>🏥</span> الأقسام التدريبية المعتمدة ({Array.isArray(selectedUniApp.trainingDepartments) ? selectedUniApp.trainingDepartments.length : (selectedUniApp.trainingDepartments ? 1 : 0)}):
                      </span>
                      <button
                        type="button"
                        onClick={() => openUniAppModal(selectedUniApp, true)}
                        style={{
                          background: 'none',
                          border: 'none',
                          color: '#38bdf8',
                          fontSize: '0.78rem',
                          fontWeight: 700,
                          cursor: 'pointer',
                          fontFamily: 'Tajawal',
                          textDecoration: 'underline'
                        }}
                      >
                        + تعديل أو إضافة قسم
                      </button>
                    </div>

                    <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                      {selectedUniApp.trainingDepartments && (
                        Array.isArray(selectedUniApp.trainingDepartments) ? selectedUniApp.trainingDepartments : [selectedUniApp.trainingDepartments]
                      ).length > 0 ? (
                        (Array.isArray(selectedUniApp.trainingDepartments) ? selectedUniApp.trainingDepartments : [selectedUniApp.trainingDepartments]).map((dept: string, idx: number) => (
                          <span key={idx} style={{
                            background: 'rgba(56, 189, 248, 0.15)',
                            color: '#38bdf8',
                            border: '1px solid rgba(56, 189, 248, 0.35)',
                            padding: '4px 12px',
                            borderRadius: '14px',
                            fontWeight: 800,
                            fontSize: '0.85rem',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                          }}>
                            <span>قسم {idx + 1}:</span>
                            <span style={{ color: isDarkMode ? '#f8fafc' : '#0f172a' }}>{dept}</span>
                          </span>
                        ))
                      ) : (
                        <span style={{ color: '#94a3b8', fontSize: '0.85rem' }}>لم يتم تخصيص أقسام تدريبية حتى الآن</span>
                      )}
                    </div>
                  </div>

                  {/* Training Dates & Days */}
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '10px' }}>
                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>فترة التدريب:</span>
                      <strong>من {selectedUniApp.startDate || selectedUniApp.trainingStartDate || '—'} إلى {selectedUniApp.endDate || selectedUniApp.trainingEndDate || '—'}</strong>
                    </div>

                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block', marginBottom: '2px' }}>أيام الدوام الأسبوعية:</span>
                      <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                        {selectedUniApp.workDays && (
                          (Array.isArray(selectedUniApp.workDays) ? selectedUniApp.workDays : [selectedUniApp.workDays]).map((d: string, idx: number) => (
                            <span key={idx} style={{
                              background: 'rgba(16, 185, 129, 0.15)',
                              color: '#10b981',
                              padding: '2px 8px',
                              borderRadius: '10px',
                              fontSize: '0.78rem',
                              fontWeight: 700
                            }}>
                              {d}
                            </span>
                          ))
                        )}
                        {(!selectedUniApp.workDays || selectedUniApp.workDays.length === 0) && <span>—</span>}
                      </div>
                    </div>
                  </div>

                  {selectedUniApp.teachingCourses && (
                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>المساقات التدريسية:</span>
                      <strong>{Array.isArray(selectedUniApp.teachingCourses) ? selectedUniApp.teachingCourses.join('، ') : selectedUniApp.teachingCourses}</strong>
                    </div>
                  )}

                  {selectedUniApp.notes && (
                    <div>
                      <span style={{ color: '#94a3b8', fontSize: '0.8rem', display: 'block' }}>ملاحظات:</span>
                      <div style={{
                        background: isDarkMode ? '#0f172a' : '#f1f5f9',
                        padding: '8px 12px',
                        borderRadius: '8px',
                        fontSize: '0.85rem'
                      }}>
                        {selectedUniApp.notes}
                      </div>
                    </div>
                  )}
                </div>

                {/* VIEW MODE FOOTER ACTIONS */}
                <div style={{
                  display: 'flex',
                  gap: '10px',
                  marginTop: '22px',
                  borderTop: isDarkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid #e2e8f0',
                  paddingTop: '16px',
                  flexWrap: 'wrap'
                }}>
                  <button
                    type="button"
                    onClick={() => openUniAppModal(selectedUniApp, true)}
                    style={{
                      padding: '10px 16px',
                      borderRadius: '10px',
                      background: 'rgba(245, 158, 11, 0.15)',
                      color: '#f59e0b',
                      border: '1px solid rgba(245, 158, 11, 0.4)',
                      fontWeight: 800,
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '6px'
                    }}
                  >
                    <i className="fas fa-edit"></i>
                    <span>تعديل كامل للطلب ✏️</span>
                  </button>

                  <button
                    type="button"
                    onClick={() => printUniApplication(selectedUniApp)}
                    style={{
                      padding: '10px 18px',
                      borderRadius: '10px',
                      background: 'linear-gradient(135deg, #ffd700, #d97706)',
                      color: '#0f172a',
                      border: 'none',
                      fontWeight: 800,
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '6px'
                    }}
                  >
                    <i className="fas fa-print"></i>
                    <span>طباعة A4</span>
                  </button>

                  {(!selectedUniApp.status || selectedUniApp.status === 'pending' || selectedUniApp.status === 'new') && (
                    <button
                      type="button"
                      onClick={() => handleAcceptUniApp(selectedUniApp)}
                      disabled={isProcessingUniApp}
                      style={{
                        padding: '10px 16px',
                        borderRadius: '10px',
                        background: 'linear-gradient(135deg, #059669 0%, #10b981 100%)',
                        color: 'white',
                        border: 'none',
                        fontWeight: 800,
                        cursor: 'pointer',
                        fontFamily: 'Tajawal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '6px',
                        boxShadow: '0 4px 12px rgba(16, 185, 129, 0.3)'
                      }}
                    >
                      <i className="fas fa-user-check"></i>
                      <span>اعتماد وإضافة للمستشفى ✓</span>
                    </button>
                  )}

                  {(!selectedUniApp.status || selectedUniApp.status === 'pending' || selectedUniApp.status === 'new') && (
                    <button
                      type="button"
                      onClick={() => handleRejectUniApp(selectedUniApp)}
                      disabled={isProcessingUniApp}
                      style={{
                        padding: '10px 14px',
                        borderRadius: '10px',
                        background: 'rgba(239, 68, 68, 0.15)',
                        color: '#ef4444',
                        border: '1px solid rgba(239, 68, 68, 0.4)',
                        fontWeight: 800,
                        cursor: 'pointer',
                        fontFamily: 'Tajawal'
                      }}
                    >
                      رفض وأرشفة
                    </button>
                  )}

                  <button
                    type="button"
                    onClick={() => handleDeleteUniApp(selectedUniApp)}
                    disabled={isProcessingUniApp}
                    style={{
                      padding: '10px 14px',
                      borderRadius: '10px',
                      background: 'rgba(239, 68, 68, 0.1)',
                      color: '#ef4444',
                      border: '1px solid rgba(239, 68, 68, 0.3)',
                      fontWeight: 700,
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      fontSize: '0.82rem'
                    }}
                    title="حذف هذا الطلب نهائياً"
                  >
                    <i className="fas fa-trash-alt"></i>
                    <span>حذف نهائي</span>
                  </button>

                  <button
                    type="button"
                    onClick={() => { setSelectedUniApp(null); setIsEditingUniApp(false); }}
                    style={{
                      padding: '10px 18px',
                      borderRadius: '10px',
                      background: '#64748b',
                      color: 'white',
                      border: 'none',
                      fontWeight: 700,
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      marginRight: 'auto'
                    }}
                  >
                    إغلاق
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════
           ASSIGN TRAINER MODAL (MAIN DASHBOARD)
      ══════════════════════════════════════════════════ */}
      {showAssignTrainerModal && assignModalStudent && (
        <div
          style={{
            position: 'fixed', inset: 0, zIndex: 9998,
            background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(6px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: '16px'
          }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowAssignTrainerModal(false); }}
        >
          <div style={{
            background: 'var(--card-bg, #fff)',
            borderRadius: '20px',
            boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
            width: '100%',
            maxWidth: '540px',
            maxHeight: '82vh',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            border: '1px solid var(--border, #e2e8f0)',
            fontFamily: 'Tajawal, sans-serif',
            direction: 'rtl'
          }}>
            {/* Header */}
            <div style={{
              background: 'linear-gradient(135deg, #0891b2 0%, #0e7490 100%)',
              padding: '20px 24px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: '12px'
            }}>
              <div>
                <div style={{ color: 'white', fontWeight: 900, fontSize: '1.15rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <i className="fas fa-chalkboard-teacher" />
                  تعيين لمدرب سريري ونقل للتدريب الجامعي
                </div>
                <div style={{ color: 'rgba(255,255,255,0.9)', fontSize: '0.85rem', marginTop: '5px' }}>
                  الطالب: <strong style={{ color: '#fff' }}>{assignModalStudent.name}</strong>
                  {assignModalStudent.university && <span style={{ marginRight: '8px', opacity: 0.85 }}>({normalizeUniversityName(assignModalStudent.university)})</span>}
                </div>
              </div>
              <button
                onClick={() => setShowAssignTrainerModal(false)}
                style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: 'white', width: '34px', height: '34px', borderRadius: '50%', cursor: 'pointer', fontSize: '1.1rem', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s', flexShrink: 0 }}
              >✕</button>
            </div>

            {/* Info notice about leaving source department */}
            <div style={{ background: '#f0fdf4', borderBottom: '1px solid #bbf7d0', padding: '10px 18px', fontSize: '0.82rem', color: '#166534', display: 'flex', alignItems: 'center', gap: '8px' }}>
              <i className="fas fa-info-circle" style={{ color: '#15803d', fontSize: '0.95rem', flexShrink: 0 }} />
              <span>
                سيتم <strong>إخراج الطالب تلقائياً</strong> من قسم <strong>({assignModalSourceDept || 'قسمه الحالي'})</strong> ونقله مباشرة إلى قسم <strong>({getTrainerDeptForStudentDept(assignModalSourceDept || assignModalStudent?.department)})</strong> تحت اسم المدرب المختار بدون أي تكرار.
              </span>
            </div>

            {/* Search + Filter */}
            <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border, #e2e8f0)', background: 'var(--bg, #f8fafc)', display: 'flex', flexDirection: 'column', gap: '10px' }}>
              <div style={{ position: 'relative' }}>
                <i className="fas fa-search" style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: '#94a3b8', fontSize: '0.9rem' }} />
                <input
                  type="text"
                  placeholder="ابحث باسم المدرب أو جامعته أو اكتب اسماً جديداً..."
                  value={assignTrainerSearch}
                  onChange={e => setAssignTrainerSearch(e.target.value)}
                  style={{
                    width: '100%', padding: '10px 40px 10px 14px', borderRadius: '10px',
                    border: '1.5px solid var(--border, #e2e8f0)', background: 'var(--card-bg, #fff)',
                    color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', outline: 'none',
                    boxSizing: 'border-box'
                  }}
                  autoFocus
                />
              </div>

              {/* Filter Pills across specialties */}
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {[
                  { key: 'all', label: `الكل (${availableTrainersList.length})` },
                  { key: 'radiology', label: `☢️ مدربو الأشعة (${availableTrainersList.filter(t => t.specialtyGroup === 'radiology' || t.department === 'مدربي أشعة').length})` },
                  { key: 'lab', label: `🧪 مدربو المختبر (${availableTrainersList.filter(t => t.specialtyGroup === 'lab' || t.department === 'مدربي مختبر').length})` },
                  { key: 'pt', label: `🏃 مدربو العلاج الطبيعي (${availableTrainersList.filter(t => t.specialtyGroup === 'pt' || t.department === 'مدربي علاج طبيعي').length})` },
                  { key: 'nursing', label: `🩺 مدربو التمريض (${availableTrainersList.filter(t => t.specialtyGroup === 'nursing' || t.department === 'تدريب تمريض الجامعات').length})` },
                  { key: 'pharmacy', label: `💊 مدربو الصيدلة (${availableTrainersList.filter(t => t.specialtyGroup === 'pharmacy' || t.department === 'مدربي صيدلية').length})` },
                  { key: 'nutrition', label: `🥗 مدربو التغذية (${availableTrainersList.filter(t => t.specialtyGroup === 'nutrition' || t.department === 'مدربي تغذية').length})` },
                  { key: 'biomedical', label: `⚙️ مدربو الهندسة الطبية (${availableTrainersList.filter(t => t.specialtyGroup === 'biomedical' || t.department === 'مدربي هندسة طبية').length})` },
                  { key: 'ot', label: `🤲 مدربو العلاج الوظيفي (${availableTrainersList.filter(t => t.specialtyGroup === 'ot' || t.department === 'مدربي علاج وظيفي').length})` },
                ].map(tab => (
                  <button
                    key={tab.key}
                    type="button"
                    onClick={() => setAssignTrainerFilter(tab.key as any)}
                    style={{
                      padding: '5px 12px',
                      borderRadius: '16px',
                      fontSize: '0.8rem',
                      fontWeight: 700,
                      fontFamily: 'Tajawal',
                      cursor: 'pointer',
                      border: '1px solid',
                      borderColor: assignTrainerFilter === tab.key ? '#0891b2' : 'var(--border, #cbd5e1)',
                      background: assignTrainerFilter === tab.key ? '#0891b2' : 'var(--card-bg, #fff)',
                      color: assignTrainerFilter === tab.key ? '#fff' : 'var(--text, #334155)',
                      transition: 'all 0.15s ease'
                    }}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>

              {/* Manual assign if typed name not in list */}
              {assignTrainerSearch.trim() && !availableTrainersList.find(t => t.name === assignTrainerSearch.trim()) && (
                <button
                  type="button"
                  onClick={() => handleAssignTrainerFromMain(assignTrainerSearch.trim())}
                  disabled={isAssigningTrainer}
                  style={{
                    display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 16px',
                    borderRadius: '10px', border: '2px dashed #0891b2', background: '#e0f2fe',
                    color: '#0891b2', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.9rem',
                    cursor: 'pointer', width: '100%', justifyContent: 'center'
                  }}
                >
                  <i className="fas fa-plus-circle" />
                  تعيين باسم مخصص: "{assignTrainerSearch.trim()}"
                </button>
              )}
            </div>

            {/* Trainers List */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
              {(() => {
                const filtered = availableTrainersList.filter(t => {
                  if (assignTrainerFilter !== 'all') {
                    if (assignTrainerFilter === 'website' && t.source !== 'website') return false;
                    if (assignTrainerFilter === 'approved' && t.source !== 'approved') return false;
                    if (['radiology','lab','pt','nursing','pharmacy','nutrition','biomedical','ot'].includes(assignTrainerFilter)) {
                      const matchesGroup = t.specialtyGroup === assignTrainerFilter;
                      const matchesDept = 
                        (assignTrainerFilter === 'radiology' && t.department === 'مدربي أشعة') ||
                        (assignTrainerFilter === 'lab' && t.department === 'مدربي مختبر') ||
                        (assignTrainerFilter === 'pt' && t.department === 'مدربي علاج طبيعي') ||
                        (assignTrainerFilter === 'nursing' && t.department === 'تدريب تمريض الجامعات') ||
                        (assignTrainerFilter === 'pharmacy' && t.department === 'مدربي صيدلية') ||
                        (assignTrainerFilter === 'nutrition' && t.department === 'مدربي تغذية') ||
                        (assignTrainerFilter === 'biomedical' && t.department === 'مدربي هندسة طبية') ||
                        (assignTrainerFilter === 'ot' && t.department === 'مدربي علاج وظيفي');
                      if (!matchesGroup && !matchesDept) return false;
                    }
                  }
                  if (assignTrainerSearch.trim()) {
                    const q = assignTrainerSearch.trim().toLowerCase();
                    return t.name.toLowerCase().includes(q) || (t.university || '').toLowerCase().includes(q) || (t.phone || '').includes(q);
                  }
                  return true;
                });

                if (filtered.length === 0) {
                  return (
                    <div style={{ textAlign: 'center', padding: '30px 20px', color: '#94a3b8' }}>
                      <i className="fas fa-search" style={{ fontSize: '2.5rem', marginBottom: '12px', display: 'block', color: '#cbd5e1' }} />
                      <div style={{ fontWeight: 700, fontSize: '1rem', color: 'var(--text, #374151)' }}>لا يوجد مدربون يطابقون البحث</div>
                      <div style={{ fontSize: '0.85rem', marginTop: '6px' }}>يمكنك كتابة اسم المدرب في حقل البحث وتعيينه مباشرة</div>
                    </div>
                  );
                }

                return filtered.map((trainer, idx) => (
                  <button
                    key={idx}
                    type="button"
                    disabled={isAssigningTrainer}
                    onClick={() => handleAssignTrainerFromMain(trainer.name)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: '14px',
                      padding: '12px 16px', borderRadius: '12px', border: '1.5px solid transparent',
                      background: trainer.source === 'website' ? 'rgba(8, 145, 178, 0.05)' : 'var(--bg, #f8fafc)',
                      cursor: isAssigningTrainer ? 'not-allowed' : 'pointer',
                      textAlign: 'right', width: '100%', transition: 'all 0.2s',
                      fontFamily: 'Tajawal'
                    }}
                    onMouseEnter={e => { (e.currentTarget as HTMLElement).style.background = '#e0f2fe'; (e.currentTarget as HTMLElement).style.borderColor = '#0891b2'; }}
                    onMouseLeave={e => { (e.currentTarget as HTMLElement).style.background = trainer.source === 'website' ? 'rgba(8, 145, 178, 0.05)' : 'var(--bg, #f8fafc)'; (e.currentTarget as HTMLElement).style.borderColor = 'transparent'; }}
                  >
                    {/* Avatar */}
                    <div style={{
                      width: '42px', height: '42px', borderRadius: '50%', flexShrink: 0,
                      background: trainer.source === 'website'
                        ? 'linear-gradient(135deg, #0891b2, #0e7490)'
                        : 'linear-gradient(135deg, #64748b, #475569)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: 'white', fontWeight: 900, fontSize: '1.1rem'
                    }}>
                      {trainer.name.charAt(0)}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', marginBottom: '3px' }}>
                        <span style={{ fontWeight: 800, fontSize: '0.96rem', color: 'var(--text, #0f172a)' }}>
                          {trainer.name}
                        </span>
                        {trainer.badge && (
                          <span style={{
                            fontSize: '0.72rem', fontWeight: 700, padding: '2px 8px', borderRadius: '12px',
                            background: trainer.source === 'website' ? '#ecfdf5' : '#f1f5f9',
                            color: trainer.source === 'website' ? '#047857' : '#475569',
                            border: trainer.source === 'website' ? '1px solid #a7f3d0' : '1px solid #e2e8f0'
                          }}>
                            {trainer.badge}
                          </span>
                        )}
                      </div>
                      <div style={{ fontSize: '0.8rem', color: '#64748b', display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
                          <i className="fas fa-university" style={{ color: '#0891b2', fontSize: '0.72rem' }} />
                          {trainer.university || '—'}
                        </span>
                        {trainer.phone && (
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px', direction: 'ltr' }}>
                            <i className="fas fa-phone" style={{ color: '#059669', fontSize: '0.7rem' }} />
                            {trainer.phone}
                          </span>
                        )}
                      </div>
                    </div>
                    <div style={{
                      fontSize: '0.8rem', fontWeight: 800, color: '#0891b2',
                      background: '#e0f2fe', padding: '6px 14px', borderRadius: '20px', flexShrink: 0,
                      display: 'flex', alignItems: 'center', gap: '4px'
                    }}>
                      تعيين <i className="fas fa-arrow-left" style={{ fontSize: '0.75rem' }} />
                    </div>
                  </button>
                ));
              })()}
            </div>

            {/* Footer */}
            <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border, #e2e8f0)', background: 'var(--bg, #f8fafc)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: '0.82rem', color: '#64748b' }}>
                {availableTrainersList.length > 0 ? `${availableTrainersList.filter(t => !assignTrainerSearch.trim() || t.name.includes(assignTrainerSearch.trim())).length} من ${availableTrainersList.length} شخص` : 'لا يوجد أشخاص'}
              </span>
              <button
                type="button"
                onClick={() => setShowAssignTrainerModal(false)}
                style={{ padding: '8px 20px', borderRadius: '10px', border: '1.5px solid var(--border, #e2e8f0)', background: 'transparent', color: 'var(--text, #374151)', fontFamily: 'Tajawal', fontWeight: 700, cursor: 'pointer', fontSize: '0.9rem' }}
              >
                إلغاء
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════
           MODAL 1: إضافة طالب جديد تحت إشراف مدرب محدد
      ══════════════════════════════════════════════════════════ */}
      {quickTrainerStudentModal.isOpen && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 99999,
          background: 'rgba(15, 23, 42, 0.65)', backdropFilter: 'blur(8px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '16px', direction: 'rtl'
        }}>
          <div style={{
            background: 'var(--card-bg, #ffffff)',
            borderRadius: '20px', width: '100%', maxWidth: '580px',
            maxHeight: '90vh', display: 'flex', flexDirection: 'column',
            overflow: 'hidden', boxShadow: '0 25px 60px -15px rgba(0,0,0,0.3)',
            border: '1px solid var(--border, #e2e8f0)', fontFamily: 'Tajawal'
          }}>
            {/* Header */}
            <div style={{
              background: 'linear-gradient(135deg, #0891b2 0%, #0e7490 100%)',
              padding: '20px 24px', color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between'
            }}>
              <div>
                <div style={{ fontSize: '1.15rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fas fa-user-plus" />
                  إضافة طالب تحت إشراف المدرب
                </div>
                <div style={{ color: 'rgba(255,255,255,0.92)', fontSize: '0.85rem', marginTop: '4px' }}>
                  👤 المدرب: <strong style={{ color: '#fff' }}>{quickTrainerStudentModal.trainerName}</strong> — قسم: {quickTrainerStudentModal.dept}
                </div>
              </div>
              <button
                type="button"
                onClick={() => setQuickTrainerStudentModal({ isOpen: false, trainerName: '', dept: '' })}
                style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: 'white', width: '32px', height: '32px', borderRadius: '50%', cursor: 'pointer', fontSize: '1.1rem', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >✕</button>
            </div>

            {/* Form */}
            <form onSubmit={handleSaveQuickStudent} style={{ padding: '20px 24px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '14px' }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>
                  اسم الطالب رباعي <span style={{ color: '#ef4444' }}>*</span>
                </label>
                <input
                  type="text"
                  required
                  placeholder="مثال: أحمد محمد علي حسن"
                  value={quickStudentForm.name}
                  onChange={e => setQuickStudentForm({ ...quickStudentForm, name: e.target.value })}
                  style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  autoFocus
                />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>رقم الهاتف</label>
                  <input
                    type="text"
                    dir="ltr"
                    placeholder="059xxxxxxx"
                    value={quickStudentForm.phone}
                    onChange={e => setQuickStudentForm({ ...quickStudentForm, phone: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box', textAlign: 'right' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>رقم الهوية</label>
                  <input
                    type="text"
                    placeholder="رقم الهوية (اختياري)"
                    value={quickStudentForm.idNumber}
                    onChange={e => setQuickStudentForm({ ...quickStudentForm, idNumber: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>الجامعة / الكلية</label>
                <input
                  type="text"
                  placeholder="مثال: جامعة بوليتكنك فلسطين، جامعة الخليل..."
                  value={quickStudentForm.university}
                  onChange={e => setQuickStudentForm({ ...quickStudentForm, university: e.target.value })}
                  style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>تاريخ البدء</label>
                  <input
                    type="date"
                    value={quickStudentForm.startDate}
                    onChange={e => setQuickStudentForm({ ...quickStudentForm, startDate: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>تاريخ الانتهاء</label>
                  <input
                    type="date"
                    value={quickStudentForm.endDate}
                    onChange={e => setQuickStudentForm({ ...quickStudentForm, endDate: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>أيام الدوام الأسبوعية</label>
                  <input
                    type="text"
                    placeholder="مثال: سبت / اثنين / أربعاء"
                    value={quickStudentForm.attendanceDays}
                    onChange={e => setQuickStudentForm({ ...quickStudentForm, attendanceDays: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>مكان السكن</label>
                  <input
                    type="text"
                    placeholder="مثال: الخليل، دورا، يطا..."
                    value={quickStudentForm.address}
                    onChange={e => setQuickStudentForm({ ...quickStudentForm, address: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              {/* Notice */}
              <div style={{ background: '#f0fdf4', border: '1px solid #bbf7d0', padding: '10px 14px', borderRadius: '10px', fontSize: '0.8rem', color: '#166534', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <i className="fas fa-check-circle" style={{ color: '#16a34a', flexShrink: 0 }} />
                <span>سيتم حفظ الطالب مباشرة في قاعدة البيانات تحت إشراف المدرب <strong>{quickTrainerStudentModal.trainerName}</strong>.</span>
              </div>

              {/* Actions */}
              <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '10px' }}>
                <button
                  type="button"
                  onClick={() => setQuickTrainerStudentModal({ isOpen: false, trainerName: '', dept: '' })}
                  style={{ padding: '9px 18px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'transparent', color: 'var(--text, #334155)', fontFamily: 'Tajawal', fontWeight: 700, cursor: 'pointer' }}
                >
                  إلغاء
                </button>
                <button
                  type="submit"
                  style={{
                    padding: '9px 22px', borderRadius: '10px', border: 'none',
                    background: 'linear-gradient(135deg, #0891b2, #0e7490)',
                    color: 'white', fontFamily: 'Tajawal', fontWeight: 800,
                    cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px',
                    boxShadow: '0 4px 12px rgba(8, 145, 178, 0.3)'
                  }}
                >
                  <i className="fas fa-save" />
                  حفظ وإضافة الطالب
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════
           MODAL 2: تعيين طالب مسجل في النظام تحت إشراف مدرب محدد
      ══════════════════════════════════════════════════════════ */}
      {quickAssignModal.isOpen && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 99999,
          background: 'rgba(15, 23, 42, 0.65)', backdropFilter: 'blur(8px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '16px', direction: 'rtl'
        }}>
          <div style={{
            background: 'var(--card-bg, #ffffff)',
            borderRadius: '20px', width: '100%', maxWidth: '640px',
            maxHeight: '90vh', display: 'flex', flexDirection: 'column',
            overflow: 'hidden', boxShadow: '0 25px 60px -15px rgba(0,0,0,0.3)',
            border: '1px solid var(--border, #e2e8f0)', fontFamily: 'Tajawal'
          }}>
            {/* Header */}
            <div style={{
              background: 'linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)',
              padding: '20px 24px', color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between'
            }}>
              <div>
                <div style={{ fontSize: '1.15rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fas fa-link" />
                  تعيين طالب مسجل للمدرب
                </div>
                <div style={{ color: 'rgba(255,255,255,0.92)', fontSize: '0.85rem', marginTop: '4px' }}>
                  👤 المدرب: <strong style={{ color: '#fff' }}>{quickAssignModal.trainerName}</strong> — قسم: {quickAssignModal.dept}
                </div>
              </div>
              <button
                type="button"
                onClick={() => setQuickAssignModal({ isOpen: false, trainerName: '', dept: '', search: '', showAllStudents: false })}
                style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: 'white', width: '32px', height: '32px', borderRadius: '50%', cursor: 'pointer', fontSize: '1.1rem', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >✕</button>
            </div>

            {/* Filter & Search Bar */}
            <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border, #e2e8f0)', background: 'var(--bg, #f8fafc)', display: 'flex', flexDirection: 'column', gap: '10px' }}>
              <div style={{ position: 'relative' }}>
                <i className="fas fa-search" style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: '#94a3b8', fontSize: '0.9rem' }} />
                <input
                  type="text"
                  placeholder="ابحث باسم الطالب، رقمه، أو جامعته..."
                  value={quickAssignModal.search}
                  onChange={e => setQuickAssignModal({ ...quickAssignModal, search: e.target.value })}
                  style={{
                    width: '100%', padding: '10px 40px 10px 14px', borderRadius: '10px',
                    border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--card-bg, #fff)',
                    color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem',
                    boxSizing: 'border-box'
                  }}
                  autoFocus
                />
              </div>

              {/* Scope toggle */}
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <button
                  type="button"
                  onClick={() => setQuickAssignModal({ ...quickAssignModal, showAllStudents: false })}
                  style={{
                    padding: '5px 12px', borderRadius: '16px', fontSize: '0.8rem', fontWeight: 700, fontFamily: 'Tajawal',
                    border: '1px solid', cursor: 'pointer',
                    borderColor: !quickAssignModal.showAllStudents ? '#7c3aed' : 'var(--border, #cbd5e1)',
                    background: !quickAssignModal.showAllStudents ? '#7c3aed' : 'var(--card-bg, #fff)',
                    color: !quickAssignModal.showAllStudents ? '#fff' : 'var(--text, #334155)'
                  }}
                >
                  طلاب التخصص المعني ({getRelatedTraineeDepts(quickAssignModal.dept).join('، ') || 'المتدربين'})
                </button>
                <button
                  type="button"
                  onClick={() => setQuickAssignModal({ ...quickAssignModal, showAllStudents: true })}
                  style={{
                    padding: '5px 12px', borderRadius: '16px', fontSize: '0.8rem', fontWeight: 700, fontFamily: 'Tajawal',
                    border: '1px solid', cursor: 'pointer',
                    borderColor: quickAssignModal.showAllStudents ? '#7c3aed' : 'var(--border, #cbd5e1)',
                    background: quickAssignModal.showAllStudents ? '#7c3aed' : 'var(--card-bg, #fff)',
                    color: quickAssignModal.showAllStudents ? '#fff' : 'var(--text, #334155)'
                  }}
                >
                  جميع طلاب المستشفى
                </button>
              </div>
            </div>

            {/* Candidate Students List */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '12px 18px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
              {(() => {
                const relatedDepts = getRelatedTraineeDepts(quickAssignModal.dept);
                let pool: { student: Student; sourceDept: string }[] = [];

                if (quickAssignModal.showAllStudents) {
                  Object.keys(studentsData).forEach(d => {
                    (studentsData[d] || []).forEach(st => {
                      if (st.assignedTrainer !== quickAssignModal.trainerName) {
                        pool.push({ student: st, sourceDept: d });
                      }
                    });
                  });
                } else {
                  // Candidates from related trainee departments + current dept unassigned
                  relatedDepts.forEach(rd => {
                    (studentsData[rd] || []).forEach(st => {
                      if (st.assignedTrainer !== quickAssignModal.trainerName) {
                        pool.push({ student: st, sourceDept: rd });
                      }
                    });
                  });
                  (studentsData[quickAssignModal.dept] || []).forEach(st => {
                    if (st.assignedTrainer !== quickAssignModal.trainerName && (st.assignedTrainer || st.internshipYear === 'طالب متدرب')) {
                      pool.push({ student: st, sourceDept: quickAssignModal.dept });
                    }
                  });
                }

                // Filter by search
                const q = quickAssignModal.search.trim().toLowerCase();
                const filtered = pool.filter(({ student }) => {
                  if (!q) return true;
                  return (student.name || '').toLowerCase().includes(q) ||
                    (student.phone || '').includes(q) ||
                    (student.university || '').toLowerCase().includes(q) ||
                    (student.idNumber || '').includes(q);
                });

                if (filtered.length === 0) {
                  return (
                    <div style={{ textAlign: 'center', padding: '36px 20px', color: '#94a3b8' }}>
                      <i className="fas fa-user-slash" style={{ fontSize: '2.4rem', color: '#cbd5e1', marginBottom: '10px', display: 'block' }} />
                      <div style={{ fontWeight: 700, fontSize: '0.98rem', color: 'var(--text, #334155)' }}>لا يوجد طلاب متطابقين</div>
                      <div style={{ fontSize: '0.82rem', marginTop: '4px' }}>جرب البحث باسم آخر أو اختر "جميع طلاب المستشفى" أعلاه</div>
                    </div>
                  );
                }

                return filtered.map(({ student, sourceDept }, idx) => (
                  <div
                    key={idx}
                    style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      padding: '12px 16px', borderRadius: '12px', background: 'var(--bg, #f8fafc)',
                      border: '1px solid var(--border, #e2e8f0)', gap: '12px'
                    }}
                  >
                    <div>
                      <div style={{ fontWeight: 800, fontSize: '0.94rem', color: 'var(--text, #0f172a)' }}>
                        {student.name}
                      </div>
                      <div style={{ display: 'flex', gap: '8px', fontSize: '0.78rem', color: '#64748b', marginTop: '3px', flexWrap: 'wrap' }}>
                        <span style={{ background: '#e0f2fe', color: '#0369a1', padding: '1px 6px', borderRadius: '4px', fontWeight: 700 }}>
                          {sourceDept}
                        </span>
                        {student.university && <span>🎓 {normalizeUniversityName(student.university)}</span>}
                        {student.phone && <span dir="ltr">📞 {student.phone}</span>}
                        {student.assignedTrainer && (
                          <span style={{ color: '#b45309', fontWeight: 700 }}>
                            (حالياً مع: {student.assignedTrainer})
                          </span>
                        )}
                      </div>
                    </div>

                    <button
                      type="button"
                      disabled={isAssigningTrainer}
                      onClick={async () => {
                        setAssignModalStudent(student);
                        setAssignModalSourceDept(sourceDept);
                        await handleAssignTrainerFromMain(quickAssignModal.trainerName);
                        setQuickAssignModal({ isOpen: false, trainerName: '', dept: '', search: '', showAllStudents: false });
                      }}
                      style={{
                        padding: '7px 14px', borderRadius: '8px', border: 'none',
                        background: 'linear-gradient(135deg, #7c3aed, #6d28d9)',
                        color: 'white', fontFamily: 'Tajawal', fontWeight: 800,
                        fontSize: '0.82rem', cursor: isAssigningTrainer ? 'not-allowed' : 'pointer',
                        display: 'inline-flex', alignItems: 'center', gap: '6px', flexShrink: 0,
                        boxShadow: '0 2px 6px rgba(124, 58, 237, 0.3)'
                      }}
                    >
                      <i className="fas fa-check" />
                      تعيين لهذا المدرب
                    </button>
                  </div>
                ));
              })()}
            </div>

            {/* Footer */}
            <div style={{ padding: '12px 20px', borderTop: '1px solid var(--border, #e2e8f0)', background: 'var(--bg, #f8fafc)', display: 'flex', justifyContent: 'flex-end' }}>
              <button
                type="button"
                onClick={() => setQuickAssignModal({ isOpen: false, trainerName: '', dept: '', search: '', showAllStudents: false })}
                style={{ padding: '8px 18px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'transparent', color: 'var(--text, #334155)', fontFamily: 'Tajawal', fontWeight: 700, cursor: 'pointer' }}
              >
                إغلاق
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════
           MODAL 3: إضافة مدرب سريري جديد في أي قسم
      ══════════════════════════════════════════════════════════ */}
      {quickAddTrainerModal.isOpen && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 99999,
          background: 'rgba(15, 23, 42, 0.65)', backdropFilter: 'blur(8px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '16px', direction: 'rtl'
        }}>
          <div style={{
            background: 'var(--card-bg, #ffffff)',
            borderRadius: '20px', width: '100%', maxWidth: '580px',
            maxHeight: '90vh', display: 'flex', flexDirection: 'column',
            overflow: 'hidden', boxShadow: '0 25px 60px -15px rgba(0,0,0,0.3)',
            border: '1px solid var(--border, #e2e8f0)', fontFamily: 'Tajawal'
          }}>
            {/* Header */}
            <div style={{
              background: 'linear-gradient(135deg, #0284c7 0%, #0369a1 100%)',
              padding: '20px 24px', color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between'
            }}>
              <div>
                <div style={{ fontSize: '1.15rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fas fa-chalkboard-teacher" />
                  إضافة مدرب سريري جديد
                </div>
                <div style={{ color: 'rgba(255,255,255,0.92)', fontSize: '0.85rem', marginTop: '4px' }}>
                  قسم: <strong style={{ color: '#fff' }}>{quickAddTrainerModal.dept}</strong>
                </div>
              </div>
              <button
                type="button"
                onClick={() => setQuickAddTrainerModal({ isOpen: false, dept: '' })}
                style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: 'white', width: '32px', height: '32px', borderRadius: '50%', cursor: 'pointer', fontSize: '1.1rem', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >✕</button>
            </div>

            {/* Form */}
            <form onSubmit={handleSaveQuickTrainer} style={{ padding: '20px 24px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '14px' }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>
                  اسم المدرب السريري رباعي <span style={{ color: '#ef4444' }}>*</span>
                </label>
                <input
                  type="text"
                  required
                  placeholder="مثال: أ. محمد أحمد شاور"
                  value={quickTrainerForm.name}
                  onChange={e => setQuickTrainerForm({ ...quickTrainerForm, name: e.target.value })}
                  style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  autoFocus
                />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>رقم الهاتف</label>
                  <input
                    type="text"
                    dir="ltr"
                    placeholder="059xxxxxxx"
                    value={quickTrainerForm.phone}
                    onChange={e => setQuickTrainerForm({ ...quickTrainerForm, phone: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box', textAlign: 'right' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>رقم الهوية</label>
                  <input
                    type="text"
                    placeholder="رقم الهوية (اختياري)"
                    value={quickTrainerForm.idNumber}
                    onChange={e => setQuickTrainerForm({ ...quickTrainerForm, idNumber: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>الجامعة / جهة التعاقد</label>
                  <input
                    type="text"
                    placeholder="مثال: جامعة بوليتكنك فلسطين"
                    value={quickTrainerForm.university}
                    onChange={e => setQuickTrainerForm({ ...quickTrainerForm, university: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>طبيعة الوظيفة / التخصص</label>
                  <input
                    type="text"
                    placeholder="مثال: مدرب سريري"
                    value={quickTrainerForm.specialty}
                    onChange={e => setQuickTrainerForm({ ...quickTrainerForm, specialty: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>تاريخ بدء التعاقد / التدريب</label>
                  <input
                    type="date"
                    value={quickTrainerForm.startDate}
                    onChange={e => setQuickTrainerForm({ ...quickTrainerForm, startDate: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 700, marginBottom: '6px', color: 'var(--text, #1e293b)' }}>تاريخ الانتهاء</label>
                  <input
                    type="date"
                    value={quickTrainerForm.endDate}
                    onChange={e => setQuickTrainerForm({ ...quickTrainerForm, endDate: e.target.value })}
                    style={{ width: '100%', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'var(--bg, #f8fafc)', color: 'var(--text, #0f172a)', fontFamily: 'Tajawal', fontSize: '0.95rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              {/* Notice */}
              <div style={{ background: '#f0f9ff', border: '1px solid #bae6fd', padding: '10px 14px', borderRadius: '10px', fontSize: '0.8rem', color: '#0369a1', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <i className="fas fa-info-circle" style={{ color: '#0284c7', flexShrink: 0 }} />
                <span>سيتم إضافة هذا المدرب في قسم <strong>{quickAddTrainerModal.dept}</strong> وتخصيص جدول وقسم مخصص له لإضافة الطلاب تحته مباشرة.</span>
              </div>

              {/* Actions */}
              <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '10px' }}>
                <button
                  type="button"
                  onClick={() => setQuickAddTrainerModal({ isOpen: false, dept: '' })}
                  style={{ padding: '9px 18px', borderRadius: '10px', border: '1.5px solid var(--border, #cbd5e1)', background: 'transparent', color: 'var(--text, #334155)', fontFamily: 'Tajawal', fontWeight: 700, cursor: 'pointer' }}
                >
                  إلغاء
                </button>
                <button
                  type="submit"
                  style={{
                    padding: '9px 22px', borderRadius: '10px', border: 'none',
                    background: 'linear-gradient(135deg, #0284c7, #0369a1)',
                    color: 'white', fontFamily: 'Tajawal', fontWeight: 800,
                    cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px',
                    boxShadow: '0 4px 12px rgba(2, 132, 199, 0.3)'
                  }}
                >
                  <i className="fas fa-save" />
                  حفظ وإضافة المدرب
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Loading Overlay */}
      {isLoading && (
        <div className="loading-overlay">
          <div className="loading-content">
            <div className="loading-spinner"></div>
            <p>جاري تحميل البيانات...</p>
            <small>يتم المزامنة مع السيرفر</small>
          </div>
        </div>
      )}

      {/* ════════════════════════════════════════════════════════════
          GOLDEN MODAL: تقرير الجامعات الشريكة — إحصائيات تفصيلية
      ════════════════════════════════════════════════════════════ */}
      {showUniStatsModal && (() => {
        // ── Helper to normalize ONLY recognized contracted partner universities (never graduation universities!) ──
        const normalizeContractedPartner = (raw?: string | null): string | null => {
          if (!raw || typeof raw !== 'string') return null;
          const clean = raw.trim()
            .replace(/[\u064B-\u065F]/g, '')
            .replace(/[إأآا]/g, 'ا')
            .replace(/[ة]/g, 'ه')
            .replace(/[ى]/g, 'ي')
            .toLowerCase();

          // ⚠️ جهات التعاقد المعتمدة لدى المستشفى هي 3 جهات فقط: البوليتكنك، الخليل، الكلية الذكية
          // جامعة القدس (أبو ديس) أو أي جامعة أخرى هي جامعات تخرج وليست جهات تعاقد
          if (clean.includes('قدس') || clean.includes('ابو ديس') || clean.includes('ابوديس')) {
            return null;
          }

          if (clean.includes('بوليتكنك') || clean.includes('بولتكنك') || clean.includes('polytechnic') || clean.includes('بولتكنيك') || clean.includes('بلوتكنيك')) {
            return 'جامعة بوليتكنك فلسطين';
          }
          if (clean.includes('خليل')) {
            return 'جامعة الخليل';
          }
          if (clean.includes('ذكيه') || clean.includes('ذكية') || clean.includes('smart')) {
            return 'الكلية الذكية الجامعية للتعليم الحديث';
          }
          return null; // أي جامعة أخرى ليست جهة تعاقد معتمدة
        };

        // ── Helper to extract ALL contracted partner universities for a student/doctor ──
        const getContractedPartnerUnis = (s: any): string[] => {
          const result = new Set<string>();

          const n = (s.name || '').trim();
          const idNum = String(s.idNumber || s.id_number || '').replace(/\D/g, '');

          // 0. High priority: User overrides & moved faculties
          const key = s.idNumber || s.name;
          const override = partnerStaffOverrides[key];
          if (override?.partnerUniversity) {
            const norm = normalizeContractedPartner(override.partnerUniversity) || override.partnerUniversity;
            return [norm];
          }
          if (s.partnerUniversity) {
            const norm = normalizeContractedPartner(s.partnerUniversity) || s.partnerUniversity;
            return [norm];
          }
          if (Array.isArray(s.contractedUniversities) && s.contractedUniversities.length > 0) {
            return s.contractedUniversities.map((u: string) => normalizeContractedPartner(u) || u);
          }
          if (s.contractedUniversity) {
            const norm = normalizeContractedPartner(s.contractedUniversity);
            if (norm) return [norm];
          }

          // Explicit confirmed mappings requested by user (never graduation university!)
          if ((n.includes('مهران') && n.includes('درويش')) || idNum === '860162031') {
            return ['جامعة بوليتكنك فلسطين'];
          }
          if ((n.includes('باسل') && (n.includes('عمرو') || n.includes('عمر'))) || idNum === '402724918') {
            return ['جامعة بوليتكنك فلسطين'];
          }
          if ((n.includes('عمر') && (n.includes('رجوب') || n.includes('ارجوب'))) || idNum === '854113719') {
            return ['جامعة بوليتكنك فلسطين'];
          }
          if (n.includes('طلحه') || n.includes('طلحة') || idNum === '402066195') {
            return ['جامعة بوليتكنك فلسطين'];
          }
          if (n.toLowerCase().includes('dababsa') || n.includes('دبابسة') || n.includes('دبابسه') || idNum === '403139025') {
            return ['جامعة بوليتكنك فلسطين'];
          }
          if (n.includes('محمد راتب') || n.includes('جلق') || idNum === '854614047') {
            return ['جامعة بوليتكنك فلسطين'];
          }
          if ((n.includes('بلال') && (n.includes('امواس') || n.includes('مناصرة'))) || idNum === '954308822') {
            return ['الكلية الذكية الجامعية للتعليم الحديث'];
          }
          if (n.includes('محمود فخري') || idNum === '854997632') {
            return ['الكلية الذكية الجامعية للتعليم الحديث'];
          }

          const checkAndAdd = (val: any) => {
            if (!val) return;
            if (Array.isArray(val)) {
              val.forEach(v => checkAndAdd(v));
              return;
            }
            if (typeof val === 'string') {
              const trimmed = val.trim();
              if (!trimmed || trimmed === '[]' || trimmed === 'null' || trimmed === 'None') return;
              if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
                try {
                  const parsed = JSON.parse(trimmed);
                  if (Array.isArray(parsed)) {
                    parsed.forEach(v => checkAndAdd(v));
                    return;
                  }
                } catch {}
              }
              const parts = trimmed.split(/[,،/]|(\s+و\s+)/);
              parts.forEach(p => {
                if (!p) return;
                const norm = normalizeContractedPartner(p);
                if (norm) result.add(norm);
              });
              const directNorm = normalizeContractedPartner(trimmed);
              if (directNorm) result.add(directNorm);
            }
          };

          // 1. Explicit contracted university fields (HIGHEST PRIORITY)
          checkAndAdd(s.contractedUniversities);
          checkAndAdd(s.contracted_universities);
          checkAndAdd(s.contractedUniversity);
          checkAndAdd(s.contracted_university);
          checkAndAdd(s.previousContractedUniversity);
          checkAndAdd(s.customContractedUniversity);

          // Contracted universities are ONLY derived from explicit contracted fields
          return Array.from(result);
        };

        // ── Collect all contracted staff from studentsData ──
        const allContractedDocs: Student[] = [
          ...(studentsData['الأطباء المتعاقدون'] || []),
          ...allStatisticalStudents.filter(s => isContractedDoctorStudent(s))
        ].filter((s, idx, arr) => arr.findIndex(x => (x.idNumber || x.name) === (s.idNumber || s.name)) === idx);

        // ── Collect Trainers across ALL departments (Nursing, Radiology, PT, Labs, Pharmacy, OT, Nutrition) ──
        const TRAINER_KEYS = [
          'تدريب تمريض الجامعات',
          'مدربي أشعة',
          'مدربي علاج طبيعي',
          'مدربي مختبر',
          'مدربي مختبرات',
          'مدربي صيدلية',
          'مدربي صيدلة',
          'مدربي علاج وظيفي',
          'مدربي تغذية',
          'مدربي هندسة طبية'
        ];

        const isAnyClinicalTrainer = (s: Student) => {
          if (isContractedDoctorStudent(s)) return false;
          if (isNursingTrainer(s)) return true;
          const dept = (s.department || s.originalDepartment || s.deptLabel || '').trim();
          const job = (s.crescentJobNature || s.internshipYear || '').trim();
          const cat = ((s as any).category || (s as any).categoryId || '').trim();
          if (job.includes('مدرب') || job.includes('مشرف')) return true;
          if (cat.includes('trainer') || cat.includes('مدرب')) return true;
          if (TRAINER_KEYS.some(k => dept.includes(k) || k.includes(dept))) return true;
          if (dept.includes('مدرب') || dept.includes('مشرف')) return true;
          return false;
        };

        const allTrainersCollected: Student[] = [];
        TRAINER_KEYS.forEach(k => {
          if (Array.isArray(studentsData[k])) {
            studentsData[k].forEach(s => {
              if (!isContractedDoctorStudent(s)) {
                allTrainersCollected.push({
                  ...s,
                  department: s.department || k,
                  deptLabel: s.deptLabel || k
                });
              }
            });
          }
        });

        Object.keys(studentsData).forEach(k => {
          if ((k.includes('مدرب') || k.includes('مشرف')) && !TRAINER_KEYS.includes(k)) {
            if (Array.isArray(studentsData[k])) {
              studentsData[k].forEach(s => {
                if (!isContractedDoctorStudent(s)) {
                  allTrainersCollected.push({
                    ...s,
                    department: s.department || k,
                    deptLabel: s.deptLabel || k
                  });
                }
              });
            }
          }
        });

        allStatisticalStudents.forEach(s => {
          if (isAnyClinicalTrainer(s)) {
            allTrainersCollected.push(s);
          }
        });

        const allNursingTrainersList: Student[] = allTrainersCollected.filter((s, idx, arr) => 
          arr.findIndex(x => (x.idNumber || x.name) === (s.idNumber || s.name)) === idx
        );

        // ── Merge according to tab ──
        const baseList = uniStatsTab === 'doctors' ? allContractedDocs
          : uniStatsTab === 'nursing' ? allNursingTrainersList
          : [...allContractedDocs, ...allNursingTrainersList];

        // ── Filter to ONLY people who have a valid contracted partner university ──
        const onlyContractedStaff = baseList.filter(s => getContractedPartnerUnis(s).length > 0);

        // ── Compute status for each entry ──
        const today = new Date();
        today.setHours(0,0,0,0);
        const parseD = (d?: string) => {
          if (!d) return null;
          const parts = String(d).split(/[\/\-]/).map(Number);
          if (parts.length < 3) return null;
          const [a,b,c] = parts;
          return a > 31 ? new Date(a,b-1,c) : new Date(c,b-1,a);
        };
        const withStatus = onlyContractedStaff.map(s => {
          const start = parseD(s.startDate);
          const end = parseD(s.endDate);
          let status = 'active';
          if (start && start > today) status = 'upcoming';
          else if (end && end < today) status = 'completed';
          return { ...s, _status: status };
        });

        // ── Priority universities to show first ──
        const PRIORITY_UNIS = [
          'جامعة الخليل',
          'جامعة بوليتكنك فلسطين',
          'الكلية الذكية الجامعية للتعليم الحديث'
        ];

        // ── Build per-university stats (supports multi-contract per staff member) ──
        const uniMap: { [uni: string]: { doctors: any[]; nursing: any[] } } = {};
        withStatus.forEach(s => {
          const unis = getContractedPartnerUnis(s);
          unis.forEach(uni => {
            if (!uniMap[uni]) uniMap[uni] = { doctors: [], nursing: [] };
            if (isContractedDoctorStudent(s)) {
              if (!uniMap[uni].doctors.some(x => (x.idNumber || x.name) === (s.idNumber || s.name))) {
                uniMap[uni].doctors.push(s);
              }
            } else {
              if (!uniMap[uni].nursing.some(x => (x.idNumber || x.name) === (s.idNumber || s.name))) {
                uniMap[uni].nursing.push(s);
              }
            }
          });
        });

        const uniEntries = Object.entries(uniMap).sort(([a], [b]) => {
          const ia = PRIORITY_UNIS.indexOf(a);
          const ib = PRIORITY_UNIS.indexOf(b);
          if (ia !== -1 && ib !== -1) return ia - ib;
          if (ia !== -1) return -1;
          if (ib !== -1) return 1;
          const ta = (uniMap[a].doctors.length + uniMap[a].nursing.length);
          const tb = (uniMap[b].doctors.length + uniMap[b].nursing.length);
          return tb - ta;
        });

        // ── Grand totals ──
        const grandTotal = withStatus.length;
        const grandDoctors = withStatus.filter(s => isContractedDoctorStudent(s)).length;
        const grandNursing = withStatus.filter(s => isNursingTrainer(s)).length;
        const grandActive = withStatus.filter(s => s._status === 'active').length;
        const grandCompleted = withStatus.filter(s => s._status === 'completed').length;
        const grandUpcoming = withStatus.filter(s => s._status === 'upcoming').length;

        const UNI_COLORS: {[k:string]: string} = {
          'جامعة الخليل': '#dc2626',
          'جامعة بوليتكنك فلسطين': '#2563eb',
          'الكلية الذكية الجامعية للتعليم الحديث': '#7c3aed'
        };
        const getUniColor = (u: string) => UNI_COLORS[u] || '#0369a1';

        return (
          <div
            onClick={e => e.target === e.currentTarget && setShowUniStatsModal(false)}
            style={{
              position: 'fixed', inset: 0,
              background: 'rgba(0,0,0,0.82)',
              backdropFilter: 'blur(14px)',
              zIndex: 99999,
              display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
              padding: '20px 16px 40px',
              overflowY: 'auto'
            }}
          >
            <div style={{
              background: 'linear-gradient(160deg, #0f172a 0%, #1e293b 60%, #0f172a 100%)',
              border: '2px solid rgba(255,215,0,0.5)',
              borderRadius: '24px',
              width: '100%', maxWidth: '950px',
              boxShadow: '0 0 60px rgba(255,215,0,0.15), 0 30px 80px rgba(0,0,0,0.7)',
              fontFamily: 'Tajawal, sans-serif',
              direction: 'rtl',
              overflow: 'hidden'
            }}>
              {/* ── Header ── */}
              <div style={{
                background: 'linear-gradient(135deg, #78350f 0%, #b45309 50%, #d97706 100%)',
                padding: '22px 28px 18px',
                borderBottom: '1px solid rgba(255,215,0,0.3)',
                position: 'relative'
              }}>
                <button
                  onClick={() => setShowUniStatsModal(false)}
                  style={{
                    position: 'absolute', top: '16px', left: '20px',
                    background: 'rgba(0,0,0,0.3)', border: '1px solid rgba(255,255,255,0.2)',
                    color: 'white', width: '36px', height: '36px', borderRadius: '50%',
                    cursor: 'pointer', fontSize: '1.2rem', display: 'flex',
                    alignItems: 'center', justifyContent: 'center'
                  }}
                >×</button>
                <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                  <div style={{ fontSize: '2.5rem' }}>📊</div>
                  <div>
                    <div style={{ fontSize: '1.4rem', fontWeight: 900, color: '#fff', letterSpacing: '0.5px' }}>
                      تقرير الجامعات الشريكة المتعاقد معها
                    </div>
                    <div style={{ fontSize: '0.88rem', color: 'rgba(255,255,255,0.85)', marginTop: '3px' }}>
                      مستشفى الهلال الأحمر التخصصي — إحصائيات الأطباء المتعاقدين ومدربي التمريض حسب الجامعات المتعاقد معها فقط
                    </div>
                    <div style={{ 
                      marginTop: '8px', 
                      display: 'inline-flex', 
                      alignItems: 'center', 
                      gap: '8px',
                      background: 'rgba(0,0,0,0.3)',
                      border: '1px solid rgba(255,215,0,0.5)',
                      padding: '4px 14px',
                      borderRadius: '20px',
                      fontSize: '0.78rem',
                      color: '#fef08a'
                    }}>
                      <span>🤝 يتم احتساب وتصنيف الكادر وفقاً للجامعات المتعاقد معها رسمياً مع المستشفى فقط (استثناء جامعات التخرج)</span>
                    </div>
                  </div>
                </div>

                {/* ── Grand KPI Cards ── */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))', gap: '10px', marginTop: '18px' }}>
                  {[
                    { label: 'الإجمالي الكلي', value: grandTotal, icon: '👥', color: '#fbbf24' },
                    { label: 'الأطباء المتعاقدون', value: grandDoctors, icon: '🩺', color: '#93c5fd' },
                    { label: 'المدربون والمشرفون السريريون', value: grandNursing, icon: '🏥', color: '#6ee7b7' },
                    { label: 'نشط حالياً', value: grandActive, icon: '🟢', color: '#86efac' },
                    { label: 'مكتمل', value: grandCompleted, icon: '✅', color: '#a5b4fc' },
                    { label: 'قادم', value: grandUpcoming, icon: '🔵', color: '#7dd3fc' },
                  ].map(kpi => (
                    <div key={kpi.label} style={{
                      background: 'rgba(0,0,0,0.35)',
                      borderRadius: '12px', padding: '10px 12px', textAlign: 'center',
                      border: '1px solid rgba(255,255,255,0.12)'
                    }}>
                      <div style={{ fontSize: '1.4rem' }}>{kpi.icon}</div>
                      <div style={{ fontSize: '1.6rem', fontWeight: 900, color: kpi.color, lineHeight: 1.1 }}>{kpi.value}</div>
                      <div style={{ fontSize: '0.72rem', color: 'rgba(255,255,255,0.75)', marginTop: '3px', fontWeight: 700 }}>{kpi.label}</div>
                    </div>
                  ))}
                </div>
              </div>
              {/* ── Selection of University Section (الجامعات الشريكة للاختيار) ── */}
              <div style={{
                padding: '20px 28px 16px',
                borderBottom: '1px solid rgba(255,255,255,0.08)',
                background: 'rgba(0,0,0,0.18)'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '14px', flexWrap: 'wrap', gap: '10px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <span style={{ fontSize: '1.4rem' }}>🏛️</span>
                    <div>
                      <div style={{ fontSize: '1.05rem', fontWeight: 900, color: '#fef08a' }}>
                        اختر الجامعة لعرض أسماء الكوادر (أطباء ومدربين):
                      </div>
                      <div style={{ fontSize: '0.78rem', color: 'rgba(255,255,255,0.55)', marginTop: '2px' }}>
                        {selectedUniStatsName 
                          ? `الجامعة المختارة حالياً: ${selectedUniStatsName === 'all' ? 'جميع الجامعات الشريكة' : selectedUniStatsName}`
                          : 'اضغط على بطاقة أي جامعة لإظهار أسماء وتفاصيل الأطباء والمدربين التابعين لها'}
                      </div>
                    </div>
                  </div>

                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    {selectedUniStatsName && (
                      <button
                        onClick={() => {
                          setSelectedUniStatsName(null);
                          setUniStatsSearch('');
                        }}
                        style={{
                          background: 'rgba(239, 68, 68, 0.15)',
                          border: '1px solid rgba(239, 68, 68, 0.4)',
                          color: '#fca5a5',
                          padding: '6px 14px',
                          borderRadius: '10px',
                          fontSize: '0.8rem',
                          fontWeight: 800,
                          cursor: 'pointer',
                          fontFamily: 'Tajawal, sans-serif',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '6px',
                          transition: 'all 0.2s'
                        }}
                      >
                        <span>✕ إلغاء التحديد (إخفاء الأسماء)</span>
                      </button>
                    )}
                    <button
                      onClick={() => {
                        setSelectedUniStatsName('all');
                        setUniStatsSearch('');
                      }}
                      style={{
                        background: selectedUniStatsName === 'all' ? 'linear-gradient(135deg, #78350f, #d97706)' : 'rgba(255,255,255,0.06)',
                        border: selectedUniStatsName === 'all' ? '1.5px solid #ffd700' : '1px solid rgba(255,255,255,0.15)',
                        color: selectedUniStatsName === 'all' ? '#ffffff' : 'rgba(255,255,255,0.7)',
                        padding: '6px 14px',
                        borderRadius: '10px',
                        fontSize: '0.8rem',
                        fontWeight: 800,
                        cursor: 'pointer',
                        fontFamily: 'Tajawal, sans-serif',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '6px',
                        boxShadow: selectedUniStatsName === 'all' ? '0 0 12px rgba(255,215,0,0.3)' : 'none',
                        transition: 'all 0.2s'
                      }}
                    >
                      <span>🌐 عرض جميع الجامعات</span>
                    </button>
                  </div>
                </div>

                {/* University Selection Cards Grid */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '12px' }}>
                  {uniEntries.map(([uniName, data]) => {
                    const isSelected = selectedUniStatsName === uniName;
                    const color = getUniColor(uniName);
                    const icon = uniName.includes('خليل') ? '🏛️' : uniName.includes('بوليتكنك') ? '🔬' : uniName.includes('ذكية') ? '💡' : '🎓';
                    const docCount = data.doctors.length;
                    const nurseCount = data.nursing.length;
                    const totalStaff = docCount + nurseCount;
                    const activeCount = [...data.doctors, ...data.nursing].filter(s => s._status === 'active').length;

                    return (
                      <div
                        key={uniName}
                        onClick={() => {
                          setSelectedUniStatsName(isSelected ? null : uniName);
                          setUniStatsSearch('');
                        }}
                        style={{
                          background: isSelected 
                            ? `linear-gradient(135deg, ${color}35 0%, rgba(15,23,42,0.95) 100%)` 
                            : 'rgba(255,255,255,0.04)',
                          border: isSelected ? `2.5px solid ${color}` : '1.5px solid rgba(255,255,255,0.1)',
                          borderRadius: '16px',
                          padding: '16px 18px',
                          cursor: 'pointer',
                          transition: 'all 0.25s ease',
                          transform: isSelected ? 'translateY(-2px)' : 'none',
                          boxShadow: isSelected ? `0 0 25px ${color}55, 0 6px 15px rgba(0,0,0,0.4)` : 'none',
                          position: 'relative',
                          overflow: 'hidden'
                        }}
                        onMouseOver={(e) => {
                          if (!isSelected) {
                            e.currentTarget.style.borderColor = `${color}99`;
                            e.currentTarget.style.background = 'rgba(255,255,255,0.08)';
                          }
                        }}
                        onMouseOut={(e) => {
                          if (!isSelected) {
                            e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
                            e.currentTarget.style.background = 'rgba(255,255,255,0.04)';
                          }
                        }}
                      >
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                          <span style={{ fontSize: '1.8rem' }}>{icon}</span>
                          {isSelected ? (
                            <span style={{
                              background: color,
                              color: '#ffffff',
                              padding: '3px 10px',
                              borderRadius: '20px',
                              fontSize: '0.74rem',
                              fontWeight: 900,
                              display: 'flex',
                              alignItems: 'center',
                              gap: '4px'
                            }}>
                              ✓ محددة والأسماء معروضة
                            </span>
                          ) : (
                            <span style={{
                              background: 'rgba(255,255,255,0.08)',
                              color: 'rgba(255,255,255,0.7)',
                              padding: '3px 10px',
                              borderRadius: '20px',
                              fontSize: '0.72rem',
                              fontWeight: 700
                            }}>
                              اضغط لإظهار الأسماء 👈
                            </span>
                          )}
                        </div>

                        <div style={{ fontSize: '1.05rem', fontWeight: 900, color: isSelected ? '#ffffff' : '#f1f5f9', marginBottom: '6px' }}>
                          {uniName}
                        </div>

                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', fontSize: '0.78rem', color: 'rgba(255,255,255,0.75)' }}>
                          <span style={{ color: '#93c5fd', fontWeight: 700 }}>🩺 أطباء: {docCount}</span>
                          <span>•</span>
                          <span style={{ color: '#6ee7b7', fontWeight: 700 }}>🏥 مدربين: {nurseCount}</span>
                          <span>•</span>
                          <span style={{ color: '#86efac', fontWeight: 800 }}>🟢 نشط: {activeCount}</span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* ── Condition: If NO university selected, show helpful prompt (Names do NOT appear yet) ── */}
              {!selectedUniStatsName ? (
                <div style={{
                  margin: '24px 28px 36px',
                  padding: '50px 24px',
                  background: 'linear-gradient(135deg, rgba(255,215,0,0.04) 0%, rgba(255,255,255,0.02) 100%)',
                  borderRadius: '20px',
                  border: '1.5px dashed rgba(255,215,0,0.35)',
                  textAlign: 'center'
                }}>
                  <div style={{ fontSize: '3.5rem', marginBottom: '14px' }}>👆</div>
                  <div style={{ fontSize: '1.3rem', fontWeight: 900, color: '#fef08a' }}>
                    الرجاء تحديد الجامعة الشريكة أولاً من البطاقات أعلاه
                  </div>
                  <div style={{ fontSize: '0.92rem', color: 'rgba(255,255,255,0.7)', marginTop: '8px', maxWidth: '560px', margin: '8px auto 20px', lineHeight: 1.6 }}>
                    لن تظهر كشوفات الأسماء إلا بعد اختيار الجامعة المطلوبة (جامعة بوليتكنك فلسطين، جامعة الخليل، أو الكلية الذكية) لتسهيل القراءة وتجنب تداخل البيانات.
                  </div>
                  <div style={{ display: 'flex', gap: '10px', justifyContent: 'center', flexWrap: 'wrap' }}>
                    {uniEntries.map(([uniName]) => (
                      <button
                        key={uniName}
                        onClick={() => setSelectedUniStatsName(uniName)}
                        style={{
                          background: 'rgba(255,255,255,0.08)',
                          border: `1px solid ${getUniColor(uniName)}99`,
                          color: '#ffffff',
                          padding: '8px 16px',
                          borderRadius: '12px',
                          fontSize: '0.85rem',
                          fontWeight: 800,
                          cursor: 'pointer',
                          fontFamily: 'Tajawal, sans-serif'
                        }}
                      >
                        {uniName.includes('خليل') ? '🏛️ الخليل' : uniName.includes('بوليتكنك') ? '🔬 البوليتكنك' : uniName.includes('ذكية') ? '💡 الكلية الذكية' : uniName}
                      </button>
                    ))}
                  </div>
                </div>
              ) : (
                /* ── Condition: University Selected -> Filter Controls & Names List ── */
                <>
                  {/* Filter Tabs & Search Controls */}
                  <div style={{
                    padding: '16px 28px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    flexWrap: 'wrap',
                    gap: '12px',
                    borderBottom: '1px solid rgba(255,255,255,0.08)'
                  }}>
                    <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                      {([
                        { id: 'all', label: 'الكل', icon: '📊' },
                        { id: 'doctors', label: 'الأطباء المتعاقدون', icon: '🩺' },
                        { id: 'nursing', label: 'المدربون السريريون والمشرفون', icon: '🏥' }
                      ] as { id: 'all'|'doctors'|'nursing'; label: string; icon: string }[]).map(tab => (
                        <button
                          key={tab.id}
                          onClick={() => setUniStatsTab(tab.id)}
                          style={{
                            padding: '7px 16px', borderRadius: '10px', fontSize: '0.85rem',
                            fontFamily: 'Tajawal, sans-serif', fontWeight: 800, cursor: 'pointer',
                            border: uniStatsTab === tab.id ? '1.5px solid rgba(255,215,0,0.7)' : '1px solid rgba(255,255,255,0.1)',
                            background: uniStatsTab === tab.id
                              ? 'linear-gradient(135deg, #78350f, #d97706)'
                              : 'rgba(255,255,255,0.05)',
                            color: uniStatsTab === tab.id ? '#fff' : 'rgba(255,255,255,0.65)',
                            boxShadow: uniStatsTab === tab.id ? '0 0 12px rgba(255,215,0,0.3)' : 'none',
                            transition: 'all 0.25s ease'
                          }}
                        >{tab.icon} {tab.label}</button>
                      ))}
                    </div>

                    {/* Search Input for staff within selected university */}
                    <div style={{ position: 'relative', minWidth: '240px', flex: '1 1 240px', maxWidth: '340px' }}>
                      <input
                        type="text"
                        value={uniStatsSearch}
                        onChange={(e) => setUniStatsSearch(e.target.value)}
                        placeholder="🔍 بحث بالاسم أو التخصص..."
                        style={{
                          width: '100%',
                          padding: '7px 14px',
                          background: 'rgba(255,255,255,0.08)',
                          border: '1px solid rgba(255,255,255,0.2)',
                          borderRadius: '10px',
                          color: '#fff',
                          fontSize: '0.85rem',
                          fontFamily: 'Tajawal, sans-serif',
                          outline: 'none'
                        }}
                      />
                      {uniStatsSearch && (
                        <button
                          onClick={() => setUniStatsSearch('')}
                          style={{
                            position: 'absolute',
                            left: '8px',
                            top: '50%',
                            transform: 'translateY(-50%)',
                            background: 'transparent',
                            border: 'none',
                            color: '#94a3b8',
                            cursor: 'pointer',
                            fontSize: '0.8rem'
                          }}
                        >✕</button>
                      )}
                    </div>
                  </div>

                  {/* ── Per-University Names Cards ── */}
                  <div style={{ padding: '20px 24px 28px', display: 'flex', flexDirection: 'column', gap: '18px' }}>
                    {(() => {
                      const filteredEntries = selectedUniStatsName === 'all'
                        ? uniEntries
                        : uniEntries.filter(([name]) => name === selectedUniStatsName);

                      if (filteredEntries.length === 0) {
                        return (
                          <div style={{ textAlign: 'center', color: 'rgba(255,255,255,0.4)', padding: '40px', fontSize: '1rem' }}>
                            لا توجد بيانات متاحة
                          </div>
                        );
                      }

                      return filteredEntries.map(([uniName, data]) => {
                        const searchLower = uniStatsSearch.trim().toLowerCase();
                        const filterFn = (s: any) => {
                          if (!searchLower) return true;
                          return (s.name || '').toLowerCase().includes(searchLower) ||
                            (s.specialty || '').toLowerCase().includes(searchLower) ||
                            (s.nursingSpecialty || '').toLowerCase().includes(searchLower) ||
                            (s.phone || '').includes(searchLower) ||
                            (s.idNumber || '').includes(searchLower);
                        };

                        const relevantDocs = (uniStatsTab === 'nursing' ? [] : data.doctors).filter(filterFn);
                        const relevantNursing = (uniStatsTab === 'doctors' ? [] : data.nursing).filter(filterFn);
                        const total = relevantDocs.length + relevantNursing.length;

                        const activeCount = [...relevantDocs, ...relevantNursing].filter(s => s._status === 'active').length;
                        const completedCount = [...relevantDocs, ...relevantNursing].filter(s => s._status === 'completed').length;
                        const upcomingCount = [...relevantDocs, ...relevantNursing].filter(s => s._status === 'upcoming').length;
                        const isPriority = PRIORITY_UNIS.includes(uniName);
                        const color = getUniColor(uniName);

                        return (
                          <div key={uniName} style={{
                            background: isPriority
                              ? `linear-gradient(135deg, rgba(${color === '#dc2626' ? '220,38,38' : color === '#2563eb' ? '37,99,235' : color === '#059669' ? '5,150,105' : '124,58,237'},0.12) 0%, rgba(15,23,42,0.9) 100%)`
                              : 'rgba(255,255,255,0.04)',
                            borderRadius: '16px',
                            border: isPriority ? `1.5px solid ${color}55` : '1px solid rgba(255,255,255,0.1)',
                            overflow: 'hidden',
                            boxShadow: isPriority ? `0 4px 20px ${color}22` : 'none'
                          }}>
                            {/* Card Header */}
                            <div style={{
                              padding: '14px 20px',
                              borderBottom: '1px solid rgba(255,255,255,0.07)',
                              display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap'
                            }}>
                              <div style={{
                                width: '42px', height: '42px', borderRadius: '12px',
                                background: isPriority ? color : '#334155',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                fontSize: '1.3rem', flexShrink: 0,
                                boxShadow: isPriority ? `0 0 12px ${color}55` : 'none'
                              }}>
                                {uniName.includes('خليل') ? '🏛️' : uniName.includes('بوليتكنك') ? '🔬' : uniName.includes('ذكية') ? '💡' : '🎓'}
                              </div>
                              <div style={{ flex: 1 }}>
                                <div style={{ fontSize: '1.1rem', fontWeight: 900, color: isPriority ? '#fde68a' : '#e2e8f0' }}>
                                  {uniName}
                                  {isPriority && <span style={{ marginRight: '8px', fontSize: '0.7rem', background: 'rgba(255,215,0,0.2)', border: '1px solid rgba(255,215,0,0.4)', color: '#fbbf24', borderRadius: '6px', padding: '2px 7px' }}>جامعة متعاقد معها رئيسية</span>}
                                </div>
                                <div style={{ fontSize: '0.8rem', color: 'rgba(255,255,255,0.5)', marginTop: '2px' }}>
                                  إجمالي المعروض: {total} شخص (أطباء: {relevantDocs.length} • مدربين: {relevantNursing.length})
                                </div>
                              </div>
                              {/* Mini KPIs & Add Staff Button */}
                              <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'flex-start' }}>
                                <span style={{ background: 'rgba(16,185,129,0.15)', border: '1px solid rgba(16,185,129,0.35)', color: '#6ee7b7', borderRadius: '8px', padding: '4px 10px', fontSize: '0.78rem', fontWeight: 800 }}>🟢 {activeCount} نشط</span>
                                <span style={{ background: 'rgba(99,102,241,0.15)', border: '1px solid rgba(99,102,241,0.35)', color: '#a5b4fc', borderRadius: '8px', padding: '4px 10px', fontSize: '0.78rem', fontWeight: 800 }}>✅ {completedCount} مكتمل</span>
                                {upcomingCount > 0 && <span style={{ background: 'rgba(56,189,248,0.15)', border: '1px solid rgba(56,189,248,0.35)', color: '#7dd3fc', borderRadius: '8px', padding: '4px 10px', fontSize: '0.78rem', fontWeight: 800 }}>🔵 {upcomingCount} قادم</span>}
                                <button
                                  type="button"
                                  onClick={() => handleOpenAddStaff(uniName)}
                                  style={{
                                    display: 'inline-flex', alignItems: 'center', gap: '6px',
                                    background: 'linear-gradient(135deg, #10b981, #059669)',
                                    border: '1px solid rgba(16,185,129,0.5)',
                                    color: '#ffffff',
                                    borderRadius: '8px',
                                    padding: '5px 12px',
                                    fontSize: '0.78rem',
                                    fontWeight: 800,
                                    cursor: 'pointer',
                                    boxShadow: '0 2px 8px rgba(16,185,129,0.3)',
                                    fontFamily: 'Tajawal, sans-serif'
                                  }}
                                  title={`إضافة كادر طبي أو تدريبي لـ ${uniName}`}
                                >
                                  ➕ إضافة كادر لـ {uniName}
                                </button>
                              </div>
                            </div>

                            {/* Sub-sections: Doctors + Nursing Names */}
                            {total === 0 ? (
                              <div style={{ padding: '30px 20px', textAlign: 'center', color: 'rgba(255,255,255,0.4)', fontSize: '0.9rem' }}>
                                لا توجد أسماء مطابقة لخيارات الفلترة أو البحث
                              </div>
                            ) : (
                              <div style={{ display: 'grid', gridTemplateColumns: relevantDocs.length > 0 && relevantNursing.length > 0 ? '1fr 1fr' : '1fr', gap: '0' }}>
                                {relevantDocs.length > 0 && (
                                  <div style={{ padding: '16px 20px', borderLeft: relevantNursing.length > 0 ? '1px solid rgba(255,255,255,0.07)' : 'none' }}>
                                    <div style={{ fontSize: '0.85rem', fontWeight: 800, color: '#93c5fd', marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                                      <span>🩺</span> الأطباء المتعاقدون ({relevantDocs.length})
                                    </div>
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                      {relevantDocs.map((doc, idx) => (
                                        <div key={idx} style={{
                                          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap',
                                          padding: '9px 12px', borderRadius: '10px',
                                          background: doc._status === 'active' ? 'rgba(16,185,129,0.08)' : doc._status === 'completed' ? 'rgba(99,102,241,0.08)' : 'rgba(56,189,248,0.08)',
                                          border: `1px solid ${doc._status === 'active' ? 'rgba(16,185,129,0.25)' : doc._status === 'completed' ? 'rgba(99,102,241,0.25)' : 'rgba(56,189,248,0.25)'}`,
                                          transition: 'all 0.15s ease'
                                        }}>
                                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', flex: '1 1 160px' }}>
                                            <span style={{ fontSize: '0.75rem' }}>{doc._status === 'active' ? '🟢' : doc._status === 'completed' ? '✅' : '🔵'}</span>
                                            <span style={{ fontSize: '0.86rem', color: '#f8fafc', fontWeight: 800 }}>{doc.name || '—'}</span>
                                            {doc.specialty && (
                                              <span style={{ fontSize: '0.7rem', color: '#93c5fd', background: 'rgba(147,197,253,0.12)', padding: '2px 8px', borderRadius: '6px', whiteSpace: 'nowrap', fontWeight: 700 }}>{doc.specialty}</span>
                                            )}
                                            {doc.phone && (
                                              <a href={`tel:${doc.phone}`} style={{ fontSize: '0.7rem', color: '#a7f3d0', textDecoration: 'none', background: 'rgba(16,185,129,0.1)', padding: '2px 8px', borderRadius: '6px', whiteSpace: 'nowrap', direction: 'ltr' }} title="اتصال">
                                                📞 {doc.phone}
                                              </a>
                                            )}
                                            {(doc.graduatedUniversity || doc.university) && (doc.graduatedUniversity || doc.university) !== uniName && (
                                              <span style={{ fontSize: '0.68rem', color: '#94a3b8', whiteSpace: 'nowrap' }} title="جامعة التخرج الأصلية">
                                                خريج: {doc.graduatedUniversity || doc.university}
                                              </span>
                                            )}
                                          </div>

                                          {/* Faculty Movement & Edit Actions */}
                                          <div style={{ display: 'flex', alignItems: 'center', gap: '5px', flexShrink: 0 }}>
                                            {/* Quick Dropdown: Move in 1 Click */}
                                            <select
                                              value=""
                                              onChange={(e) => {
                                                const targetUni = e.target.value;
                                                if (targetUni) {
                                                  handleDirectMoveStaff(doc, uniName, targetUni);
                                                }
                                              }}
                                              style={{
                                                background: 'rgba(15, 23, 42, 0.85)',
                                                border: '1px solid rgba(56, 189, 248, 0.45)',
                                                color: '#7dd3fc',
                                                padding: '3px 8px',
                                                borderRadius: '7px',
                                                fontSize: '0.72rem',
                                                fontWeight: 700,
                                                cursor: 'pointer',
                                                fontFamily: 'Tajawal, sans-serif',
                                                outline: 'none'
                                              }}
                                              title={`نقل سريع ومباشر لـ ${doc.name} إلى كلية/جامعة أخرى بنقرة واحدة`}
                                            >
                                              <option value="" disabled>🔁 نقل سريع إلى...</option>
                                              {[
                                                'جامعة بوليتكنك فلسطين',
                                                'جامعة الخليل',
                                                'الكلية الذكية الجامعية للتعليم الحديث',
                                                'جامعة القدس (أبو ديس)',
                                                'جامعة النجاح الوطنية',
                                                'الجامعة العربية الأمريكية'
                                              ].filter(u => u !== uniName).map(u => (
                                                <option key={u} value={u} style={{ background: '#0f172a', color: '#fff' }}>
                                                  {u}
                                                </option>
                                              ))}
                                            </select>

                                            {/* Advanced Move Modal Button */}
                                            <button
                                              type="button"
                                              onClick={(e) => {
                                                e.stopPropagation();
                                                handleOpenMoveStaff(doc, uniName);
                                              }}
                                              style={{
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                gap: '4px',
                                                background: 'linear-gradient(135deg, rgba(56,189,248,0.25), rgba(14,165,233,0.35))',
                                                border: '1px solid rgba(56,189,248,0.5)',
                                                color: '#38bdf8',
                                                padding: '3px 8px',
                                                borderRadius: '7px',
                                                fontSize: '0.72rem',
                                                fontWeight: 800,
                                                cursor: 'pointer',
                                                whiteSpace: 'nowrap',
                                                fontFamily: 'Tajawal, sans-serif',
                                                boxShadow: '0 2px 6px rgba(56,189,248,0.2)',
                                                transition: 'all 0.15s ease'
                                              }}
                                              title={`خيارات نقل متقدمة لـ ${doc.name}`}
                                            >
                                              <span>🔁</span> نقل الكلية
                                            </button>

                                            {/* Edit Staff Button */}
                                            <button
                                              type="button"
                                              onClick={(e) => {
                                                e.stopPropagation();
                                                handleOpenEditStaff(doc, uniName);
                                              }}
                                              style={{
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                gap: '2px',
                                                background: 'rgba(234,179,8,0.15)',
                                                border: '1px solid rgba(234,179,8,0.35)',
                                                color: '#fde047',
                                                padding: '3px 7px',
                                                borderRadius: '7px',
                                                fontSize: '0.72rem',
                                                fontWeight: 800,
                                                cursor: 'pointer',
                                                whiteSpace: 'nowrap',
                                                fontFamily: 'Tajawal, sans-serif'
                                              }}
                                              title={`تعديل بيانات ${doc.name}`}
                                            >
                                              <span>✏️</span>
                                            </button>
                                          </div>
                                        </div>
                                      ))}
                                    </div>
                                  </div>
                                )}
                                {relevantNursing.length > 0 && (
                                  <div style={{ padding: '16px 20px' }}>
                                    <div style={{ fontSize: '0.85rem', fontWeight: 800, color: '#6ee7b7', marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                                      <span>🏥</span> المدربون السريريون والمشرفون ({relevantNursing.length})
                                    </div>
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                      {relevantNursing.map((trainer, idx) => (
                                        <div key={idx} style={{
                                          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap',
                                          padding: '9px 12px', borderRadius: '10px',
                                          background: trainer._status === 'active' ? 'rgba(16,185,129,0.08)' : trainer._status === 'completed' ? 'rgba(99,102,241,0.08)' : 'rgba(56,189,248,0.08)',
                                          border: `1px solid ${trainer._status === 'active' ? 'rgba(16,185,129,0.25)' : trainer._status === 'completed' ? 'rgba(99,102,241,0.25)' : 'rgba(56,189,248,0.25)'}`,
                                          transition: 'all 0.15s ease'
                                        }}>
                                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', flex: '1 1 160px' }}>
                                            <span style={{ fontSize: '0.75rem' }}>{trainer._status === 'active' ? '🟢' : trainer._status === 'completed' ? '✅' : '🔵'}</span>
                                            <span style={{ fontSize: '0.86rem', color: '#f8fafc', fontWeight: 800 }}>{trainer.name || '—'}</span>
                                            {trainer.nursingSpecialty && (
                                              <span style={{ fontSize: '0.7rem', color: '#6ee7b7', background: 'rgba(110,231,183,0.12)', padding: '2px 8px', borderRadius: '6px', whiteSpace: 'nowrap', fontWeight: 700 }}>{trainer.nursingSpecialty}</span>
                                            )}
                                            {trainer.phone && (
                                              <a href={`tel:${trainer.phone}`} style={{ fontSize: '0.7rem', color: '#a7f3d0', textDecoration: 'none', background: 'rgba(16,185,129,0.1)', padding: '2px 8px', borderRadius: '6px', whiteSpace: 'nowrap', direction: 'ltr' }} title="اتصال">
                                                📞 {trainer.phone}
                                              </a>
                                            )}
                                            {(trainer.graduatedUniversity || trainer.university) && (trainer.graduatedUniversity || trainer.university) !== uniName && (
                                              <span style={{ fontSize: '0.68rem', color: '#94a3b8', whiteSpace: 'nowrap' }} title="جامعة التخرج الأصلية">
                                                خريج: {trainer.graduatedUniversity || trainer.university}
                                              </span>
                                            )}
                                          </div>

                                          {/* Faculty Movement & Edit Actions */}
                                          <div style={{ display: 'flex', alignItems: 'center', gap: '5px', flexShrink: 0 }}>
                                            {/* Quick Dropdown: Move in 1 Click */}
                                            <select
                                              value=""
                                              onChange={(e) => {
                                                const targetUni = e.target.value;
                                                if (targetUni) {
                                                  handleDirectMoveStaff(trainer, uniName, targetUni);
                                                }
                                              }}
                                              style={{
                                                background: 'rgba(15, 23, 42, 0.85)',
                                                border: '1px solid rgba(56, 189, 248, 0.45)',
                                                color: '#7dd3fc',
                                                padding: '3px 8px',
                                                borderRadius: '7px',
                                                fontSize: '0.72rem',
                                                fontWeight: 700,
                                                cursor: 'pointer',
                                                fontFamily: 'Tajawal, sans-serif',
                                                outline: 'none'
                                              }}
                                              title={`نقل سريع ومباشر لـ ${trainer.name} إلى كلية/جامعة أخرى بنقرة واحدة`}
                                            >
                                              <option value="" disabled>🔁 نقل سريع إلى...</option>
                                              {[
                                                'جامعة بوليتكنك فلسطين',
                                                'جامعة الخليل',
                                                'الكلية الذكية الجامعية للتعليم الحديث',
                                                'جامعة القدس (أبو ديس)',
                                                'جامعة النجاح الوطنية',
                                                'الجامعة العربية الأمريكية'
                                              ].filter(u => u !== uniName).map(u => (
                                                <option key={u} value={u} style={{ background: '#0f172a', color: '#fff' }}>
                                                  {u}
                                                </option>
                                              ))}
                                            </select>

                                            {/* Advanced Move Modal Button */}
                                            <button
                                              type="button"
                                              onClick={(e) => {
                                                e.stopPropagation();
                                                handleOpenMoveStaff(trainer, uniName);
                                              }}
                                              style={{
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                gap: '4px',
                                                background: 'linear-gradient(135deg, rgba(56,189,248,0.25), rgba(14,165,233,0.35))',
                                                border: '1px solid rgba(56,189,248,0.5)',
                                                color: '#38bdf8',
                                                padding: '3px 8px',
                                                borderRadius: '7px',
                                                fontSize: '0.72rem',
                                                fontWeight: 800,
                                                cursor: 'pointer',
                                                whiteSpace: 'nowrap',
                                                fontFamily: 'Tajawal, sans-serif',
                                                boxShadow: '0 2px 6px rgba(56,189,248,0.2)',
                                                transition: 'all 0.15s ease'
                                              }}
                                              title={`خيارات نقل متقدمة لـ ${trainer.name}`}
                                            >
                                              <span>🔁</span> نقل الكلية
                                            </button>

                                            {/* Edit Staff Button */}
                                            <button
                                              type="button"
                                              onClick={(e) => {
                                                e.stopPropagation();
                                                handleOpenEditStaff(trainer, uniName);
                                              }}
                                              style={{
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                gap: '2px',
                                                background: 'rgba(234,179,8,0.15)',
                                                border: '1px solid rgba(234,179,8,0.35)',
                                                color: '#fde047',
                                                padding: '3px 7px',
                                                borderRadius: '7px',
                                                fontSize: '0.72rem',
                                                fontWeight: 800,
                                                cursor: 'pointer',
                                                whiteSpace: 'nowrap',
                                                fontFamily: 'Tajawal, sans-serif'
                                              }}
                                              title={`تعديل بيانات ${trainer.name}`}
                                            >
                                              <span>✏️</span>
                                            </button>
                                          </div>
                                        </div>
                                      ))}
                                    </div>
                                  </div>
                                )}
                              </div>
                            )}
                          </div>
                        );
                      });
                    })()}
                  </div>
                </>
              )}

              {/* ══════════ Faculty Move Modal ══════════ */}
              {showFacultyMoveModal && moveTargetStaff && (
                <div style={{
                  position: 'fixed', inset: 0, zIndex: 100010,
                  background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(8px)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  padding: '16px'
                }} onClick={e => e.target === e.currentTarget && setShowFacultyMoveModal(false)}>
                  <div style={{
                    background: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
                    border: '1.5px solid rgba(56,189,248,0.4)',
                    borderRadius: '20px',
                    maxWidth: '560px', width: '100%',
                    padding: '24px 28px',
                    color: '#fff',
                    boxShadow: '0 25px 60px rgba(0,0,0,0.7), 0 0 30px rgba(56,189,248,0.2)',
                    fontFamily: 'Tajawal, sans-serif',
                    direction: 'rtl'
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '12px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                        <span style={{ fontSize: '1.5rem', background: 'rgba(56,189,248,0.15)', padding: '6px 10px', borderRadius: '12px', border: '1px solid rgba(56,189,248,0.3)' }}>🔁</span>
                        <div>
                          <h3 style={{ margin: 0, fontSize: '1.15rem', fontWeight: 900, color: '#f8fafc' }}>
                            نقل أو ارتباط الكادر بين الكليات والجامعات
                          </h3>
                          <div style={{ fontSize: '0.78rem', color: '#94a3b8', marginTop: '2px' }}>
                            تحديد الجامعة أو الكلية الشريكة التابع لها الكادر وتحديث السحابة فوراً
                          </div>
                        </div>
                      </div>
                      <button
                        type="button"
                        onClick={() => setShowFacultyMoveModal(false)}
                        style={{ background: 'transparent', border: 'none', color: '#94a3b8', fontSize: '1.3rem', cursor: 'pointer', padding: '4px 8px' }}
                      >✕</button>
                    </div>

                    <div style={{
                      background: 'rgba(255,255,255,0.04)',
                      border: '1px solid rgba(255,255,255,0.1)',
                      borderRadius: '12px',
                      padding: '12px 16px',
                      marginBottom: '18px',
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '8px'
                    }}>
                      <div>
                        <div style={{ fontSize: '0.95rem', fontWeight: 900, color: '#38bdf8' }}>
                          👤 {moveTargetStaff.name || 'بدون اسم'}
                        </div>
                        <div style={{ fontSize: '0.78rem', color: '#94a3b8', marginTop: '3px' }}>
                          {moveTargetStaff.specialty || moveTargetStaff.nursingSpecialty || 'كادر طبي / تدريبي'}
                          {moveTargetStaff.phone ? ` • 📞 ${moveTargetStaff.phone}` : ''}
                        </div>
                      </div>
                      <div style={{
                        background: 'rgba(234,179,8,0.15)',
                        border: '1px solid rgba(234,179,8,0.35)',
                        color: '#fde047',
                        padding: '4px 10px',
                        borderRadius: '8px',
                        fontSize: '0.75rem',
                        fontWeight: 800
                      }}>
                        الكلية الحالية: {moveCurrentUni}
                      </div>
                    </div>

                    <div style={{ marginBottom: '18px' }}>
                      <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '8px' }}>
                        🎯 اختر الكلية أو الجامعة الشريكة الجديدة:
                      </label>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '10px' }}>
                        {[
                          'جامعة بوليتكنك فلسطين',
                          'جامعة الخليل',
                          'الكلية الذكية الجامعية للتعليم الحديث',
                          'جامعة القدس (أبو ديس)',
                          'جامعة النجاح الوطنية',
                          'الجامعة العربية الأمريكية'
                        ].map(u => (
                          <div
                            key={u}
                            style={{
                              padding: '8px 12px',
                              borderRadius: '10px',
                              border: moveSelectedNewUni === u ? '1.5px solid #38bdf8' : '1px solid rgba(255,255,255,0.1)',
                              background: moveSelectedNewUni === u ? 'rgba(56,189,248,0.2)' : 'rgba(255,255,255,0.04)',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'space-between',
                              gap: '6px',
                              cursor: 'pointer',
                              transition: 'all 0.2s ease'
                            }}
                            onClick={() => { setMoveSelectedNewUni(u); setMoveCustomUniText(''); }}
                          >
                            <span style={{ fontSize: '0.82rem', fontWeight: 800, color: moveSelectedNewUni === u ? '#38bdf8' : '#e2e8f0' }}>
                              {moveSelectedNewUni === u ? '✓ ' : '• '}{u}
                            </span>
                            {u !== moveCurrentUni && (
                              <button
                                type="button"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setMoveSelectedNewUni(u);
                                  setMoveCustomUniText('');
                                  handleDirectMoveStaff(moveTargetStaff, moveCurrentUni, u);
                                  setShowFacultyMoveModal(false);
                                }}
                                style={{
                                  background: 'linear-gradient(135deg, #0284c7, #0ea5e9)',
                                  border: 'none',
                                  color: '#fff',
                                  padding: '3px 8px',
                                  borderRadius: '6px',
                                  fontSize: '0.72rem',
                                  fontWeight: 800,
                                  cursor: 'pointer',
                                  whiteSpace: 'nowrap',
                                  fontFamily: 'Tajawal, sans-serif',
                                  boxShadow: '0 2px 6px rgba(14,165,233,0.3)'
                                }}
                                title={`نقل فوري ومباشر إلى ${u}`}
                              >
                                نقل فوري ↵
                              </button>
                            )}
                          </div>
                        ))}
                      </div>

                      <div style={{ marginTop: '6px' }}>
                        <button
                          type="button"
                          onClick={() => setMoveSelectedNewUni('custom')}
                          style={{
                            padding: '6px 12px',
                            borderRadius: '8px',
                            fontSize: '0.78rem',
                            fontWeight: 800,
                            cursor: 'pointer',
                            fontFamily: 'Tajawal, sans-serif',
                            border: moveSelectedNewUni === 'custom' ? '1.5px solid #38bdf8' : '1px dashed rgba(255,255,255,0.2)',
                            background: moveSelectedNewUni === 'custom' ? 'rgba(56,189,248,0.15)' : 'transparent',
                            color: moveSelectedNewUni === 'custom' ? '#38bdf8' : '#94a3b8'
                          }}
                        >
                          ✏️ كلية / جامعة أخرى (كتابة يدوية)
                        </button>
                        {moveSelectedNewUni === 'custom' && (
                          <input
                            type="text"
                            value={moveCustomUniText}
                            onChange={e => setMoveCustomUniText(e.target.value)}
                            placeholder="اكتب اسم الجامعة أو الكلية الجديدة..."
                            style={{
                              width: '100%', marginTop: '8px',
                              padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)',
                              border: '1.5px solid #38bdf8',
                              borderRadius: '10px',
                              color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                            autoFocus
                          />
                        )}
                      </div>
                    </div>

                    <div style={{ marginBottom: '22px', background: 'rgba(255,255,255,0.03)', padding: '12px 14px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.07)' }}>
                      <div style={{ fontSize: '0.82rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '8px' }}>
                        ⚙️ نمط النقل والارتباط:
                      </div>
                      <div style={{ display: 'flex', gap: '14px', flexWrap: 'wrap' }}>
                        <label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.8rem', cursor: 'pointer', color: moveMode === 'replace' ? '#38bdf8' : '#94a3b8', fontWeight: moveMode === 'replace' ? 800 : 500 }}>
                          <input
                            type="radio"
                            name="moveFacultyMode"
                            checked={moveMode === 'replace'}
                            onChange={() => setMoveMode('replace')}
                          />
                          استبدال الكلية الحالية بالجديدة
                        </label>
                        <label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.8rem', cursor: 'pointer', color: moveMode === 'append' ? '#38bdf8' : '#94a3b8', fontWeight: moveMode === 'append' ? 800 : 500 }}>
                          <input
                            type="radio"
                            name="moveFacultyMode"
                            checked={moveMode === 'append'}
                            onChange={() => setMoveMode('append')}
                          />
                          إضافة ارتباط جديد (الظهور في الكليتين معاً)
                        </label>
                      </div>
                    </div>

                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '10px' }}>
                      <button
                        type="button"
                        onClick={() => setShowFacultyMoveModal(false)}
                        disabled={isSavingMove}
                        style={{
                          padding: '9px 18px', borderRadius: '10px',
                          background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.15)',
                          color: 'rgba(255,255,255,0.7)', fontSize: '0.85rem', fontWeight: 700,
                          cursor: isSavingMove ? 'not-allowed' : 'pointer', fontFamily: 'Tajawal, sans-serif'
                        }}
                      >
                        إلغاء
                      </button>
                      <button
                        type="button"
                        onClick={handleExecuteMoveFaculty}
                        disabled={isSavingMove}
                        style={{
                          padding: '9px 24px', borderRadius: '10px',
                          background: 'linear-gradient(135deg, #0284c7, #0ea5e9)',
                          border: '1px solid rgba(56,189,248,0.5)',
                          color: '#fff', fontSize: '0.88rem', fontWeight: 900,
                          cursor: isSavingMove ? 'not-allowed' : 'pointer', fontFamily: 'Tajawal, sans-serif',
                          boxShadow: '0 4px 14px rgba(14,165,233,0.4)',
                          display: 'flex', alignItems: 'center', gap: '6px'
                        }}
                      >
                        {isSavingMove ? '⏳ جارٍ النقل والمزامنة...' : '✓ تأكيد النقل والمزامنة'}
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {/* ══════════ Staff Add/Edit Modal ══════════ */}
              {showStaffEditModal && (
                <div style={{
                  position: 'fixed', inset: 0, zIndex: 100010,
                  background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(8px)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  padding: '16px'
                }} onClick={e => e.target === e.currentTarget && setShowStaffEditModal(false)}>
                  <div style={{
                    background: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
                    border: '1.5px solid rgba(234,179,8,0.4)',
                    borderRadius: '20px',
                    maxWidth: '620px', width: '100%',
                    padding: '24px 28px',
                    color: '#fff',
                    boxShadow: '0 25px 60px rgba(0,0,0,0.7), 0 0 30px rgba(234,179,8,0.2)',
                    fontFamily: 'Tajawal, sans-serif',
                    direction: 'rtl',
                    maxHeight: '90vh',
                    overflowY: 'auto'
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '12px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                        <span style={{ fontSize: '1.5rem', background: 'rgba(234,179,8,0.15)', padding: '6px 10px', borderRadius: '12px', border: '1px solid rgba(234,179,8,0.3)' }}>✏️</span>
                        <div>
                          <h3 style={{ margin: 0, fontSize: '1.15rem', fontWeight: 900, color: '#fde047' }}>
                            {editingStaffItem ? 'تعديل بيانات الكادر / الطبيب' : 'إضافة كادر جديد للجامعة الشريكة'}
                          </h3>
                          <div style={{ fontSize: '0.78rem', color: '#94a3b8', marginTop: '2px' }}>
                            تحديث بيانات الكادر في تقرير الجامعات الشريكة وقاعدة بيانات D1
                          </div>
                        </div>
                      </div>
                      <button
                        type="button"
                        onClick={() => setShowStaffEditModal(false)}
                        style={{ background: 'transparent', border: 'none', color: '#94a3b8', fontSize: '1.3rem', cursor: 'pointer', padding: '4px 8px' }}
                      >✕</button>
                    </div>

                    <form onSubmit={handleSaveStaff} style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>الاسم الرباعي *</label>
                          <input
                            type="text"
                            required
                            value={staffFormName}
                            onChange={e => setStaffFormName(e.target.value)}
                            placeholder="مثال: د. أحمد محمد..."
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>رقم الهوية</label>
                          <input
                            type="text"
                            value={staffFormIdNumber}
                            onChange={e => setStaffFormIdNumber(e.target.value)}
                            placeholder="مثال: 405123456"
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          />
                        </div>
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>الصفة / الكادر *</label>
                          <select
                            value={staffFormType}
                            onChange={e => setStaffFormType(e.target.value as 'doctor' | 'trainer')}
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: '#1e293b', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          >
                            <option value="doctor">🩺 طبيب متعاقد</option>
                            <option value="trainer">🏥 مدرب سريري / مشرف</option>
                          </select>
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>الجامعة / الكلية الشريكة *</label>
                          <select
                            value={staffFormUni}
                            onChange={e => setStaffFormUni(e.target.value)}
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: '#1e293b', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          >
                            <option value="جامعة بوليتكنك فلسطين">🔬 جامعة بوليتكنك فلسطين</option>
                            <option value="جامعة الخليل">🏛️ جامعة الخليل</option>
                            <option value="الكلية الذكية الجامعية للتعليم الحديث">💡 الكلية الذكية الجامعية للتعليم الحديث</option>
                            <option value="جامعة القدس (أبو ديس)">🎓 جامعة القدس (أبو ديس)</option>
                            <option value="جامعة النجاح الوطنية">🎓 جامعة النجاح الوطنية</option>
                            <option value="الجامعة العربية الأمريكية">🎓 الجامعة العربية الأمريكية</option>
                          </select>
                        </div>
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>التخصص الطبي / التدريبي</label>
                          <input
                            type="text"
                            value={staffFormSpecialty}
                            onChange={e => setStaffFormSpecialty(e.target.value)}
                            placeholder="مثال: جراحة عامة / تمريض باطني..."
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>رقم الهاتف / الجوال</label>
                          <input
                            type="text"
                            value={staffFormPhone}
                            onChange={e => setStaffFormPhone(e.target.value)}
                            placeholder="مثال: 0599123456"
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          />
                        </div>
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>تاريخ البدء</label>
                          <input
                            type="text"
                            value={staffFormStartDate}
                            onChange={e => setStaffFormStartDate(e.target.value)}
                            placeholder="DD/MM/YYYY"
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>تاريخ الانتهاء</label>
                          <input
                            type="text"
                            value={staffFormEndDate}
                            onChange={e => setStaffFormEndDate(e.target.value)}
                            placeholder="DD/MM/YYYY"
                            style={{
                              width: '100%', padding: '9px 12px',
                              background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                              borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                              fontFamily: 'Tajawal, sans-serif', outline: 'none'
                            }}
                          />
                        </div>
                      </div>

                      <div>
                        <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>حالة الكادر</label>
                        <select
                          value={staffFormStatus}
                          onChange={e => setStaffFormStatus(e.target.value as any)}
                          style={{
                            width: '100%', padding: '9px 12px',
                            background: '#1e293b', border: '1px solid rgba(255,255,255,0.15)',
                            borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                            fontFamily: 'Tajawal, sans-serif', outline: 'none'
                          }}
                        >
                          <option value="auto">🔄 تلقائي (حسب تواريخ العقد/التدريب)</option>
                          <option value="active">🟢 نشط حالياً</option>
                          <option value="completed">✅ مكتمل / منهي</option>
                          <option value="upcoming">🔵 قادم لم يبدأ بعد</option>
                        </select>
                      </div>

                      <div>
                        <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#cbd5e1', marginBottom: '4px' }}>ملاحظات إضافية</label>
                        <textarea
                          value={staffFormNotes}
                          onChange={e => setStaffFormNotes(e.target.value)}
                          rows={2}
                          placeholder="أي ملاحظات أو تفاصيل تعاقد..."
                          style={{
                            width: '100%', padding: '9px 12px',
                            background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.15)',
                            borderRadius: '10px', color: '#fff', fontSize: '0.85rem',
                            fontFamily: 'Tajawal, sans-serif', outline: 'none', resize: 'vertical'
                          }}
                        />
                      </div>

                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '10px', marginTop: '10px' }}>
                        <button
                          type="button"
                          onClick={() => setShowStaffEditModal(false)}
                          style={{
                            padding: '9px 18px', borderRadius: '10px',
                            background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.15)',
                            color: 'rgba(255,255,255,0.7)', fontSize: '0.85rem', fontWeight: 700,
                            cursor: 'pointer', fontFamily: 'Tajawal, sans-serif'
                          }}
                        >
                          إلغاء
                        </button>
                        <button
                          type="submit"
                          style={{
                            padding: '9px 24px', borderRadius: '10px',
                            background: 'linear-gradient(135deg, #d97706, #f59e0b)',
                            border: '1px solid rgba(251,191,36,0.5)',
                            color: '#000', fontSize: '0.88rem', fontWeight: 900,
                            cursor: 'pointer', fontFamily: 'Tajawal, sans-serif',
                            boxShadow: '0 4px 14px rgba(245,158,11,0.4)'
                          }}
                        >
                          ✓ حفظ ومزامنة السحابة
                        </button>
                      </div>
                    </form>
                  </div>
                </div>
              )}

              {/* ── Footer ── */}
              <div style={{
                borderTop: '1px solid rgba(255,215,0,0.2)',
                padding: '14px 28px',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                background: 'rgba(0,0,0,0.3)'
              }}>
                <div style={{ fontSize: '0.78rem', color: 'rgba(255,255,255,0.35)' }}>
                  📅 التقرير مُولَّد في: {new Date().toLocaleDateString('ar-PS', { year: 'numeric', month: 'long', day: 'numeric' })}
                </div>
                <button
                  onClick={() => setShowUniStatsModal(false)}
                  style={{
                    padding: '8px 22px', borderRadius: '10px',
                    background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.15)',
                    color: 'rgba(255,255,255,0.7)', fontFamily: 'Tajawal, sans-serif',
                    fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer'
                  }}
                >إغلاق</button>
              </div>
            </div>
          </div>
        );
      })()}

      {/* Toast */}
      <div className={`toast ${toastMessage ? 'show' : ''}`}>
        {toastMessage}
      </div>
    </div>
  );
}
