'use client';
import { useState, useEffect, useRef, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';

interface Student {
  name: string;
  phone?: string;
  university?: string;
  globalStartDate?: string;
  globalEndDate?: string;
  startDate?: string;
  endDate?: string;
  department?: string;
  deptLabel?: string;
  internshipYear?: string;
  idNumber?: string;
  bloodType?: string;
  [key: string]: any;
}

interface StudentEntry {
  name: string;
  dept: string;
  student: Student;
}

export const HOSPITAL_DEPARTMENTS = [
  // أطباء الامتياز
  'طب الأطفال',
  'الجراحة العامة',
  'النسائية والتوليد',
  'الباطني',
  'الطوارئ',
  'العناية المركزة ICU',
  'العناية المركزة للأطفال PICU',
  'الحضانة وحديثي الولادة NICU',
  'العمليات الجراحية',
  'قبل الولادة',
  'بعد الولادة',
  'الكلى والغسيل الكلوي',

  // التمريض
  'التمريض العام',
  'تمريض تدريب',
  'تمريض امتياز',
  'تمريض تطوع',

  // المهن المساندة
  'المختبرات الطبية وبنك الدم',
  'الأشعة والتصوير الطبي',
  'العلاج الطبيعي والتأهيل',
  'العلاج الوظيفي',
  'التغذية السريرية والحميات',
  'الصحة النفسية والدعم النفسي',
  'الخدمة الاجتماعية',
  'ضباط الإسعاف والطوارئ',

  // الإدارة والخدمات والتطوع
  'الإدارة الطبية والخدمات',
  'المحاسبة والمالية',
  'المطبخ والخدمات',
  'طب تطوع',
  'العمل المجتمعي والتطوع'
];

const deptFormalName: Record<string, string> = {
  'جراحة': 'الجراحة العامة',
  'الجراحة': 'الجراحة العامة',
  'نسائية': 'النسائية والتوليد',
  'النسائية': 'النسائية والتوليد',
  'الاطفال': 'طب الأطفال',
  'أطفال': 'طب الأطفال',
  'اطفال': 'طب الأطفال',
  'الأطفال': 'طب الأطفال',
  'طوارئ': 'الطوارئ',
  'الطوارئ': 'الطوارئ',
  'باطني': 'الباطني',
  'الباطني': 'الباطني',
  'عمليات': 'العمليات الجراحية',
  'العمليات': 'العمليات الجراحية',
  'التمريض': 'التمريض العام',
  'تمريض': 'التمريض العام',
  'العلاج الطبيعي': 'العلاج الطبيعي والتأهيل',
  'الصحة النفسية': 'الصحة النفسية والدعم النفسي',
  'أشعة': 'الأشعة والتصوير الطبي',
  'الأشعة': 'الأشعة والتصوير الطبي',
  'تغذية': 'التغذية السريرية والحميات',
  'التغذية': 'التغذية السريرية والحميات',
  'خدمة اجتماعية': 'الخدمة الاجتماعية',
  'ضباط الإسعاف': 'ضباط الإسعاف والطوارئ',
  'إدارة': 'الإدارة الطبية والخدمات',
  'المحاسبة': 'المحاسبة والمالية',
  'المطبخ': 'المطبخ والخدمات',
  'المغادرين': 'خريج',
  'الاستئناف': 'استئناف'
};

const deptToDefaultTitle: Record<string, string> = {
  'جراحة': 'طبيب امتياز',
  'الجراحة': 'طبيب امتياز',
  'الجراحة العامة': 'طبيب امتياز',
  'نسائية': 'طبيب امتياز',
  'النسائية والتوليد': 'طبيب امتياز',
  'الاطفال': 'طبيب امتياز',
  'طب الأطفال': 'طبيب امتياز',
  'أطفال': 'طبيب امتياز',
  'طوارئ': 'طبيب امتياز',
  'باطني': 'طبيب امتياز',
  'التمريض': 'ممرض/ة',
  'التمريض العام': 'ممرض/ة',
  'تمريض تدريب': 'متدرب/ة تمريض',
  'تمريض امتياز': 'طالب/ة امتياز تمريض',
  'العلاج الطبيعي': 'معالج/ة طبيعي/ة',
  'العلاج الوظيفي': 'معالج/ة وظيفي/ة',
  'المطبخ': 'موظف مطبخ',
  'إدارة': 'موظف إداري',
  'المحاسبة': 'محاسب',
  'طب تطوع': 'طبيب متطوع',
  'تمريض تطوع': 'ممرض/ة متطوع/ة',
  'تغذية': 'أخصائي/ة تغذية',
  'أشعة': 'تقني/ة أشعة',
  'خدمة اجتماعية': 'أخصائي/ة اجتماعي/ة',
  'ضباط الإسعاف': 'ضابط إسعاف',
  'العمل المجتمعي': 'متطوع/ة مجتمعي/ة',
};

// Reusable function to generate card HTML with contenteditable fields
export function buildCardHtml(
  data: { name: string; title: string; dept: string; endDate: string; idNumber?: string; bloodType?: string; trainerName?: string },
  isInteractive: boolean = false
): string {
  const extraRow = data.bloodType ? `
    <div style="display:flex;align-items:center;justify-content:center;gap:12px;margin-top:1px;">
      <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:3px;padding:1px 5px;display:flex;align-items:center;"><span style="font-size:7px;font-weight:800;color:#ef4444;margin-left:3px;">فصيلة الدم:</span><span style="font-size:8px;font-weight:800;color:#b91c1c;" dir="ltr" ${isInteractive ? 'contenteditable="true"' : ''}>${data.bloodType}</span></div>
    </div>` : '';

  const editAttr = isInteractive ? 'contenteditable="true" spellcheck="false"' : '';
  const deptHighlightStyle = isInteractive ? 'background:#eff6ff;outline:1px dashed #3b82f6;' : '';

  return `<div class="id-card" style="width:85mm;height:54mm;border:1px solid #bbb;overflow:hidden;display:flex;flex-direction:column;font-family:'Tajawal',sans-serif;background:white;position:relative;box-sizing:border-box;box-shadow:0 4px 15px rgba(0,0,0,0.08);">
    <div style="display:flex;align-items:center;justify-content:space-between;padding:5px 7px;border-bottom:2.5px solid #CE1126;background:#f9f9f9;">
      <div style="text-align:right;flex:1;direction:rtl;">
        <div style="font-size:7px;font-weight:800;color:#CE1126;">جمعية الهلال الأحمر الفلسطيني - الخليل</div>
        <div style="font-size:6px;font-weight:700;color:#333;">مستشفى الهلال الأحمر التخصصي - الخليل</div>
      </div>
      <div style="margin:0 5px;flex-shrink:0;width:30px;height:30px;border-radius:50%;border:1px solid #CE1126;overflow:hidden;display:flex;align-items:center;justify-content:center;background:white;">
        <img src="/prcs-logo.png" style="width:24px;height:24px;object-fit:contain;" alt="Logo" />
      </div>
      <div style="text-align:left;flex:1;">
        <div style="font-size:6px;font-weight:800;color:#CE1126;">Palestine Red Crescent Society- Hebron</div>
        <div style="font-size:5px;font-weight:600;color:#555;">Red Crescent Specilized Hospital - Hebron</div>
      </div>
    </div>
    <div style="flex:1;padding:5px 10px;direction:rtl;display:flex;flex-direction:column;justify-content:center;gap:4px;">
      <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
        <span style="font-size:9px;font-weight:800;min-width:60px;color:#222;">الاسم :</span>
        <span style="font-size:10px;font-weight:800;color:#CE1126;" ${editAttr} class="editable-name">${data.name}</span>
      </div>
      <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
        <span style="font-size:9px;font-weight:800;min-width:60px;color:#222;">المسمى:</span>
        <span style="font-size:9px;font-weight:700;color:#333;" ${editAttr} class="editable-title">${data.title}</span>
      </div>
      <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
        <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">القسم :</span>
        <span style="font-size:9px;font-weight:700;color:#333;${deptHighlightStyle}padding:1px 4px;border-radius:3px;" ${editAttr} class="editable-dept" title="القسم - قابل للتعديل">${data.dept}</span>
      </div>
      ${data.trainerName ? `
      <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
        <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">المدرب المشرف:</span>
        <span style="font-size:9.5px;font-weight:800;color:#0284c7;" ${editAttr} class="editable-trainer">${data.trainerName}</span>
      </div>` : ''}
      <div style="display:flex;align-items:center;border-bottom:1px dotted #ccc;padding-bottom:2px;">
        <span style="font-size:9px;font-weight:800;min-width:75px;color:#222;">تاريخ الإنتهاء :</span>
        <span style="font-size:9px;font-weight:700;color:#333;" ${editAttr} class="editable-date">${data.endDate}</span>
      </div>
      ${extraRow}
    </div>
    <div style="padding:2px 12px 9px;display:flex;justify-content:flex-start;align-items:center;direction:ltr;">
      <div style="text-align:center;line-height:1.25;direction:rtl;">
        <div style="font-size:7px;font-weight:800;color:#0f172a;">مديرة وحدة التطوير والتدريب</div>
        <div style="font-size:6.5px;font-weight:800;color:#CE1126;">أ. نسرين عابدين</div>
      </div>
    </div>
    <div style="height:6px;background:linear-gradient(to bottom,#CE1126,#8B0000);position:absolute;bottom:0;width:100%;"></div>
  </div>`;
}

function IdCardContent() {
  const searchParams = useSearchParams();
  const [allStudents, setAllStudents] = useState<StudentEntry[]>([]);
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  
  // Single card fields
  const [doctorName, setDoctorName] = useState('');
  const [department, setDepartment] = useState('');
  const [jobTitle, setJobTitle] = useState('طبيب امتياز');
  const [endDate, setEndDate] = useState('');
  const [idNumber, setIdNumber] = useState('');
  const [bloodType, setBloodType] = useState('');
  const [trainerName, setTrainerName] = useState('');
  
  // Helper to resolve trainer for departments
  const resolveTrainer = (st: any, dName: string) => {
    if (st?.assignedTrainer && String(st.assignedTrainer).trim()) return String(st.assignedTrainer).trim();
    if (st?.assigned_trainer && String(st.assigned_trainer).trim()) return String(st.assigned_trainer).trim();
    if (st?.trainerName && String(st.trainerName).trim()) return String(st.trainerName).trim();
    if (st?.supervisorName && String(st.supervisorName).trim()) return String(st.supervisorName).trim();
    const d = (dName || st?.department || '').toLowerCase();
    if (d.includes('أشعة') || d.includes('اشعة')) return 'ضياء الدين هيموني';
    if (d.includes('علاج طبيعي')) return 'مشرف قسم العلاج الطبيعي';
    if (d.includes('مختبر')) return 'مشرف قسم المختبرات الطبية';
    if (d.includes('تغذية')) return 'مشرف قسم التغذية السريرية';
    if (d.includes('صيدل')) return 'مشرف قسم الصيدلة السريرية';
    if (d.includes('تمريض')) return 'مشرف قسم التمريض السريري';
    return '';
  };

  // Multi-card batch mode
  const [batchSelected, setBatchSelected] = useState<Set<string>>(new Set());
  const [deptOverrides, setDeptOverrides] = useState<Record<string, string>>({});
  const [bulkDept, setBulkDept] = useState('');
  const [mode, setMode] = useState<'single' | 'batch'>('single');
  const [cardsPerPage, setCardsPerPage] = useState(8);
  
  // Custom manual entries (not from database)
  const [customEntries, setCustomEntries] = useState<StudentEntry[]>([]);
  const [customName, setCustomName] = useState('');
  const [customDept, setCustomDept] = useState('');
  const [customTitle, setCustomTitle] = useState('طبيب امتياز');
  const [customEndDate, setCustomEndDate] = useState('');
  
  const [isLoading, setIsLoading] = useState(true);

  // Load students
  useEffect(() => {
    const loadStudents = async () => {
      let studentsData: any = null;
      try {
        const res = await fetch('/api/students');
        if (res.ok) {
          studentsData = await res.json();
        }
      } catch {}
      if (!studentsData) {
        try {
          const saved = localStorage.getItem('studentsData');
          if (saved) studentsData = JSON.parse(saved);
        } catch {}
      }
      if (studentsData) {
        const list: StudentEntry[] = [];
        const seen = new Set<string>();
        for (const dept of Object.keys(studentsData)) {
          for (const s of studentsData[dept]) {
            const key = s.name;
            if (!seen.has(key)) {
              seen.add(key);
              list.push({ name: s.name, dept, student: s });
            }
          }
        }
        setAllStudents(list);

        // Check query parameters (e.g. ?student=...&dept=...&trainer=...)
        const studentParam = searchParams.get('student');
        const deptParam = searchParams.get('dept');
        const titleParam = searchParams.get('title');
        const endParam = searchParams.get('endDate');
        const trainerParam = searchParams.get('trainer');

        if (studentParam) {
          const found = list.find(item => item.name === studentParam || item.name.includes(studentParam));
          if (found) {
            setSelectedStudent(found.student);
            setDoctorName(found.student.name);
            const rawDept = deptParam || found.student.department || found.dept || '';
            setDepartment(deptFormalName[rawDept] || rawDept);
            setJobTitle(titleParam || found.student.internshipYear || deptToDefaultTitle[rawDept] || 'طبيب امتياز');
            setEndDate(endParam || found.student.globalEndDate || found.student.endDate || '');
            setIdNumber(found.student.idNumber || '');
            setBloodType(found.student.bloodType || '');
            setTrainerName(trainerParam || resolveTrainer(found.student, rawDept));
          } else {
            setDoctorName(studentParam);
            setDepartment(deptFormalName[deptParam || ''] || deptParam || '');
            setJobTitle(titleParam || 'طبيب امتياز');
            if (endParam) setEndDate(endParam);
            if (trainerParam) setTrainerName(trainerParam);
          }
        }
      }
      setIsLoading(false);
    };
    loadStudents();
  }, [searchParams]);

  const selectStudent = (entry: StudentEntry) => {
    const s = entry.student;
    setSelectedStudent(s);
    setDoctorName(s.name);
    const dept = s.department || entry.dept || '';
    setDepartment(deptFormalName[dept] || dept);
    const defaultTitle = deptToDefaultTitle[dept] || dept || 'متدرب/ة';
    setJobTitle(s.internshipYear || defaultTitle);
    setEndDate(s.globalEndDate || s.endDate || '');
    setIdNumber(s.idNumber || '');
    setBloodType(s.bloodType || '');
    setTrainerName(resolveTrainer(s, dept));
  };

  // === SINGLE CARD PRINT WITH DIRECT EDITABILITY ===
  const handlePrintSingle = () => {
    const cardHtml = buildCardHtml({ name: doctorName, title: jobTitle, dept: department, endDate, idNumber, bloodType, trainerName }, true);
    const pw = window.open('', '_blank');
    if (!pw) return;
    pw.document.write(`<html lang="ar" dir="rtl">
      <head>
        <title>بطاقة - ${doctorName}</title>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;800&display=swap');
          * { margin:0; padding:0; box-sizing:border-box; }
          @page { size: 85mm 54mm; margin: 0; }
          body {
            width: 85mm; height: 54mm;
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            -webkit-print-color-adjust: exact; print-color-adjust: exact;
            font-family: 'Tajawal', sans-serif;
            background: #f8fafc;
            padding: 0;
          }
          .editable-dept:hover, .editable-name:hover, .editable-title:hover, .editable-date:hover {
            outline: 1.5px dashed #059669;
            background: #ecfdf5 !important;
            cursor: text;
          }
          .print-toolbar {
            position: fixed; top: 8px; left: 50%; transform: translateX(-50%);
            background: #0f172a; color: white; padding: 7px 16px; border-radius: 30px;
            display: flex; align-items: center; gap: 12px; z-index: 9999;
            box-shadow: 0 4px 20px rgba(0,0,0,0.35); font-size: 11px; white-space: nowrap;
          }
          .print-toolbar button {
            background: #059669; color: white; border: none; padding: 5px 14px;
            border-radius: 20px; font-family: 'Tajawal'; font-weight: 800; cursor: pointer;
            display: flex; align-items: center; gap: 6px; font-size: 12px;
          }
          @media print {
            body { background: white; }
            .print-toolbar { display: none !important; }
            .editable-dept { background: transparent !important; outline: none !important; }
          }
        </style>
      </head>
      <body>
        <div class="print-toolbar">
          <span>✏️ يمكنك تعديل القسم أو أي حقل بالنقر عليه مباشرة</span>
          <button onclick="window.print()">🖨️ طباعة البطاقة</button>
        </div>
        ${cardHtml}
      </body>
    </html>`);
    pw.document.close();
  };

  // === BATCH: Combined list (DB students + custom entries) ===
  const combinedList = [...allStudents, ...customEntries];

  const toggleBatchStudent = (key: string) => {
    const next = new Set(batchSelected);
    if (next.has(key)) { next.delete(key); } else { next.add(key); }
    setBatchSelected(next);
  };

  const selectAllBatch = () => {
    if (batchSelected.size === combinedList.length) {
      setBatchSelected(new Set());
    } else {
      setBatchSelected(new Set(combinedList.map(s => s.name)));
    }
  };

  // Apply bulk department change to all selected batch trainees
  const applyBulkDepartment = () => {
    if (!bulkDept.trim()) return;
    const newOverrides = { ...deptOverrides };
    batchSelected.forEach(name => {
      newOverrides[name] = bulkDept.trim();
    });
    setDeptOverrides(newOverrides);
  };

  const addCustomEntry = () => {
    if (!customName.trim()) return;
    const entry: StudentEntry = {
      name: customName.trim(),
      dept: customDept || 'غير محدد',
      student: {
        name: customName.trim(),
        department: customDept,
        internshipYear: customTitle || 'طبيب امتياز',
        globalEndDate: customEndDate,
        endDate: customEndDate
      }
    };
    setCustomEntries(prev => [...prev, entry]);
    setBatchSelected(prev => new Set([...prev, customName.trim()]));
    setCustomName(''); setCustomDept(''); setCustomTitle('طبيب امتياز'); setCustomEndDate('');
  };

  const removeCustomEntry = (name: string) => {
    setCustomEntries(prev => prev.filter(e => e.name !== name));
    setBatchSelected(prev => { const n = new Set(prev); n.delete(name); return n; });
  };

  // Layout configs for different cards-per-page options
  const layoutConfig: Record<number, { cols: number; rows: number }> = {
    2: { cols: 1, rows: 2 },
    4: { cols: 2, rows: 2 },
    6: { cols: 2, rows: 3 },
    8: { cols: 2, rows: 4 }
  };

  const handlePrintBatch = () => {
    const selected = combinedList.filter(s => batchSelected.has(s.name));
    if (selected.length === 0) return;

    const cards = selected.map(entry => {
      const s = entry.student;
      const rawDept = deptOverrides[s.name] || s.department || entry.dept || '';
      const finalDept = deptFormalName[rawDept] || rawDept;
      return buildCardHtml({
        name: s.name,
        title: s.internshipYear || deptToDefaultTitle[rawDept] || 'طبيب امتياز',
        dept: finalDept,
        endDate: s.globalEndDate || s.endDate || '',
        idNumber: s.idNumber || '',
        bloodType: s.bloodType || '',
        trainerName: resolveTrainer(s, rawDept)
      }, true);
    });

    const { cols, rows } = layoutConfig[cardsPerPage] || layoutConfig[8];
    const perPage = cols * rows;

    const pages: string[][] = [];
    for (let i = 0; i < cards.length; i += perPage) {
      pages.push(cards.slice(i, i + perPage));
    }

    const pagesHtml = pages.map((pageCards, pi) => {
      while (pageCards.length < perPage) {
        pageCards.push(`<div style="width:85mm;height:54mm;border:1px dashed #ddd;box-sizing:border-box;"></div>`);
      }
      let rowsHtml = '';
      for (let r = 0; r < rows; r++) {
        let cellsHtml = '';
        for (let c = 0; c < cols; c++) {
          cellsHtml += pageCards[r * cols + c];
        }
        rowsHtml += `<div style="display:flex;justify-content:center;gap:0;">${cellsHtml}</div>`;
      }
      return `<div class="print-page" style="width:210mm;height:297mm;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:0;${pi > 0 ? 'page-break-before:always;' : ''}">${rowsHtml}</div>`;
    }).join('');

    const pw = window.open('', '_blank');
    if (!pw) return;
    pw.document.write(`<html lang="ar" dir="rtl"><head><title>طباعة ${selected.length} بطاقة</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;800&display=swap');
        * { margin:0; padding:0; box-sizing:border-box; }
        @page { size:A4; margin:0; }
        body { -webkit-print-color-adjust:exact; print-color-adjust:exact; font-family:'Tajawal',sans-serif; }
        @media print { .print-page { page-break-inside:avoid; } }
      </style></head><body>${pagesHtml}</body></html>`);
    pw.document.close();
    setTimeout(() => { pw.focus(); pw.print(); }, 1000);
  };

  if (isLoading) {
    return (
      <div dir="rtl" style={{ fontFamily: 'Tajawal, sans-serif', padding: '60px', textAlign: 'center' }}>
        <p style={{ fontSize: '1.2rem', color: '#059669', fontWeight: 700 }}>⏳ جاري تحميل بيانات المتدربين والبطاقات...</p>
      </div>
    );
  }

  return (
    <div dir="rtl" style={{ fontFamily: 'Tajawal, sans-serif', background: '#f8f9fa', minHeight: '100vh', padding: '20px' }}>
      {/* Top Bar */}
      <div style={{ maxWidth: '1050px', margin: '0 auto 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '10px' }}>
        <Link href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', color: '#059669', fontWeight: 700, textDecoration: 'none', fontSize: '1rem' }}>
          <i className="fas fa-arrow-right"></i> رجوع للوحة التحكم
        </Link>

        {/* Mode Toggle */}
        <div style={{ display: 'flex', gap: '6px', background: 'white', borderRadius: '12px', padding: '4px', boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
          <button onClick={() => setMode('single')} style={{
            padding: '10px 20px', borderRadius: '10px', border: 'none', cursor: 'pointer', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.9rem',
            background: mode === 'single' ? 'linear-gradient(135deg, #059669, #047857)' : 'transparent',
            color: mode === 'single' ? 'white' : '#666'
          }}>
            <i className="fas fa-id-card" style={{ marginLeft: '6px' }}></i> بطاقة واحدة
          </button>
          <button onClick={() => setMode('batch')} style={{
            padding: '10px 20px', borderRadius: '10px', border: 'none', cursor: 'pointer', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.9rem',
            background: mode === 'batch' ? 'linear-gradient(135deg, #7c3aed, #6d28d9)' : 'transparent',
            color: mode === 'batch' ? 'white' : '#666'
          }}>
            <i className="fas fa-th-large" style={{ marginLeft: '6px' }}></i> طباعة جماعية (A4)
          </button>
        </div>
      </div>

      {/* ══════════ SINGLE MODE ══════════ */}
      {mode === 'single' && (
        <div style={{ maxWidth: '1050px', margin: '0 auto', display: 'grid', gridTemplateColumns: 'minmax(320px, 440px) 1fr', gap: '24px' }}>
          {/* Controls */}
          <div style={{ background: 'white', borderRadius: '16px', padding: '24px', boxShadow: '0 4px 20px rgba(0,0,0,0.08)', height: 'fit-content' }}>
            <h3 style={{ fontSize: '1.2rem', fontWeight: 800, color: '#059669', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              <i className="fas fa-id-badge"></i> إصدار وتعديل البطاقة
            </h3>

            {/* Doctor Search input */}
            <div style={{ marginBottom: '16px' }}>
              <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '6px', color: '#1e293b' }}>
                <i className="fas fa-search" style={{ marginLeft: '6px', color: '#059669' }}></i> ابحث واختر الطبيب أو المتدرب:
              </label>
              <input 
                list="doctors-list"
                placeholder="اكتب اسم المتدرب للبحث التلقائي..." 
                onChange={e => {
                  const entry = allStudents.find(s => s.name === e.target.value);
                  if (entry) selectStudent(entry);
                }}
                style={{ width: '100%', padding: '10px 12px', borderRadius: '10px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.9rem' }}
              />
              <datalist id="doctors-list">
                {allStudents.map((s, i) => (
                  <option key={i} value={s.name}>{s.dept}</option>
                ))}
              </datalist>
            </div>

            {/* Editing Form */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
              {/* الاسم */}
              <div>
                <label style={{ fontSize: '0.8rem', fontWeight: 700, display: 'block', marginBottom: '4px', color: '#334155' }}>الاسم الكامل:</label>
                <input type="text" value={doctorName} onChange={e => setDoctorName(e.target.value)} placeholder="اسم المتدرب..."
                  style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.95rem', fontWeight: 700, color: '#CE1126' }} />
              </div>

              {/* ══════════ القسم (EDITABLE 100%) ══════════ */}
              <div style={{ background: '#f0fdf4', border: '2px solid #86efac', borderRadius: '12px', padding: '14px', position: 'relative' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                  <label style={{ fontSize: '0.88rem', fontWeight: 800, color: '#166534', display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <i className="fas fa-hospital-alt"></i> القسم : (قابل للتعديل 100%)
                  </label>
                  <span style={{ fontSize: '0.72rem', background: '#16a34a', color: 'white', padding: '2px 8px', borderRadius: '12px', fontWeight: 700 }}>
                    ✏️ تعديل مباشر
                  </span>
                </div>

                {/* Direct Text Input */}
                <input 
                  type="text" 
                  value={department} 
                  onChange={e => setDepartment(e.target.value)} 
                  placeholder="اكتب القسم المطلوب هنا..."
                  style={{ 
                    width: '100%', padding: '9px 12px', borderRadius: '8px', 
                    border: '2px solid #16a34a', background: 'white', fontFamily: 'Tajawal', 
                    fontSize: '0.95rem', fontWeight: 700, color: '#0f172a', marginBottom: '8px' 
                  }} 
                />

                {/* Dropdown Selector */}
                <select
                  value={HOSPITAL_DEPARTMENTS.includes(department) ? department : ''}
                  onChange={e => { if (e.target.value) setDepartment(e.target.value); }}
                  style={{ width: '100%', padding: '8px 10px', borderRadius: '8px', border: '1px solid #cbd5e1', background: 'white', fontFamily: 'Tajawal', fontSize: '0.85rem', fontWeight: 600, color: '#334155', marginBottom: '8px' }}
                >
                  <option value="">-- أو اختر من قائمة أقسام المستشفى --</option>
                  <optgroup label="أقسام أطباء الامتياز">
                    <option value="طب الأطفال">طب الأطفال</option>
                    <option value="الجراحة العامة">الجراحة العامة</option>
                    <option value="النسائية والتوليد">النسائية والتوليد</option>
                    <option value="الباطني">الباطني</option>
                    <option value="الطوارئ">الطوارئ</option>
                    <option value="العناية المركزة ICU">العناية المركزة ICU</option>
                    <option value="الحضانة وحديثي الولادة NICU">الحضانة وحديثي الولادة NICU</option>
                    <option value="العمليات الجراحية">العمليات الجراحية</option>
                  </optgroup>
                  <optgroup label="أقسام التمريض">
                    <option value="التمريض العام">التمريض العام</option>
                    <option value="تمريض تدريب">تمريض تدريب</option>
                    <option value="تمريض امتياز">تمريض امتياز</option>
                    <option value="تمريض تطوع">تمريض تطوع</option>
                  </optgroup>
                  <optgroup label="المهن الطبية المساندة">
                    <option value="المختبرات الطبية وبنك الدم">المختبرات الطبية وبنك الدم</option>
                    <option value="الأشعة والتصوير الطبي">الأشعة والتصوير الطبي</option>
                    <option value="العلاج الطبيعي والتأهيل">العلاج الطبيعي والتأهيل</option>
                    <option value="العلاج الوظيفي">العلاج الوظيفي</option>
                    <option value="التغذية السريرية والحميات">التغذية السريرية والحميات</option>
                    <option value="الصحة النفسية والدعم النفسي">الصحة النفسية والدعم النفسي</option>
                    <option value="الخدمة الاجتماعية">الخدمة الاجتماعية</option>
                    <option value="ضباط الإسعاف والطوارئ">ضباط الإسعاف والطوارئ</option>
                  </optgroup>
                  <optgroup label="الإدارة والخدمات والتطوع">
                    <option value="الإدارة الطبية والخدمات">الإدارة الطبية والخدمات</option>
                    <option value="المحاسبة والمالية">المحاسبة والمالية</option>
                    <option value="المطبخ والخدمات">المطبخ والخدمات</option>
                    <option value="طب تطوع">طب تطوع</option>
                    <option value="العمل المجتمعي والتطوع">العمل المجتمعي والتطوع</option>
                  </optgroup>
                </select>

                {/* Quick Pills */}
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                  {['طب الأطفال', 'الجراحة العامة', 'النسائية والتوليد', 'الطوارئ', 'ICU', 'NICU', 'التمريض العام', 'المختبر', 'الأشعة'].map(d => (
                    <button
                      key={d}
                      type="button"
                      onClick={() => setDepartment(d)}
                      style={{
                        fontSize: '0.72rem', padding: '3px 8px', borderRadius: '6px', cursor: 'pointer', fontFamily: 'Tajawal',
                        border: department === d ? '1.5px solid #16a34a' : '1px solid #cbd5e1',
                        background: department === d ? '#16a34a' : 'white',
                        color: department === d ? 'white' : '#334155',
                        fontWeight: department === d ? 800 : 600
                      }}
                    >
                      {d}
                    </button>
                  ))}
                </div>
              </div>

              {/* المسمى */}
              <div>
                <label style={{ fontSize: '0.8rem', fontWeight: 700, display: 'block', marginBottom: '4px', color: '#334155' }}>المسمى الوظيفي:</label>
                <div style={{ display: 'flex', gap: '6px' }}>
                  <input type="text" value={jobTitle} onChange={e => setJobTitle(e.target.value)}
                    style={{ flex: 1, padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.9rem' }} />
                  <select 
                    onChange={e => { if (e.target.value) setJobTitle(e.target.value); }}
                    style={{ padding: '8px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.85rem' }}
                  >
                    <option value="">اقتراحات</option>
                    <option value="طبيب امتياز">طبيب امتياز</option>
                    <option value="ممرض/ة">ممرض/ة</option>
                    <option value="متدرب/ة تمريض">متدرب/ة تمريض</option>
                    <option value="أخصائي/ة">أخصائي/ة</option>
                    <option value="طبيب متطوع">طبيب متطوع</option>
                    <option value="متدرب/ة">متدرب/ة</option>
                  </select>
                </div>
              </div>

              {/* المدرب المشرف */}
              <div>
                <label style={{ fontSize: '0.8rem', fontWeight: 700, display: 'block', marginBottom: '4px', color: '#0369a1' }}>
                  <i className="fas fa-chalkboard-teacher" style={{ marginLeft: '4px' }}></i> المدرب المشرف (يظهر على البطاقة):
                </label>
                <div style={{ display: 'flex', gap: '6px', marginBottom: '6px' }}>
                  <input
                    type="text"
                    value={trainerName}
                    onChange={e => setTrainerName(e.target.value)}
                    placeholder="اسم المدرب أو المشرف السريري..."
                    style={{ flex: 1, padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #38bdf8', fontFamily: 'Tajawal', fontSize: '0.9rem', fontWeight: 700, color: '#0284c7' }}
                  />
                  <select 
                    onChange={e => { if (e.target.value !== undefined) setTrainerName(e.target.value); }}
                    style={{ padding: '8px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.85rem' }}
                  >
                    <option value="">اقتراحات المدربين</option>
                    <option value="ضياء الدين هيموني">ضياء الدين هيموني (أشعة)</option>
                    <option value="مشرف قسم الأشعة">مشرف قسم الأشعة</option>
                    <option value="سلام نسيم محمود ابو عياش">سلام نسيم ابو عياش (تمريض)</option>
                    <option value="ساجده محمد علي عايش">ساجده عايش (تمريض)</option>
                    <option value="ولاء محمد سلمان نعمان سكافي">ولاء سكافي (تمريض)</option>
                    <option value="جبريل سليمان ابراهيم الهرينات">جبريل الهرينات (تمريض)</option>
                    <option value="ضياء عبد الحليم يوسف عواوده">ضياء عواوده (تمريض)</option>
                    <option value="احمد بجالي">أحمد بجالي (تمريض)</option>
                    <option value="مشرف قسم المختبرات الطبية">مشرف قسم المختبرات الطبية</option>
                    <option value="مشرف قسم العلاج الطبيعي">مشرف قسم العلاج الطبيعي</option>
                    <option value="مشرف قسم التغذية السريرية">مشرف قسم التغذية السريرية</option>
                    <option value="مشرف قسم الصيدلة السريرية">مشرف قسم الصيدلة السريرية</option>
                  </select>
                </div>
                {/* Quick Trainer Pills */}
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                  {[
                    { label: 'ضياء الدين هيموني (أشعة)', val: 'ضياء الدين هيموني' },
                    { label: 'سلام ابو عياش', val: 'سلام نسيم محمود ابو عياش' },
                    { label: 'ساجده عايش', val: 'ساجده محمد علي عايش' },
                    { label: 'ولاء سكافي', val: 'ولاء محمد سلمان نعمان سكافي' },
                    { label: 'جبريل الهرينات', val: 'جبريل سليمان ابراهيم الهرينات' },
                    { label: 'ضياء عواوده', val: 'ضياء عبد الحليم يوسف عواوده' },
                    { label: 'أحمد بجالي', val: 'احمد بجالي' },
                    { label: 'إزالة المدرب ✖', val: '' }
                  ].map((t, ti) => (
                    <button
                      key={ti}
                      type="button"
                      onClick={() => setTrainerName(t.val)}
                      style={{
                        fontSize: '0.72rem', padding: '3px 8px', borderRadius: '6px', cursor: 'pointer', fontFamily: 'Tajawal',
                        border: trainerName === t.val ? '1.5px solid #0284c7' : '1px solid #cbd5e1',
                        background: trainerName === t.val ? '#0284c7' : '#f0f9ff',
                        color: trainerName === t.val ? 'white' : '#0369a1',
                        fontWeight: 700
                      }}
                    >
                      {t.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* تاريخ الانتهاء */}
              <div>
                <label style={{ fontSize: '0.8rem', fontWeight: 700, display: 'block', marginBottom: '4px', color: '#334155' }}>تاريخ الإنتهاء :</label>
                <input type="text" value={endDate} onChange={e => setEndDate(e.target.value)} dir="ltr" placeholder="DD/MM/YYYY"
                  style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', textAlign: 'right' }} />
              </div>

              {/* رقم الهوية وفصيلة الدم */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
                <div>
                  <label style={{ fontSize: '0.8rem', fontWeight: 700, display: 'block', marginBottom: '4px', color: '#334155' }}>رقم الهوية (اختياري):</label>
                  <input type="text" value={idNumber} onChange={e => setIdNumber(e.target.value)}
                    style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal' }} />
                </div>
                <div>
                  <label style={{ fontSize: '0.8rem', fontWeight: 700, display: 'block', marginBottom: '4px', color: '#334155' }}>فصيلة الدم:</label>
                  <input type="text" value={bloodType} onChange={e => setBloodType(e.target.value)} placeholder="O+" dir="ltr"
                    style={{ width: '100%', padding: '9px 12px', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', textAlign: 'right' }} />
                </div>
              </div>

              {/* Print Button */}
              <button onClick={handlePrintSingle} disabled={!doctorName.trim()} style={{
                marginTop: '10px', padding: '14px', borderRadius: '12px', border: 'none',
                background: !doctorName.trim() ? '#cbd5e1' : 'linear-gradient(135deg, #059669, #047857)', 
                color: 'white', fontFamily: 'Tajawal', fontWeight: 800, fontSize: '1.05rem', 
                cursor: !doctorName.trim() ? 'not-allowed' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px',
                boxShadow: '0 6px 20px rgba(5,150,105,0.3)'
              }}>
                <i className="fas fa-print"></i> طباعة البطاقة بالقسم المعدل
              </button>
            </div>
          </div>

          {/* Preview Panel */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', padding: '20px' }}>
            <div style={{ background: 'white', borderRadius: '16px', padding: '25px', boxShadow: '0 4px 20px rgba(0,0,0,0.06)', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <div style={{ marginBottom: '16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', borderBottom: '1px solid #f1f5f9', paddingBottom: '10px' }}>
                <span style={{ fontSize: '0.9rem', fontWeight: 800, color: '#334155', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fas fa-eye" style={{ color: '#059669' }}></i> معاينة البطاقة الحية
                </span>
                <span style={{ fontSize: '0.78rem', background: '#ecfdf5', color: '#047857', padding: '3px 10px', borderRadius: '20px', fontWeight: 700 }}>
                  85mm × 54mm
                </span>
              </div>

              {doctorName.trim() ? (
                <>
                  <div style={{ transform: 'scale(1.35)', transformOrigin: 'top center', margin: '20px 0 35px' }}
                    dangerouslySetInnerHTML={{ __html: buildCardHtml({ name: doctorName, title: jobTitle, dept: department || 'طب الأطفال', endDate, idNumber, bloodType, trainerName }, true) }}
                  />
                  <div style={{ width: '100%', background: '#f8fafc', padding: '12px 16px', borderRadius: '10px', border: '1px solid #e2e8f0', marginTop: '20px', fontSize: '0.82rem', color: '#475569' }}>
                    <i className="fas fa-info-circle" style={{ color: '#059669', marginLeft: '6px' }}></i>
                    <b>ملاحظة:</b> القسم المعتمد حالياً على البطاقة هو: <span style={{ color: '#059669', fontWeight: 800 }}>{department || 'لم يتم تحديده بعد'}</span>.
                    يمكنك تغييره في أي لحظة من الخيارات على اليمين قبل الطباعة.
                  </div>
                </>
              ) : (
                <div style={{ textAlign: 'center', color: '#94a3b8', padding: '80px 20px' }}>
                  <i className="fas fa-id-card" style={{ fontSize: '4rem', marginBottom: '16px', opacity: 0.3 }}></i>
                  <p style={{ fontSize: '1rem', fontWeight: 600 }}>اختر طبيباً من القائمة أو اكتب اسماً لمعاينة وطباعة بطاقته</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ══════════ BATCH MODE ══════════ */}
      {mode === 'batch' && (
        <div style={{ maxWidth: '1050px', margin: '0 auto' }}>
          {/* Batch Header */}
          <div style={{ background: 'linear-gradient(135deg, #7c3aed, #6d28d9)', borderRadius: '16px', padding: '25px', marginBottom: '20px', color: 'white' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '15px', marginBottom: '15px' }}>
              <div>
                <h3 style={{ margin: 0, fontSize: '1.3rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <i className="fas fa-th-large"></i> طباعة جماعية للبطاقات ✂️
                </h3>
                <p style={{ margin: '6px 0 0', opacity: 0.9, fontSize: '0.9rem' }}>
                  اختر الأطباء، عدّل القسم إن لزم، ثم اطبع حتى 8 بطاقات في الورقة الواحدة
                </p>
              </div>
              <div style={{ display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
                <span style={{ background: 'rgba(255,255,255,0.2)', padding: '8px 16px', borderRadius: '20px', fontWeight: 700 }}>
                  {batchSelected.size} مختار • {Math.ceil(batchSelected.size / cardsPerPage) || 0} ورقة
                </span>
                <button onClick={selectAllBatch} style={{
                  background: 'rgba(255,255,255,0.2)', border: '2px solid rgba(255,255,255,0.4)', padding: '10px 18px',
                  borderRadius: '10px', color: 'white', cursor: 'pointer', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.9rem'
                }}>
                  {batchSelected.size === combinedList.length ? 'إلغاء الكل' : 'تحديد الكل'}
                </button>
                <button onClick={handlePrintBatch} disabled={batchSelected.size === 0} style={{
                  background: batchSelected.size === 0 ? 'rgba(255,255,255,0.1)' : 'white',
                  color: batchSelected.size === 0 ? 'rgba(255,255,255,0.4)' : '#7c3aed',
                  border: 'none', padding: '12px 24px', borderRadius: '10px', cursor: batchSelected.size === 0 ? 'not-allowed' : 'pointer',
                  fontFamily: 'Tajawal', fontWeight: 800, fontSize: '1rem', display: 'flex', alignItems: 'center', gap: '8px',
                  boxShadow: '0 4px 15px rgba(0,0,0,0.15)'
                }}>
                  <i className="fas fa-print"></i> طباعة {batchSelected.size} بطاقة
                </button>
              </div>
            </div>

            {/* Bulk Department Setter & Cards per page */}
            <div style={{ borderTop: '1px solid rgba(255,255,255,0.2)', paddingTop: '15px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                <span style={{ fontWeight: 700, fontSize: '0.85rem' }}>تعديل القسم للمحددين:</span>
                <select 
                  value={bulkDept} 
                  onChange={e => setBulkDept(e.target.value)}
                  style={{ padding: '6px 12px', borderRadius: '8px', border: 'none', fontFamily: 'Tajawal', fontWeight: 600, fontSize: '0.85rem', color: '#1e293b' }}
                >
                  <option value="">-- اختر قسماً جماعياً --</option>
                  {HOSPITAL_DEPARTMENTS.map((d, i) => (
                    <option key={i} value={d}>{d}</option>
                  ))}
                </select>
                <button 
                  onClick={applyBulkDepartment}
                  disabled={!bulkDept || batchSelected.size === 0}
                  style={{
                    background: 'rgba(255,255,255,0.25)', border: '1px solid white', color: 'white',
                    padding: '6px 14px', borderRadius: '8px', cursor: 'pointer', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.82rem'
                  }}
                >
                  تطبيق القسم على ({batchSelected.size}) بطاقة
                </button>
              </div>

              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <span style={{ fontWeight: 700, fontSize: '0.85rem' }}>بطاقات في الورقة:</span>
                {[2, 4, 6, 8].map(n => (
                  <button key={n} onClick={() => setCardsPerPage(n)} style={{
                    padding: '6px 14px', borderRadius: '20px', border: 'none', cursor: 'pointer',
                    fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.85rem',
                    background: cardsPerPage === n ? 'white' : 'rgba(255,255,255,0.15)',
                    color: cardsPerPage === n ? '#7c3aed' : 'rgba(255,255,255,0.8)'
                  }}>
                    {n}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Add Custom Name Form */}
          <div style={{ background: 'white', borderRadius: '16px', padding: '20px', boxShadow: '0 4px 20px rgba(0,0,0,0.08)', marginBottom: '15px' }}>
            <h4 style={{ marginBottom: '12px', color: '#7c3aed', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '1rem' }}>
              <i className="fas fa-user-plus"></i> إضافة اسم يدوياً (غير موجود بالنظام)
            </h4>
            <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'flex-end' }}>
              <div style={{ flex: '2', minWidth: '150px' }}>
                <label style={{ fontSize: '0.75rem', fontWeight: 600, display: 'block', marginBottom: '3px' }}>الاسم *</label>
                <input type="text" value={customName} onChange={e => setCustomName(e.target.value)} placeholder="اسم الطبيب"
                  style={{ width: '100%', padding: '9px', borderRadius: '8px', border: '1px solid #ddd', fontFamily: 'Tajawal', fontSize: '0.9rem' }} />
              </div>
              <div style={{ flex: '1.5', minWidth: '130px' }}>
                <label style={{ fontSize: '0.75rem', fontWeight: 600, display: 'block', marginBottom: '3px' }}>القسم *</label>
                <input type="text" value={customDept} onChange={e => setCustomDept(e.target.value)} placeholder="القسم (مثال: طب الأطفال)"
                  style={{ width: '100%', padding: '9px', borderRadius: '8px', border: '1px solid #ddd', fontFamily: 'Tajawal', fontSize: '0.9rem' }} />
              </div>
              <div style={{ flex: '1', minWidth: '120px' }}>
                <label style={{ fontSize: '0.75rem', fontWeight: 600, display: 'block', marginBottom: '3px' }}>المسمى</label>
                <input type="text" value={customTitle} onChange={e => setCustomTitle(e.target.value)} placeholder="طبيب امتياز"
                  style={{ width: '100%', padding: '9px', borderRadius: '8px', border: '1px solid #ddd', fontFamily: 'Tajawal', fontSize: '0.9rem' }} />
              </div>
              <div style={{ flex: '1', minWidth: '100px' }}>
                <label style={{ fontSize: '0.75rem', fontWeight: 600, display: 'block', marginBottom: '3px' }}>تاريخ الانتهاء</label>
                <input type="text" value={customEndDate} onChange={e => setCustomEndDate(e.target.value)} placeholder="DD/MM/YYYY" dir="ltr"
                  style={{ width: '100%', padding: '9px', borderRadius: '8px', border: '1px solid #ddd', fontFamily: 'Tajawal', fontSize: '0.9rem', textAlign: 'right' }} />
              </div>
              <button onClick={addCustomEntry} disabled={!customName.trim()} style={{
                padding: '10px 20px', borderRadius: '10px', border: 'none', cursor: customName.trim() ? 'pointer' : 'not-allowed',
                background: customName.trim() ? 'linear-gradient(135deg, #7c3aed, #6d28d9)' : '#e5e7eb',
                color: customName.trim() ? 'white' : '#999', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.9rem',
                display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap'
              }}>
                <i className="fas fa-plus"></i> إضافة
              </button>
            </div>
            {customEntries.length > 0 && (
              <div style={{ marginTop: '10px', display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                {customEntries.map((e, i) => (
                  <span key={i} style={{
                    background: '#f5f3ff', border: '1px solid #c4b5fd', borderRadius: '20px', padding: '5px 12px',
                    fontSize: '0.85rem', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '6px'
                  }}>
                    {e.name} ({e.dept})
                    <button onClick={() => removeCustomEntry(e.name)} style={{
                      background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer', fontSize: '1rem', padding: '0 2px', fontWeight: 800
                    }}>×</button>
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* Student Checkbox Grid */}
          <div style={{ background: 'white', borderRadius: '16px', padding: '20px', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <div style={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', 
              gap: '10px',
              maxHeight: '440px',
              overflowY: 'auto'
            }}>
              {combinedList.map((entry, i) => {
                const isChecked = batchSelected.has(entry.name);
                const isCustom = customEntries.some(c => c.name === entry.name);
                const currentDept = deptOverrides[entry.name] || deptFormalName[entry.dept] || entry.dept;
                return (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    padding: '10px 14px', borderRadius: '10px',
                    background: isChecked ? '#f5f3ff' : '#f8f9fa',
                    border: isChecked ? '2px solid #7c3aed' : '2px solid transparent',
                    transition: 'all 0.2s'
                  }}>
                    <label style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: 1, cursor: 'pointer', minWidth: 0 }}>
                      <input type="checkbox" checked={isChecked} onChange={() => toggleBatchStudent(entry.name)}
                        style={{ width: '18px', height: '18px', accentColor: '#7c3aed' }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: '0.9rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: '6px' }}>
                          {entry.name}
                          {isCustom && <span style={{ background: '#fbbf24', color: '#78350f', fontSize: '0.65rem', padding: '1px 6px', borderRadius: '6px', fontWeight: 700 }}>يدوي</span>}
                        </div>
                        <div style={{ fontSize: '0.75rem', color: deptOverrides[entry.name] ? '#7c3aed' : '#888', fontWeight: deptOverrides[entry.name] ? 700 : 400 }}>
                          القسم: {currentDept}
                        </div>
                      </div>
                    </label>

                    {/* Inline Quick Dept Edit for this student */}
                    <button 
                      onClick={() => {
                        const next = prompt('تعديل قسم المتدرب (' + entry.name + '):', currentDept);
                        if (next && next.trim()) {
                          setDeptOverrides({ ...deptOverrides, [entry.name]: next.trim() });
                        }
                      }}
                      title="تعديل القسم لهذا المتدرب"
                      style={{ background: 'none', border: 'none', color: '#7c3aed', cursor: 'pointer', padding: '4px 6px', fontSize: '0.85rem' }}
                    >
                      <i className="fas fa-edit"></i>
                    </button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default function IdCardPage() {
  return (
    <Suspense fallback={
      <div dir="rtl" style={{ fontFamily: 'Tajawal, sans-serif', padding: '60px 20px', textAlign: 'center', fontSize: '1.2rem', color: '#059669' }}>
        ⏳ جاري تحميل نظام بطاقات المتدربين...
      </div>
    }>
      <IdCardContent />
    </Suspense>
  );
}
