"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import PartnerUniversitiesModal from '@/app/components/PartnerUniversitiesModal';
import { 
  ArrowRight, FileText, Calendar, Phone, User, 
  GraduationCap, Activity, Utensils, Briefcase, Calculator, 
  HeartPulse, HandHeart, Stethoscope, Apple, Scan, Users, Siren,
  Grid, List, CheckCircle, XCircle, Edit3, Trash2, UserPlus, Archive, Search, Filter, Download
} from "lucide-react";

const categoryConfig: any = {
  "المتقدمين للإمتياز": { icon: GraduationCap, color: "linear-gradient(135deg, #3498db 0%, #2980b9 100%)" },
  "العلاج الطبيعي": { icon: Activity, color: "linear-gradient(135deg, #2ecc71 0%, #27ae60 100%)" },
  "علاج طبيعي تدريب": { icon: Activity, color: "linear-gradient(135deg, #2ecc71 0%, #27ae60 100%)" },
  "علاج طبيعي امتياز": { icon: Activity, color: "linear-gradient(135deg, #10b981 0%, #047857 100%)" },
  "العلاج الوظيفي": { icon: Activity, color: "linear-gradient(135deg, #1abc9c 0%, #16a085 100%)" },
  "المطبخ": { icon: Utensils, color: "linear-gradient(135deg, #e67e22 0%, #d35400 100%)" },
  "إدارة": { icon: Briefcase, color: "linear-gradient(135deg, #34495e 0%, #2c3e50 100%)" },
  "المحاسبة": { icon: Calculator, color: "linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%)" },
  "التمريض": { icon: HeartPulse, color: "linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)" },
  "طب تطوع": { icon: HandHeart, color: "linear-gradient(135deg, #f1c40f 0%, #f39c12 100%)" },
  "تمريض تطوع": { icon: HandHeart, color: "linear-gradient(135deg, #00bcd4 0%, #0097a7 100%)" },
  "تمريض تدريب": { icon: Stethoscope, color: "linear-gradient(135deg, #e91e63 0%, #c2185b 100%)" },
  "تمريض امتياز": { icon: Stethoscope, color: "linear-gradient(135deg, #9c27b0 0%, #7b1fa2 100%)" },
  "تغذية": { icon: Apple, color: "linear-gradient(135deg, #8bc34a 0%, #689f38 100%)" },
  "أشعة": { icon: Scan, color: "linear-gradient(135deg, #607d8b 0%, #455a64 100%)" },
  "خدمة اجتماعية": { icon: Users, color: "linear-gradient(135deg, #795548 0%, #5d4037 100%)" },
  "العمل المجتمعي": { icon: Users, color: "linear-gradient(135deg, #00897b 0%, #00695c 100%)" },
  "تدريب ضباط الإسعاف": { icon: Siren, color: "linear-gradient(135deg, #ea580c 0%, #c2410c 100%)" },
  "طب تدريب": { icon: Stethoscope, color: "linear-gradient(135deg, #0284c7 0%, #1e40af 100%)" },
  "طلاب الطب المتدربين": { icon: Stethoscope, color: "linear-gradient(135deg, #0284c7 0%, #1e40af 100%)" },
  "مختبرات طبية": { icon: Activity, color: "linear-gradient(135deg, #059669 0%, #047857 100%)" },
  "هندسة طبية": { icon: Activity, color: "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)" },
  "سكرتارية طبية": { icon: Briefcase, color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)" },
  "تقديم طلبات لتدريب طلاب التمريض في الجامعات": { icon: HeartPulse, color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)" },
  "تدريب طلاب التمريض في الجامعات": { icon: HeartPulse, color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)" },
  "تدريب تمريض الجامعات": { icon: HeartPulse, color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)" },
  "الأطباء المتعاقدين مع الجامعات": { icon: Stethoscope, color: "linear-gradient(135deg, #4338ca 0%, #312e81 100%)" },
  "الأطباء المتعاقدون مع الجامعات": { icon: Stethoscope, color: "linear-gradient(135deg, #4338ca 0%, #312e81 100%)" },
  "الأطباء المتعاقدون": { icon: Stethoscope, color: "linear-gradient(135deg, #4338ca 0%, #312e81 100%)" },
  // ── Health Support Trainers ──
  "مدربي أشعة": { icon: Scan, color: "linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)" },
  "مدربو أشعة": { icon: Scan, color: "linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)" },
  "مدربي علاج طبيعي": { icon: Activity, color: "linear-gradient(135deg, #059669 0%, #047857 100%)" },
  "مدربو علاج طبيعي": { icon: Activity, color: "linear-gradient(135deg, #059669 0%, #047857 100%)" },
  "مدربي صيدلية": { icon: HeartPulse, color: "linear-gradient(135deg, #b45309 0%, #92400e 100%)" },
  "مدربو صيدلية": { icon: HeartPulse, color: "linear-gradient(135deg, #b45309 0%, #92400e 100%)" },
  "مدربي تغذية": { icon: Apple, color: "linear-gradient(135deg, #16a34a 0%, #15803d 100%)" },
  "مدربو تغذية": { icon: Apple, color: "linear-gradient(135deg, #16a34a 0%, #15803d 100%)" },
  "مدربي مختبر": { icon: Activity, color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)" },
  "مدربو مختبر": { icon: Activity, color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)" },
  "مدربي هندسة طبية": { icon: Activity, color: "linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%)" },
  "مدربو هندسة طبية": { icon: Activity, color: "linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%)" },
  "مدربي علاج وظيفي": { icon: HandHeart, color: "linear-gradient(135deg, #0f766e 0%, #115e59 100%)" },
  "مدربو علاج وظيفي": { icon: HandHeart, color: "linear-gradient(135deg, #0f766e 0%, #115e59 100%)" },
  "إرشاد وصحة نفسية": { icon: Activity, color: "linear-gradient(135deg, #059669 0%, #10b981 100%)" },
  "الصحة النفسية": { icon: Activity, color: "linear-gradient(135deg, #059669 0%, #10b981 100%)" },
};

// Departments for the main dashboard
const departments = [
  { key: "جراحة", label: "الجراحة العامة", color: "#8B1A2B" },
  { key: "نسائية", label: "النسائية والتوليد", color: "#6B3A7D" },
  { key: "الاطفال", label: "طب الأطفال", color: "#2B5F8B" },
  { key: "التمريض", label: "التمريض", color: "#e74c3c" },
  { key: "علاج طبيعي تدريب", label: "علاج طبيعي - تدريب", color: "#27ae60" },
  { key: "علاج طبيعي امتياز", label: "علاج طبيعي - امتياز", color: "#059669" },
  { key: "العلاج الطبيعي", label: "العلاج الطبيعي", color: "#2ecc71" },
  { key: "العلاج الوظيفي", label: "العلاج الوظيفي", color: "#16a085" },
  { key: "المطبخ", label: "المطبخ", color: "#d35400" },
  { key: "إدارة", label: "إدارة", color: "#2c3e50" },
  { key: "المحاسبة", label: "المحاسبة", color: "#8e44ad" },
  { key: "طب تطوع", label: "طب تطوع", color: "#f39c12" },
  { key: "تمريض تطوع", label: "تمريض تطوع", color: "#0097a7" },
  { key: "تمريض تدريب", label: "تمريض تدريب", color: "#c2185b" },
  { key: "تمريض امتياز", label: "تمريض امتياز", color: "#7b1fa2" },
  { key: "تغذية", label: "تغذية", color: "#689f38" },
  { key: "أشعة", label: "أشعة", color: "#455a64" },
  { key: "خدمة اجتماعية", label: "خدمة اجتماعية", color: "#5d4037" },
  { key: "ضباط الإسعاف", label: "ضباط الإسعاف", color: "#FF5722" },
  { key: "العمل المجتمعي", label: "العمل المجتمعي", color: "#00695c" },
  { key: "تدريب تمريض الجامعات", label: "تدريب تمريض الجامعات", color: "#00838f" },
  { key: "الأطباء المتعاقدون", label: "الأطباء المتعاقدون", color: "#283593" },
  { key: "مختبرات", label: "المختبرات الطبية", color: "#059669" },
  { key: "هندسة طبية", label: "الهندسة الطبية", color: "#6366f1" },
  { key: "سكرتارية طبية", label: "السكرتارية الطبية", color: "#0284c7" },
  { key: "مدربي أشعة", label: "مدربي أشعة", color: "#7c3aed" },
  { key: "مدربي علاج طبيعي", label: "مدربي علاج طبيعي", color: "#059669" },
  { key: "مدربي مختبر", label: "مدربي مختبرات", color: "#0284c7" },
  { key: "مدربي صيدلية", label: "مدربي صيدلية", color: "#b45309" },
  { key: "مدربي علاج وظيفي", label: "مدربي علاج وظيفي", color: "#0f766e" },
  { key: "مدربي تغذية", label: "مدربي تغذية", color: "#16a34a" },
  { key: "مدربي هندسة طبية", label: "مدربي هندسة طبية", color: "#1d4ed8" },
  { key: "الصحة النفسية", label: "إرشاد وصحة نفسية", color: "#059669" }
];

// Map application category name to department key
const categoryToDept: {[key: string]: string} = {
  "المتقدمين للإمتياز": "جراحة",
  "التمريض": "التمريض",
  "العلاج الطبيعي": "علاج طبيعي تدريب",
  "علاج طبيعي تدريب": "علاج طبيعي تدريب",
  "علاج طبيعي امتياز": "علاج طبيعي امتياز",
  "العلاج الطبيعي - تدريب": "علاج طبيعي تدريب",
  "العلاج الطبيعي - امتياز": "علاج طبيعي امتياز",
  "العلاج الوظيفي": "العلاج الوظيفي",
  "المطبخ": "المطبخ",
  "إدارة": "إدارة",
  "المحاسبة": "المحاسبة",
  "طب تطوع": "طب تطوع",
  "تمريض تطوع": "تمريض تطوع",
  "تمريض تدريب": "تمريض تدريب",
  "تمريض امتياز": "تمريض امتياز",
  "تغذية": "تغذية",
  "أشعة": "أشعة",
  "خدمة اجتماعية": "خدمة اجتماعية",
  "تدريب ضباط الإسعاف": "ضباط الإسعاف",
  "العمل المجتمعي": "العمل المجتمعي",
  "تقديم طلبات لتدريب طلاب التمريض في الجامعات": "تدريب تمريض الجامعات",
  "تدريب طلاب التمريض في الجامعات": "تدريب تمريض الجامعات",
  "تدريب تمريض الجامعات": "تدريب تمريض الجامعات",
  "الأطباء المتعاقدين مع الجامعات": "الأطباء المتعاقدون",
  "الأطباء المتعاقدون مع الجامعات": "الأطباء المتعاقدون",
  "الأطباء المتعاقدون": "الأطباء المتعاقدون",
  "طب تدريب": "جراحة",
  "طلاب الطب المتدربين": "جراحة",
  "مختبرات طبية": "مختبرات",
  "هندسة طبية": "هندسة طبية",
  "سكرتارية طبية": "سكرتارية طبية",
  // ── Health Support Trainer Mappings ──
  "مدربي أشعة":         "مدربي أشعة",
  "مدربو أشعة":         "مدربي أشعة",
  "مدربي علاج طبيعي":   "مدربي علاج طبيعي",
  "مدربو علاج طبيعي":   "مدربي علاج طبيعي",
  "مدربي صيدلية":       "مدربي صيدلية",
  "مدربو صيدلية":       "مدربي صيدلية",
  "مدربي تغذية":        "مدربي تغذية",
  "مدربو تغذية":        "مدربي تغذية",
  "مدربي مختبر":        "مدربي مختبر",
  "مدربو مختبر":        "مدربي مختبر",
  "مدربي هندسة طبية":   "مدربي هندسة طبية",
  "مدربو هندسة طبية":   "مدربي هندسة طبية",
  "مدربي علاج وظيفي":   "مدربي علاج وظيفي",
  "مدربو علاج وظيفي":   "مدربي علاج وظيفي",
  "إرشاد وصحة نفسية":   "الصحة النفسية",
  "الصحة النفسية":      "الصحة النفسية",
};

export default function AdminApplications() {
  const router = useRouter();
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [applications, setApplications] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'pending' | 'archive' | 'universities' | 'health-trainers'>('pending');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [selectedApp, setSelectedApp] = useState<any>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [toast, setToast] = useState<string | null>(null);
  const [showUniStatsModal, setShowUniStatsModal] = useState(false);

  // Pending Tab Controls
  const [pendingSearch, setPendingSearch] = useState('');
  const [pendingViewMode, setPendingViewMode] = useState<'cards' | 'all'>('cards');

  const isUniversityApp = (app: any) => {
    let c = (app.category || app.categoryId || '').toLowerCase();
    try { c = decodeURIComponent(c); } catch {}
    return (
      c.includes('تدريب طلاب التمريض') || 
      c.includes('تمريض الجامعات') || 
      c.includes('جامعات شريكة') ||
      c.includes('جامعات') ||
      (c.includes('university') && (c.includes('nursing') || c.includes('trainer') || c.includes('contract'))) ||
      c.includes('متعاقد') || 
      c.includes('contracted') || 
      c.includes('طبيب متعاقد') ||
      c.includes('أطباء متعاقدون') ||
      c.includes('اطباء متعاقدون')
    );
  };

  const isHealthTrainerApp = (app: any) => {
    let c = (app.category || app.categoryId || '').toLowerCase();
    try { c = decodeURIComponent(c); } catch {}
    return (
      c.includes('مدربي أشعة') || c.includes('مدربو أشعة') ||
      c.includes('مدربي علاج طبيعي') || c.includes('مدربو علاج طبيعي') ||
      c.includes('مدربي صيدلية') || c.includes('مدربو صيدلية') ||
      c.includes('مدربي تغذية') || c.includes('مدربو تغذية') ||
      c.includes('مدربي مختبر') || c.includes('مدربو مختبر') ||
      c.includes('مدربي هندسة طبية') || c.includes('مدربو هندسة طبية') ||
      c.includes('مدربي علاج وظيفي') || c.includes('مدربو علاج وظيفي')
    );
  };

  // Health trainer sub-departments definition (shared across the tab)
  const healthTrainerDepts = [
    { key: 'مدربي أشعة',        label: 'مدربو الأشعة',          icon: 'fas fa-radiation',   color: '#7c3aed', gradient: 'linear-gradient(135deg,#7c3aed,#6d28d9)', shadow: 'rgba(124,58,237,0.3)' },
    { key: 'مدربي علاج طبيعي', label: 'مدربو العلاج الطبيعي', icon: 'fas fa-walking',     color: '#059669', gradient: 'linear-gradient(135deg,#059669,#047857)', shadow: 'rgba(5,150,105,0.3)'  },
    { key: 'مدربي صيدلية',     label: 'مدربو الصيدلة',         icon: 'fas fa-pills',       color: '#b45309', gradient: 'linear-gradient(135deg,#b45309,#92400e)', shadow: 'rgba(180,83,9,0.3)'   },
    { key: 'مدربي تغذية',      label: 'مدربو التغذية',         icon: 'fas fa-apple-alt',   color: '#16a34a', gradient: 'linear-gradient(135deg,#16a34a,#15803d)', shadow: 'rgba(22,163,74,0.3)'  },
    { key: 'مدربي مختبر',      label: 'مدربو المختبرات',       icon: 'fas fa-flask',       color: '#0284c7', gradient: 'linear-gradient(135deg,#0284c7,#0369a1)', shadow: 'rgba(2,132,199,0.3)'  },
    { key: 'مدربي هندسة طبية', label: 'مدربو الهندسة الطبية', icon: 'fas fa-microchip',   color: '#1d4ed8', gradient: 'linear-gradient(135deg,#1d4ed8,#1e40af)', shadow: 'rgba(29,78,216,0.3)'  },
    { key: 'مدربي علاج وظيفي', label: 'مدربو العلاج الوظيفي', icon: 'fas fa-hands',       color: '#0f766e', gradient: 'linear-gradient(135deg,#0f766e,#115e59)', shadow: 'rgba(15,118,110,0.3)' },
  ];

  // Application Completeness Score Helper (100 / 100)
  const getAppCompleteness = (app: any) => {
    if (!app) return { score: 100, isFull: true, hasPhoto: true, hasPhone: true, hasId: true };
    const photo = app.photoBase64 || app.doctorPhotoBase64 || (app.hasPhoto ? 'valid' : '');
    const hasPhoto = Boolean(photo && String(photo).length > 10);
    const hasPhone = Boolean(app.phone && String(app.phone).trim().length >= 7);
    const hasId = Boolean(app.idNumber && String(app.idNumber).trim().length >= 5);
    const hasName = Boolean(app.name && String(app.name).trim().length >= 3);
    let score = 0;
    if (hasName) score += 20;
    if (hasPhoto) score += 30;
    if (hasPhone) score += 30;
    if (hasId) score += 20;
    return { score, isFull: score === 100, hasPhoto, hasPhone, hasId };
  };

  // Archive search & filter controls
  const [archiveSearch, setArchiveSearch] = useState('');
  const [archiveStatusFilter, setArchiveStatusFilter] = useState<'all' | 'accepted' | 'rejected' | 'pending'>('all');
  const [archiveCategoryFilter, setArchiveCategoryFilter] = useState<string>('all');

  // Universities tab filters
  const [uniSearch, setUniSearch] = useState('');
  const [uniCategoryFilter, setUniCategoryFilter] = useState<'all' | 'nursing' | 'doctors'>('all');
  const [uniStatusFilter, setUniStatusFilter] = useState<'all' | 'pending' | 'accepted' | 'rejected'>('all');

  // Health Trainers tab filters
  const [htSearch, setHtSearch] = useState('');
  const [htDeptFilter, setHtDeptFilter] = useState<string>('all');
  const [htStatusFilter, setHtStatusFilter] = useState<'all' | 'pending' | 'accepted' | 'rejected'>('all');

  // ── Assign Trainer Modal State ──────────────────────────────────────────
  const [showAssignTrainerModal, setShowAssignTrainerModal] = useState(false);
  const [assignTargetApp, setAssignTargetApp] = useState<any>(null);
  const [trainerSearch, setTrainerSearch] = useState('');
  const [isAssigning, setIsAssigning] = useState(false);
  const [trainersList, setTrainersList] = useState<{
    name: string;
    university: string;
    dept: string;
    badge?: string;
    isNursingTrainer?: boolean;
    phone?: string;
    source?: string;
  }[]>([]);
  const [trainerFilterTab, setTrainerFilterTab] = useState<'all' | 'nursing' | 'approved'>('all');

  // Editable form state for accept flow
  const [editForm, setEditForm] = useState({ 
    name: '', phone: '', university: '', graduatedUniversity: '', contractedUniversity: '',
    graduationYear: '', address: '', studySystem: '', internshipYear: '',
    startDate: '', endDate: '', deptStartDate: '', deptEndDate: '', shiftSystem: '', targetDept: '',
    assignedTrainer: ''
  });

  // Dedicated multi-department management for University Trainers
  const [adminUniDepts, setAdminUniDepts] = useState<string[]>([]);
  const [adminCustomDeptInput, setAdminCustomDeptInput] = useState<string>('');

  // Rotation system
  const [rotationCount, setRotationCount] = useState(1);
  const [rotations, setRotations] = useState<{dept: string; startDate: string; endDate: string; shiftSystem: string}[]>([
    { dept: '', startDate: '', endDate: '', shiftSystem: '' }
  ]);

  // Auto-calculate rotation dates based on studySystem + globalStartDate
  const calcRotations = (count: number, studySystem: string, globalStart: string) => {
    const monthsPerRotation = studySystem === '6+1' ? 2 : 3;
    const newRotations: {dept: string; startDate: string; endDate: string; shiftSystem: string}[] = [];
    let currentStart = globalStart;
    for (let i = 0; i < count; i++) {
      const startD = new Date(currentStart);
      const endD = new Date(currentStart);
      endD.setMonth(endD.getMonth() + monthsPerRotation);
      newRotations.push({
        dept: rotations[i]?.dept || '',
        startDate: isNaN(startD.getTime()) ? '' : startD.toISOString().split('T')[0],
        endDate: isNaN(endD.getTime()) ? '' : endD.toISOString().split('T')[0],
        shiftSystem: rotations[i]?.shiftSystem || ''
      });
      currentStart = endD.toISOString().split('T')[0];
    }
    return newRotations;
  };

  const showToast = (msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(null), 3500);
  };

  const loadData = async () => {
    try {
      const response = await fetch('/api/applications');
      let apps: any[] = [];
      if (response.ok) {
        const data = await response.json();
        apps = data.applications || [];
      }
      setApplications(apps);
    } catch (error) {
      console.error("Error loading applications:", error);
    } finally {
      setIsLoading(false);
    }
  };

  // ── Open Assign Trainer Modal: fetch trainers from website apps & studentsData ──
  const openAssignTrainerModal = async (app: any) => {
    setAssignTargetApp(app);
    setTrainerSearch('');
    setTrainerFilterTab('all');
    setShowAssignTrainerModal(true);

    const trainersMap = new Map<string, {
      name: string;
      university: string;
      dept: string;
      badge: string;
      isNursingTrainer: boolean;
      source: string;
      phone?: string;
    }>();

    const addTrainer = (
      name: string,
      university: string,
      dept: string,
      badge: string,
      isNursingTrainer: boolean,
      source: string,
      phone?: string
    ) => {
      const cleanName = (name || '').trim();
      if (!cleanName) return;
      if (!trainersMap.has(cleanName)) {
        trainersMap.set(cleanName, {
          name: cleanName,
          university: university || '—',
          dept,
          badge,
          isNursingTrainer,
          source,
          phone: phone || ''
        });
      } else {
        const existing = trainersMap.get(cleanName)!;
        if (isNursingTrainer && !existing.isNursingTrainer) {
          existing.isNursingTrainer = true;
          existing.badge = badge;
          existing.dept = dept;
        }
        if (!existing.phone && phone) existing.phone = phone;
      }
    };

    // 1. TOP PRIORITY: Website Applicants for Nursing Training (المدربين المسجلين بالموقع)
    const currentApps = (applications && applications.length > 0) ? applications : [];
    currentApps.forEach((a: any) => {
      const c = (a.category || a.categoryId || '').toLowerCase();
      const isNursingTrainer = (
        c.includes('تدريب طلاب التمريض') ||
        c.includes('university-nursing-trainers') ||
        c.includes('تمريض الجامعات') ||
        c.includes('جامعات شريكة') ||
        (c.includes('تمريض') && (c.includes('مدرب') || c.includes('trainer') || c.includes('مشرف')))
      );
      if (isNursingTrainer) {
        const unis = a.contractedUniversities && a.contractedUniversities.length > 0
          ? (Array.isArray(a.contractedUniversities) ? a.contractedUniversities.join('، ') : a.contractedUniversities)
          : (a.contractedUniversity || a.university || 'جامعات شريكة');
        addTrainer(
          a.name,
          unis,
          'مدرب تمريض جامعات (الموقع)',
          '🩺 مدرب تمريض (الموقع)',
          true,
          'website',
          a.phone
        );
      }
    });

    // Populate immediately with website applications so modal is never empty
    const initialList = Array.from(trainersMap.values()).sort((a, b) => {
      if (a.isNursingTrainer && !b.isNursingTrainer) return -1;
      if (!a.isNursingTrainer && b.isNursingTrainer) return 1;
      return a.name.localeCompare(b.name, 'ar');
    });
    setTrainersList(initialList);

    // 2. SECOND PRIORITY: Approved Staff from /api/students (كادر تدريب تمريض الجامعات المعتمد)
    try {
      const res = await fetch('/api/students');
      if (res.ok) {
        const data = await res.json();
        const allStudents: any = data.students || data || {};

        // Specifically from "تدريب تمريض الجامعات"
        const uniStaff = allStudents['تدريب تمريض الجامعات'] || [];
        if (Array.isArray(uniStaff)) {
          uniStaff.forEach((s: any) => {
            // Must NOT include students who were assigned to trainers as trainers themselves
            if (s.internshipYear === 'طالب متدرب' || s.crescentJobNature === 'طالب تمريض متدرب' || s.assignedTrainer) {
              return;
            }
            const unis = s.contractedUniversity || (Array.isArray(s.contractedUniversities) ? s.contractedUniversities.join('، ') : s.contractedUniversities) || s.university || 'تدريب تمريض الجامعات';
            addTrainer(
              s.name,
              unis,
              'تدريب تمريض الجامعات',
              '🎓 مدرب تمريض معتمد',
              true,
              'database',
              s.phone
            );
          });
        }

        // Also check any other clinical trainers or health trainers
        Object.entries(allStudents).forEach(([dept, arr]: any) => {
          if (Array.isArray(arr)) {
            arr.forEach((s: any) => {
              if (s.assignedTrainer) return; // Skip assigned students
              if (s.internshipYear === 'مدرب سريري' || s.isUniversityTrainer || dept.startsWith('مدربي ')) {
                const isNursing = dept === 'تدريب تمريض الجامعات' || (s.studySystem || '').includes('تمريض');
                addTrainer(
                  s.name,
                  s.contractedUniversity || s.university || dept,
                  dept,
                  dept.startsWith('مدربي ') ? `🏥 ${dept}` : (isNursing ? '🩺 مدرب سريري' : '👨‍🏫 مدرب'),
                  isNursing,
                  'staff',
                  s.phone
                );
              }
            });
          }
        });
      }
    } catch (e) {
      console.error('Error fetching students for trainers:', e);
    }

    // Convert map to sorted array: Nursing Trainers FIRST, then alphabetical
    const finalList = Array.from(trainersMap.values()).sort((a, b) => {
      if (a.isNursingTrainer && !b.isNursingTrainer) return -1;
      if (!a.isNursingTrainer && b.isNursingTrainer) return 1;
      return a.name.localeCompare(b.name, 'ar');
    });

    setTrainersList(finalList);
  };

  // ── Assign student to trainer: moves student from other depts to TARGET_DEPT ───
  const handleAssignToTrainer = async (trainerName: string) => {
    if (!assignTargetApp || !trainerName) return;
    setIsAssigning(true);
    try {
      // Fetch current studentsData
      const res = await fetch('/api/students');
      if (!res.ok) throw new Error('Failed to fetch students');
      const data = await res.json();
      const studentsData: any = data.students || data || {};

      const applicantName = (assignTargetApp.name || '').trim();
      const applicantPhone = (assignTargetApp.phone || '').trim();
      const applicantId = (assignTargetApp.idNumber || '').trim();

      const TARGET_DEPT = 'تدريب تمريض الجامعات';
      if (!studentsData[TARGET_DEPT]) studentsData[TARGET_DEPT] = [];

      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();

      // ✅ 1. Remove the student from ANY other department (e.g. تمريض تدريب, تمريض امتياز, التمريض...)
      // The student MUST leave their old department completely so there are NO DUPLICATES!
      Object.keys(studentsData).forEach(dept => {
        if (dept !== TARGET_DEPT && Array.isArray(studentsData[dept])) {
          studentsData[dept] = studentsData[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. Find or update in TARGET_DEPT (تدريب تمريض الجامعات)
      const existingIdx = studentsData[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)
        );
      });

      const today = new Date().toISOString().split('T')[0];
      const formatD = (d: string) => {
        if (!d) return '';
        const parts = d.split('-');
        return parts.length === 3 ? `${parts[2]}/${parts[1]}/${parts[0]}` : d;
      };

      if (existingIdx !== -1) {
        // Student already in TARGET_DEPT → update assignedTrainer and status
        studentsData[TARGET_DEPT][existingIdx].assignedTrainer = trainerName;
        studentsData[TARGET_DEPT][existingIdx].internshipYear = 'طالب متدرب';
        studentsData[TARGET_DEPT][existingIdx].crescentJobNature = 'طالب تمريض متدرب';
        studentsData[TARGET_DEPT][existingIdx].isUniversityTrainer = false;
        studentsData[TARGET_DEPT][existingIdx].department = TARGET_DEPT;
      } else {
        // Add student to TARGET_DEPT
        const newStudent: any = {
          name: applicantName,
          phone: applicantPhone,
          idNumber: assignTargetApp.idNumber || '',
          address: assignTargetApp.address || '',
          university: assignTargetApp.university || assignTargetApp.contractedUniversity || '',
          contractedUniversity: assignTargetApp.contractedUniversity || '',
          contractedUniversities: assignTargetApp.contractedUniversities || [],
          graduatedUniversity: assignTargetApp.graduatedUniversity || '',
          graduationYear: assignTargetApp.graduationYear || '',
          startDate: formatD(assignTargetApp.startDate || assignTargetApp.trainingStartDate || today),
          endDate: formatD(assignTargetApp.endDate || assignTargetApp.trainingEndDate || ''),
          globalStartDate: formatD(assignTargetApp.startDate || today),
          globalEndDate: formatD(assignTargetApp.endDate || ''),
          studySystem: 'تمريض جامعات',
          internshipYear: 'طالب متدرب',
          isUniversityTrainer: false,
          department: TARGET_DEPT,
          originalDepartment: assignTargetApp.category || 'تمريض تدريب',
          assignedTrainer: trainerName,
          crescentJobNature: 'طالب تمريض متدرب',
          workDays: assignTargetApp.workDays || [],
          trainingDepartments: assignTargetApp.trainingDepartments || [],
        };
        studentsData[TARGET_DEPT].push(newStudent);
      }

      // ✅ 3. Guarantee NO DUPLICATES in TARGET_DEPT
      const seen = new Set<string>();
      studentsData[TARGET_DEPT] = studentsData[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;
      });

      // Update localStorage immediately
      if (typeof window !== 'undefined') {
        try {
          localStorage.setItem('studentsData', JSON.stringify(studentsData));
        } catch {}
      }

      // Save via API (PUT)
      const saveRes = await fetch('/api/students', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(studentsData),
      });
      if (!saveRes.ok) throw new Error('Failed to save');

      // Update application in database and local state
      const appId = assignTargetApp._supabaseId || assignTargetApp.id;
      if (appId) {
        await fetch('/api/applications', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            id: appId, 
            status: 'accepted', 
            assignedTrainer: trainerName,
            department: TARGET_DEPT,
            applicantData: {
              ...assignTargetApp,
              status: 'accepted',
              assignedTrainer: trainerName,
              department: TARGET_DEPT,
              acceptedAt: today,
              acceptedDept: TARGET_DEPT
            }
          }),
        });
      }

      // Update local applications state
      setApplications(prev => prev.map(a => {
        const id = a._supabaseId || a.id;
        if (id === appId || (cleanStr(a.name) === cAppName && cleanPhone(a.phone) === cAppPhone)) {
          return { ...a, status: 'accepted', assignedTrainer: trainerName, department: TARGET_DEPT };
        }
        return a;
      }));

      setShowAssignTrainerModal(false);
      setAssignTargetApp(null);
      showToast(`✅ تم نقل "${applicantName}" من تدريب التمريض وتعيينه للمدرب "${trainerName}" بنجاح بدون تكرار`);
      loadData();
    } catch (e) {
      console.error(e);
      showToast('❌ حدث خطأ أثناء التعيين، يرجى المحاولة مجدداً');
    } finally {
      setIsAssigning(false);
    }
  };

  const handleAdminLogout = () => {
    localStorage.removeItem('crescentSession');
    router.push('/admin/login');
  };

  useEffect(() => {
    const session = localStorage.getItem('crescentSession');
    if (!session) {
      router.push('/admin/login?redirect=/admin/applications');
      return;
    }
    try {
      const parsed = JSON.parse(session);
      if (!parsed.username || !parsed.loggedIn) {
        router.push('/admin/login?redirect=/admin/applications');
        return;
      }
      setCurrentUser(parsed);
    } catch {
      router.push('/admin/login?redirect=/admin/applications');
      return;
    }

    loadData();
    if (typeof window !== 'undefined') {
      const search = window.location.search;
      if (search.includes('universities') || search.includes('group=universities')) {
        setActiveTab('universities');
      } else if (search.includes('health-trainers') || search.includes('group=health-trainers')) {
        setActiveTab('health-trainers');
      }
    }
    // Auto-refresh every 15 seconds
    const interval = setInterval(loadData, 15000);
    return () => clearInterval(interval);
  }, [router]);

  // Populate edit form when opening detail modal
  const openAppDetail = async (app: any) => {
    setSelectedApp(app);
    // If applicant has photo/document that wasn't loaded in compact list, fetch full details asynchronously
    if (app.hasPhoto && (!app.photoBase64 && !app.doctorPhotoBase64)) {
      try {
        const appId = app._supabaseId || app.id;
        const res = await fetch(`/api/applications?id=${appId}`);
        if (res.ok) {
          const detail = await res.json();
          if (detail.application) {
            setSelectedApp((prev: any) => {
              if (prev && (prev.id === appId || prev._supabaseId === appId)) {
                return { ...prev, ...detail.application };
              }
              return prev;
            });
          }
        }
      } catch (e) {
        console.warn('Could not fetch full details:', e);
      }
    }
    const today = new Date();
    const endDate = new Date();
    endDate.setMonth(endDate.getMonth() + 2);
    
    const isInternship = app.category === 'المتقدمين للإمتياز' || app.categoryId === 'internship';
    const sys = isInternship ? (app.studySystem || '5+2') : '';
    // Use the start/end dates submitted in the application if available
    const rawStart = app.trainingStartDate || app.startDate || app.volunteerStartDate || app.date || today.toISOString().split('T')[0];
    const rawEnd = app.trainingEndDate || app.endDate || app.volunteerEndDate || endDate.toISOString().split('T')[0];
    const globalStartStr = toInputDate(rawStart);
    const globalEndStr = toInputDate(rawEnd);
    // Map to correct dept — check desiredDepartment first, then trainingDepartments, then category mapping, then fallback
    const trainDeptsDisplay = (app.trainingDepartments && app.trainingDepartments.length > 0)
      ? (Array.isArray(app.trainingDepartments) ? app.trainingDepartments.join('، ') : app.trainingDepartments)
      : '';
    const defaultDept = app.desiredDepartment || trainDeptsDisplay || categoryToDept[app.category] || app.department || app.assignedDept || app.targetDept || '';
    
    const isTrainerApp = isUniversityApp(app);
    const appContractedUnis = app.contractedUniversities && app.contractedUniversities.length > 0
      ? (Array.isArray(app.contractedUniversities) ? app.contractedUniversities : [app.contractedUniversities])
      : (app.contractedUniversity ? [app.contractedUniversity] : (app.previousContractedUniversity ? [app.previousContractedUniversity] : []));
    const contractedUniStr = app.contractedUniversity || appContractedUnis.join('، ') || (isTrainerApp ? (app.previousContractedUniversity || '') : '') || '';
    const gradUniStr = app.graduatedUniversity || (isTrainerApp ? (contractedUniStr !== app.university ? app.university : '') : app.university) || '';

    setEditForm({
      name: app.name || '',
      phone: app.phone || '',
      university: contractedUniStr || app.university || '',
      graduatedUniversity: gradUniStr,
      contractedUniversity: contractedUniStr,
      graduationYear: app.graduationYear || '',
      address: app.address || '',
      studySystem: sys,
      internshipYear: isInternship ? (app.internshipYear || '') : '',
      shiftSystem: '',
      startDate: globalStartStr,
      endDate: globalEndStr,
      deptStartDate: globalStartStr,
      deptEndDate: globalEndStr,
      targetDept: defaultDept,
      assignedTrainer: app.assignedTrainer || app.trainerName || app.supervisorName || ''
    });

    const monthsPer = sys === '6+1' ? 2 : 3;
    const rotEnd = new Date(globalStartStr);
    rotEnd.setMonth(rotEnd.getMonth() + monthsPer);
    setRotationCount(1);
    setRotations([{
      dept: defaultDept, 
      startDate: globalStartStr, 
      endDate: isNaN(rotEnd.getTime()) ? globalEndStr : rotEnd.toISOString().split('T')[0], 
      shiftSystem: ''
    }]);

    // Normalize training departments for university staff
    let uniDeptsList: string[] = [];
    if (Array.isArray(app.trainingDepartments)) {
      uniDeptsList = app.trainingDepartments.map((d: any) => String(d).trim()).filter(Boolean);
    } else if (typeof app.trainingDepartments === 'string' && app.trainingDepartments.trim()) {
      uniDeptsList = app.trainingDepartments.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean);
    }
    setAdminUniDepts(uniDeptsList);
    setAdminCustomDeptInput('');
  };

  // Helper to check if an application is pending
  const isPendingApp = (app: any) => {
    const s = (app.status || '').toLowerCase();
    return !s || s === 'pending' || s === 'new' || s === 'قيد الانتظار';
  };

  // Helper for cleaning Arabic strings to make search completely resilient to hamzas/tashkeel
  const cleanArabicText = (txt: string) => {
    return (txt || '')
      .toLowerCase()
      .replace(/[أإآ]/g, 'ا')
      .replace(/[ى]/g, 'ي')
      .replace(/[ة]/g, 'ه')
      .replace(/[\u064B-\u065F]/g, '')
      .trim();
  };

  // Check search match
  const matchesSearch = (app: any, query: string) => {
    if (!query.trim()) return true;
    const q = cleanArabicText(query);
    const name = cleanArabicText(app.name);
    const phone = (app.phone || '').toLowerCase();
    const idNum = (app.idNumber || '').toLowerCase();
    const uni = cleanArabicText(app.university || '');
    const cat = cleanArabicText(app.category || '');
    const dept = cleanArabicText(app.desiredDepartment || app.currentHospitalDepartment || '');
    return name.includes(q) || phone.includes(q) || idNum.includes(q) || uni.includes(q) || cat.includes(q) || dept.includes(q);
  };

  // Pending vs Archived breakdown (Exclude university, contracted doctor, and health trainer applications from Tab 1 since they have dedicated tabs)
  const pendingApplications = applications.filter(app => isPendingApp(app) && !isUniversityApp(app) && !isHealthTrainerApp(app));
  
  // Pending category grouping
  const pendingByCategory = pendingApplications.reduce((acc: any, app: any) => {
    const cat = app.category || 'غير مصنف';
    if (!acc[cat]) acc[cat] = [];
    acc[cat].push(app);
    return acc;
  }, {});

  const activeCategories = Object.keys(pendingByCategory);

  // Search filtered pending applications
  const searchedPendingApps = pendingApplications.filter(app => matchesSearch(app, pendingSearch));

  const filteredPendingApps = selectedCategory 
    ? (pendingByCategory[selectedCategory] || []).filter((app: any) => matchesSearch(app, pendingSearch))
    : searchedPendingApps;

  // Filtered Archive applications
  const filteredArchiveApps = applications.filter((app: any) => {
    // Status filter
    const status = (app.status || '').toLowerCase();
    if (archiveStatusFilter === 'accepted' && status !== 'accepted' && status !== 'مقبول') return false;
    if (archiveStatusFilter === 'rejected' && status !== 'rejected' && status !== 'مرفوض') return false;
    if (archiveStatusFilter === 'pending' && !isPendingApp(app)) return false;

    // Category filter
    if (archiveCategoryFilter !== 'all' && app.category !== archiveCategoryFilter) return false;

    // Search query
    if (archiveSearch.trim()) {
      const q = archiveSearch.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);
      const matchCat = (app.category || '').toLowerCase().includes(q);
      return matchName || matchPhone || matchId || matchUni || matchCat;
    }

    return true;
  });

  // Archive count statistics
  const acceptedCount = applications.filter(a => (a.status || '').toLowerCase() === 'accepted' || a.status === 'مقبول').length;
  const rejectedCount = applications.filter(a => (a.status || '').toLowerCase() === 'rejected' || a.status === 'مرفوض').length;
  const pendingCount = applications.filter(isPendingApp).length;

  // Universities applications
  const universityApplicationsList = applications.filter(isUniversityApp);
  const pendingUniCount = universityApplicationsList.filter(isPendingApp).length;
  const nursingUniCount = universityApplicationsList.filter(a => {
    const c = (a.category || a.categoryId || '').toLowerCase();
    return c.includes('تمريض') || c.includes('nursing');
  }).length;
  const doctorsUniCount = universityApplicationsList.filter(a => {
    const c = (a.category || a.categoryId || '').toLowerCase();
    return c.includes('متعاقد') || c.includes('doctor');
  }).length;

  const filteredUniApps = universityApplicationsList.filter((app: any) => {
    // Status filter
    const status = (app.status || '').toLowerCase();
    if (uniStatusFilter === 'accepted' && status !== 'accepted' && status !== 'مقبول') return false;
    if (uniStatusFilter === 'rejected' && status !== 'rejected' && status !== 'مرفوض') return false;
    if (uniStatusFilter === 'pending' && !isPendingApp(app)) return false;

    // Category filter
    const cat = (app.category || app.categoryId || '').toLowerCase();
    const isDoctor = cat.includes('متعاقد') || cat.includes('doctor');
    const isNursing = cat.includes('تمريض') || cat.includes('nursing');
    if (uniCategoryFilter === 'doctors' && !isDoctor) return false;
    if (uniCategoryFilter === 'nursing' && !isNursing) return false;

    // Search query
    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);
      const matchCat = (app.category || '').toLowerCase().includes(q);
      const matchDept = (app.desiredDepartment || app.currentHospitalDepartment || '').toLowerCase().includes(q);
      return matchName || matchPhone || matchId || matchUni || matchCat || matchDept;
    }

    return true;
  });

  // Health Trainers applications
  const healthTrainerApplicationsList = applications.filter(isHealthTrainerApp);
  const pendingHtCount = healthTrainerApplicationsList.filter(isPendingApp).length;

  const filteredHtApps = healthTrainerApplicationsList.filter((app: any) => {
    // Status filter
    const status = (app.status || '').toLowerCase();
    if (htStatusFilter === 'accepted' && status !== 'accepted' && status !== 'مقبول') return false;
    if (htStatusFilter === 'rejected' && status !== 'rejected' && status !== 'مرفوض') return false;
    if (htStatusFilter === 'pending' && !isPendingApp(app)) return false;

    // Department filter
    if (htDeptFilter !== 'all') {
      const cat = (app.category || app.categoryId || '').trim();
      // Match the key (مدربي أشعة) or the label variant (مدربو أشعة)
      const deptLower = htDeptFilter.toLowerCase();
      const catLower = cat.toLowerCase();
      if (!catLower.includes(deptLower.replace('مدربي ', '').replace('مدربو ', ''))) return false;
    }

    // Search query
    if (htSearch.trim()) {
      const q = htSearch.trim().toLowerCase();
      const matchName = (app.name || '').toLowerCase().includes(q);
      const matchPhone = (app.phone || '').toLowerCase().includes(q);
      const matchId = (app.idNumber || '').toLowerCase().includes(q);
      const matchCat = (app.category || '').toLowerCase().includes(q);
      const matchDept = (app.desiredDepartment || app.currentHospitalDepartment || '').toLowerCase().includes(q);
      return matchName || matchPhone || matchId || matchCat || matchDept;
    }

    return true;
  });

  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const parts = dateStr.split('-');
    if (parts.length === 3) return `${parts[2]}/${parts[1]}/${parts[0]}`;
    return dateStr;
  };

  const toInputDate = (dateStr: string) => {
    if (!dateStr) return '';
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return dateStr;
    if (dateStr.includes('/')) {
      const parts = dateStr.split('/');
      if (parts.length === 3) {
        const d = parts[0].padStart(2, '0');
        const m = parts[1].padStart(2, '0');
        const y = parts[2];
        if (y.length === 4) return `${y}-${m}-${d}`;
      }
    }
    return dateStr;
  };

  // ACCEPT: Add to dashboard AND preserve in archive with status = 'accepted'
  // ACCEPT: Add to dashboard AND preserve in archive with status = 'accepted'
  const handleAccept = async () => {
    if (!selectedApp || isProcessing) return;
    const applicantName = (editForm.name || selectedApp.name || '').trim();
    const applicantPhone = (editForm.phone || selectedApp.phone || '').trim();
    if (!applicantName) { alert('يرجى التأكد من اسم مقدم الطلب'); return; }

    setIsProcessing(true);
    try {
      let studentsData: any = null;
      try {
        const studentsRes = await fetch('/api/students');
        if (studentsRes.ok) {
          const apiData = await studentsRes.json();
          if (apiData && typeof apiData === 'object') {
            studentsData = apiData;
          }
        }
      } catch (e) {
        console.warn('API fetch failed, trying localStorage:', e);
      }
      
      if (!studentsData) {
        try {
          const localData = localStorage.getItem('studentsData');
          if (localData) {
            const parsed = JSON.parse(localData);
            if (parsed && typeof parsed === 'object') {
              studentsData = parsed;
            }
          }
        } catch (e) {
          console.error('localStorage fallback failed:', e);
        }
      }
      
      if (!studentsData || typeof studentsData !== 'object') {
        studentsData = {};
      }

      const isUni = isUniversityApp(selectedApp);
      const catLower = (selectedApp.category || selectedApp.categoryId || '').toLowerCase();
      const isDoc = catLower.includes('متعاقد') || catLower.includes('doctor');
      const targetSpecialDept = isDoc ? 'الأطباء المتعاقدون' : 'تدريب تمريض الجامعات';

      const todayStr = new Date().toISOString().split('T')[0];
      const defaultEndDate = new Date();
      defaultEndDate.setMonth(defaultEndDate.getMonth() + 3);
      const defaultEndDateStr = defaultEndDate.toISOString().split('T')[0];

      const assignedTr = (
        (editForm as any).assignedTrainer || 
        selectedApp.assignedTrainer || 
        selectedApp.trainerName || 
        selectedApp.supervisorName || 
        ''
      ).trim();

      if (isUni) {
        if (!studentsData[targetSpecialDept]) {
          studentsData[targetSpecialDept] = [];
        }

        const uniStaff: any = {
          name: applicantName,
          phone: applicantPhone,
          idNumber: selectedApp.idNumber || '',
          globalStartDate: formatDate(editForm.startDate) || formatDate(selectedApp.startDate) || formatDate(todayStr),
          globalEndDate: formatDate(editForm.endDate) || formatDate(selectedApp.endDate) || formatDate(defaultEndDateStr),
          startDate: formatDate(editForm.startDate) || formatDate(selectedApp.startDate) || formatDate(todayStr),
          endDate: formatDate(editForm.endDate) || formatDate(selectedApp.endDate) || formatDate(defaultEndDateStr),
          trainingStartDate: editForm.startDate || selectedApp.startDate || todayStr,
          trainingEndDate: editForm.endDate || selectedApp.endDate || defaultEndDateStr,
          address: editForm.address || selectedApp.address || '',
          // 🎓 الجامعة المتخرج منها
          graduatedUniversity: editForm.graduatedUniversity || selectedApp.graduatedUniversity || (editForm.contractedUniversity !== selectedApp.university ? selectedApp.university : '') || '',
          // 🤝 الجامعات المتعاقد معها
          contractedUniversity: editForm.contractedUniversity || (selectedApp.contractedUniversities ? (Array.isArray(selectedApp.contractedUniversities) ? selectedApp.contractedUniversities.join('، ') : selectedApp.contractedUniversities) : '') || selectedApp.previousContractedUniversity || selectedApp.contractedUniversity || '',
          contractedUniversities: (editForm.contractedUniversity ? editForm.contractedUniversity.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean) : (selectedApp.contractedUniversities || [])),
          university: editForm.contractedUniversity || editForm.university || (selectedApp.contractedUniversities ? (Array.isArray(selectedApp.contractedUniversities) ? selectedApp.contractedUniversities.join('، ') : selectedApp.contractedUniversities) : selectedApp.university || ''),
          graduationYear: editForm.graduationYear || selectedApp.graduationYear || '',
          department: targetSpecialDept,
          originalDepartment: targetSpecialDept,
          deptLabel: targetSpecialDept,
          studySystem: isDoc ? 'تعاقد جامعي' : 'تمريض جامعات',
          internshipYear: isDoc ? 'طبيب متعاقد' : 'مدرب سريري',
          isUniversityTrainer: !isDoc,
          isContractedDoctor: isDoc,
          crescentJobNature: selectedApp.crescentJobNature || selectedApp.employmentType || '',
          workDays: selectedApp.workDays || [],
          trainingDepartments: adminUniDepts.length > 0 ? adminUniDepts : (selectedApp.trainingDepartments || []),
          teachingCourses: selectedApp.teachingCourses || [],
          dailyStudentsCount: selectedApp.dailyStudentsCount || '',
          notes: selectedApp.notes || ''
        };

        const existingIdx = studentsData[targetSpecialDept].findIndex((s: any) => 
          (s.name === uniStaff.name && s.phone === uniStaff.phone) ||
          (uniStaff.idNumber && s.idNumber === uniStaff.idNumber)
        );
        if (existingIdx !== -1) {
          studentsData[targetSpecialDept][existingIdx] = uniStaff;
        } else {
          studentsData[targetSpecialDept].push(uniStaff);
        }
      } else {
        const assignedDept = editForm.targetDept || selectedApp.category || 'غير مصنف';
        if (!studentsData[assignedDept]) {
          studentsData[assignedDept] = [];
        }

        for (let ri = 0; ri < rotations.length; ri++) {
          const rot = rotations[ri];
          const rotDept = rot.dept || assignedDept;
          if (!studentsData[rotDept]) studentsData[rotDept] = [];

          const newStudent: any = {
            name: applicantName,
            globalStartDate: formatDate(editForm.startDate) || formatDate(selectedApp.startDate) || '',
            globalEndDate: formatDate(editForm.endDate) || formatDate(selectedApp.endDate) || '',
            startDate: formatDate(rot.startDate) || formatDate(editForm.startDate) || '',
            endDate: formatDate(rot.endDate) || formatDate(editForm.endDate) || '',
            phone: applicantPhone,
            idNumber: selectedApp.idNumber || '',
            address: editForm.address || selectedApp.address || '',
            studySystem: editForm.studySystem || selectedApp.studySystem || '',
            internshipYear: editForm.internshipYear || selectedApp.internshipYear || (assignedTr ? 'طالب متدرب' : ''),
            crescentJobNature: (selectedApp.category === 'تمريض تدريب' || selectedApp.category?.includes('تمريض')) ? 'طالب تمريض متدرب' : (selectedApp.crescentJobNature || ''),
            shiftSystem: rot.shiftSystem || 'صباحي',
            assignedTrainer: assignedTr,
            trainerName: assignedTr,
            supervisorName: assignedTr,
            supervisor: assignedTr,
            rotationNumber: ri + 1,
            totalRotations: rotations.length,
            allRotations: rotations.map((r, idx) => ({ num: idx+1, dept: r.dept, start: r.startDate, end: r.endDate }))
          };
          if ((editForm.graduatedUniversity || selectedApp.graduatedUniversity)?.trim()) {
            newStudent.graduatedUniversity = (editForm.graduatedUniversity || selectedApp.graduatedUniversity).trim();
          }
          if ((editForm.contractedUniversity || selectedApp.contractedUniversity || selectedApp.contractedUniversities)) {
            const cUni = (editForm.contractedUniversity || selectedApp.contractedUniversity || (Array.isArray(selectedApp.contractedUniversities) ? selectedApp.contractedUniversities.join('، ') : selectedApp.contractedUniversities) || '').trim();
            if (cUni) {
              newStudent.contractedUniversity = cUni;
              newStudent.contractedUniversities = cUni.split(/[,،]/).map((s: string) => s.trim()).filter(Boolean);
            }
          }
          if ((editForm.university || selectedApp.university)?.trim()) {
            newStudent.university = (editForm.university || selectedApp.university).trim();
          }
          if ((editForm.graduationYear || selectedApp.graduationYear)?.trim()) {
            newStudent.graduationYear = (editForm.graduationYear || selectedApp.graduationYear).trim();
          }
          studentsData[rotDept].push(newStudent);
        }
      }
      
      try {
        localStorage.setItem('studentsData', JSON.stringify(studentsData));
      } catch (storageErr) {
        console.warn('LocalStorage quota or storage write warning:', storageErr);
      }
      
      try {
        await fetch('/api/students', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(studentsData)
        });
      } catch (putErr) {
        console.warn('PUT /api/students warning:', putErr);
      }

      // UPDATE STATUS TO 'accepted' IN DATABASE (Preserves application in Archive)
      const finalAcceptedDept = isUni ? targetSpecialDept : (editForm.targetDept || selectedApp.category || '');
      const updatedApplicantData = {
        ...selectedApp,
        name: applicantName,
        phone: applicantPhone,
        university: editForm.university || selectedApp.university,
        graduationYear: editForm.graduationYear || selectedApp.graduationYear,
        address: editForm.address || selectedApp.address,
        studySystem: editForm.studySystem || selectedApp.studySystem,
        startDate: editForm.startDate || selectedApp.startDate || todayStr,
        endDate: editForm.endDate || selectedApp.endDate || defaultEndDateStr,
        trainingStartDate: editForm.startDate || selectedApp.startDate || todayStr,
        trainingEndDate: editForm.endDate || selectedApp.endDate || defaultEndDateStr,
        trainingDepartments: adminUniDepts.length > 0 ? adminUniDepts : (selectedApp.trainingDepartments || []),
        status: 'accepted',
        acceptedAt: todayStr,
        acceptedDept: finalAcceptedDept,
        assignedTrainer: assignedTr,
        trainerName: assignedTr,
        supervisorName: assignedTr
      };

      const appId = String(selectedApp._supabaseId || selectedApp.id || '');
      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: updatedApplicantData
            })
          });
          if (res.ok) patchDone = true;
        } catch (patchErr) {
          console.warn('Initial PATCH with full applicantData failed:', patchErr);
        }

        if (!patchDone) {
          await fetch('/api/applications', {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              id: appId,
              status: 'accepted'
            })
          });
        }
      }

      setApplications(prev => prev.map(app => {
        if (String(app._supabaseId || app.id) === appId) {
          return { ...updatedApplicantData, _supabaseId: appId };
        }
        return app;
      }));

      setSelectedApp(null);
      showToast(`✅ تم قبول ${applicantName} واعتماده بنجاح`);
    } catch (error: any) {
      console.error("Error approving application:", error);
      alert('حدث خطأ أثناء معالجة الطلب: ' + (error?.message || 'يرجى المحاولة مرة أخرى'));
    } finally {
      setIsProcessing(false);
    }
  };

  // REJECT / ARCHIVE: Update application status to 'rejected'
  const handleReject = async (appToReject = selectedApp) => {
    if (!appToReject || isProcessing) return;
    if (!confirm(`هل أنت متأكد من أرشفة/رفض طلب ${appToReject.name}؟`)) return;

    setIsProcessing(true);
    try {
      const updatedApplicantData = {
        ...appToReject,
        status: 'rejected',
        rejectedAt: new Date().toISOString().split('T')[0]
      };

      const appId = appToReject._supabaseId || appToReject.id;
      if (appId) {
        await fetch('/api/applications', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: appId,
            status: 'rejected',
            applicantData: updatedApplicantData
          })
        });
      }

      setApplications(prev => prev.map(app => {
        if (app._supabaseId === appId || app.id === appId) {
          return { ...updatedApplicantData, _supabaseId: appId };
        }
        return app;
      }));

      if (selectedApp?.id === appId || selectedApp?._supabaseId === appId) {
        setSelectedApp(null);
      }
      showToast('📁 تم أرشفة الطلب كـ (مرفوض)');
    } catch (error) {
      console.error("Error rejecting:", error);
      alert('حدث خطأ أثناء أرشفة الطلب');
    } finally {
      setIsProcessing(false);
    }
  };

  // PERMANENT DELETE: Remove from archive/database completely
  const handlePermanentDelete = async (appToDelete: any) => {
    if (!appToDelete || isProcessing) return;
    if (!confirm(`هل أنت متأكد من حذف طلب "${appToDelete.name}" نهائياً من الأرشيف؟ لا يمكن التراجع عن هذا الإجراء.`)) return;

    setIsProcessing(true);
    try {
      const appId = appToDelete._supabaseId || appToDelete.id;
      if (appId) {
        await fetch('/api/applications', {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id: appId })
        });
      }

      setApplications(prev => prev.filter(app => 
        app._supabaseId ? app._supabaseId !== appId : app.id !== appId
      ));

      if (selectedApp?.id === appId || selectedApp?._supabaseId === appId) {
        setSelectedApp(null);
      }
      showToast('🗑️ تم حذف الطلب من الأرشيف نهائياً');
    } catch (error) {
      console.error("Error deleting permanently:", error);
      alert('حدث خطأ أثناء حذف الطلب');
    } finally {
      setIsProcessing(false);
    }
  };

  const printApplication = async (appToPrint?: any) => {
    let targetApp = appToPrint || selectedApp;
    if (!targetApp) return;

    // Open print window immediately to avoid popup blockers in modern browsers
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      alert('يرجى السماح بالنوافذ المنبثقة لطباعة الاستمارة الرسمية');
      return;
    }

    // Display instant loading message while preparing high-res images
    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 the full high-resolution applicant photo
    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 || '';
            // Cache in local state
            setApplications(prev => prev.map(a => (a.id === appId || a._supabaseId === appId) ? { ...a, ...detail.application } : a));
            if (selectedApp && (selectedApp.id === appId || selectedApp._supabaseId === appId)) {
              setSelectedApp((prev: any) => prev ? { ...prev, ...detail.application } : prev);
            }
          }
        }
      } catch (e) {
        console.warn('Could not load full photo for printing:', e);
      }
    }

    // Check if university trainer or contracted doctor
    const isUni = 
      targetApp.categoryId === 'university-nursing-trainers' ||
      targetApp.categoryId === 'contracted-doctors' ||
      (targetApp.category || '').includes('مدرب') ||
      (targetApp.category || '').includes('متعاقد') ||
      (targetApp.category || '').includes('تمريض الجامعات') ||
      (targetApp.category || '').includes('طلاب التمريض في الجامعات');

    const isUniNursing = 
      targetApp.categoryId === 'university-nursing-trainers' ||
      (targetApp.category || '').includes('تمريض الجامعات') ||
      (targetApp.category || '').includes('طلاب التمريض في الجامعات');

    const isContractedDoctor = 
      targetApp.categoryId === 'contracted-doctors' ||
      (targetApp.category || '').includes('متعاقد') ||
      (targetApp.department || '') === 'الأطباء المتعاقدون' ||
      (targetApp.assignedDept || '') === 'الأطباء المتعاقدون' ||
      (targetApp.targetDept || '') === 'الأطباء المتعاقدون';

    const isModalTarget = Boolean(selectedApp && (selectedApp.id === targetApp.id || selectedApp._supabaseId === targetApp.id || selectedApp.idNumber === targetApp.idNumber));
    const activeDept = isModalTarget ? (editForm.targetDept || '') : '';
    const activeRotations = isModalTarget ? rotations : [];

    const rotDepts = (Array.isArray(targetApp.rotations) ? targetApp.rotations.map((r: any) => r.dept || r.name || '') : []).join(' ');
    const modalRotDepts = (Array.isArray(activeRotations) ? activeRotations.map((r: any) => r.dept || r.name || '') : []).join(' ');
    const trainDepts = (Array.isArray(targetApp.trainingDepartments) ? targetApp.trainingDepartments.join(' ') : (targetApp.trainingDepartments || ''));

    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,
      modalRotDepts,
      activeDept
    ].filter(Boolean).join(' ').toLowerCase();

    let isNursing = 
      isUniNursing ||
      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 && (
        searchBlob.includes('doctor') ||
        searchBlob.includes('internship') ||
        searchBlob.includes('medical') ||
        searchBlob.includes('طبيب') ||
        searchBlob.includes('أطباء') ||
        searchBlob.includes('امتياز') ||
        searchBlob.includes('طب') ||
        searchBlob.includes('جراحة') ||
        searchBlob.includes('نسائية') ||
        searchBlob.includes('أطفال') ||
        searchBlob.includes('علاج') ||
        searchBlob.includes('أشعة') ||
        searchBlob.includes('مختبر') ||
        searchBlob.includes('إسعاف')
      );

    // Extract exact department for University Nursing Trainers (e.g. قسم الطوارئ, قسم الباطني, etc.)
    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)
      : '';

    // Determine target department and category
    const categoryName = targetApp.category || targetApp.categoryId || (isUni ? (isDoctor ? 'الأطباء المتعاقدون مع الجامعات' : 'تدريب طلاب التمريض في الجامعات') : (isNursing ? 'تمريض تدريب' : 'طب تدريب'));

    let targetDept = (isModalTarget && activeDept) ? activeDept : (targetApp.assignedDept || targetApp.targetDept || targetApp.desiredDepartment || targetApp.department || '');

    if (isUniNursing) {
      targetDept = uniTrainDeptsDisplay || (isModalTarget && activeDept && activeDept !== 'تدريب تمريض الجامعات' ? activeDept : '') || targetApp.assignedDept || targetApp.targetDept || targetApp.desiredDepartment || targetApp.department || '';
      if (!targetDept || targetDept === 'تدريب تمريض الجامعات' || targetDept.includes('تقديم طلبات لتدريب طلاب التمريض')) {
        targetDept = uniTrainDeptsDisplay || 'قسم التمريض العام والطوارئ';
      }
    } else if (!targetDept) {
      targetDept = isUni ? (isDoctor ? 'الأطباء المتعاقدون' : 'تدريب تمريض الجامعات') : (isNursing ? 'تمريض تدريب' : 'طب تدريب');
    }

    if (
      targetDept.includes('تمريض') || 
      targetDept.includes('nursing') || 
      targetDept.includes('ممرض') || 
      targetDept.includes('قبالة') ||
      targetDept.includes('قباله') ||
      targetDept === 'التمريض' ||
      targetDept === 'التمريض العام' ||
      targetDept === 'تمريض تدريب' ||
      targetDept === 'تمريض امتياز' ||
      targetDept === 'تمريض تطوع' ||
      targetDept === 'تدريب تمريض الجامعات'
    ) {
      isNursing = true;
    }

    // Dates formatting
    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;
    };

    // Use dates from active editForm if currently open in modal
    const hasModalDates = selectedApp && (selectedApp.id === targetApp.id || selectedApp._supabaseId === targetApp.id || selectedApp.idNumber === targetApp.idNumber);
    const activeStart = (hasModalDates && editForm.startDate) ? editForm.startDate : null;
    const activeEnd = (hasModalDates && editForm.endDate) ? editForm.endDate : null;

    const rawStart = activeStart || 
      targetApp.trainingStartDate || 
      targetApp.startDate || 
      targetApp.deptStartDate || 
      targetApp.globalStartDate || 
      targetApp.volunteerStartDate || 
      targetApp.desiredStartDate || 
      targetApp.date || 
      targetApp.createdAt || 
      targetApp.created_at;

    let rawEnd = activeEnd || 
      targetApp.trainingEndDate || 
      targetApp.endDate || 
      targetApp.deptEndDate || 
      targetApp.globalEndDate || 
      targetApp.volunteerEndDate;

    // If rawEnd is missing, calculate standard academic semester end
    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 workShift = targetApp.shiftSystem || targetApp.workShift || targetApp.workHours || 'افتراضي';

    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 === 'مرفوض') 
        ? 'مرفوض' 
        : 'قيد المعالجة';

    const isInternship = 
      targetApp.category === 'المتقدمين للإمتياز' ||
      targetApp.category === 'تمريض امتياز' ||
      targetApp.categoryId === 'internship' ||
      targetApp.categoryId === 'nursing-internship' ||
      (targetApp.category || '').includes('امتياز');

    const studySys = targetApp.studySystem || targetApp.internshipYear || '';
    let gradAndSystem = targetApp.graduationYear || '—';
    if (isInternship && studySys) {
      gradAndSystem = `${targetApp.graduationYear || '—'} - (${studySys})`;
    }

    // Rotations / Schedule rows
    let rotationsRows = '';
    if (isUniNursing && Array.isArray(targetApp.trainingDepartments) && targetApp.trainingDepartments.length > 0) {
      rotationsRows = targetApp.trainingDepartments.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 if (!isUni && Array.isArray(targetApp.rotations) && targetApp.rotations.length > 0) {
      rotationsRows = targetApp.rotations.map((r: any, 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: 13px; font-weight: 800; color: #0f172a;">${r.dept || targetDept}</td>
          <td dir="ltr" style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12.5px; font-weight: 700; color: #0f172a;">${formatIsoDate(r.startDate || r.start)}</td>
          <td dir="ltr" style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12.5px; font-weight: 700; color: #0f172a;">${formatIsoDate(r.endDate || r.end)}</td>
          <td style="border: 1.2px solid #94a3b8; padding: 14px 8px; font-size: 12px; font-weight: 700; color: #0f172a;">${r.shiftSystem || workShift}</td>
        </tr>
      `).join('');
    } else {
      rotationsRows = `
        <tr>
          <td style="border: 1.2px solid #94a3b8; padding: 16px 8px; font-size: 12px; font-weight: 700; color: #0f172a;">${isUni ? 'اعتماد 1' : 'الدورة 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;">${isUni ? workDaysDisplay : workShift}</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)' : isContractedDoctor ? 'repeat(3, 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);">
              ${isUniNursing ? `القسم: ${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">💫 ${isUniNursing ? 'القسم المخصص والوجهة المعتمدة لتدريب تمريض الجامعات:' : (isDoctor ? 'القسم المخصص والوجهة المعتمدة للأطباء المتعاقدين:' : 'القسم المخصص والوجهة المعتمدة للتدريب:')}</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;">${isUni ? (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;">${isUni ? 'الجامعة / الجامعات:' : 'الجامعة / الكلية:'}</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;">${isUni ? 'فترة التدريب / التعاقد:' : 'سنة التخرج / النظام:'}</span>
              <span class="info-value" dir="ltr" style="${isUni ? 'color: #1e3a8a; font-weight: 900;' : ''}">
                ${isUni ? `من ${startDate} إلى ${endDate}` : gradAndSystem}
              </span>
            </div>

            ${isUni ? `
            <!-- 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>
            ` : ''}

            ${isUniNursing ? `
            <!-- 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">${isUni ? 'تفاصيل فترة التدريب / التعاقد والجدول الزمني المعتمد' : 'تفاصيل الدورات والجدول الزمني (Rotations)'}</div>
        <table class="rotations-table">
          <thead>
            <tr>
              <th style="width: 14%;">${isUni ? 'رقم الاعتماد' : 'رقم الدورة'}</th>
              <th style="width: 28%;">${isUni ? 'القسم والوجهة المعتمدة' : 'القسم المخصص'}</th>
              <th style="width: 20%;">تاريخ البدء (من)</th>
              <th style="width: 20%;">تاريخ الانتهاء (إلى)</th>
              <th style="width: 18%;">${isUni ? 'أيام وساعات الدوام' : 'نظام الدوام'}</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 -->
          ${!isContractedDoctor ? `
          <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();
  };

  // Helper function for status badges
  const renderStatusBadge = (status: string) => {
    const s = (status || '').toLowerCase();
    if (s === 'accepted' || s === 'مقبول') {
      return (
        <span style={{ background: '#dcfce7', color: '#15803d', padding: '4px 12px', borderRadius: '20px', fontSize: '0.8rem', fontWeight: '700', display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
          <CheckCircle size={14} /> مقبول
        </span>
      );
    }
    if (s === 'rejected' || s === 'مرفوض') {
      return (
        <span style={{ background: '#fee2e2', color: '#b91c1c', padding: '4px 12px', borderRadius: '20px', fontSize: '0.8rem', fontWeight: '700', display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
          <XCircle size={14} /> مرفوض
        </span>
      );
    }
    return (
      <span style={{ background: '#fef3c7', color: '#b45309', padding: '4px 12px', borderRadius: '20px', fontSize: '0.8rem', fontWeight: '700', display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
        <Calendar size={14} /> قيد الانتظار
      </span>
    );
  };

  return (
    <div className="dashboard-container">
      {/* Header Banner */}
      <div className="header" style={{ padding: '30px', marginBottom: '25px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '20px' }}>
        <div className="header-content">
          <h1>لوحة إدارة الطلبات والأرشيف</h1>
          <div className="subtitle">عرض طلبات التدريب، أرشفة الطلبات، والقبول في النظام</div>
          {currentUser && (
            <div style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: '10px',
              marginTop: '12px',
              padding: '6px 16px',
              background: 'rgba(255, 255, 255, 0.15)',
              borderRadius: '20px',
              border: '1px solid rgba(255, 255, 255, 0.25)',
              fontSize: '0.86rem',
              color: 'white',
              backdropFilter: 'blur(8px)'
            }}>
              <i className="fas fa-user-shield" style={{ color: '#ffd700' }} />
              <span>{currentUser.username === 'omkhaled' || currentUser.username === 'nissren' || (currentUser.displayName || '').includes('خالد') || (currentUser.displayName || '').includes('نسرين') ? 'المديرة: ' : 'المشرف المسجل: '}<strong>{currentUser.displayName || currentUser.username}</strong></span>
              <button
                type="button"
                onClick={handleAdminLogout}
                style={{
                  background: 'rgba(239, 68, 68, 0.3)',
                  border: '1px solid rgba(239, 68, 68, 0.5)',
                  color: '#fee2e2',
                  padding: '3px 10px',
                  borderRadius: '12px',
                  cursor: 'pointer',
                  fontSize: '0.78rem',
                  fontWeight: 700,
                  fontFamily: 'inherit',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '4px'
                }}
                title="تسجيل الخروج من لوحة الإدارة"
              >
                <i className="fas fa-sign-out-alt" />
                خروج
              </button>
            </div>
          )}
        </div>

        {/* Supervisor Badge with Image - Extra Large & Clear */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '16px',
          background: 'rgba(255, 255, 255, 0.22)',
          backdropFilter: 'blur(20px)',
          padding: '10px 28px 10px 12px',
          borderRadius: '60px',
          border: '2px solid rgba(255, 215, 0, 0.7)',
          boxShadow: '0 12px 35px rgba(0,0,0,0.35)'
        }}>
          <img 
            src="/supervisor.png" 
            alt="أ. نسرين عابدين" 
            style={{
              width: '85px',
              height: '85px',
              borderRadius: '50%',
              objectFit: 'cover',
              objectPosition: 'center top',
              border: '3.5px solid #ffd700',
              boxShadow: '0 6px 20px rgba(0,0,0,0.45)',
              background: '#ffffff'
            }} 
          />
          <div>
            <div style={{ fontSize: '0.88rem', color: '#ffd700', fontWeight: '800', letterSpacing: '0.6px', marginBottom: '2px' }}>مديرة وحدة التطوير والتدريب</div>
            <div style={{ fontSize: '1.35rem', color: 'white', fontWeight: '900', display: 'flex', alignItems: 'center', gap: '8px', textShadow: '0 2px 8px rgba(0,0,0,0.4)' }}>
              <i className="fas fa-star-and-crescent" style={{ fontSize: '1rem', color: '#ffd700' }}></i>
              أ. نسرين عابدين (أم خالد)
              <i className="fas fa-star-and-crescent" style={{ fontSize: '1rem', color: '#ffd700' }}></i>
            </div>
          </div>
        </div>
      </div>

      {/* Navigation Toolbar & Main Tabs */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '15px', marginBottom: '25px' }}>
        <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
          <Link href="/" className="back-btn" style={{ 
            display: 'inline-flex', alignItems: 'center', gap: '10px',
            padding: '12px 22px', background: 'var(--card-bg)', borderRadius: '12px', 
            textDecoration: 'none', color: 'var(--text)', fontWeight: 'bold', boxShadow: 'var(--shadow)'
          }}>
            <ArrowRight size={20} />
            عودة للرئيسية
          </Link>

          {selectedCategory && activeTab === 'pending' && (
            <button onClick={() => setSelectedCategory(null)} style={{ 
              display: 'inline-flex', alignItems: 'center', gap: '10px',
              padding: '12px 22px', background: 'var(--primary)', borderRadius: '12px', 
              border: 'none', color: 'white', fontWeight: 'bold', boxShadow: 'var(--shadow)',
              cursor: 'pointer', fontFamily: 'Tajawal'
            }}>
              <Grid size={20} />
              عرض كل تصنيفات الطلبات
            </button>
          )}
        </div>

        {/* Tab Switcher: Pending vs Archive */}
        <div style={{ display: 'flex', background: 'var(--card-bg)', padding: '5px', borderRadius: '14px', boxShadow: 'var(--shadow)', border: '1px solid var(--border)' }}>
          <button
            onClick={() => { setActiveTab('pending'); setSelectedCategory(null); }}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: '8px',
              padding: '10px 22px', borderRadius: '10px', border: 'none',
              background: activeTab === 'pending' ? 'var(--primary)' : 'transparent',
              color: activeTab === 'pending' ? 'white' : 'var(--text)',
              fontWeight: 'bold', fontFamily: 'Tajawal', cursor: 'pointer', transition: 'all 0.2s',
              fontSize: '0.95rem'
            }}
          >
            <FileText size={18} />
            الطلبات الجديدة ({pendingApplications.length})
          </button>
          <button
            onClick={() => { setActiveTab('archive'); setSelectedCategory(null); }}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: '8px',
              padding: '10px 22px', borderRadius: '10px', border: 'none',
              background: activeTab === 'archive' ? '#4338ca' : 'transparent',
              color: activeTab === 'archive' ? 'white' : 'var(--text)',
              fontWeight: 'bold', fontFamily: 'Tajawal', cursor: 'pointer', transition: 'all 0.2s',
              fontSize: '0.95rem'
            }}
          >
            <Archive size={18} />
            أرشيف الطلبات ({applications.length})
          </button>
          <button
            onClick={() => { setActiveTab('universities'); setSelectedCategory(null); }}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: '8px',
              padding: '10px 22px', borderRadius: '10px',
              background: activeTab === 'universities' ? 'linear-gradient(135deg, #1e1b4b 0%, #312e81 100%)' : 'transparent',
              color: activeTab === 'universities' ? 'white' : 'var(--text)',
              fontWeight: 'bold', fontFamily: 'Tajawal', cursor: 'pointer', transition: 'all 0.2s',
              fontSize: '0.95rem',
              border: activeTab === 'universities' ? '1.5px solid #a855f7' : 'none',
              boxShadow: activeTab === 'universities' ? '0 0 15px rgba(168, 85, 247, 0.4)' : 'none'
            }}
          >
            <GraduationCap size={18} color={activeTab === 'universities' ? '#c084fc' : undefined} />
            <span>طلبات تدريب تمريض الجامعات والأطباء المتعاقدون</span>
            {universityApplicationsList.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 8px rgba(239, 68, 68, 0.6)' : 'none'
              }}>
                {universityApplicationsList.length}
              </span>
            )}
          </button>
          <button
            onClick={() => { setActiveTab('health-trainers'); setSelectedCategory(null); }}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: '8px',
              padding: '10px 22px', borderRadius: '10px',
              background: activeTab === 'health-trainers' ? 'linear-gradient(135deg, #0c4a6e 0%, #0891b2 100%)' : 'transparent',
              color: activeTab === 'health-trainers' ? 'white' : 'var(--text)',
              fontWeight: 'bold', fontFamily: 'Tajawal', cursor: 'pointer', transition: 'all 0.2s',
              fontSize: '0.95rem',
              border: activeTab === 'health-trainers' ? '1.5px solid #38bdf8' : 'none',
              boxShadow: activeTab === 'health-trainers' ? '0 0 15px rgba(56, 189, 248, 0.4)' : 'none'
            }}
          >
            <i className="fas fa-chalkboard-teacher" style={{ fontSize: '1rem', color: activeTab === 'health-trainers' ? '#7dd3fc' : undefined }} />
            <span>مدربين الأقسام الصحية المساندة</span>
            {healthTrainerApplicationsList.length > 0 && (
              <span style={{
                background: pendingHtCount > 0 ? '#ef4444' : '#10b981',
                color: 'white',
                borderRadius: '20px',
                padding: '2px 8px',
                fontSize: '0.75rem',
                fontWeight: '900',
                boxShadow: pendingHtCount > 0 ? '0 0 8px rgba(239, 68, 68, 0.6)' : 'none'
              }}>
                {healthTrainerApplicationsList.length}
              </span>
            )}
          </button>
        </div>
      </div>

      {isLoading ? (
        <div className="loading-content" style={{ marginTop: '50px' }}>
          <div className="loading-spinner"></div>
          <p>جاري تحميل الطلبات والأرشيف...</p>
        </div>
      ) : (
        <>
          {/* ═════════════════ TAB 1: PENDING APPLICATIONS ═════════════════ */}
          {activeTab === 'pending' && (
            <>
              {/* Dedicated Banner for University Training & Contracted Doctors Tab */}
              {universityApplicationsList.length > 0 && (
                <div style={{
                  background: 'linear-gradient(135deg, rgba(30, 27, 75, 0.04) 0%, rgba(49, 46, 129, 0.08) 100%)',
                  border: '1.5px solid rgba(99, 102, 241, 0.35)',
                  borderRadius: '16px',
                  padding: '14px 20px',
                  marginBottom: '20px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  flexWrap: 'wrap',
                  gap: '14px',
                  boxShadow: '0 2px 10px rgba(99, 102, 241, 0.06)'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <div style={{
                      width: '42px', height: '42px', borderRadius: '12px',
                      background: 'linear-gradient(135deg, #312e81 0%, #1e1b4b 100%)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: '#c084fc', flexShrink: 0,
                      boxShadow: '0 4px 12px rgba(49, 46, 129, 0.25)'
                    }}>
                      <GraduationCap size={24} />
                    </div>
                    <div>
                      <div style={{ fontWeight: 800, color: '#312e81', fontSize: '0.98rem' }}>
                        طلبات تدريب تمريض الجامعات والأطباء المتعاقدون مفصولة في تبويبها المخصص
                      </div>
                      <div style={{ fontSize: '0.84rem', color: '#64748b', marginTop: '2px' }}>
                        تم نقل وإتاحة طلبات تدريب طلاب تمريض الجامعات والأطباء المتعاقدون ({universityApplicationsList.length} طلب) في التبويب الثالث المخصص لها.
                      </div>
                    </div>
                  </div>
                  <button
                    onClick={() => { setActiveTab('universities'); setSelectedCategory(null); }}
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '8px',
                      padding: '9px 20px',
                      background: 'linear-gradient(135deg, #1e1b4b 0%, #312e81 100%)',
                      color: 'white',
                      borderRadius: '10px',
                      border: '1px solid #818cf8',
                      fontWeight: 700,
                      fontSize: '0.88rem',
                      cursor: 'pointer',
                      fontFamily: 'Tajawal',
                      boxShadow: '0 4px 14px rgba(49, 46, 129, 0.3)',
                      transition: 'all 0.2s'
                    }}
                  >
                    <GraduationCap size={16} color="#c084fc" />
                    فتح طلبات الجامعات ({universityApplicationsList.length})
                  </button>
                </div>
              )}

              {/* Dedicated Banner for Health Support Trainers Tab */}
              {healthTrainerApplicationsList.length > 0 && (
                <div style={{
                  background: 'linear-gradient(135deg, rgba(8,145,178,0.04) 0%, rgba(3,105,161,0.08) 100%)',
                  border: '1.5px solid rgba(8,145,178,0.3)',
                  borderRadius: '16px',
                  padding: '14px 20px',
                  marginBottom: '20px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  flexWrap: 'wrap',
                  gap: '14px'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <div style={{
                      width: '42px', height: '42px', borderRadius: '12px',
                      background: 'linear-gradient(135deg, #0891b2 0%, #0369a1 100%)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: 'white', flexShrink: 0,
                      boxShadow: '0 4px 12px rgba(8,145,178,0.25)',
                      fontSize: '1.2rem'
                    }}>🏥</div>
                    <div>
                      <div style={{ fontWeight: 800, color: '#0369a1', fontSize: '0.98rem' }}>
                        طلبات مدربين الأقسام الصحية المساندة مفصولة في تبويبها المخصص
                      </div>
                      <div style={{ fontSize: '0.84rem', color: '#64748b', marginTop: '2px' }}>
                        طلبات مدربي (الأشعة، العلاج الطبيعي، الصيدلة، التغذية، المختبر، الهندسة الطبية، العلاج الوظيفي) — {healthTrainerApplicationsList.length} طلب
                      </div>
                    </div>
                  </div>
                  <button
                    onClick={() => { setActiveTab('health-trainers'); setSelectedCategory(null); }}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: '8px',
                      padding: '9px 20px',
                      background: 'linear-gradient(135deg, #0c4a6e 0%, #0891b2 100%)',
                      color: 'white', borderRadius: '10px',
                      border: '1px solid #38bdf8', fontWeight: 700, fontSize: '0.88rem',
                      cursor: 'pointer', fontFamily: 'Tajawal',
                      boxShadow: '0 4px 14px rgba(8,145,178,0.3)', transition: 'all 0.2s'
                    }}
                  >
                    🏥 فتح طلبات المدربين ({healthTrainerApplicationsList.length})
                  </button>
                </div>
              )}

              {/* Top Controls: Search Bar & View Mode Toggle */}
              <div style={{
                display: 'flex',
                gap: '14px',
                alignItems: 'center',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                marginBottom: '22px',
                background: 'var(--card-bg)',
                padding: '16px 20px',
                borderRadius: '16px',
                border: '1px solid var(--border)',
                boxShadow: 'var(--shadow)'
              }}>
                {/* Search input with live count */}
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: '1 1 340px', position: 'relative' }}>
                  <Search size={19} color="var(--text-light)" style={{ position: 'absolute', right: '14px' }} />
                  <input
                    type="text"
                    placeholder="🔍 بحث سريع في الطلبات الجديدة (الاسم، الهاتف، الهوية، الجامعة، القسم)..."
                    value={pendingSearch}
                    onChange={(e) => setPendingSearch(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '11px 42px 11px 14px',
                      borderRadius: '10px',
                      border: '1.5px solid var(--border)',
                      background: 'var(--bg)',
                      color: 'var(--text)',
                      fontSize: '0.95rem',
                      fontFamily: 'Tajawal',
                      outline: 'none'
                    }}
                  />
                  {pendingSearch && (
                    <button
                      onClick={() => setPendingSearch('')}
                      style={{
                        position: 'absolute', left: '12px', background: 'none', border: 'none',
                        cursor: 'pointer', color: 'var(--text-light)', fontWeight: 800, fontSize: '1rem'
                      }}
                      title="مسح البحث"
                    >
                      ✕
                    </button>
                  )}
                </div>

                {/* View mode toggle buttons */}
                <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                  <button
                    onClick={() => { setPendingViewMode('cards'); setSelectedCategory(null); }}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: '6px',
                      padding: '10px 16px', borderRadius: '10px',
                      border: '1.5px solid var(--border)',
                      background: (pendingViewMode === 'cards' && !pendingSearch.trim() && !selectedCategory) ? 'var(--primary)' : 'var(--card-bg)',
                      color: (pendingViewMode === 'cards' && !pendingSearch.trim() && !selectedCategory) ? 'white' : 'var(--text)',
                      fontWeight: 700, fontFamily: 'Tajawal', cursor: 'pointer', fontSize: '0.88rem', transition: 'all 0.2s'
                    }}
                  >
                    <Grid size={16} />
                    <span>عرض البطاقات حسب الأقسام ({activeCategories.length})</span>
                  </button>

                  <button
                    onClick={() => { setPendingViewMode('all'); setSelectedCategory(null); }}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: '6px',
                      padding: '10px 18px', borderRadius: '10px',
                      border: '1.5px solid var(--border)',
                      background: (pendingViewMode === 'all' || pendingSearch.trim()) ? 'linear-gradient(135deg, #0284c7 0%, #0369a1 100%)' : 'var(--card-bg)',
                      color: (pendingViewMode === 'all' || pendingSearch.trim()) ? 'white' : 'var(--text)',
                      fontWeight: 700, fontFamily: 'Tajawal', cursor: 'pointer', fontSize: '0.88rem',
                      boxShadow: (pendingViewMode === 'all' || pendingSearch.trim()) ? '0 4px 12px rgba(2, 132, 199, 0.3)' : 'none',
                      transition: 'all 0.2s'
                    }}
                  >
                    <List size={16} />
                    <span>عرض كافة الطلبات الجديدة ({searchedPendingApps.length})</span>
                  </button>
                </div>
              </div>

              {/* View 1: Categorized Cards (when not searching and mode is 'cards' and no specific category chosen) */}
              {!selectedCategory && !pendingSearch.trim() && pendingViewMode === 'cards' && (
                <div className="departments-grid">
                  {activeCategories.length === 0 ? (
                    <div style={{ gridColumn: '1/-1', textAlign: 'center', padding: '60px', background: 'var(--card-bg)', borderRadius: '20px', boxShadow: 'var(--shadow)' }}>
                      <FileText size={50} color="var(--text-light)" style={{ marginBottom: '20px' }} />
                      <h3>لا توجد طلبات جديدة حالياً</h3>
                      <p style={{ color: 'var(--text-muted)', marginTop: '8px' }}>جميع الطلبات تمت معالجتها وحفظها في الأرشيف.</p>
                      <button onClick={() => setActiveTab('archive')} style={{ marginTop: '16px', padding: '10px 20px', borderRadius: '10px', background: '#4338ca', color: 'white', border: 'none', fontWeight: 700, cursor: 'pointer', fontFamily: 'Tajawal' }}>
                        الانتقال إلى أرشيف الطلبات
                      </button>
                    </div>
                  ) : (
                    activeCategories.map((cat) => {
                      const config = categoryConfig[cat] || { icon: FileText, color: 'linear-gradient(135deg, #0284c7 0%, #0369a1 100%)' };
                      const Icon = config.icon;
                      return (
                        <div key={cat} className="department-card" onClick={() => setSelectedCategory(cat)}>
                          <div className="card-header" style={{ background: config.color }}>
                            <div className="icon" style={{ display: 'flex', justifyContent: 'center' }}>
                              <Icon size={40} />
                            </div>
                            <h3 style={{ fontSize: '1.2rem' }}>{cat}</h3>
                            <div className="count">{pendingByCategory[cat].length}</div>
                            <div className="count-label">طلب جديد</div>
                          </div>
                          <div className="card-body">
                            <div className="click-hint">
                              <List size={16} />
                              <span>عرض الطلبات</span>
                            </div>
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              )}

              {/* View 2: Single Selected Category Table */}
              {selectedCategory && !pendingSearch.trim() && pendingViewMode === 'cards' && (
                <div className="students-section visible" style={{ display: 'block' }}>
                  <div className="section-header">
                    <div className="title-group" style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                      <button
                        onClick={() => setSelectedCategory(null)}
                        style={{
                          display: 'inline-flex', alignItems: 'center', gap: '6px',
                          padding: '8px 14px', borderRadius: '8px', border: '1px solid var(--border)',
                          background: 'var(--card-bg)', color: 'var(--text)', cursor: 'pointer',
                          fontWeight: 700, fontSize: '0.85rem'
                        }}
                      >
                        <ArrowRight size={16} />
                        <span>عودة لكافة الأقسام</span>
                      </button>
                      <h2 style={{ margin: 0 }}>
                        <List size={24} />
                        طلبات جديدة: {selectedCategory}
                      </h2>
                    </div>
                    <div className="controls-group">
                      <span style={{ fontWeight: 'bold', color: 'var(--text-light)' }}>
                        العدد: {filteredPendingApps.length}
                      </span>
                    </div>
                  </div>
                  
                  <div className="table-container">
                    <table>
                      <thead>
                        <tr>
                          <th>#</th>
                          <th>الصورة والاسم</th>
                          <th>الجامعة</th>
                          <th>رقم الهوية</th>
                          <th>رقم الهاتف</th>
                          <th>تاريخ التقديم</th>
                          <th>ورقة النقابة / الصورة</th>
                          <th>الإجراءات</th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredPendingApps.map((app: any, index: number) => {
                          const photo = app.photoBase64 || app.doctorPhotoBase64 || '';
                          const hasValidUnionPaper = Boolean(
                            app.unionPaperBase64 &&
                            app.unionPaperBase64 !== (app.photoBase64 || app.doctorPhotoBase64)
                          );
                          return (
                            <tr key={app._supabaseId || app.id || index}>
                              <td style={{ fontWeight: 700, color: 'var(--primary)' }}>{index + 1}</td>
                              <td>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                  {photo ? (
                                    <img 
                                      src={photo} 
                                      alt="" 
                                      style={{ width: '38px', height: '38px', borderRadius: '50%', objectFit: 'cover', border: '2px solid var(--primary)' }} 
                                    />
                                  ) : (
                                    <div style={{ width: '38px', height: '38px', borderRadius: '50%', background: '#e0e7ff', color: '#3730a3', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: '0.85rem' }}>
                                      {app.name ? app.name.slice(0, 1) : 'M'}
                                    </div>
                                  )}
                                  <div>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
                                      <strong style={{ fontSize: '0.95rem' }}>{app.name}</strong>
                                      {getAppCompleteness(app).isFull ? (
                                        <span style={{
                                          display: 'inline-flex', alignItems: 'center', gap: '3px',
                                          background: 'rgba(16, 185, 129, 0.15)', color: '#059669',
                                          border: '1px solid rgba(16, 185, 129, 0.3)', borderRadius: '10px',
                                          padding: '1px 7px', fontSize: '0.72rem', fontWeight: 800
                                        }} title="مستوفي كافة الشروط والصورة ورقم الهاتف بنسبة 100%">
                                          <CheckCircle size={11} /> 100/100
                                        </span>
                                      ) : (
                                        <span style={{
                                          display: 'inline-flex', alignItems: 'center', gap: '3px',
                                          background: 'rgba(245, 158, 11, 0.12)', color: '#d97706',
                                          border: '1px solid rgba(245, 158, 11, 0.3)', borderRadius: '10px',
                                          padding: '1px 6px', fontSize: '0.7rem', fontWeight: 700
                                        }}>
                                          {getAppCompleteness(app).score}/100
                                        </span>
                                      )}
                                    </div>
                                    {app.email && (
                                      <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{app.email}</div>
                                    )}
                                  </div>
                                </div>
                              </td>
                              <td>{app.university || '—'}</td>
                              <td>{app.idNumber || '—'}</td>
                              <td>
                                <a href={`tel:${app.phone}`} className="phone-link" onClick={(e) => e.stopPropagation()}>
                                  <Phone size={14} /> {app.phone}
                                </a>
                              </td>
                              <td>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                  <Calendar size={14} color="var(--text-light)" />
                                  {app.date}
                                </div>
                                {(app.trainingStartDate || app.startDate || app.volunteerStartDate) && (
                                  <div style={{ fontSize: '0.75rem', color: '#059669', fontWeight: 700, marginTop: '3px' }}>
                                    تدريب: {formatDate(app.trainingStartDate || app.startDate || app.volunteerStartDate)} → {formatDate(app.trainingEndDate || app.endDate || app.volunteerEndDate)}
                                  </div>
                                )}
                              </td>
                              <td>
                                {hasValidUnionPaper ? (
                                  <a
                                    href={app.unionPaperBase64}
                                    download={app.unionPaperFileName || `${app.name}_ورقة_النقابة`}
                                    style={{ color: '#2563eb', fontWeight: 600, fontSize: '0.85rem', textDecoration: 'underline' }}
                                  >
                                    📥 ورقة النقابة
                                  </a>
                                ) : (
                                  <span style={{ color: '#94a3b8', fontSize: '0.8rem' }}>لا يوجد</span>
                                )}
                              </td>
                              <td>
                                <div style={{ display: 'flex', gap: '6px', justifyContent: 'center', flexWrap: 'wrap' }}>
                                  <button onClick={() => openAppDetail(app)} className="btn-icon" style={{ 
                                    background: 'var(--success)', color: 'white', width: '34px', height: '34px',
                                    border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                    alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
                                  }} title="معاينة وقبول">
                                    <UserPlus size={16} />
                                  </button>
                                  {/* ── Assign to Trainer button ── */}
                                  <button
                                    onClick={(e) => { e.stopPropagation(); openAssignTrainerModal(app); }}
                                    className="btn-icon"
                                    style={{
                                      background: 'linear-gradient(135deg, #0891b2, #0e7490)', color: 'white',
                                      width: '34px', height: '34px', border: 'none', borderRadius: '8px',
                                      cursor: 'pointer', display: 'flex', alignItems: 'center',
                                      justifyContent: 'center', transition: 'all 0.2s',
                                      boxShadow: '0 2px 8px rgba(8,145,178,0.4)'
                                    }}
                                    title="تعيين لمدرب سريري"
                                  >
                                    <i className="fas fa-chalkboard-teacher" style={{ fontSize: '14px' }} />
                                  </button>
                                  <button
                                    onClick={() => {
                                      setSelectedApp(app);
                                      printApplication(app);
                                    }}
                                    className="btn-icon"
                                    style={{
                                      background: '#0284c7', color: 'white', width: '34px', height: '34px',
                                      border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                      alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
                                    }}
                                    title="طباعة الاستمارة الرسمية A4"
                                  >
                                    <Download size={16} />
                                  </button>
                                  <button onClick={(e) => { e.stopPropagation(); handleReject(app); }} className="btn-icon" style={{ 
                                    background: '#dc3545', color: 'white', width: '34px', height: '34px',
                                    border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                    alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
                                  }} title="أرشفة / رفض">
                                    <Archive size={16} />
                                  </button>
                                </div>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {/* View 3: Comprehensive Unified Table (when viewMode is 'all' or when searching) */}
              {(pendingViewMode === 'all' || pendingSearch.trim()) && (
                <div className="students-section visible" style={{ display: 'block' }}>
                  <div className="section-header">
                    <div className="title-group">
                      <h2>
                        <List size={24} />
                        {pendingSearch.trim() ? `نتائج البحث في الطلبات الجديدة (${searchedPendingApps.length})` : `كافة الطلبات الجديدة (${pendingApplications.length})`}
                      </h2>
                    </div>
                    <div className="controls-group">
                      <span style={{ fontWeight: 'bold', color: 'var(--text-light)' }}>
                        المعروض: {searchedPendingApps.length} من أصل {pendingApplications.length}
                      </span>
                    </div>
                  </div>

                  <div className="table-container">
                    {searchedPendingApps.length === 0 ? (
                      <div style={{ textAlign: 'center', padding: '50px', background: 'var(--card-bg)', borderRadius: '16px' }}>
                        <FileText size={45} color="var(--text-muted)" style={{ marginBottom: '16px' }} />
                        <h4>لا توجد طلبات جديدة تطابق البحث "{pendingSearch}"</h4>
                        <p style={{ color: 'var(--text-muted)', margin: '8px 0 0 0' }}>يرجى التحقق من الاسم أو رقم الهاتف أو مسح نص البحث.</p>
                      </div>
                    ) : (
                      <table>
                        <thead>
                          <tr>
                            <th>#</th>
                            <th>الصورة والاسم</th>
                            <th>القسم / التخصص</th>
                            <th>الجامعة</th>
                            <th>رقم الهوية</th>
                            <th>رقم الهاتف</th>
                            <th>تاريخ التقديم</th>
                            <th>ورقة النقابة / الصورة</th>
                            <th>الإجراءات</th>
                          </tr>
                        </thead>
                        <tbody>
                          {searchedPendingApps.map((app: any, index: number) => {
                            const photo = app.photoBase64 || app.doctorPhotoBase64 || '';
                            const hasValidUnionPaper = Boolean(
                              app.unionPaperBase64 &&
                              app.unionPaperBase64 !== (app.photoBase64 || app.doctorPhotoBase64)
                            );
                            const catConfig = categoryConfig[app.category] || { color: '#0284c7' };
                            return (
                              <tr key={app._supabaseId || app.id || index}>
                                <td style={{ fontWeight: 700, color: 'var(--primary)' }}>{index + 1}</td>
                                <td>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                    {photo ? (
                                      <img 
                                        src={photo} 
                                        alt="" 
                                        style={{ width: '38px', height: '38px', borderRadius: '50%', objectFit: 'cover', border: '2px solid #0284c7' }} 
                                      />
                                    ) : (
                                      <div style={{ width: '38px', height: '38px', borderRadius: '50%', background: '#e0e7ff', color: '#3730a3', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: '0.85rem' }}>
                                        {app.name ? app.name.slice(0, 1) : 'M'}
                                      </div>
                                    )}
                                    <div>
                                      <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
                                        <strong style={{ fontSize: '0.95rem' }}>{app.name}</strong>
                                        {getAppCompleteness(app).isFull ? (
                                          <span style={{
                                            display: 'inline-flex', alignItems: 'center', gap: '3px',
                                            background: 'rgba(16, 185, 129, 0.15)', color: '#059669',
                                            border: '1px solid rgba(16, 185, 129, 0.3)', borderRadius: '10px',
                                            padding: '1px 7px', fontSize: '0.72rem', fontWeight: 800
                                          }} title="مستوفي كافة الشروط والصورة ورقم الهاتف بنسبة 100%">
                                            <CheckCircle size={11} /> 100/100
                                          </span>
                                        ) : (
                                          <span style={{
                                            display: 'inline-flex', alignItems: 'center', gap: '3px',
                                            background: 'rgba(245, 158, 11, 0.12)', color: '#d97706',
                                            border: '1px solid rgba(245, 158, 11, 0.3)', borderRadius: '10px',
                                            padding: '1px 6px', fontSize: '0.7rem', fontWeight: 700
                                          }}>
                                            {getAppCompleteness(app).score}/100
                                          </span>
                                        )}
                                      </div>
                                      {app.email && (
                                        <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{app.email}</div>
                                      )}
                                    </div>
                                  </div>
                                </td>
                                <td>
                                  <span style={{
                                    display: 'inline-block',
                                    background: catConfig.color?.includes('gradient') ? '#0284c7' : (catConfig.color || '#0284c7'),
                                    color: 'white',
                                    padding: '4px 10px',
                                    borderRadius: '16px',
                                    fontSize: '0.8rem',
                                    fontWeight: 700
                                  }}>
                                    {app.category || 'عام'}
                                  </span>
                                  {app.desiredDepartment && (
                                    <div style={{ fontSize: '0.78rem', color: '#0369a1', fontWeight: 800, marginTop: '4px' }}>
                                      🏥 {app.desiredDepartment}
                                    </div>
                                  )}
                                  {(app.assignedTrainer || app.trainerName || app.supervisorName) && (
                                    <div style={{ fontSize: '0.78rem', color: '#059669', fontWeight: 800, marginTop: '4px' }}>
                                      🩺 المدرب: {app.assignedTrainer || app.trainerName || app.supervisorName}
                                    </div>
                                  )}
                                </td>
                                <td>{app.university || '—'}</td>
                                <td>{app.idNumber || '—'}</td>
                                <td>
                                  <a href={`tel:${app.phone}`} className="phone-link" onClick={(e) => e.stopPropagation()}>
                                    <Phone size={14} /> {app.phone}
                                  </a>
                                </td>
                                <td>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                    <Calendar size={14} color="var(--text-light)" />
                                    {app.date}
                                  </div>
                                  {(app.trainingStartDate || app.startDate || app.volunteerStartDate) && (
                                    <div style={{ fontSize: '0.75rem', color: '#059669', fontWeight: 700, marginTop: '3px' }}>
                                      تدريب: {formatDate(app.trainingStartDate || app.startDate || app.volunteerStartDate)} → {formatDate(app.trainingEndDate || app.endDate || app.volunteerEndDate)}
                                    </div>
                                  )}
                                </td>
                                <td>
                                  {hasValidUnionPaper ? (
                                    <a
                                      href={app.unionPaperBase64}
                                      download={app.unionPaperFileName || `${app.name}_ورقة_النقابة`}
                                      style={{ color: '#2563eb', fontWeight: 600, fontSize: '0.85rem', textDecoration: 'underline' }}
                                    >
                                      📥 ورقة النقابة
                                    </a>
                                  ) : (
                                    <span style={{ color: '#94a3b8', fontSize: '0.8rem' }}>لا يوجد</span>
                                  )}
                                </td>
                                <td>
                                  <div style={{ display: 'flex', gap: '6px', justifyContent: 'center', flexWrap: 'wrap' }}>
                                    <button onClick={() => openAppDetail(app)} className="btn-icon" style={{ 
                                      background: 'var(--success)', color: 'white', width: '34px', height: '34px',
                                      border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                      alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
                                    }} title="معاينة واعتماد وقبول">
                                      <UserPlus size={16} />
                                    </button>
                                    {/* ── Assign to Trainer button ── */}
                                    <button
                                      onClick={(e) => { e.stopPropagation(); openAssignTrainerModal(app); }}
                                      className="btn-icon"
                                      style={{
                                        background: 'linear-gradient(135deg, #0891b2, #0e7490)', color: 'white',
                                        width: '34px', height: '34px', border: 'none', borderRadius: '8px',
                                        cursor: 'pointer', display: 'flex', alignItems: 'center',
                                        justifyContent: 'center', transition: 'all 0.2s',
                                        boxShadow: '0 2px 8px rgba(8,145,178,0.4)'
                                      }}
                                      title="تعيين لمدرب سريري"
                                    >
                                      <i className="fas fa-chalkboard-teacher" style={{ fontSize: '14px' }} />
                                    </button>
                                    <button
                                      onClick={() => {
                                        setSelectedApp(app);
                                        printApplication(app);
                                      }}
                                      className="btn-icon"
                                      style={{
                                        background: '#0284c7', color: 'white', width: '34px', height: '34px',
                                        border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                        alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
                                      }}
                                      title="طباعة الاستمارة الرسمية A4"
                                    >
                                      <Download size={16} />
                                    </button>
                                    <button onClick={(e) => { e.stopPropagation(); handleReject(app); }} className="btn-icon" style={{ 
                                      background: '#dc3545', color: 'white', width: '34px', height: '34px',
                                      border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                      alignItems: 'center', justifyContent: 'center', transition: 'all 0.2s'
                                    }} title="أرشفة / رفض">
                                      <Archive size={16} />
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    )}
                  </div>
                </div>
              )}
            </>
          )}

          {/* ═════════════════ TAB 2: APPLICATION ARCHIVE ═════════════════ */}
          {activeTab === 'archive' && (
            <div className="students-section visible" style={{ display: 'block' }}>
              {/* Archive Search & Filter Bar */}
              <div style={{ background: 'var(--card-bg)', borderRadius: '16px', padding: '20px', marginBottom: '20px', boxShadow: 'var(--shadow)', border: '1px solid var(--border)' }}>
                <div style={{ display: 'flex', gap: '15px', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between' }}>
                  
                  {/* Search Input */}
                  <div style={{ flex: '1 1 300px', position: 'relative' }}>
                    <Search size={18} style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }} />
                    <input
                      type="text"
                      placeholder="بحث باسم المتقدم، الهاتف، رقم الهوية، الجامعة، القسم..."
                      value={archiveSearch}
                      onChange={e => setArchiveSearch(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', outline: 'none'
                      }}
                    />
                  </div>

                  {/* Status Filter Pills */}
                  <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                    {[
                      { key: 'all', label: `الكل (${applications.length})` },
                      { key: 'accepted', label: `المقبولة 🟢 (${acceptedCount})` },
                      { key: 'rejected', label: `المرفوضة 🔴 (${rejectedCount})` },
                      { key: 'pending', label: `قيد الانتظار 🟡 (${pendingCount})` },
                    ].map(f => (
                      <button
                        key={f.key}
                        onClick={() => setArchiveStatusFilter(f.key as any)}
                        style={{
                          padding: '8px 14px', borderRadius: '20px', border: 'none',
                          background: archiveStatusFilter === f.key ? '#4338ca' : 'var(--bg)',
                          color: archiveStatusFilter === f.key ? 'white' : 'var(--text)',
                          fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer', fontFamily: 'Tajawal',
                          transition: 'all 0.2s'
                        }}
                      >
                        {f.label}
                      </button>
                    ))}
                  </div>

                  {/* Category Filter Dropdown */}
                  <div style={{ minWidth: '180px' }}>
                    <select
                      value={archiveCategoryFilter}
                      onChange={e => setArchiveCategoryFilter(e.target.value)}
                      style={{
                        width: '100%', padding: '10px 14px', borderRadius: '10px',
                        border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)',
                        fontFamily: 'Tajawal', fontWeight: 600, fontSize: '0.9rem'
                      }}
                    >
                      <option value="all">كل الأقسام والصفوف</option>
                      {Object.keys(categoryConfig).map(cat => (
                        <option key={cat} value={cat}>{cat}</option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>

              {/* Archive Table */}
              <div className="table-container">
                {filteredArchiveApps.length === 0 ? (
                  <div style={{ textAlign: 'center', padding: '50px', background: 'var(--card-bg)', borderRadius: '16px' }}>
                    <Archive size={45} color="var(--text-muted)" style={{ marginBottom: '16px' }} />
                    <h4>لا توجد طلبات أرشفة تطابق البحث والفلترة</h4>
                  </div>
                ) : (
                  <table>
                    <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>
                      {filteredArchiveApps.map((app: any, index: number) => (
                        <tr key={app._supabaseId || app.id || index}>
                          <td style={{ fontWeight: 700, color: 'var(--primary)' }}>{index + 1}</td>
                          <td>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
                              <strong>{app.name}</strong>
                              {getAppCompleteness(app).isFull ? (
                                <span style={{
                                  display: 'inline-flex', alignItems: 'center', gap: '3px',
                                  background: 'rgba(16, 185, 129, 0.15)', color: '#059669',
                                  border: '1px solid rgba(16, 185, 129, 0.3)', borderRadius: '10px',
                                  padding: '1px 7px', fontSize: '0.72rem', fontWeight: 800
                                }}>
                                  <CheckCircle size={11} /> 100/100
                                </span>
                              ) : (
                                <span style={{
                                  display: 'inline-flex', alignItems: 'center', gap: '3px',
                                  background: 'rgba(245, 158, 11, 0.12)', color: '#d97706',
                                  border: '1px solid rgba(245, 158, 11, 0.3)', borderRadius: '10px',
                                  padding: '1px 6px', fontSize: '0.7rem', fontWeight: 700
                                }}>
                                  {getAppCompleteness(app).score}/100
                                </span>
                              )}
                            </div>
                          </td>
                          <td>{app.idNumber || '—'}</td>
                          <td>
                            <span style={{ background: 'var(--primary)', color: 'white', padding: '3px 10px', borderRadius: '16px', fontSize: '0.8rem', fontWeight: 600 }}>
                              {app.category}
                            </span>
                            {app.desiredDepartment && (
                              <div style={{ fontSize: '0.76rem', color: '#0284c7', fontWeight: 800, marginTop: '2px' }}>
                                🏥 {app.desiredDepartment}
                              </div>
                            )}
                            {(app.assignedTrainer || app.trainerName || app.supervisorName) && (
                              <div style={{ fontSize: '0.76rem', color: '#059669', fontWeight: 800, marginTop: '2px' }}>
                                🩺 المدرب: {app.assignedTrainer || app.trainerName || app.supervisorName}
                              </div>
                            )}
                          </td>
                          <td>{renderStatusBadge(app.status)}</td>
                          <td>
                            <a href={`tel:${app.phone}`} className="phone-link" onClick={(e) => e.stopPropagation()}>
                              <Phone size={14} /> {app.phone}
                            </a>
                          </td>
                          <td>{app.university || '—'}</td>
                          <td>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                              <Calendar size={14} color="var(--text-light)" />
                              {app.date}
                            </div>
                          </td>
                          <td>
                            {Boolean(
                              app.unionPaperBase64 &&
                              app.unionPaperBase64 !== (app.photoBase64 || app.doctorPhotoBase64)
                            ) ? (
                              <a
                                href={app.unionPaperBase64}
                                download={app.unionPaperFileName || `${app.name}_ورقة_النقابة`}
                                style={{ color: '#2563eb', fontWeight: 600, fontSize: '0.85rem', textDecoration: 'underline' }}
                              >
                                📥 ورقة النقابة
                              </a>
                            ) : (
                              <span style={{ color: '#94a3b8', fontSize: '0.8rem' }}>لا يوجد</span>
                            )}
                          </td>
                          <td>
                            <div style={{ display: 'flex', gap: '6px', justifyContent: 'center' }}>
                              <button
                                onClick={() => openAppDetail(app)}
                                className="btn-icon"
                                style={{
                                  background: '#4338ca', color: 'white', width: '34px', height: '34px',
                                  border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                  alignItems: 'center', justifyContent: 'center'
                                }}
                                title="معاينة التفاصيل والقبول"
                              >
                                <Edit3 size={16} />
                              </button>
                              <button
                                onClick={() => handlePermanentDelete(app)}
                                className="btn-icon"
                                style={{
                                  background: '#dc3545', color: 'white', width: '34px', height: '34px',
                                  border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                  alignItems: 'center', justifyContent: 'center'
                                }}
                                title="حذف نهائي من الأرشيف"
                              >
                                <Trash2 size={16} />
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
          )}

          {/* ═════════════════ TAB 3: UNIVERSITIES & CONTRACTED DOCTORS ═════════════════ */}
          {activeTab === 'universities' && (
            <div className="archive-section" style={{ display: 'block' }}>
              {/* Universities Header & Statistics Banner */}
              <div style={{
                background: 'linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #4338ca 100%)',
                borderRadius: '18px',
                padding: '24px 28px',
                color: 'white',
                marginBottom: '24px',
                boxShadow: '0 10px 25px rgba(49, 46, 129, 0.35)',
                border: '1px solid rgba(168, 85, 247, 0.4)'
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '18px', marginBottom: '20px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <div style={{
                      width: '56px', height: '56px', borderRadius: '14px',
                      background: 'rgba(255,255,255,0.12)', backdropFilter: 'blur(10px)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      border: '1px solid rgba(255,255,255,0.2)'
                    }}>
                      <GraduationCap size={32} color="#c084fc" />
                    </div>
                    <div>
                      <h2 style={{ fontSize: '1.45rem', fontWeight: 900, margin: 0, display: 'flex', alignItems: 'center', gap: '10px' }}>
                        إدارة طلبات تدريب تمريض الجامعات والأطباء المتعاقدون
                      </h2>
                      <p style={{ margin: '4px 0 0 0', opacity: 0.85, fontSize: '0.9rem' }}>
                        إدارة ومتابعة كافة الطلبات المقدمة عبر روابط الجامعات الشريكة وتدريب طلاب التمريض والأطباء المتعاقدين
                      </p>
                    </div>
                  </div>

                  <Link href="/recruitment" target="_blank" style={{
                    display: 'inline-flex', alignItems: 'center', gap: '8px',
                    background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(8px)',
                    color: 'white', textDecoration: 'none', padding: '10px 18px',
                    borderRadius: '10px', fontSize: '0.85rem', fontWeight: 700,
                    border: '1px solid rgba(255,255,255,0.25)', transition: 'all 0.2s'
                  }}>
                    <span>عرض بوابات وروابط التقديم 🔗</span>
                  </Link>
                </div>

                {/* 4 Stats Cards */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '14px' }}>
                  <div style={{ background: 'rgba(255,255,255,0.08)', borderRadius: '12px', padding: '14px 18px', border: '1px solid rgba(255,255,255,0.12)' }}>
                    <div style={{ fontSize: '0.82rem', opacity: 0.8 }}>إجمالي طلبات الشركاء</div>
                    <div style={{ fontSize: '1.7rem', fontWeight: 900, marginTop: '4px' }}>{universityApplicationsList.length}</div>
                  </div>
                  <div style={{ background: 'rgba(255,255,255,0.08)', borderRadius: '12px', padding: '14px 18px', border: '1px solid rgba(255,255,255,0.12)' }}>
                    <div style={{ fontSize: '0.82rem', opacity: 0.8 }}>تدريب طلاب التمريض</div>
                    <div style={{ fontSize: '1.7rem', fontWeight: 900, marginTop: '4px', color: '#38bdf8' }}>{nursingUniCount}</div>
                  </div>
                  <div style={{ background: 'rgba(255,255,255,0.08)', borderRadius: '12px', padding: '14px 18px', border: '1px solid rgba(255,255,255,0.12)' }}>
                    <div style={{ fontSize: '0.82rem', opacity: 0.8 }}>الأطباء المتعاقدون</div>
                    <div style={{ fontSize: '1.7rem', fontWeight: 900, marginTop: '4px', color: '#c084fc' }}>{doctorsUniCount}</div>
                  </div>
                  <div style={{ background: 'rgba(255,255,255,0.08)', borderRadius: '12px', padding: '14px 18px', border: '1px solid rgba(255,255,255,0.12)' }}>
                    <div style={{ fontSize: '0.82rem', opacity: 0.8 }}>بانتظار الاعتماد</div>
                    <div style={{ fontSize: '1.7rem', fontWeight: 900, marginTop: '4px', color: pendingUniCount > 0 ? '#f87171' : '#4ade80' }}>
                      {pendingUniCount}
                    </div>
                  </div>
                </div>
              </div>

              {/* Filter and Search Bar */}
              <div style={{ background: 'var(--card-bg)', borderRadius: '16px', padding: '18px', marginBottom: '20px', boxShadow: 'var(--shadow)', border: '1px solid var(--border)' }}>
                <div style={{ display: 'flex', gap: '14px', flexWrap: 'wrap', alignItems: 'center' }}>
                  {/* Search Input */}
                  <div style={{ flex: '1 1 280px', position: 'relative' }}>
                    <Search size={18} style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }} />
                    <input
                      type="text"
                      placeholder="بحث بالاسم، رقم الهاتف، الجامعة، القسم أو الهوية..."
                      value={uniSearch}
                      onChange={e => setUniSearch(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', outline: 'none'
                      }}
                    />
                  </div>

                  {/* Category Filter Pills */}
                  <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                    {[
                      { key: 'all', label: `الكل (${universityApplicationsList.length})` },
                      { key: 'nursing', label: `تدريب التمريض 🩺 (${nursingUniCount})` },
                      { key: 'doctors', label: `الأطباء المتعاقدون 👨‍⚕️ (${doctorsUniCount})` },
                    ].map(f => (
                      <button
                        key={f.key}
                        onClick={() => setUniCategoryFilter(f.key as any)}
                        style={{
                          padding: '8px 14px', borderRadius: '20px',
                          background: uniCategoryFilter === f.key ? '#312e81' : 'var(--bg)',
                          color: uniCategoryFilter === f.key ? 'white' : 'var(--text)',
                          fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer', fontFamily: 'Tajawal',
                          transition: 'all 0.2s',
                          border: uniCategoryFilter === f.key ? '1px solid #818cf8' : '1px solid transparent'
                        }}
                      >
                        {f.label}
                      </button>
                    ))}
                  </div>

                  {/* Status Filter Pills */}
                  <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                    {[
                      { key: 'all', label: 'كل الحالات' },
                      { key: 'pending', label: 'قيد الانتظار 🟡' },
                      { key: 'accepted', label: 'المقبولة 🟢' },
                      { key: 'rejected', label: 'المرفوضة 🔴' },
                    ].map(f => (
                      <button
                        key={f.key}
                        onClick={() => setUniStatusFilter(f.key as any)}
                        style={{
                          padding: '8px 14px', borderRadius: '20px', border: 'none',
                          background: uniStatusFilter === f.key ? 'var(--primary)' : 'var(--bg)',
                          color: uniStatusFilter === f.key ? 'white' : 'var(--text)',
                          fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer', fontFamily: 'Tajawal',
                          transition: 'all 0.2s'
                        }}
                      >
                        {f.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>

              {/* Table of Applications */}
              <div className="table-container">
                {filteredUniApps.length === 0 ? (
                  <div style={{ textAlign: 'center', padding: '50px', background: 'var(--card-bg)', borderRadius: '16px' }}>
                    <GraduationCap size={48} color="var(--text-muted)" style={{ marginBottom: '16px' }} />
                    <h4 style={{ fontSize: '1.2rem', margin: '0 0 8px 0' }}>لا توجد طلبات تطابق معايير البحث</h4>
                    <p style={{ color: 'var(--text-muted)', margin: 0 }}>تأكد من اختيار الفلاتر المناسبة أو مسح نص البحث.</p>
                  </div>
                ) : (
                  <table>
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>اسم المتقدم / المشرف</th>
                        <th>التصنيف والنوع</th>
                        <th>الجامعة المتعاقد معها (شراكة) 🤝</th>
                        <th>الجامعة المتخرج منها (مؤهل) 🎓</th>
                        <th>رقم الهاتف</th>
                        <th>القسم / المساقات</th>
                        <th>تاريخ التقديم</th>
                        <th>الحالة</th>
                        <th>المرفقات</th>
                        <th>الإجراءات</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredUniApps.map((app: any, index: number) => {
                        const catLower = (app.category || app.categoryId || '').toLowerCase();
                        const isDoctor = catLower.includes('متعاقد') || catLower.includes('doctor');
                        const isNursing = catLower.includes('تمريض') || catLower.includes('nursing');
                        
                        const contractedUnis = app.contractedUniversities && app.contractedUniversities.length > 0
                          ? (Array.isArray(app.contractedUniversities) ? app.contractedUniversities : [app.contractedUniversities])
                          : (app.contractedUniversity ? [app.contractedUniversity] : (app.previousContractedUniversity ? [app.previousContractedUniversity] : []));
                        const contractedDisplay = contractedUnis.length > 0 ? contractedUnis.join('، ') : (app.contractedUniversity || '—');

                        const gradUniDisplay = app.graduatedUniversity || (contractedDisplay !== app.university ? app.university : '') || '—';

                        return (
                          <tr key={app._supabaseId || app.id || index}>
                            <td style={{ fontWeight: 700, color: '#6366f1' }}>{index + 1}</td>
                            <td>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                {(app.photoBase64 || app.doctorPhotoBase64) ? (
                                  <img 
                                    src={app.photoBase64 || app.doctorPhotoBase64} 
                                    alt="" 
                                    style={{ width: '36px', height: '36px', borderRadius: '50%', objectFit: 'cover', border: '2px solid #818cf8' }} 
                                  />
                                ) : (
                                  <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: '#e0e7ff', color: '#3730a3', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: '0.85rem' }}>
                                    {app.name ? app.name.slice(0, 1) : 'U'}
                                  </div>
                                )}
                                <div>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
                                    <strong style={{ fontSize: '0.95rem' }}>{app.name}</strong>
                                    {getAppCompleteness(app).isFull && (
                                      <span style={{
                                        display: 'inline-flex', alignItems: 'center', gap: '3px',
                                        background: 'rgba(16, 185, 129, 0.15)', color: '#059669',
                                        border: '1px solid rgba(16, 185, 129, 0.3)', borderRadius: '10px',
                                        padding: '1px 7px', fontSize: '0.72rem', fontWeight: 800
                                      }}>
                                        <CheckCircle size={11} /> 100/100
                                      </span>
                                    )}
                                  </div>
                                  {app.idNumber && (
                                    <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>هوية: {app.idNumber}</div>
                                  )}
                                </div>
                              </div>
                            </td>
                            <td>
                              <span style={{
                                display: 'inline-flex', alignItems: 'center', gap: '5px',
                                background: isDoctor ? '#f3e8ff' : '#e0f2fe',
                                color: isDoctor ? '#6b21a8' : '#0369a1',
                                border: isDoctor ? '1px solid #d8b4fe' : '1px solid #bae6fd',
                                padding: '4px 10px', borderRadius: '20px', fontSize: '0.8rem', fontWeight: 700
                              }}>
                                {isDoctor ? <Stethoscope size={13} /> : <HeartPulse size={13} />}
                                {isDoctor ? 'طبيب متعاقد' : 'تدريب تمريض'}
                              </span>
                            </td>
                            {/* 1. الجامعة المتعاقد معها (شراكة) */}
                            <td>
                              {contractedUnis.length > 0 ? (
                                <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                                  {contractedUnis.map((u: string, uIdx: number) => (
                                    <span key={uIdx} style={{ background: '#f5f3ff', color: '#6d28d9', padding: '3px 8px', borderRadius: '8px', fontSize: '0.78rem', fontWeight: 700, border: '1px solid #ddd6fe' }}>
                                      🤝 {u}
                                    </span>
                                  ))}
                                </div>
                              ) : (
                                <span style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>{contractedDisplay}</span>
                              )}
                            </td>
                            {/* 2. الجامعة المتخرج منها (مؤهل) */}
                            <td>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexWrap: 'wrap' }}>
                                <span style={{ background: '#f1f5f9', color: '#334155', padding: '3px 8px', borderRadius: '8px', fontSize: '0.8rem', fontWeight: 700, border: '1px solid #e2e8f0' }}>
                                  🎓 {gradUniDisplay}
                                </span>
                                {app.graduationYear && (
                                  <span style={{ fontSize: '0.72rem', color: '#64748b', fontWeight: 600 }}>({app.graduationYear})</span>
                                )}
                              </div>
                            </td>
                            <td>
                              <a href={`tel:${app.phone}`} className="phone-link" onClick={(e) => e.stopPropagation()}>
                                <Phone size={14} /> {app.phone}
                              </a>
                            </td>
                            <td>
                              <div style={{ fontSize: '0.85rem', fontWeight: 600 }}>
                                {app.specialty || app.desiredDepartment || app.currentHospitalDepartment || (app.teachingCourses && app.teachingCourses.length > 0 ? (Array.isArray(app.teachingCourses) ? app.teachingCourses.join('، ') : app.teachingCourses) : '—')}
                              </div>
                            </td>
                            <td>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.85rem' }}>
                                <Calendar size={14} color="var(--text-light)" />
                                {app.date}
                              </div>
                              {(app.trainingStartDate || app.startDate) && (
                                <div style={{ fontSize: '0.75rem', color: '#059669', fontWeight: 700, marginTop: '2px' }}>
                                  تدريب: {formatDate(app.trainingStartDate || app.startDate)} → {formatDate(app.trainingEndDate || app.endDate)}
                                </div>
                              )}
                            </td>
                            <td>{renderStatusBadge(app.status)}</td>
                            <td>
                              {Boolean(
                                app.unionPaperBase64 &&
                                app.unionPaperBase64 !== (app.photoBase64 || app.doctorPhotoBase64)
                              ) ? (
                                <a
                                  href={app.unionPaperBase64}
                                  download={app.unionPaperFileName || `${app.name}_مرفق_الطلب`}
                                  style={{ color: '#2563eb', fontWeight: 600, fontSize: '0.82rem', textDecoration: 'underline' }}
                                >
                                  📥 تحميل المرفق
                                </a>
                              ) : (
                                <span style={{ color: '#94a3b8', fontSize: '0.8rem' }}>لا يوجد</span>
                              )}
                            </td>
                            <td>
                              <div style={{ display: 'flex', gap: '6px', justifyContent: 'center' }}>
                                <button
                                  onClick={() => openAppDetail(app)}
                                  className="btn-icon"
                                  style={{
                                    background: '#4338ca', color: 'white', width: '34px', height: '34px',
                                    border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                    alignItems: 'center', justifyContent: 'center'
                                  }}
                                  title="معاينة التفاصيل والاعتماد"
                                >
                                  <Edit3 size={16} />
                                </button>
                                <button
                                  onClick={() => {
                                    setSelectedApp(app);
                                    printApplication(app);
                                  }}
                                  className="btn-icon"
                                  style={{
                                    background: '#0284c7', color: 'white', width: '34px', height: '34px',
                                    border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                    alignItems: 'center', justifyContent: 'center'
                                  }}
                                  title="طباعة الاستمارة الرسمية A4"
                                >
                                  <Download size={16} />
                                </button>
                                <button
                                  onClick={() => handlePermanentDelete(app)}
                                  className="btn-icon"
                                  style={{
                                    background: '#dc3545', color: 'white', width: '34px', height: '34px',
                                    border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex',
                                    alignItems: 'center', justifyContent: 'center'
                                  }}
                                  title="حذف نهائي"
                                >
                                  <Trash2 size={16} />
                                </button>
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
          )}

          {/* ═════════════════ TAB 4: HEALTH SUPPORT TRAINERS ═════════════════ */}
          {activeTab === 'health-trainers' && (
            <div className="archive-section" style={{ display: 'block' }}>

              {/* ── Hero Banner ── */}
              <div style={{
                background: 'linear-gradient(135deg, #0c4a6e 0%, #0369a1 50%, #0891b2 100%)',
                borderRadius: '18px', padding: '24px 28px', color: 'white',
                marginBottom: '24px', boxShadow: '0 10px 30px rgba(8,145,178,0.35)',
                border: '1px solid rgba(56,189,248,0.3)'
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '18px', marginBottom: '22px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <div style={{
                      width: '58px', height: '58px', borderRadius: '14px',
                      background: 'rgba(255,255,255,0.12)', backdropFilter: 'blur(10px)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      border: '1px solid rgba(255,255,255,0.2)', fontSize: '1.8rem'
                    }}>🏥</div>
                    <div>
                      <h2 style={{ fontSize: '1.4rem', fontWeight: 900, margin: 0 }}>
                        إدارة طلبات مدربين الأقسام الصحية المساندة
                      </h2>
                      <p style={{ margin: '4px 0 0 0', opacity: 0.85, fontSize: '0.9rem' }}>
                        متابعة ومعالجة طلبات التدريب لجميع أقسام الدعم الصحي
                      </p>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                    {/* summary pill */}
                    <div style={{ background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(8px)', borderRadius: '10px', padding: '8px 18px', border: '1px solid rgba(255,255,255,0.25)', textAlign: 'center' }}>
                      <div style={{ fontSize: '0.78rem', opacity: 0.8 }}>الإجمالي</div>
                      <div style={{ fontSize: '1.5rem', fontWeight: 900 }}>{healthTrainerApplicationsList.length}</div>
                    </div>
                    <div style={{ background: pendingHtCount > 0 ? 'rgba(239,68,68,0.3)' : 'rgba(16,185,129,0.2)', backdropFilter: 'blur(8px)', borderRadius: '10px', padding: '8px 18px', border: `1px solid ${pendingHtCount > 0 ? 'rgba(239,68,68,0.5)' : 'rgba(16,185,129,0.4)'}`, textAlign: 'center' }}>
                      <div style={{ fontSize: '0.78rem', opacity: 0.8 }}>بانتظار الاعتماد</div>
                      <div style={{ fontSize: '1.5rem', fontWeight: 900, color: pendingHtCount > 0 ? '#fca5a5' : '#6ee7b7' }}>{pendingHtCount}</div>
                    </div>
                  </div>
                </div>

                {/* ── Per-Dept Stat Cards ── */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: '12px' }}>
                  {healthTrainerDepts.map(dept => {
                    const deptApps = healthTrainerApplicationsList.filter((a: any) => {
                      const c = (a.category || a.categoryId || '').toLowerCase();
                      const keyword = dept.key.replace('مدربي ', '').replace('مدربو ', '');
                      return c.includes(keyword);
                    });
                    const deptPending = deptApps.filter(isPendingApp).length;
                    return (
                      <div
                        key={dept.key}
                        onClick={() => { setHtDeptFilter(htDeptFilter === dept.key ? 'all' : dept.key); }}
                        style={{
                          background: htDeptFilter === dept.key ? dept.gradient : 'rgba(255,255,255,0.08)',
                          borderRadius: '12px', padding: '14px 16px',
                          border: htDeptFilter === dept.key ? `2px solid rgba(255,255,255,0.5)` : '1px solid rgba(255,255,255,0.12)',
                          cursor: 'pointer', transition: 'all 0.25s',
                          boxShadow: htDeptFilter === dept.key ? `0 6px 20px ${dept.shadow}` : 'none'
                        }}
                      >
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                          <i className={dept.icon} style={{ fontSize: '1.1rem', opacity: 0.9 }} />
                          {deptPending > 0 && (
                            <span style={{ background: '#ef4444', color: 'white', borderRadius: '10px', padding: '1px 7px', fontSize: '0.72rem', fontWeight: 900 }}>
                              {deptPending}
                            </span>
                          )}
                        </div>
                        <div style={{ fontSize: '0.78rem', opacity: 0.85, marginBottom: '4px', lineHeight: 1.3 }}>{dept.label}</div>
                        <div style={{ fontSize: '1.6rem', fontWeight: 900 }}>{deptApps.length}</div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* ── Search & Filter Bar ── */}
              <div style={{ background: 'var(--card-bg)', borderRadius: '16px', padding: '18px', marginBottom: '20px', boxShadow: 'var(--shadow)', border: '1px solid var(--border)' }}>
                <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', alignItems: 'center' }}>

                  {/* Search */}
                  <div style={{ flex: '1 1 260px', position: 'relative' }}>
                    <Search size={18} style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }} />
                    <input
                      type="text"
                      placeholder="بحث بالاسم، الهاتف، رقم الهوية، القسم..."
                      value={htSearch}
                      onChange={e => setHtSearch(e.target.value)}
                      style={{
                        width: '100%', padding: '11px 42px 11px 14px', borderRadius: '12px',
                        border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)',
                        fontFamily: 'Tajawal', fontSize: '0.95rem', outline: 'none'
                      }}
                    />
                  </div>

                  {/* Dept filter pills */}
                  <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                    <button
                      onClick={() => setHtDeptFilter('all')}
                      style={{
                        padding: '7px 14px', borderRadius: '20px',
                        background: htDeptFilter === 'all' ? '#0891b2' : 'var(--bg)',
                        color: htDeptFilter === 'all' ? 'white' : 'var(--text)',
                        border: htDeptFilter === 'all' ? '1px solid #38bdf8' : '1px solid transparent',
                        fontWeight: 700, fontSize: '0.82rem', cursor: 'pointer', fontFamily: 'Tajawal', transition: 'all 0.2s'
                      }}
                    >
                      الكل ({healthTrainerApplicationsList.length})
                    </button>
                    {healthTrainerDepts.map(dept => {
                      const cnt = healthTrainerApplicationsList.filter((a: any) => {
                        const c = (a.category || a.categoryId || '').toLowerCase();
                        return c.includes(dept.key.replace('مدربي ', '').replace('مدربو ', ''));
                      }).length;
                      return (
                        <button
                          key={dept.key}
                          onClick={() => setHtDeptFilter(htDeptFilter === dept.key ? 'all' : dept.key)}
                          style={{
                            padding: '7px 14px', borderRadius: '20px',
                            background: htDeptFilter === dept.key ? dept.color : 'var(--bg)',
                            color: htDeptFilter === dept.key ? 'white' : 'var(--text)',
                            border: htDeptFilter === dept.key ? `1px solid ${dept.color}` : '1px solid transparent',
                            fontWeight: 700, fontSize: '0.82rem', cursor: 'pointer', fontFamily: 'Tajawal', transition: 'all 0.2s'
                          }}
                        >
                          {dept.label} ({cnt})
                        </button>
                      );
                    })}
                  </div>

                  {/* Status filter */}
                  <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                    {[
                      { key: 'all',      label: 'كل الحالات' },
                      { key: 'pending',  label: 'قيد الانتظار 🟡' },
                      { key: 'accepted', label: 'المقبولة 🟢' },
                      { key: 'rejected', label: 'المرفوضة 🔴' },
                    ].map(f => (
                      <button
                        key={f.key}
                        onClick={() => setHtStatusFilter(f.key as any)}
                        style={{
                          padding: '7px 14px', borderRadius: '20px', border: 'none',
                          background: htStatusFilter === f.key ? 'var(--primary)' : 'var(--bg)',
                          color: htStatusFilter === f.key ? 'white' : 'var(--text)',
                          fontWeight: 700, fontSize: '0.82rem', cursor: 'pointer', fontFamily: 'Tajawal', transition: 'all 0.2s'
                        }}
                      >
                        {f.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>

              {/* ── Applications Table ── */}
              <div className="table-container">
                {filteredHtApps.length === 0 ? (
                  <div style={{ textAlign: 'center', padding: '60px', background: 'var(--card-bg)', borderRadius: '16px' }}>
                    <div style={{ fontSize: '3rem', marginBottom: '16px' }}>🏥</div>
                    <h4 style={{ fontSize: '1.2rem', margin: '0 0 8px 0' }}>لا توجد طلبات تطابق معايير البحث</h4>
                    <p style={{ color: 'var(--text-muted)', margin: 0 }}>تأكد من اختيار الفلاتر المناسبة أو مسح نص البحث.</p>
                  </div>
                ) : (
                  <table>
                    <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>
                      {filteredHtApps.map((app: any, index: number) => {
                        // Find the matching dept config for badge colour
                        const appCatLower = (app.category || app.categoryId || '').toLowerCase();
                        const matchedDept = healthTrainerDepts.find(d =>
                          appCatLower.includes(d.key.replace('مدربي ', '').replace('مدربو ', ''))
                        );
                        const badgeColor = matchedDept?.color || '#0891b2';
                        const badgeGradient = matchedDept?.gradient || 'linear-gradient(135deg,#0891b2,#0369a1)';

                        return (
                          <tr key={app._supabaseId || app.id || index} style={{ cursor: 'pointer' }} onClick={() => openAppDetail(app)}>
                            <td style={{ fontWeight: 700, color: '#0891b2' }}>{index + 1}</td>
                            <td>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                {(app.photoBase64 || app.doctorPhotoBase64) ? (
                                  <img
                                    src={app.photoBase64 || app.doctorPhotoBase64}
                                    alt=""
                                    style={{ width: '36px', height: '36px', borderRadius: '50%', objectFit: 'cover', border: `2px solid ${badgeColor}` }}
                                  />
                                ) : (
                                  <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: badgeGradient, color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: '0.9rem' }}>
                                    {app.name ? app.name.slice(0, 1) : 'م'}
                                  </div>
                                )}
                                <div>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
                                    <strong style={{ fontSize: '0.95rem' }}>{app.name}</strong>
                                    {getAppCompleteness(app).isFull && (
                                      <span style={{
                                        display: 'inline-flex', alignItems: 'center', gap: '3px',
                                        background: 'rgba(16, 185, 129, 0.15)', color: '#059669',
                                        border: '1px solid rgba(16, 185, 129, 0.3)', borderRadius: '10px',
                                        padding: '1px 7px', fontSize: '0.72rem', fontWeight: 800
                                      }}>
                                        <CheckCircle size={11} /> 100/100
                                      </span>
                                    )}
                                  </div>
                                  {app.idNumber && (
                                    <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>هوية: {app.idNumber}</div>
                                  )}
                                </div>
                              </div>
                            </td>
                            <td>
                              <span style={{
                                display: 'inline-block', background: badgeGradient,
                                color: 'white', padding: '4px 12px', borderRadius: '20px',
                                fontSize: '0.8rem', fontWeight: 700
                              }}>
                                {app.category || '—'}
                              </span>
                            </td>
                            <td>{app.idNumber || '—'}</td>
                            <td>
                              <a href={`tel:${app.phone}`} className="phone-link" onClick={e => e.stopPropagation()}>
                                <Phone size={14} /> {app.phone}
                              </a>
                            </td>
                            <td>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.85rem' }}>
                                <Calendar size={14} color="var(--text-light)" />
                                {app.date}
                              </div>
                            </td>
                            <td>
                              {(app.trainingStartDate || app.startDate) ? (
                                <div style={{ fontSize: '0.8rem', color: '#059669', fontWeight: 700 }}>
                                  {formatDate(app.trainingStartDate || app.startDate)} → {formatDate(app.trainingEndDate || app.endDate)}
                                </div>
                              ) : <span style={{ color: 'var(--text-muted)' }}>—</span>}
                            </td>
                            <td>{renderStatusBadge(app.status)}</td>
                            <td>
                              {app.unionPaperBase64 && app.unionPaperBase64 !== (app.photoBase64 || app.doctorPhotoBase64) ? (
                                <a
                                  href={app.unionPaperBase64}
                                  download={app.unionPaperFileName || `${app.name}_مرفق`}
                                  style={{ color: '#2563eb', fontWeight: 600, fontSize: '0.82rem', textDecoration: 'underline' }}
                                  onClick={e => e.stopPropagation()}
                                >
                                  📥 تحميل
                                </a>
                              ) : (
                                <span style={{ color: '#94a3b8', fontSize: '0.8rem' }}>لا يوجد</span>
                              )}
                            </td>
                            <td>
                              <div style={{ display: 'flex', gap: '6px', justifyContent: 'center' }}>
                                <button
                                  onClick={e => { e.stopPropagation(); openAppDetail(app); }}
                                  className="btn-icon"
                                  style={{ background: badgeColor, color: 'white', width: '34px', height: '34px', border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                                  title="معاينة واعتماد"
                                >
                                  <Edit3 size={16} />
                                </button>
                                <button
                                  onClick={e => { e.stopPropagation(); setSelectedApp(app); printApplication(app); }}
                                  className="btn-icon"
                                  style={{ background: '#0284c7', color: 'white', width: '34px', height: '34px', border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                                  title="طباعة الاستمارة A4"
                                >
                                  <Download size={16} />
                                </button>
                                <button
                                  onClick={e => { e.stopPropagation(); handlePermanentDelete(app); }}
                                  className="btn-icon"
                                  style={{ background: '#dc3545', color: 'white', width: '34px', height: '34px', border: 'none', borderRadius: '8px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                                  title="حذف نهائي"
                                >
                                  <Trash2 size={16} />
                                </button>
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                )}
              </div>
            </div>
          )}

        </>
      )}

      {/* ═══════════ DETAIL + ACCEPT / VIEW MODAL ═══════════ */}
      {selectedApp && (
        <div className="modal-overlay active" onClick={(e) => e.target === e.currentTarget && !isProcessing && setSelectedApp(null)}>
          <div className="modal" style={{ maxWidth: '650px', maxHeight: '90vh', overflowY: 'auto' }}>
            {/* Header */}
            <div className="modal-header" style={{ borderBottom: '2px solid var(--border)', paddingBottom: '16px' }}>
              <h3 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <Edit3 size={22} /> تفاصيل الطلب والأرشيف
              </h3>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                {renderStatusBadge(selectedApp.status)}
                <button className="modal-close" onClick={() => !isProcessing && setSelectedApp(null)}>&times;</button>
              </div>
            </div>

            {/* Original Application Info */}
            <div style={{ 
              background: 'var(--bg-light)', borderRadius: '12px', padding: '18px', marginBottom: '24px',
              border: '1px solid var(--border)'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '14px', flexWrap: 'wrap', gap: '10px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                  <h4 style={{ fontSize: '0.85rem', color: 'var(--text-muted)', margin: 0, fontWeight: '600', letterSpacing: '0.5px' }}>
                    📋 معلومات الطلب الأصلية
                  </h4>
                  {getAppCompleteness(selectedApp).isFull ? (
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: '4px',
                      background: 'rgba(16, 185, 129, 0.15)', color: '#059669',
                      border: '1px solid rgba(16, 185, 129, 0.4)', borderRadius: '12px',
                      padding: '3px 10px', fontSize: '0.78rem', fontWeight: 800
                    }}>
                      <CheckCircle size={13} /> استيفاء البيانات: 100 / 100 (مكتمل بالصورة ورقم الهاتف)
                    </span>
                  ) : (
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: '4px',
                      background: 'rgba(245, 158, 11, 0.15)', color: '#d97706',
                      border: '1px solid rgba(245, 158, 11, 0.4)', borderRadius: '12px',
                      padding: '3px 8px', fontSize: '0.75rem', fontWeight: 700
                    }}>
                      اكتمال البيانات: {getAppCompleteness(selectedApp).score} / 100
                    </span>
                  )}
                </div>
                {(selectedApp.photoBase64 || selectedApp.doctorPhotoBase64) && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <img 
                      src={selectedApp.photoBase64 || selectedApp.doctorPhotoBase64} 
                      alt="صورة المتقدم" 
                      style={{ width: '60px', height: '60px', borderRadius: '50%', objectFit: 'cover', border: '2.5px solid var(--primary)', boxShadow: '0 3px 10px rgba(0,0,0,0.15)' }} 
                    />
                    <a
                      href={selectedApp.photoBase64 || selectedApp.doctorPhotoBase64}
                      download={selectedApp.photoFileName || `${selectedApp.name}_صورة_شخصية.jpg`}
                      style={{
                        display: 'inline-flex', alignItems: 'center', gap: '5px',
                        padding: '5px 12px', background: '#eff6ff', color: '#1d4ed8',
                        border: '1px solid #bfdbfe', borderRadius: '8px', fontSize: '0.8rem',
                        fontWeight: 700, textDecoration: 'none'
                      }}
                      title="تحميل الصورة الشخصية"
                    >
                      📥 تحميل الصورة الشخصية
                    </a>
                  </div>
                )}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>الاسم</small>
                  <div style={{ fontWeight: '700' }}>{selectedApp.name}</div>
                </div>
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>القسم المتقدم له</small>
                  <div style={{ fontWeight: '600' }}>
                    <span style={{ background: 'var(--primary)', color: 'white', padding: '2px 10px', borderRadius: '20px', fontSize: '0.8rem' }}>
                      {selectedApp.category}
                    </span>
                  </div>
                </div>
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>رقم الهوية</small>
                  <div style={{ fontWeight: '600' }}>{selectedApp.idNumber || '—'}</div>
                </div>
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>رقم الهاتف</small>
                  <div style={{ fontWeight: '600', direction: 'ltr', textAlign: 'right' }}>{selectedApp.phone}</div>
                </div>
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>مكان السكن</small>
                  <div style={{ fontWeight: '600' }}>{selectedApp.address || '—'}</div>
                </div>
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>البريد الإلكتروني</small>
                  <div style={{ fontWeight: '600' }}>{selectedApp.email || '—'}</div>
                </div>
                {(selectedApp.category === 'المتقدمين للإمتياز' || selectedApp.categoryId === 'internship') && (
                  <>
                    <div>
                      <small style={{ color: 'var(--text-muted)' }}>نظام الدراسة</small>
                      <div style={{ fontWeight: '600' }}>{selectedApp.studySystem || '—'}</div>
                    </div>
                    <div>
                      <small style={{ color: 'var(--text-muted)' }}>مستوى الامتياز</small>
                      <div style={{ fontWeight: '600' }}>{selectedApp.internshipYear || '—'}</div>
                    </div>
                  </>
                )}
                {selectedApp.desiredDepartment && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>القسم الطبي المطلوب التدريب فيه</small>
                    <div style={{ fontWeight: '800', color: '#0284c7' }}>🏥 {selectedApp.desiredDepartment}</div>
                  </div>
                )}
                {(selectedApp.assignedTrainer || selectedApp.trainerName || selectedApp.supervisorName) && (
                  <div style={{ background: '#ecfdf5', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid #10b981' }}>
                    <small style={{ color: '#047857', fontWeight: 800 }}>🩺 المدرب السريري المشرف (المحدد بالطلب)</small>
                    <div style={{ fontWeight: '900', color: '#065f46', fontSize: '1.05rem', marginTop: '2px' }}>
                      👤 {selectedApp.assignedTrainer || selectedApp.trainerName || selectedApp.supervisorName}
                    </div>
                  </div>
                )}
                {isUniversityApp(selectedApp) ? (
                  <>
                    <div style={{ gridColumn: 'span 2', background: '#f5f3ff', padding: '12px 16px', borderRadius: '12px', border: '1.5px solid #ddd6fe' }}>
                      <small style={{ color: '#6d28d9', fontWeight: 800, fontSize: '0.85rem' }}>🤝 الجامعة / الجامعات المتعاقد معها (شراكة المستشفى والتدريب):</small>
                      <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginTop: '6px' }}>
                        {((selectedApp.contractedUniversities && selectedApp.contractedUniversities.length > 0)
                          ? (Array.isArray(selectedApp.contractedUniversities) ? selectedApp.contractedUniversities : [selectedApp.contractedUniversities])
                          : (selectedApp.contractedUniversity ? [selectedApp.contractedUniversity] : (selectedApp.previousContractedUniversity ? [selectedApp.previousContractedUniversity] : []))
                        ).map((u: string, idx: number) => (
                          <span key={idx} style={{ background: '#ede9fe', color: '#5b21b6', padding: '4px 12px', borderRadius: '12px', fontSize: '0.85rem', fontWeight: 800, border: '1px solid #c4b5fd' }}>
                            🤝 {u}
                          </span>
                        ))}
                      </div>
                    </div>

                    <div style={{ gridColumn: 'span 2', background: '#f8fafc', padding: '12px 16px', borderRadius: '12px', border: '1.5px solid #e2e8f0' }}>
                      <small style={{ color: '#0f766e', fontWeight: 800, fontSize: '0.85rem' }}>🎓 الجامعة المتخرج منها (المؤهل العلمي والشهادة الأكاديمية):</small>
                      <div style={{ fontWeight: 800, color: '#0f172a', marginTop: '4px', fontSize: '0.95rem' }}>
                        {selectedApp.graduatedUniversity || (selectedApp.contractedUniversity !== selectedApp.university ? selectedApp.university : '') || '—'}
                        {selectedApp.graduationYear && (
                          <span style={{ fontSize: '0.82rem', color: '#64748b', fontWeight: 600, marginRight: '8px' }}>
                            (سنة التخرج: {selectedApp.graduationYear})
                          </span>
                        )}
                      </div>
                    </div>
                  </>
                ) : (
                  <>
                    <div>
                      <small style={{ color: 'var(--text-muted)' }}>الجامعة</small>
                      <div style={{ fontWeight: '600' }}>{selectedApp.university || '—'}</div>
                    </div>
                    <div>
                      <small style={{ color: 'var(--text-muted)' }}>سنة التخرج</small>
                      <div style={{ fontWeight: '600', direction: 'ltr', textAlign: 'right' }}>{selectedApp.graduationYear || '—'}</div>
                    </div>
                  </>
                )}
                <div>
                  <small style={{ color: 'var(--text-muted)' }}>تاريخ التقديم</small>
                  <div style={{ fontWeight: '600' }}>{selectedApp.date}</div>
                </div>
                {(selectedApp.trainingStartDate || selectedApp.startDate || selectedApp.volunteerStartDate) && (
                  <div style={{ gridColumn: 'span 2', background: '#f0fdf4', padding: '10px 14px', borderRadius: '10px', border: '1.5px solid #bbf7d0' }}>
                    <small style={{ color: '#15803d', fontWeight: 800 }}>📅 فترة التدريب المحددة في الطلب:</small>
                    <div style={{ fontWeight: 800, color: '#166534', marginTop: '2px', fontSize: '0.95rem' }}>
                      من {formatDate(selectedApp.trainingStartDate || selectedApp.startDate || selectedApp.volunteerStartDate)} إلى {formatDate(selectedApp.trainingEndDate || selectedApp.endDate || selectedApp.volunteerEndDate || '—')}
                    </div>
                  </div>
                )}
                {selectedApp.age && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>العمر</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.age}</div>
                  </div>
                )}
                {selectedApp.gender && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>الجنس</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.gender}</div>
                  </div>
                )}
                {selectedApp.degree && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>الدرجة العلمية</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.degree}</div>
                  </div>
                )}
                {(selectedApp.crescentJobNature || selectedApp.employmentType) && (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>طبيعة الوظيفة في مستشفى الهلال الأحمر</small>
                    <div style={{ fontWeight: '700', color: '#4338ca', marginTop: '2px' }}>
                      {selectedApp.crescentJobNature || selectedApp.employmentType}
                    </div>
                  </div>
                )}
                {selectedApp.paidTraining && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>هل تتقاضى أجر على التدريب</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.paidTraining}</div>
                  </div>
                )}
                {selectedApp.teachingExperienceYears && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>سنوات الخبرة التدريسية</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.teachingExperienceYears}</div>
                  </div>
                )}
                {selectedApp.previousUniversitiesCountAndPeriod && (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>الجامعات المتعاقد معها سابقاً والفترة</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.previousUniversitiesCountAndPeriod}</div>
                  </div>
                )}
                {selectedApp.teachingCourses && selectedApp.teachingCourses.length > 0 && (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>المساقات التي تدرسها</small>
                    <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginTop: '4px' }}>
                      {(Array.isArray(selectedApp.teachingCourses) ? selectedApp.teachingCourses : [selectedApp.teachingCourses]).map((c: string, idx: number) => (
                        <span key={idx} style={{ background: '#e0f2fe', color: '#0369a1', padding: '2px 10px', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 600 }}>
                          {c}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
                {selectedApp.previousContractedUniversity && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>اسم الجامعة المتعاقد معها</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.previousContractedUniversity}</div>
                  </div>
                )}
                {selectedApp.specialty && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>التخصص</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.specialty}</div>
                  </div>
                )}
                {selectedApp.dailyStudentsCount && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>عدد الطلاب اليومي</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.dailyStudentsCount}</div>
                  </div>
                )}
                {selectedApp.groupsPerDay && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>عدد المجموعات باليوم</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.groupsPerDay}</div>
                  </div>
                )}
                {selectedApp.totalSemesterTrainees && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>إجمالي المتدربين في الفصل</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.totalSemesterTrainees}</div>
                  </div>
                )}
                {selectedApp.workHours && (
                  <div>
                    <small style={{ color: 'var(--text-muted)' }}>أوقات الدوام بالساعة</small>
                    <div style={{ fontWeight: '600' }}>{selectedApp.workHours}</div>
                  </div>
                )}
                {selectedApp.workDays && selectedApp.workDays.length > 0 && (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>أوقات الدوام بالأيام</small>
                    <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginTop: '4px' }}>
                      {(Array.isArray(selectedApp.workDays) ? selectedApp.workDays : [selectedApp.workDays]).map((d: string, idx: number) => (
                        <span key={idx} style={{ background: '#f1f5f9', color: '#334155', padding: '2px 10px', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 600 }}>
                          {d}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
                {selectedApp.trainingDepartments && selectedApp.trainingDepartments.length > 0 && (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>أقسام التدريب</small>
                    <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginTop: '4px' }}>
                      {(Array.isArray(selectedApp.trainingDepartments) ? selectedApp.trainingDepartments : [selectedApp.trainingDepartments]).map((dept: string, idx: number) => (
                        <span key={idx} style={{ background: '#ecfdf5', color: '#047857', padding: '2px 10px', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 600 }}>
                          {dept}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
                {selectedApp.notes && (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>ملاحظات</small>
                    <div style={{ fontWeight: '500', whiteSpace: 'pre-wrap', background: 'var(--card-bg)', padding: '8px 12px', borderRadius: '8px', marginTop: '4px', fontSize: '0.9rem' }}>
                      {selectedApp.notes}
                    </div>
                  </div>
                )}
                {/* ورقة النقابة: ONLY display button if applicant truly uploaded a distinct union paper */}
                {Boolean(
                  selectedApp.unionPaperBase64 &&
                  selectedApp.unionPaperBase64 !== (selectedApp.photoBase64 || selectedApp.doctorPhotoBase64)
                ) ? (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>ورقة النقابة</small>
                    <div style={{ marginTop: '6px' }}>
                      <a
                        href={selectedApp.unionPaperBase64}
                        download={selectedApp.unionPaperFileName || `${selectedApp.name}_ورقة_النقابة`}
                        style={{
                          display: 'inline-flex', alignItems: 'center', gap: '8px',
                          padding: '10px 18px', background: 'linear-gradient(135deg, #1e3a8a, #2563eb)', color: 'white',
                          borderRadius: '10px', textDecoration: 'none', fontSize: '0.92rem',
                          fontWeight: '700', boxShadow: '0 4px 12px rgba(37, 99, 235, 0.25)'
                        }}
                      >
                        <FileText size={18} /> تحميل ورقة النقابة {selectedApp.unionPaperFileName ? `(${selectedApp.unionPaperFileName})` : ''}
                      </a>
                    </div>
                  </div>
                ) : (
                  <div style={{ gridColumn: 'span 2' }}>
                    <small style={{ color: 'var(--text-muted)' }}>ورقة النقابة</small>
                    <div style={{ marginTop: '4px', fontSize: '0.85rem', color: '#64748b', fontStyle: 'italic', background: '#f8fafc', padding: '10px 14px', borderRadius: '8px', border: '1px dashed #cbd5e1' }}>
                      📄 لم يتم إرفاق ورقة نقابة في هذا الطلب (تم إرفاق صورة شخصية فقط)
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Editable Accept Form */}
            <div style={{ marginBottom: '20px' }}>
              <h4 style={{ fontSize: '0.95rem', color: isUniversityApp(selectedApp) ? '#6b21a8' : 'var(--success)', marginBottom: '16px', fontWeight: '700', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <UserPlus size={18} /> {isUniversityApp(selectedApp) ? 'قبول واعتماد كادر التدريب الجامعي / الأطباء المتعاقدون (قسم مستقل)' : 'قبول الطالب وتخصيص الدورات (يُحفظ في الأرشيف)'}
              </h4>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                {/* Name */}
                <div className="form-group" style={{ gridColumn: 'span 2' }}>
                  <label>اسم الطبيب <span style={{ color: 'red' }}>*</span></label>
                  <input type="text" value={editForm.name} onChange={e => setEditForm({...editForm, name: e.target.value})} />
                </div>

                {/* Phone */}
                <div className="form-group">
                  <label>رقم الهاتف <span style={{ color: 'red' }}>*</span></label>
                  <input type="tel" value={editForm.phone} onChange={e => setEditForm({...editForm, phone: e.target.value})} />
                </div>

                {/* University — split for trainer apps vs regular applicants */}
                {isUniversityApp(selectedApp) ? (
                  <>
                    {/* 🤝 Contracted University — drives stats & classification */}
                    <div className="form-group" style={{ gridColumn: 'span 2' }}>
                      <label style={{ display: 'flex', alignItems: 'center', gap: '6px', color: '#5b21b6', fontWeight: 800 }}>
                        🤝 الجامعة المتعاقد معها
                        <span style={{ color: 'red' }}>*</span>
                        <span style={{
                          fontSize: '0.72rem', background: '#ede9fe', color: '#6d28d9', padding: '2px 8px',
                          borderRadius: '8px', fontWeight: 600, marginRight: 'auto'
                        }}>تُستخدم للإحصائيات وتصنيف الجامعات الشريكة</span>
                      </label>
                      <input
                        type="text"
                        value={editForm.contractedUniversity}
                        onChange={e => setEditForm({ ...editForm, contractedUniversity: e.target.value, university: e.target.value })}
                        placeholder="مثال: جامعة الخليل / جامعة بوليتكنك فلسطين"
                        style={{ border: '2px solid #7c3aed', borderRadius: '10px' }}
                      />
                    </div>

                    {/* 🎓 Graduated University — personal academic credential */}
                    <div className="form-group" style={{ gridColumn: 'span 2' }}>
                      <label style={{ display: 'flex', alignItems: 'center', gap: '6px', color: '#0f766e', fontWeight: 800 }}>
                        🎓 الجامعة المتخرج منها
                        <span style={{
                          fontSize: '0.72rem', background: '#f0fdf4', color: '#166534', padding: '2px 8px',
                          borderRadius: '8px', fontWeight: 600, marginRight: 'auto'
                        }}>المؤهل العلمي الشخصي — لا تؤثر على تصنيف الجامعات</span>
                      </label>
                      <input
                        type="text"
                        value={editForm.graduatedUniversity}
                        onChange={e => setEditForm({ ...editForm, graduatedUniversity: e.target.value })}
                        placeholder="مثال: جامعة الإسكندرية / جامعة المنصورة"
                        style={{ border: '2px solid #0d9488', borderRadius: '10px' }}
                      />
                    </div>
                  </>
                ) : (
                  /* Regular applicant — single graduation university field */
                  <div className="form-group">
                    <label>الجامعة</label>
                    <input
                      type="text"
                      value={editForm.university}
                      onChange={e => setEditForm({ ...editForm, university: e.target.value })}
                      placeholder="الجامعة"
                    />
                  </div>
                )}

                {/* Graduation Year */}
                <div className="form-group">
                  <label>سنة التخرج</label>
                  <input type="text" value={editForm.graduationYear || ''} onChange={e => setEditForm({...editForm, graduationYear: e.target.value})} placeholder="سنة التخرج" />
                </div>

                {/* Start Date & End Date for Standard applicants */}
                {!isUniversityApp(selectedApp) && (
                  <>
                    <div className="form-group">
                      <label>تاريخ البدء</label>
                      <input type="date" value={editForm.startDate} onChange={e => setEditForm({...editForm, startDate: e.target.value})} />
                    </div>

                    <div className="form-group">
                      <label>تاريخ الانتهاء</label>
                      <input type="date" value={editForm.endDate} onChange={e => setEditForm({...editForm, endDate: e.target.value})} />
                    </div>
                  </>
                )}
                
                {/* ═══ ROTATION SYSTEM OR DEDICATED UNIVERSITY TRAINER/DOCTOR SECTION ═══ */}
                {isUniversityApp(selectedApp) ? (
                  <div style={{
                    gridColumn: 'span 2',
                    background: 'linear-gradient(135deg, #f5f3ff, #ede9fe)',
                    borderRadius: '16px',
                    padding: '20px',
                    border: '2px solid #c4b5fd'
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '14px' }}>
                      <div style={{ background: '#7c3aed', color: 'white', borderRadius: '12px', padding: '10px 14px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <GraduationCap size={22} />
                      </div>
                      <div>
                        <h4 style={{ margin: 0, fontSize: '1.05rem', color: '#5b21b6', fontWeight: 800 }}>
                          {(selectedApp.categoryId === 'contracted-doctors' || (selectedApp.category || '').includes('متعاقد'))
                            ? 'اعتماد طبيب متعاقد مع الجامعات — قسم مستقل'
                            : 'اعتماد مدرب تمريض جامعات — قسم مستقل'}
                        </h4>
                        <div style={{ fontSize: '0.82rem', color: '#6d28d9', marginTop: '3px' }}>
                          ✓ يتم الحفظ والإدراج تلقائياً في المكان المخصص لكادر الجامعات ولن يتم خلطه مع أطباء الامتياز أو المتدربين العاديين
                        </div>
                      </div>
                    </div>

                    {/* 📅 تحديد واعتماد تاريخ بداية ونهاية التدريب للمدرب */}
                    <div style={{
                      marginBottom: '16px',
                      padding: '18px 20px',
                      background: '#ffffff',
                      borderRadius: '14px',
                      border: '2px solid #7c3aed',
                      boxShadow: '0 4px 15px rgba(124, 58, 237, 0.12)'
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px', flexWrap: 'wrap', gap: '8px' }}>
                        <div style={{ fontWeight: 800, color: '#5b21b6', fontSize: '1.02rem', display: 'flex', alignItems: 'center', gap: '8px' }}>
                          <span style={{ fontSize: '1.25rem' }}>📅</span> تحديد واعتماد فترة التدريب / التعاقد في المستشفى
                        </div>
                        {editForm.startDate && editForm.endDate && (
                          <span style={{ fontSize: '0.85rem', background: '#ede9fe', color: '#6d28d9', padding: '4px 12px', borderRadius: '20px', fontWeight: 700, border: '1px solid #c4b5fd' }}>
                            ✓ الفترة: من {formatDate(editForm.startDate)} إلى {formatDate(editForm.endDate)}
                          </span>
                        )}
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' }}>
                        <div>
                          <label style={{ display: 'block', marginBottom: '6px', fontWeight: 700, fontSize: '0.9rem', color: '#4b5563' }}>
                            تاريخ بداية التدريب (من تاريخ) <span style={{ color: '#e11d48' }}>*</span>
                          </label>
                          <input 
                            type="date" 
                            required
                            value={editForm.startDate} 
                            onChange={e => setEditForm({...editForm, startDate: e.target.value, deptStartDate: e.target.value})}
                            style={{ width: '100%', padding: '12px 14px', borderRadius: '10px', border: '1.5px solid #8b5cf6', fontSize: '0.95rem', fontFamily: 'Tajawal', outline: 'none', background: '#faf5ff', fontWeight: 600 }}
                          />
                        </div>

                        <div>
                          <label style={{ display: 'block', marginBottom: '6px', fontWeight: 700, fontSize: '0.9rem', color: '#4b5563' }}>
                            تاريخ نهاية التدريب (إلى تاريخ) <span style={{ color: '#e11d48' }}>*</span>
                          </label>
                          <input 
                            type="date" 
                            required
                            value={editForm.endDate} 
                            onChange={e => setEditForm({...editForm, endDate: e.target.value, deptEndDate: e.target.value})}
                            style={{ width: '100%', padding: '12px 14px', borderRadius: '10px', border: '1.5px solid #8b5cf6', fontSize: '0.95rem', fontFamily: 'Tajawal', outline: 'none', background: '#faf5ff', fontWeight: 600 }}
                          />
                        </div>
                      </div>

                      <div style={{ fontSize: '0.82rem', color: '#6d28d9', marginTop: '10px' }}>
                        💡 يمكنك تحديد أو تعديل التاريخين قبل الضغط على "قبول واعتماد"، وسيتم حفظ المدرب مباشرة بهذه التواريخ في جدول كادر التدريب ونظام إنذارات الانتهاء.
                      </div>
                    </div>

                    {/* Details grid for contracted uni/doctor */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '12px', background: 'white', padding: '16px', borderRadius: '12px', border: '1px solid #ddd6fe' }}>
                      <div>
                        <small style={{ color: '#6b7280', display: 'block', fontSize: '0.78rem' }}>القسم والوجهة المستقلة في النظام:</small>
                        <span style={{ fontWeight: 800, color: '#6b21a8', fontSize: '0.95rem' }}>
                          {(selectedApp.categoryId === 'contracted-doctors' || (selectedApp.category || '').includes('متعاقد')) ? '📁 قسم الأطباء المتعاقدون' : '📁 قسم تدريب تمريض الجامعات'}
                        </span>
                      </div>

                      {selectedApp.crescentJobNature && (
                        <div>
                          <small style={{ color: '#6b7280', display: 'block', fontSize: '0.78rem' }}>طبيعة الوظيفة في المستشفى:</small>
                          <span style={{ fontWeight: 700, color: '#1e293b' }}>{selectedApp.crescentJobNature}</span>
                        </div>
                      )}

                      {selectedApp.contractedUniversities && selectedApp.contractedUniversities.length > 0 && (
                        <div>
                          <small style={{ color: '#6b7280', display: 'block', fontSize: '0.78rem' }}>الجامعات المتعاقد معها:</small>
                          <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap', marginTop: '3px' }}>
                            {(Array.isArray(selectedApp.contractedUniversities) ? selectedApp.contractedUniversities : [selectedApp.contractedUniversities]).map((u: string, idx: number) => (
                              <span key={idx} style={{ background: '#ede9fe', color: '#6b21a8', padding: '2px 8px', borderRadius: '10px', fontSize: '0.78rem', fontWeight: 700 }}>
                                {u}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}

                      {selectedApp.teachingCourses && selectedApp.teachingCourses.length > 0 && (
                        <div style={{ gridColumn: 'span 2' }}>
                          <small style={{ color: '#6b7280', display: 'block', fontSize: '0.78rem' }}>المساقات التدريسية:</small>
                          <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap', marginTop: '3px' }}>
                            {(Array.isArray(selectedApp.teachingCourses) ? selectedApp.teachingCourses : [selectedApp.teachingCourses]).map((c: string, idx: number) => (
                              <span key={idx} style={{ background: '#e0f2fe', color: '#0369a1', padding: '2px 8px', borderRadius: '10px', fontSize: '0.78rem', fontWeight: 700 }}>
                                {c}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}

                      {selectedApp.workDays && selectedApp.workDays.length > 0 && (
                        <div style={{ gridColumn: 'span 2' }}>
                          <small style={{ color: '#6b7280', display: 'block', fontSize: '0.78rem' }}>أيام الدوام والتدريب الأسبوعية:</small>
                          <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap', marginTop: '3px' }}>
                            {(Array.isArray(selectedApp.workDays) ? selectedApp.workDays : [selectedApp.workDays]).map((d: string, idx: number) => (
                              <span key={idx} style={{ background: '#ecfdf5', color: '#065f46', padding: '2px 8px', borderRadius: '10px', fontSize: '0.78rem', fontWeight: 700 }}>
                                {d}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* 🏥 Interactive Multi-Department Manager for University Trainers */}
                      <div style={{
                        gridColumn: 'span 2',
                        background: '#faf5ff',
                        padding: '14px',
                        borderRadius: '12px',
                        border: '1.5px solid #c4b5fd'
                      }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px', flexWrap: 'wrap', gap: '6px' }}>
                          <small style={{ color: '#5b21b6', fontWeight: 800, fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '6px' }}>
                            <span>🏥</span> الأقسام التدريبية المعتمدة ({adminUniDepts.length}):
                          </small>
                          <span style={{ fontSize: '0.75rem', color: '#7c3aed', fontWeight: 700 }}>
                            ✓ يمكنك إضافة أكثر من قسم (مثل: الأطفال، جراحة، نسائية) وحذف أو تعديل أي قسم
                          </span>
                        </div>

                        {/* Current Departments Pills */}
                        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginBottom: '10px' }}>
                          {adminUniDepts.length === 0 ? (
                            <span style={{ color: '#94a3b8', fontSize: '0.82rem' }}>لا توجد أقسام مخصصة حالياً. اختر أو أضف قسماً بالأسفل.</span>
                          ) : (
                            adminUniDepts.map((td: string, idx: number) => (
                              <span key={idx} style={{
                                background: '#fef3c7',
                                color: '#92400e',
                                border: '1px solid #fde68a',
                                padding: '4px 10px',
                                borderRadius: '12px',
                                fontSize: '0.82rem',
                                fontWeight: 800,
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '6px'
                              }}>
                                <span>قسم {idx + 1}: {td}</span>
                                <button
                                  type="button"
                                  onClick={() => setAdminUniDepts(adminUniDepts.filter((_, i) => i !== idx))}
                                  style={{
                                    background: 'none',
                                    border: 'none',
                                    color: '#ef4444',
                                    cursor: 'pointer',
                                    padding: '0 2px',
                                    fontSize: '0.9rem',
                                    fontWeight: 900,
                                    lineHeight: 1
                                  }}
                                  title="حذف هذا القسم"
                                >
                                  &times;
                                </button>
                              </span>
                            ))
                          )}
                        </div>

                        {/* Add Department Controls */}
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '8px' }}>
                          <select
                            onChange={(e) => {
                              const val = e.target.value;
                              if (val && !adminUniDepts.includes(val)) {
                                setAdminUniDepts([...adminUniDepts, val]);
                              }
                              e.target.value = '';
                            }}
                            style={{
                              padding: '8px 10px',
                              borderRadius: '8px',
                              border: '1.5px solid #8b5cf6',
                              background: 'white',
                              fontWeight: 700,
                              fontSize: '0.82rem',
                              fontFamily: 'Tajawal',
                              outline: 'none'
                            }}
                          >
                            <option value="">➕ إضافة قسم من المستشفى...</option>
                            <option value="الاطفال">طب الأطفال (Pediatrics)</option>
                            <option value="جراحة">الجراحة العامة (Surgery)</option>
                            <option value="نسائية">النسائية والتوليد (Gynecology)</option>
                            <option value="التمريض">التمريض العام (Nursing)</option>
                            <option value="طوارئ">الطوارئ (Emergency)</option>
                            <option value="باطني">الباطني (Internal Medicine)</option>
                            <option value="عناية مكثفة">العناية المكثفة (ICU)</option>
                            <option value="عمليات">العمليات (OR)</option>
                            <option value="العلاج الطبيعي">العلاج الطبيعي (PT)</option>
                            <option value="مختبرات">المختبرات الطبية (Labs)</option>
                            <option value="أشعة">الأشعة (Radiology)</option>
                            <option value="العلاج الوظيفي">العلاج الوظيفي</option>
                            <option value="تغذية">التغذية</option>
                            <option value="ضباط الإسعاف">ضباط الإسعاف</option>
                          </select>

                          <div style={{ display: 'flex', gap: '6px' }}>
                            <input
                              type="text"
                              placeholder="أو اكتب اسم قسم واضغط إضافة..."
                              value={adminCustomDeptInput}
                              onChange={(e) => setAdminCustomDeptInput(e.target.value)}
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  e.preventDefault();
                                  if (adminCustomDeptInput.trim() && !adminUniDepts.includes(adminCustomDeptInput.trim())) {
                                    setAdminUniDepts([...adminUniDepts, adminCustomDeptInput.trim()]);
                                    setAdminCustomDeptInput('');
                                  }
                                }
                              }}
                              style={{
                                flex: 1,
                                padding: '8px 10px',
                                borderRadius: '8px',
                                border: '1px solid #c4b5fd',
                                background: 'white',
                                fontSize: '0.82rem',
                                fontFamily: 'Tajawal',
                                outline: 'none'
                              }}
                            />
                            <button
                              type="button"
                              onClick={() => {
                                if (adminCustomDeptInput.trim() && !adminUniDepts.includes(adminCustomDeptInput.trim())) {
                                  setAdminUniDepts([...adminUniDepts, adminCustomDeptInput.trim()]);
                                  setAdminCustomDeptInput('');
                                }
                              }}
                              style={{
                                padding: '8px 12px',
                                borderRadius: '8px',
                                background: '#7c3aed',
                                color: 'white',
                                border: 'none',
                                fontWeight: 700,
                                fontSize: '0.8rem',
                                cursor: 'pointer',
                                fontFamily: 'Tajawal',
                                whiteSpace: 'nowrap'
                              }}
                            >
                              إضافة
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div style={{ gridColumn: 'span 2', display: 'flex', flexDirection: 'column', gap: '16px' }}>
                    {/* 🩺 المدرب السريري المشرف المعيّن */}
                    <div style={{
                      background: '#ecfdf5',
                      borderRadius: '16px',
                      padding: '16px 20px',
                      border: '2px solid #10b981',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      flexWrap: 'wrap',
                      gap: '12px'
                    }}>
                      <div>
                        <div style={{ fontWeight: 800, color: '#047857', fontSize: '0.92rem', display: 'flex', alignItems: 'center', gap: '6px' }}>
                          <span>🩺</span> المدرب السريري المشرف المعتمد:
                        </div>
                        <div style={{ fontWeight: 900, color: '#065f46', fontSize: '1.15rem', marginTop: '2px' }}>
                          {editForm.assignedTrainer || selectedApp.assignedTrainer || selectedApp.trainerName || selectedApp.supervisorName || 'لم يتم تحديد مدرب'}
                        </div>
                      </div>
                      <div style={{ minWidth: '240px' }}>
                        <label style={{ display: 'block', fontSize: '0.78rem', color: '#047857', fontWeight: 700, marginBottom: '4px' }}>
                          تغيير / تعيين المدرب في النظام:
                        </label>
                        <select
                          value={editForm.assignedTrainer || ''}
                          onChange={(e) => setEditForm({ ...editForm, assignedTrainer: e.target.value })}
                          style={{
                            width: '100%',
                            padding: '9px 12px',
                            borderRadius: '10px',
                            border: '1.5px solid #059669',
                            background: 'white',
                            fontWeight: 700,
                            fontSize: '0.88rem',
                            fontFamily: 'Tajawal',
                            outline: 'none'
                          }}
                        >
                          <option value="">اختر المدرب...</option>
                          {trainersList.map(t => (
                            <option key={t.name} value={t.name}>{t.name} ({t.university || t.dept})</option>
                          ))}
                        </select>
                      </div>
                    </div>

                    <div style={{ background: 'linear-gradient(135deg,#f8f9ff,#f0f4ff)', borderRadius: '16px', padding: '20px', border: '2px solid #e0e7ff' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' }}>
                      <h4 style={{ margin: 0, fontSize: '1rem', color: '#4338ca', fontWeight: 800 }}>
                        <i className="fas fa-sync-alt" style={{ marginLeft: '8px' }}></i>
                        نظام الدورات (Rotations)
                      </h4>
                      <div style={{ display: 'flex', gap: '8px' }}>
                        {[1, 2, 3].map(n => (
                          <button key={n} type="button" onClick={() => {
                            setRotationCount(n);
                            setRotations(calcRotations(n, editForm.studySystem, editForm.startDate));
                          }}
                          style={{
                            padding: '8px 18px', borderRadius: '10px', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.9rem', cursor: 'pointer',
                            border: rotationCount === n ? '2px solid #4338ca' : '2px solid #cbd5e1',
                            background: rotationCount === n ? '#4338ca' : 'white',
                            color: rotationCount === n ? 'white' : '#333',
                            transition: 'all 0.2s'
                          }}>
                            {n} {n === 1 ? 'دورة' : 'دورات'}
                          </button>
                        ))}
                      </div>
                    </div>
                    <p style={{ fontSize: '0.8rem', color: '#6366f1', marginBottom: '16px', fontWeight: 600 }}>
                      {(selectedApp.category === 'المتقدمين للإمتياز' || selectedApp.categoryId === 'internship')
                        ? (editForm.studySystem === '6+1' ? 'نظام 6+1: كل دورة = شهرين' : 'نظام 5+2: كل دورة = 3 أشهر')
                        : 'نظام الدورات التدريبية المعتمدة'}
                      {' • '}ابتداء من {editForm.startDate || '...'}
                    </p>
                    
                    {rotations.map((rot, idx) => (
                      <div key={idx} style={{ background: 'white', borderRadius: '12px', padding: '16px', marginBottom: idx < rotations.length - 1 ? '12px' : '0', border: '1px solid #e2e8f0', position: 'relative' }}>
                        <div style={{ position: 'absolute', top: '-10px', right: '16px', background: '#4338ca', color: 'white', padding: '2px 12px', borderRadius: '20px', fontSize: '0.75rem', fontWeight: 700 }}>
                          الدورة {idx + 1}
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginTop: '8px' }}>
                          <div>
                            <label style={{ fontSize: '0.8rem', fontWeight: 600, display: 'block', marginBottom: '4px' }}>تاريخ البداية</label>
                            <input type="date" value={rot.startDate} onChange={e => {
                              const newR = [...rotations]; newR[idx].startDate = e.target.value; setRotations(newR);
                            }} style={{ width: '100%', padding: '8px', borderRadius: '8px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal' }} />
                          </div>
                          <div>
                            <label style={{ fontSize: '0.8rem', fontWeight: 600, display: 'block', marginBottom: '4px' }}>تاريخ الانتهاء</label>
                            <input type="date" value={rot.endDate} onChange={e => {
                              const newR = [...rotations]; newR[idx].endDate = e.target.value; setRotations(newR);
                            }} style={{ width: '100%', padding: '8px', borderRadius: '8px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal' }} />
                          </div>
                          <div>
                            <label style={{ fontSize: '0.8rem', fontWeight: 600, display: 'block', marginBottom: '4px' }}>نظام الدوام</label>
                            <select value={rot.shiftSystem} onChange={e => {
                              const newR = [...rotations]; newR[idx].shiftSystem = e.target.value; setRotations(newR);
                            }} style={{ width: '100%', padding: '8px', borderRadius: '8px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal' }}>
                              <option value="">اختياري</option>
                              <option value="سبت اثنين اربعاء">سبت، إثنين، أربعاء</option>
                              <option value="احد ثلاثاء خميس">أحد، ثلاثاء، خميس</option>
                            </select>
                          </div>
                          <div>
                            <label style={{ fontSize: '0.8rem', fontWeight: 600, display: 'block', marginBottom: '4px' }}>القسم <span style={{ color: 'red' }}>*</span></label>
                            <select value={rot.dept} onChange={e => {
                              const newR = [...rotations]; newR[idx].dept = e.target.value; setRotations(newR);
                            }} style={{ width: '100%', padding: '8px', borderRadius: '8px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal', fontWeight: 600 }}>
                              <option value="">اختر القسم</option>
                              {departments.map(d => <option key={d.key} value={d.key}>{d.label}</option>)}
                            </select>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                  </div>
                )}
              </div>
            </div>

            {/* Action Buttons */}
            <div style={{ 
              display: 'flex', gap: '10px', borderTop: '2px solid var(--border)', paddingTop: '20px',
              flexWrap: 'wrap'
            }}>
               {/* Print/Save Button */}
               <button 
                onClick={() => printApplication(selectedApp)}
                disabled={isProcessing}
                style={{ 
                  flex: '1', padding: '14px 20px', borderRadius: '12px', border: 'none',
                  background: 'linear-gradient(135deg, #f39c12, #d35400)',
                  color: 'white', fontFamily: 'Tajawal', fontWeight: '700', fontSize: '1rem',
                  cursor: isProcessing ? 'not-allowed' : 'pointer', display: 'flex',
                  alignItems: 'center', justifyContent: 'center', gap: '8px',
                  transition: 'all 0.3s'
                }}
              >
                <i className="fas fa-print"></i>
                طباعة / حفظ PDF
              </button>

              {/* Accept Button */}
              <button 
                onClick={handleAccept}
                disabled={isProcessing}
                style={{ 
                  flex: '2', padding: '14px 20px', borderRadius: '12px', border: 'none',
                  background: isProcessing ? '#94a3b8' : 'linear-gradient(135deg, #16a34a, #15803d)',
                  color: 'white', fontFamily: 'Tajawal', fontWeight: '800', fontSize: '1rem',
                  cursor: isProcessing ? 'not-allowed' : 'pointer', display: 'flex',
                  alignItems: 'center', justifyContent: 'center', gap: '8px',
                  boxShadow: '0 6px 20px rgba(22, 163, 74, 0.35)',
                  transition: 'all 0.3s'
                }}
              >
                <CheckCircle size={20} />
                {isProcessing ? 'جاري المعالجة...' : selectedApp.status === 'accepted' ? 'تحديث وتأكيد القبول' : 'قبول وأرشفة'}
              </button>

              {/* Certificate Button if Accepted */}
              {(selectedApp.status === 'accepted' || selectedApp.status === 'مقبول') && (
                <Link
                  href={`/certificate?student=${encodeURIComponent(editForm.name || selectedApp.name)}&dept=${encodeURIComponent(editForm.targetDept || '')}`}
                  target="_blank"
                  style={{
                    flex: '1', padding: '14px 16px', borderRadius: '12px', textDecoration: 'none',
                    background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', color: 'white',
                    fontFamily: 'Tajawal', fontWeight: '800', fontSize: '0.95rem',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px',
                    boxShadow: '0 4px 14px rgba(139, 26, 43, 0.3)',
                    transition: 'all 0.3s'
                  }}
                >
                  <FileText size={18} />
                  شهادة الخبرة
                </Link>
              )}

              {/* Reject / Archive Button */}
              <button 
                onClick={() => handleReject(selectedApp)}
                disabled={isProcessing}
                style={{ 
                  flex: '1', padding: '14px 20px', borderRadius: '12px', border: 'none',
                  background: isProcessing ? '#94a3b8' : 'linear-gradient(135deg, #dc2626, #991b1b)',
                  color: 'white', fontFamily: 'Tajawal', fontWeight: '800', fontSize: '1rem',
                  cursor: isProcessing ? 'not-allowed' : 'pointer', display: 'flex',
                  alignItems: 'center', justifyContent: 'center', gap: '8px',
                  boxShadow: '0 6px 20px rgba(220, 38, 38, 0.25)',
                  transition: 'all 0.3s'
                }}
              >
                <Archive size={20} />
                أرشفة (رفض)
              </button>

              {/* Call Button */}
              <a href={`tel:${selectedApp.phone}`} style={{ 
                flex: '1', padding: '14px 20px', borderRadius: '12px', textDecoration: 'none',
                background: 'linear-gradient(135deg, #2B5F8B, #1D4366)', color: 'white',
                fontFamily: 'Tajawal', fontWeight: '700', fontSize: '1rem',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px',
                transition: 'all 0.3s'
              }}>
                <Phone size={20} />
                اتصال
              </a>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════
           ASSIGN TRAINER MODAL
      ══════════════════════════════════════════════════ */}
      {showAssignTrainerModal && assignTargetApp && (
        <div
          style={{
            position: 'fixed', inset: 0, zIndex: 9998,
            background: 'rgba(0,0,0,0.6)', 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: '80vh',
            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.1rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <i className="fas fa-chalkboard-teacher" />
                  تعيين مدرب سريري
                </div>
                <div style={{ color: 'rgba(255,255,255,0.85)', fontSize: '0.85rem', marginTop: '4px' }}>
                  الطالب: <strong>{assignTargetApp.name}</strong>
                  {assignTargetApp.university && <span style={{ marginRight: '8px', opacity: 0.8 }}>— {assignTargetApp.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>

            {/* Search + Manual Entry */}
            <div style={{ padding: '16px 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={trainerSearch}
                  onChange={e => setTrainerSearch(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 */}
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {[
                  { key: 'all', label: `جميع المدربين (${trainersList.length})` },
                  { key: 'nursing', label: `🩺 مدربو التمريض (${trainersList.filter(t => t.isNursingTrainer).length})` },
                  { key: 'approved', label: `🎓 كادر المستشفى (${trainersList.filter(t => !t.isNursingTrainer).length})` },
                ].map(tab => (
                  <button
                    key={tab.key}
                    type="button"
                    onClick={() => setTrainerFilterTab(tab.key as any)}
                    style={{
                      padding: '5px 12px',
                      borderRadius: '16px',
                      fontSize: '0.8rem',
                      fontWeight: 700,
                      fontFamily: 'Tajawal',
                      cursor: 'pointer',
                      border: '1px solid',
                      borderColor: trainerFilterTab === tab.key ? '#0891b2' : 'var(--border, #cbd5e1)',
                      background: trainerFilterTab === tab.key ? '#0891b2' : 'var(--card-bg, #fff)',
                      color: trainerFilterTab === tab.key ? '#fff' : 'var(--text, #334155)',
                      transition: 'all 0.15s ease'
                    }}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>

              {/* Manual assign if typed name not in list */}
              {trainerSearch.trim() && !trainersList.find(t => t.name === trainerSearch.trim()) && (
                <button
                  onClick={() => handleAssignToTrainer(trainerSearch.trim())}
                  disabled={isAssigning}
                  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" />
                  تعيين باسم مخصص: "{trainerSearch.trim()}"
                </button>
              )}
            </div>

            {/* Trainers List */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
              {(() => {
                const filtered = trainersList.filter(t => {
                  if (trainerFilterTab === 'nursing' && !t.isNursingTrainer) return false;
                  if (trainerFilterTab === 'approved' && t.isNursingTrainer) return false;
                  if (trainerSearch.trim()) {
                    const q = trainerSearch.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}
                    disabled={isAssigning}
                    onClick={() => handleAssignToTrainer(trainer.name)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: '14px',
                      padding: '12px 16px', borderRadius: '12px', border: '1.5px solid transparent',
                      background: trainer.isNursingTrainer ? 'rgba(8, 145, 178, 0.05)' : 'var(--bg, #f8fafc)',
                      cursor: isAssigning ? '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.isNursingTrainer ? '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.isNursingTrainer
                        ? '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.isNursingTrainer ? '#ecfdf5' : '#f1f5f9',
                            color: trainer.isNursingTrainer ? '#047857' : '#475569',
                            border: trainer.isNursingTrainer ? '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' }}>
                {trainersList.length > 0 ? `${trainersList.filter(t => !trainerSearch.trim() || t.name.includes(trainerSearch.trim())).length} من ${trainersList.length} شخص` : 'لا يوجد أشخاص'}
              </span>
              <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>
      )}

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: '24px', right: '24px', zIndex: 9999,
          background: '#1e293b', color: 'white', padding: '14px 24px', borderRadius: '12px',
          boxShadow: '0 10px 25px rgba(0,0,0,0.2)', fontWeight: 700, fontSize: '0.95rem',
          display: 'flex', alignItems: 'center', gap: '10px'
        }}>
          {toast}
        </div>
      )}
    </div>
  );
}
