'use client';

import React, { useState, useEffect, useMemo } from 'react';

export interface PartnerUniversitiesModalProps {
  isOpen: boolean;
  onClose: () => void;
  studentsData?: { [key: string]: any[] };
  allStatisticalStudents?: any[];
  applications?: any[];
}

export default function PartnerUniversitiesModal({
  isOpen,
  onClose,
  studentsData = {},
  allStatisticalStudents = [],
  applications = []
}: PartnerUniversitiesModalProps) {
  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('');

  // Toast notification
  const [toastMsg, setToastMsg] = useState<string | null>(null);
  const showToast = (msg: string) => {
    setToastMsg(msg);
    setTimeout(() => setToastMsg(null), 3500);
  };

  // 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);
    }
  }, []);

  // ── Normalize ONLY recognized contracted partner 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();

    // Custom universities check first
    for (const cu of customPartnerUnis) {
      if (cu.name && clean.includes(cu.name.trim().toLowerCase())) {
        return cu.name;
      }
    }

    // Exclusion for graduation-only universities
    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, '');

    // Check manual override university first
    const key = s.idNumber || s.name;
    const override = partnerStaffOverrides[key];
    if (override && override.partnerUniversity) {
      const u = override.partnerUniversity.trim();
      if (u) {
        result.add(u);
        return Array.from(result);
      }
    }

    if (s.partnerUniversity) {
      result.add(s.partnerUniversity);
      return Array.from(result);
    }

    // Explicit confirmed mappings
    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);
      }
    };

    checkAndAdd(s.contractedUniversities);
    checkAndAdd(s.contracted_universities);
    checkAndAdd(s.contractedUniversity);
    checkAndAdd(s.contracted_university);
    checkAndAdd(s.previousContractedUniversity);
    checkAndAdd(s.customContractedUniversity);

    return Array.from(result);
  };

  const isContractedDoctorStudent = (s: any) => {
    const dept = (s.department || s.originalDepartment || s.deptLabel || '').trim();
    const folder = (s.folderKey || '').trim();
    const job = (s.crescentJobNature || s.internshipYear || s.studySystem || '').trim();
    const spec = (s.specialty || '').trim();
    const cat = ((s as any).category || (s as any).categoryId || '').trim();
    if (dept.includes('الأطباء المتعاقدون') || dept.includes('contracted_doctors')) return true;
    if (folder.includes('الأطباء المتعاقدون') || folder.includes('contracted_doctors')) return true;
    if (cat.includes('contracted_doctors') || cat.includes('doctor')) return true;
    if (job.includes('طبيب استشاري') || job.includes('طبيب متعاقد') || spec.includes('استشاري') || spec.includes('أخصائي')) return true;
    return false;
  };

  // ── Calculate and combine data ──
  const { uniEntries, grandTotal, grandDoctors, grandNursing, grandActive, grandCompleted, grandUpcoming } = useMemo(() => {
    // 1. Raw contracted doctors
    const rawDocs: any[] = [
      ...(studentsData['الأطباء المتعاقدون'] || []),
      ...allStatisticalStudents.filter(s => isContractedDoctorStudent(s))
    ].filter((s, idx, arr) => arr.findIndex(x => (x.idNumber || x.name) === (s.idNumber || s.name)) === idx);

    // 2. Raw trainers
    const TRAINER_KEYS = [
      'تدريب تمريض الجامعات',
      'مدربي أشعة',
      'مدربي علاج طبيعي',
      'مدربي مختبر',
      'مدربي مختبرات',
      'مدربي صيدلية',
      'مدربي صيدلة',
      'مدربي علاج وظيفي',
      'مدربي تغذية',
      'مدربي هندسة طبية'
    ];

    const rawTrainers: any[] = [];
    TRAINER_KEYS.forEach(k => {
      if (Array.isArray(studentsData[k])) {
        studentsData[k].forEach(s => {
          if (!isContractedDoctorStudent(s)) {
            rawTrainers.push({ ...s, department: s.department || k, deptLabel: s.deptLabel || k });
          }
        });
      }
    });

    allStatisticalStudents.forEach(s => {
      const dept = (s.department || s.originalDepartment || s.deptLabel || '').trim();
      const job = (s.crescentJobNature || s.internshipYear || '').trim();
      if (!isContractedDoctorStudent(s) && (dept.includes('مدرب') || dept.includes('مشرف') || job.includes('مدرب') || job.includes('مشرف') || TRAINER_KEYS.some(k => dept.includes(k)))) {
        rawTrainers.push(s);
      }
    });

    // 3. Also pull from applications if available
    applications.forEach(app => {
      const isUni = app.category === 'training_supervisors_universities' || app.category === 'contracted_doctors' || app.category === 'nursing_trainers' || app.isUniversityApplication;
      if (isUni) {
        const item = {
          name: app.fullName || app.name,
          phone: app.phone,
          idNumber: app.idNumber,
          specialty: app.specialty || app.subSpecialty || app.jobTitle,
          department: app.department || (app.category?.includes('doctor') ? 'الأطباء المتعاقدون' : 'تدريب تمريض الجامعات'),
          contractedUniversity: app.contractedUniversity || app.partnerUniversity || app.university,
          startDate: app.startDate,
          endDate: app.endDate,
          notes: app.notes
        };
        if (isContractedDoctorStudent(item) || app.category?.includes('doctor')) {
          if (!rawDocs.some(x => (x.idNumber && x.idNumber === item.idNumber) || x.name === item.name)) {
            rawDocs.push(item);
          }
        } else {
          if (!rawTrainers.some(x => (x.idNumber && x.idNumber === item.idNumber) || x.name === item.name)) {
            rawTrainers.push(item);
          }
        }
      }
    });

    const dedupTrainers = rawTrainers.filter((s, idx, arr) => arr.findIndex(x => (x.idNumber || x.name) === (s.idNumber || s.name)) === idx);

    // 4. Base list according to tab
    const baseList = uniStatsTab === 'doctors' ? rawDocs
      : uniStatsTab === 'nursing' ? dedupTrainers
      : [...rawDocs, ...dedupTrainers];

    // Filter hidden items
    const nonHidden = baseList.filter(s => {
      const key = s.idNumber || s.name;
      return !hiddenPartnerStaffKeys.includes(key);
    });

    // Map overrides and compute status
    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 formattedStaff = nonHidden.map(s => {
      const key = s.idNumber || s.name;
      const override = partnerStaffOverrides[key] || {};
      const merged = {
        ...s,
        name: override.name || s.name,
        specialty: override.specialty !== undefined ? override.specialty : (s.specialty || s.nursingSpecialty || ''),
        department: override.department !== undefined ? override.department : (s.department || s.deptLabel || ''),
        phone: override.phone !== undefined ? override.phone : (s.phone || ''),
        startDate: override.startDate !== undefined ? override.startDate : (s.startDate || ''),
        endDate: override.endDate !== undefined ? override.endDate : (s.endDate || ''),
        notes: override.notes !== undefined ? override.notes : (s.notes || ''),
        partnerUniversity: override.partnerUniversity || s.partnerUniversity,
        isCustomOverridden: Object.keys(override).length > 0
      };

      let status = 'active';
      if (override.manualStatus && override.manualStatus !== 'auto') {
        status = override.manualStatus;
      } else {
        const start = parseD(merged.startDate);
        const end = parseD(merged.endDate);
        if (start && start > today) status = 'upcoming';
        else if (end && end < today) status = 'completed';
      }

      return { ...merged, _status: status };
    });

    // Merge customPartnerStaff
    const customStaffFiltered = customPartnerStaff.filter(cs => {
      if (hiddenPartnerStaffKeys.includes(cs.id) || hiddenPartnerStaffKeys.includes(cs.name)) return false;
      if (uniStatsTab === 'doctors' && cs.type !== 'doctor') return false;
      if (uniStatsTab === 'nursing' && cs.type !== 'trainer') return false;
      return true;
    }).map(cs => {
      let status = cs.manualStatus || 'active';
      if (!cs.manualStatus || cs.manualStatus === 'auto') {
        const start = parseD(cs.startDate);
        const end = parseD(cs.endDate);
        if (start && start > today) status = 'upcoming';
        else if (end && end < today) status = 'completed';
      }
      return { ...cs, _status: status, isCustomItem: true };
    });

    const allCombined = [...formattedStaff, ...customStaffFiltered];

    // Priority default universities
    const defaultUnis = [
      'جامعة بوليتكنك فلسطين',
      'جامعة الخليل',
      'الكلية الذكية الجامعية للتعليم الحديث'
    ];

    const allUniNames = Array.from(new Set([
      ...defaultUnis,
      ...customPartnerUnis.map(u => u.name)
    ]));

    // Build per-university map
    const uniMap: { [uni: string]: { doctors: any[]; nursing: any[] } } = {};
    allUniNames.forEach(u => {
      uniMap[u] = { doctors: [], nursing: [] };
    });

    allCombined.forEach(s => {
      const unis = getContractedPartnerUnis(s);
      unis.forEach(uni => {
        if (!uniMap[uni]) uniMap[uni] = { doctors: [], nursing: [] };
        const isDoc = s.type === 'doctor' || (s.type === undefined && isContractedDoctorStudent(s));
        if (isDoc) {
          if (!uniMap[uni].doctors.some(x => (x.idNumber && x.idNumber === s.idNumber) || x.name === s.name)) {
            uniMap[uni].doctors.push(s);
          }
        } else {
          if (!uniMap[uni].nursing.some(x => (x.idNumber && x.idNumber === s.idNumber) || x.name === s.name)) {
            uniMap[uni].nursing.push(s);
          }
        }
      });
    });

    const entries = Object.entries(uniMap).sort(([a], [b]) => {
      const ia = defaultUnis.indexOf(a);
      const ib = defaultUnis.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
    let tot = 0, docs = 0, nurses = 0, act = 0, comp = 0, upc = 0;
    const countedStaffIds = new Set<string>();
    entries.forEach(([_, data]) => {
      [...data.doctors, ...data.nursing].forEach(s => {
        const key = s.idNumber || s.id || s.name;
        if (!countedStaffIds.has(key)) {
          countedStaffIds.add(key);
          tot++;
          if (s.type === 'doctor' || isContractedDoctorStudent(s)) docs++;
          else nurses++;
          if (s._status === 'active') act++;
          else if (s._status === 'completed') comp++;
          else if (s._status === 'upcoming') upc++;
        }
      });
    });

    return {
      uniEntries: entries,
      grandTotal: tot,
      grandDoctors: docs,
      grandNursing: nurses,
      grandActive: act,
      grandCompleted: comp,
      grandUpcoming: upc
    };
  }, [studentsData, allStatisticalStudents, applications, uniStatsTab, customPartnerUnis, customPartnerStaff, partnerStaffOverrides, hiddenPartnerStaffKeys]);

  // Handlers for universities
  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}) بنجاح ✓`);
  };

  // Handlers for staff
  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 handleSaveStaff = (e: React.FormEvent) => {
    e.preventDefault();
    if (!staffFormName.trim()) {
      alert('يرجى إدخال اسم الطبيب أو المدرب');
      return;
    }
    if (!staffFormUni.trim()) {
      alert('يرجى اختيار أو إدخال الجامعة الشريكة');
      return;
    }

    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: staffFormUni.trim(),
              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: staffFormUni.trim(),
            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 {}
      }
      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: staffFormUni.trim(),
        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 {}
      showToast(`تمت إضافة (${newItem.name}) بنجاح ✓`);
    }

    setShowStaffEditModal(false);
    setEditingStaffItem(null);
  };

  const handleDeleteStaff = (staff: any) => {
    if (!confirm(`هل أنت متأكد من حذف وإزالة (${staff.name || 'الكادر'}) من التقرير؟`)) return;
    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 {
      const key = staff.idNumber || staff.name;
      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('تمت استعادة الوضع الافتراضي بنجاح ✓');
  };

  const handlePrint = () => {
    window.print();
  };

  const UNI_COLORS: { [k: string]: string } = {
    'جامعة الخليل': '#dc2626',
    'جامعة بوليتكنك فلسطين': '#2563eb',
    'الكلية الذكية الجامعية للتعليم الحديث': '#7c3aed'
  };
  const getUniColor = (u: string) => {
    const custom = customPartnerUnis.find(x => x.name === u);
    if (custom && custom.color) return custom.color;
    return UNI_COLORS[u] || '#0d9488';
  };
  const getUniIcon = (u: string) => {
    const custom = customPartnerUnis.find(x => x.name === u);
    if (custom && custom.icon) return custom.icon;
    if (u.includes('خليل')) return '🏛️';
    if (u.includes('بوليتكنك')) return '🔬';
    if (u.includes('ذكية')) return '💡';
    return '🎓';
  };

  if (!isOpen) return null;

  return (
    <div
      onClick={e => e.target === e.currentTarget && onClose()}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.85)',
        backdropFilter: 'blur(16px)',
        zIndex: 99999,
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '20px 16px 40px',
        overflowY: 'auto'
      }}
    >
      {/* Toast */}
      {toastMsg && (
        <div style={{
          position: 'fixed', top: '24px', left: '50%', transform: 'translateX(-50%)',
          background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
          color: '#ffffff', padding: '12px 28px', borderRadius: '30px',
          fontWeight: 900, fontSize: '0.95rem', boxShadow: '0 10px 30px rgba(0,0,0,0.5)',
          zIndex: 100002, border: '2px solid #6ee7b7'
        }}>
          {toastMsg}
        </div>
      )}

      <div style={{
        background: 'linear-gradient(165deg, #090d16 0%, #111827 50%, #0f172a 100%)',
        border: '2px solid rgba(255,215,0,0.55)',
        borderRadius: '24px',
        width: '100%', maxWidth: '1020px',
        boxShadow: '0 0 60px rgba(255,215,0,0.18), 0 30px 80px rgba(0,0,0,0.8)',
        fontFamily: 'Tajawal, sans-serif',
        direction: 'rtl',
        overflow: 'hidden'
      }}>
        {/* ── Top Golden Header ── */}
        <div style={{
          background: 'linear-gradient(135deg, #78350f 0%, #b45309 45%, #d97706 80%, #f59e0b 100%)',
          padding: '24px 30px 20px',
          borderBottom: '2px solid rgba(255,215,0,0.4)',
          position: 'relative'
        }}>
          <button
            onClick={onClose}
            style={{
              position: 'absolute', top: '16px', left: '20px',
              background: 'rgba(0,0,0,0.35)', border: '1.5px solid rgba(255,255,255,0.3)',
              color: 'white', width: '38px', height: '38px', borderRadius: '50%',
              cursor: 'pointer', fontSize: '1.3rem', display: 'flex',
              alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
            }}
          >×</button>

          <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
            <div style={{
              width: '56px', height: '56px', borderRadius: '16px',
              background: 'linear-gradient(135deg, #ffd700 0%, #f59e0b 100%)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '2rem', boxShadow: '0 0 20px rgba(255,215,0,0.7)', flexShrink: 0
            }}>
              🏆
            </div>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                <span style={{ fontSize: '1.55rem', fontWeight: 900, color: '#ffffff', textShadow: '0 2px 10px rgba(0,0,0,0.4)' }}>
                  تقرير الجامعات الشريكة المتعاقد معها
                </span>
                <span style={{
                  background: '#ffd700', color: '#78350f', borderRadius: '20px',
                  padding: '3px 12px', fontSize: '0.78rem', fontWeight: 900,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.3)'
                }}>
                  التقرير الذهبي التفصيلي ✨
                </span>
              </div>
              <div style={{ fontSize: '0.9rem', color: '#fef3c7', marginTop: '4px' }}>
                مستشفى الهلال الأحمر التخصصي — إحصائيات وكشوفات الأطباء المتعاقدين والمدربين السريريين (قابلة للإضافة والتعديل بحرية)
              </div>
            </div>
          </div>

          {/* Quick Action Buttons in Header */}
          <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginTop: '16px', alignItems: 'center' }}>
            <button
              onClick={() => {
                setEditingUniName(null);
                setNewUniNameInput('');
                setNewUniColorInput('#2563eb');
                setNewUniIconInput('🎓');
                setShowAddUniModal(true);
              }}
              style={{
                background: 'rgba(255,255,255,0.2)', border: '1.5px solid rgba(255,255,255,0.4)',
                color: '#fff', padding: '6px 14px', borderRadius: '10px',
                fontSize: '0.82rem', fontWeight: 900, cursor: 'pointer', fontFamily: 'Tajawal',
                display: 'flex', alignItems: 'center', gap: '6px'
              }}
            >
              <span>➕ إضافة جامعة / جهة شريكة</span>
            </button>

            <button
              onClick={() => handleOpenAddStaff()}
              style={{
                background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
                border: '1.5px solid #6ee7b7', color: '#fff', padding: '6px 14px',
                borderRadius: '10px', fontSize: '0.82rem', fontWeight: 900,
                cursor: 'pointer', fontFamily: 'Tajawal', display: 'flex', alignItems: 'center', gap: '6px',
                boxShadow: '0 0 10px rgba(16,185,129,0.4)'
              }}
            >
              <span>➕ إضافة كادر (طبيب / مدرب)</span>
            </button>

            <button
              onClick={handlePrint}
              style={{
                background: 'rgba(0,0,0,0.3)', border: '1px solid rgba(255,215,0,0.5)',
                color: '#fef08a', padding: '6px 14px', borderRadius: '10px',
                fontSize: '0.82rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal',
                display: 'flex', alignItems: 'center', gap: '6px'
              }}
            >
              <span>🖨️ طباعة التقرير</span>
            </button>

            {(customPartnerStaff.length > 0 || customPartnerUnis.length > 0 || Object.keys(partnerStaffOverrides).length > 0 || hiddenPartnerStaffKeys.length > 0) && (
              <button
                onClick={handleResetAdjustments}
                style={{
                  background: 'rgba(239,68,68,0.25)', border: '1px solid rgba(239,68,68,0.6)',
                  color: '#fca5a5', padding: '6px 12px', borderRadius: '10px',
                  fontSize: '0.8rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal',
                  display: 'flex', alignItems: 'center', gap: '6px', marginRight: 'auto'
                }}
                title="إلغاء التعديلات اليدوية واستعادة البيانات الافتراضية"
              >
                <span>⚙️ استعادة الافتراضي</span>
              </button>
            )}
          </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.38)',
                borderRadius: '12px', padding: '10px 12px', textAlign: 'center',
                border: '1px solid rgba(255,255,255,0.14)'
              }}>
                <div style={{ fontSize: '1.3rem' }}>{kpi.icon}</div>
                <div style={{ fontSize: '1.65rem', fontWeight: 900, color: kpi.color, lineHeight: 1.1 }}>{kpi.value}</div>
                <div style={{ fontSize: '0.72rem', color: 'rgba(255,255,255,0.8)', marginTop: '3px', fontWeight: 700 }}>{kpi.label}</div>
              </div>
            ))}
          </div>
        </div>

        {/* ── University Selection Section ── */}
        <div style={{
          padding: '20px 28px 16px',
          borderBottom: '1px solid rgba(255,255,255,0.08)',
          background: 'rgba(0,0,0,0.22)'
        }}>
          <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.6)', 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',
                    display: 'flex', alignItems: 'center', gap: '6px'
                  }}
                >
                  ✕ إلغاء التحديد (إخفاء الأسماء)
                </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', display: 'flex', alignItems: 'center', gap: '6px',
                  boxShadow: selectedUniStatsName === 'all' ? '0 0 12px rgba(255,215,0,0.3)' : 'none'
                }}
              >
                🌐 عرض جميع الجامعات
              </button>
            </div>
          </div>

          {/* Universities Grid */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '12px' }}>
            {uniEntries.map(([uniName, data]) => {
              const isSelected = selectedUniStatsName === uniName;
              const color = getUniColor(uniName);
              const icon = getUniIcon(uniName);
              const docCount = data.doctors.length;
              const nurseCount = data.nursing.length;
              const activeCount = [...data.doctors, ...data.nursing].filter(s => s._status === 'active').length;
              const isCustomUni = customPartnerUnis.some(u => u.name === uniName);

              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'
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <span style={{ fontSize: '1.8rem' }}>{icon}</span>
                      {isCustomUni && (
                        <div style={{ display: 'flex', gap: '4px' }}>
                          <button
                            type="button"
                            onClick={(e) => {
                              e.stopPropagation();
                              const u = customPartnerUnis.find(x => x.name === uniName);
                              setEditingUniName(uniName);
                              setNewUniNameInput(uniName);
                              setNewUniColorInput(u?.color || color);
                              setNewUniIconInput(u?.icon || icon);
                              setShowAddUniModal(true);
                            }}
                            title="تعديل الجامعة"
                            style={{ background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fef08a', borderRadius: '6px', padding: '2px 6px', cursor: 'pointer' }}
                          >✏️</button>
                          <button
                            type="button"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeleteUni(uniName);
                            }}
                            title="حذف الجامعة"
                            style={{ background: 'rgba(239,68,68,0.2)', border: 'none', color: '#fca5a5', borderRadius: '6px', padding: '2px 6px', cursor: 'pointer' }}
                          >🗑️</button>
                        </div>
                      )}
                    </div>

                    {isSelected ? (
                      <span style={{
                        background: color, color: '#ffffff', padding: '3px 10px',
                        borderRadius: '20px', fontSize: '0.74rem', fontWeight: 900
                      }}>
                        ✓ محددة والأسماء معروضة
                      </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.08rem', 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>

                  {/* Quick Add staff to this uni */}
                  <div style={{ marginTop: '10px', borderTop: '1px solid rgba(255,255,255,0.08)', paddingTop: '8px', display: 'flex', justifyContent: 'flex-end' }}>
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleOpenAddStaff(uniName);
                      }}
                      style={{
                        background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)',
                        color: '#fef08a', padding: '3px 8px', borderRadius: '8px', fontSize: '0.72rem',
                        fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal'
                      }}
                    >
                      ➕ إضافة كادر لهذه الجامعة
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* ── Condition: If NO university selected, show helpful prompt ── */}
        {!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'
                  }}
                >
                  {getUniIcon(uniName)} {uniName}
                </button>
              ))}
            </div>
          </div>
        ) : (
          /* ── Condition: University Selected -> Filter Controls & Names List ── */
          <div>
            {/* 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 */}
              <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'
                    }}
                  >✕</button>
                )}
              </div>
            </div>

            {/* 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.phone || '').includes(searchLower) ||
                      (s.idNumber || '').includes(searchLower) ||
                      (s.notes || '').toLowerCase().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 color = getUniColor(uniName);
                  const icon = getUniIcon(uniName);

                  return (
                    <div key={uniName} style={{
                      background: 'rgba(255,255,255,0.03)',
                      borderRadius: '16px', border: `1.5px solid ${color}45`,
                      overflow: 'hidden', boxShadow: `0 4px 20px ${color}15`
                    }}>
                      {/* Card Header */}
                      <div style={{
                        padding: '14px 20px', borderBottom: '1px solid rgba(255,255,255,0.07)',
                        display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap',
                        background: 'rgba(0,0,0,0.18)'
                      }}>
                        <div style={{
                          width: '42px', height: '42px', borderRadius: '12px',
                          background: color, display: 'flex', alignItems: 'center',
                          justifyContent: 'center', fontSize: '1.3rem', flexShrink: 0
                        }}>
                          {icon}
                        </div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: '1.15rem', fontWeight: 900, color: '#fde68a' }}>
                            {uniName}
                          </div>
                          <div style={{ fontSize: '0.8rem', color: 'rgba(255,255,255,0.6)', marginTop: '2px' }}>
                            إجمالي المعروض: {total} شخص (أطباء: {relevantDocs.length} • مدربين: {relevantNursing.length})
                          </div>
                        </div>

                        <button
                          type="button"
                          onClick={() => handleOpenAddStaff(uniName)}
                          style={{
                            background: 'rgba(16,185,129,0.2)', border: '1px solid #10b981',
                            color: '#6ee7b7', padding: '6px 12px', borderRadius: '8px',
                            fontSize: '0.78rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal'
                          }}
                        >
                          ➕ إضافة شخص
                        </button>
                      </div>

                      {/* Content Table / Cards */}
                      <div style={{ padding: '16px 20px' }}>
                        {total === 0 ? (
                          <div style={{ textAlign: 'center', padding: '25px', color: 'rgba(255,255,255,0.4)', fontSize: '0.9rem' }}>
                            لا يوجد أطباء أو مدربين مسجلين تحت هذه الجامعة حالياً. اضغط "➕ إضافة شخص" لإضافة كادر جديد.
                          </div>
                        ) : (
                          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(290px, 1fr))', gap: '12px' }}>
                            {[...relevantDocs, ...relevantNursing].map((s, idx) => {
                              const isDoc = s.type === 'doctor' || isContractedDoctorStudent(s);
                              const statusColor = s._status === 'active' ? '#10b981' : s._status === 'completed' ? '#6366f1' : '#0ea5e9';
                              const statusText = s._status === 'active' ? 'نشط (على رأس العمل)' : s._status === 'completed' ? 'أنهى التدريب' : 'قادم (مجدول)';

                              return (
                                <div
                                  key={s.id || s.idNumber || s.name + idx}
                                  style={{
                                    background: 'rgba(0,0,0,0.3)',
                                    border: s.isCustomItem ? '1.5px solid rgba(16,185,129,0.5)' : s.isCustomOverridden ? '1.5px solid rgba(255,215,0,0.5)' : '1px solid rgba(255,255,255,0.08)',
                                    borderRadius: '12px', padding: '14px', position: 'relative'
                                  }}
                                >
                                  {/* Badges row */}
                                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                                    <span style={{
                                      background: isDoc ? 'rgba(59,130,246,0.2)' : 'rgba(16,185,129,0.2)',
                                      color: isDoc ? '#93c5fd' : '#6ee7b7',
                                      border: isDoc ? '1px solid rgba(59,130,246,0.4)' : '1px solid rgba(16,185,129,0.4)',
                                      borderRadius: '12px', padding: '2px 8px', fontSize: '0.72rem', fontWeight: 800
                                    }}>
                                      {isDoc ? '🩺 طبيب متعاقد' : '🏥 مدرب سريري'}
                                    </span>

                                    <span style={{
                                      background: `${statusColor}22`,
                                      color: statusColor,
                                      border: `1px solid ${statusColor}55`,
                                      borderRadius: '12px', padding: '2px 8px', fontSize: '0.72rem', fontWeight: 800
                                    }}>
                                      ● {statusText}
                                    </span>
                                  </div>

                                  {/* Staff Name */}
                                  <div style={{ fontSize: '1.05rem', fontWeight: 900, color: '#ffffff', marginBottom: '4px' }}>
                                    {s.name}
                                  </div>

                                  {/* Specialty / Department */}
                                  <div style={{ fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '8px' }}>
                                    {s.specialty || s.department || 'كادر تدريب متعاقد'}
                                  </div>

                                  {/* Dates & Phone */}
                                  <div style={{ fontSize: '0.75rem', color: 'rgba(255,255,255,0.6)', display: 'flex', flexDirection: 'column', gap: '3px' }}>
                                    {(s.startDate || s.endDate) && (
                                      <div>📅 الفترة: {s.startDate || '—'} إلى {s.endDate || '—'}</div>
                                    )}
                                    {s.phone && <div>📞 هاتف: {s.phone}</div>}
                                    {s.idNumber && <div>🪪 هوية: {s.idNumber}</div>}
                                    {s.notes && <div style={{ color: '#fef08a', marginTop: '2px' }}>📝 {s.notes}</div>}
                                  </div>

                                  {/* Action Buttons (Edit / Delete) */}
                                  <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '12px', borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: '8px' }}>
                                    <button
                                      type="button"
                                      onClick={() => handleOpenEditStaff(s, uniName)}
                                      style={{
                                        background: 'rgba(255,255,255,0.1)', border: 'none',
                                        color: '#fef08a', padding: '4px 10px', borderRadius: '6px',
                                        fontSize: '0.76rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal'
                                      }}
                                    >
                                      ✏️ تعديل
                                    </button>
                                    <button
                                      type="button"
                                      onClick={() => handleDeleteStaff(s)}
                                      style={{
                                        background: 'rgba(239,68,68,0.2)', border: 'none',
                                        color: '#fca5a5', padding: '4px 10px', borderRadius: '6px',
                                        fontSize: '0.76rem', fontWeight: 800, cursor: 'pointer', fontFamily: 'Tajawal'
                                      }}
                                    >
                                      🗑️ إزالة
                                    </button>
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                });
              })()}
            </div>
          </div>
        )}
      </div>

      {/* ══════════════════════════════════════════════════════
          Modal: Add / Edit University Dialog
      ══════════════════════════════════════════════════════ */}
      {showAddUniModal && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.85)',
          backdropFilter: 'blur(8px)', zIndex: 100001,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px'
        }}>
          <div style={{
            background: '#1e293b', border: '2px solid #ffd700', borderRadius: '20px',
            width: '100%', maxWidth: '480px', padding: '24px', direction: 'rtl',
            boxShadow: '0 20px 50px rgba(0,0,0,0.8)', fontFamily: 'Tajawal'
          }}>
            <h3 style={{ fontSize: '1.25rem', fontWeight: 900, color: '#ffd700', margin: '0 0 16px' }}>
              {editingUniName ? `✏️ تعديل الجامعة: ${editingUniName}` : '➕ إضافة جامعة أو جهة شريكة جديدة'}
            </h3>

            <form onSubmit={handleSaveUni}>
              <div style={{ marginBottom: '14px' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', color: '#cbd5e1', marginBottom: '6px' }}>
                  اسم الجامعة أو الكلية / الجهة: *
                </label>
                <input
                  type="text"
                  required
                  value={newUniNameInput}
                  onChange={e => setNewUniNameInput(e.target.value)}
                  placeholder="مثال: جامعة بيرزيت، جامعة النجاح الوطنية..."
                  style={{
                    width: '100%', padding: '10px 14px', borderRadius: '10px',
                    border: '1.5px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                    color: '#fff', fontSize: '0.95rem', fontFamily: 'Tajawal', outline: 'none'
                  }}
                />
              </div>

              <div style={{ marginBottom: '14px' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', color: '#cbd5e1', marginBottom: '6px' }}>
                  لون التمييز:
                </label>
                <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
                  {['#2563eb', '#dc2626', '#7c3aed', '#059669', '#d97706', '#0891b2'].map(c => (
                    <button
                      key={c}
                      type="button"
                      onClick={() => setNewUniColorInput(c)}
                      style={{
                        width: '32px', height: '32px', borderRadius: '50%', background: c,
                        border: newUniColorInput === c ? '3px solid #fff' : 'none', cursor: 'pointer',
                        boxShadow: newUniColorInput === c ? '0 0 10px #fff' : 'none'
                      }}
                    />
                  ))}
                  <input
                    type="color"
                    value={newUniColorInput}
                    onChange={e => setNewUniColorInput(e.target.value)}
                    style={{ width: '40px', height: '32px', background: 'transparent', border: 'none', cursor: 'pointer' }}
                  />
                </div>
              </div>

              <div style={{ marginBottom: '20px' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', color: '#cbd5e1', marginBottom: '6px' }}>
                  أيقونة الجامعة:
                </label>
                <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                  {['🏛️', '🔬', '💡', '🎓', '🏥', '🩺', '🌟', '📚'].map(ico => (
                    <button
                      key={ico}
                      type="button"
                      onClick={() => setNewUniIconInput(ico)}
                      style={{
                        fontSize: '1.4rem', padding: '6px 10px', borderRadius: '10px',
                        background: newUniIconInput === ico ? 'rgba(255,215,0,0.3)' : 'rgba(255,255,255,0.06)',
                        border: newUniIconInput === ico ? '2px solid #ffd700' : '1px solid rgba(255,255,255,0.1)',
                        cursor: 'pointer'
                      }}
                    >{ico}</button>
                  ))}
                </div>
              </div>

              <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  onClick={() => setShowAddUniModal(false)}
                  style={{
                    padding: '8px 16px', borderRadius: '10px', background: 'rgba(255,255,255,0.1)',
                    border: 'none', color: '#fff', cursor: 'pointer', fontFamily: 'Tajawal'
                  }}
                >
                  إلغاء
                </button>
                <button
                  type="submit"
                  style={{
                    padding: '8px 22px', borderRadius: '10px',
                    background: 'linear-gradient(135deg, #ffd700 0%, #d97706 100%)',
                    border: 'none', color: '#78350f', fontWeight: 900, cursor: 'pointer', fontFamily: 'Tajawal'
                  }}
                >
                  حفظ الجامعة ✓
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════
          Modal: Add / Edit Staff Dialog
      ══════════════════════════════════════════════════════ */}
      {showStaffEditModal && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.85)',
          backdropFilter: 'blur(8px)', zIndex: 100001,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px'
        }}>
          <div style={{
            background: '#1e293b', border: '2px solid #10b981', borderRadius: '20px',
            width: '100%', maxWidth: '540px', maxHeight: '90vh', overflowY: 'auto', padding: '24px', direction: 'rtl',
            boxShadow: '0 20px 50px rgba(0,0,0,0.8)', fontFamily: 'Tajawal'
          }}>
            <h3 style={{ fontSize: '1.25rem', fontWeight: 900, color: '#6ee7b7', margin: '0 0 16px' }}>
              {editingStaffItem ? `✏️ تعديل بيانات: ${editingStaffItem.name}` : '➕ إضافة طبيب أو مدرب جديد'}
            </h3>

            <form onSubmit={handleSaveStaff}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    الاسم الكامل: *
                  </label>
                  <input
                    type="text"
                    required
                    value={staffFormName}
                    onChange={e => setStaffFormName(e.target.value)}
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    نوع الكادر: *
                  </label>
                  <select
                    value={staffFormType}
                    onChange={e => setStaffFormType(e.target.value as any)}
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  >
                    <option value="doctor">🩺 طبيب متعاقد / استشاري</option>
                    <option value="trainer">🏥 مدرب سريري / مشرف جامعي</option>
                  </select>
                </div>
              </div>

              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                  الجامعة الشريكة المتعاقد معها: *
                </label>
                <select
                  value={staffFormUni}
                  onChange={e => setStaffFormUni(e.target.value)}
                  style={{
                    width: '100%', padding: '8px 12px', borderRadius: '8px',
                    border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                    color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                  }}
                >
                  {uniEntries.map(([uniName]) => (
                    <option key={uniName} value={uniName}>{uniName}</option>
                  ))}
                </select>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    التخصص / المسمى:
                  </label>
                  <input
                    type="text"
                    value={staffFormSpecialty}
                    onChange={e => setStaffFormSpecialty(e.target.value)}
                    placeholder="مثال: جراحة عامة، باطني..."
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    القسم المخصص للتدريب:
                  </label>
                  <input
                    type="text"
                    value={staffFormDept}
                    onChange={e => setStaffFormDept(e.target.value)}
                    placeholder="مثال: قسم الجراحة، الطوارئ..."
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    رقم الهاتف:
                  </label>
                  <input
                    type="text"
                    value={staffFormPhone}
                    onChange={e => setStaffFormPhone(e.target.value)}
                    placeholder="059xxxxxxx"
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    رقم الهوية:
                  </label>
                  <input
                    type="text"
                    value={staffFormIdNumber}
                    onChange={e => setStaffFormIdNumber(e.target.value)}
                    placeholder="9 أرقام"
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '12px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    تاريخ البدء:
                  </label>
                  <input
                    type="text"
                    value={staffFormStartDate}
                    onChange={e => setStaffFormStartDate(e.target.value)}
                    placeholder="DD/MM/YYYY"
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    تاريخ الانتهاء:
                  </label>
                  <input
                    type="text"
                    value={staffFormEndDate}
                    onChange={e => setStaffFormEndDate(e.target.value)}
                    placeholder="DD/MM/YYYY"
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                    الحالة:
                  </label>
                  <select
                    value={staffFormStatus}
                    onChange={e => setStaffFormStatus(e.target.value as any)}
                    style={{
                      width: '100%', padding: '8px 12px', borderRadius: '8px',
                      border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                      color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                    }}
                  >
                    <option value="auto">تلقائي (حسب التاريخ)</option>
                    <option value="active">🟢 نشط</option>
                    <option value="completed">✅ مكتمل</option>
                    <option value="upcoming">🔵 قادم</option>
                  </select>
                </div>
              </div>

              <div style={{ marginBottom: '18px' }}>
                <label style={{ display: 'block', fontSize: '0.82rem', color: '#cbd5e1', marginBottom: '4px' }}>
                  ملاحظات إضافية:
                </label>
                <input
                  type="text"
                  value={staffFormNotes}
                  onChange={e => setStaffFormNotes(e.target.value)}
                  placeholder="ملاحظات حول الدوام أو العيادات أو الجامعة..."
                  style={{
                    width: '100%', padding: '8px 12px', borderRadius: '8px',
                    border: '1px solid rgba(255,255,255,0.2)', background: 'rgba(0,0,0,0.3)',
                    color: '#fff', fontSize: '0.9rem', fontFamily: 'Tajawal', outline: 'none'
                  }}
                />
              </div>

              <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  onClick={() => setShowStaffEditModal(false)}
                  style={{
                    padding: '8px 16px', borderRadius: '10px', background: 'rgba(255,255,255,0.1)',
                    border: 'none', color: '#fff', cursor: 'pointer', fontFamily: 'Tajawal'
                  }}
                >
                  إلغاء
                </button>
                <button
                  type="submit"
                  style={{
                    padding: '8px 22px', borderRadius: '10px',
                    background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
                    border: 'none', color: '#fff', fontWeight: 900, cursor: 'pointer', fontFamily: 'Tajawal'
                  }}
                >
                  حفظ البيانات ✓
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
