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

/* ─────────────────────────────────────────
   GENDER DETECTION
───────────────────────────────────────── */
function detectGender(name: string): 'M' | 'F' {
  if (!name || !name.trim()) return 'M';
  const firstName = name.trim().split(/\s+/)[0];

  // Male names that look female (end in ة)
  const maleExceptions = new Set([
    'حمزة','أسامة','اسامة','عقبة','حذيفة','قتادة','سلامة','طلحة','عبادة',
    'شحادة','جمعة','عطية','ربيعة','مسيلمة','عرفة','شلالدة','معاوية','زكريا'
  ]);
  if (maleExceptions.has(firstName)) return 'M';

  // Known female names (doesn't end in ة but is female)
  const femaleNames = new Set([
    'زكيه','زكية','سالي','دانا','جهينة','اسرار','أسرار','براءه','براءة','رغد',
    'مرح','خلود','رجاء','جنا','عندليب','هبة','هبه','لارا','سجود','رشا',
    'نسمه','نسمة','تيماء','رناد','ريناد','بيان','إسراء','اسراء','رهف','ولاء',
    'انسام','أنعام','مي','نور','ديانا','رؤى','عروب','مرام','سحر','وئام',
    'شهد','الاء','آلاء','ايمان','إيمان','مريم','حنين','لانا','ميساء','نغم',
    'رولا','ربى','سجا','سجى','عزيزة','أسيل','اسيل','اية','آية','نداء','جوان',
    'أنوار','انوار','فاطمة','فاطمه','أماني','اماني','لين','غرام','شروق',
    'أفراح','افراح','تالا','منال','لجين','ندى','توليب','فايزة','فايزه',
    'شذى','سعاد','لمى','روان','منى','ضحى','مها','رنا','علا','دنيا','سلمى',
    'سارة','ساره','هالة','هاله','ندين','نادين','ميس','عبير','فداء','سوزان',
    'وفاء','نور الهدى','لمار','ميار','تالة','رتاج','يسرى','يسرا','ألاء',
    'أروى','روى','غيداء','سناء','هناء','رنيم','لجن','دلال','نجلاء','نجوى',
    'هيفاء','ريم','ليلى','ليلا','سمر','رلى','غادة','أمل','امل','نهاد'
  ]);
  if (femaleNames.has(firstName)) return 'F';

  // Suffix rules
  if (firstName.endsWith('ة') || firstName.endsWith('ه')) return 'F';
  if (firstName.endsWith('اء')) {
    if (['علاء','بهاء','ضياء'].includes(firstName)) return 'M';
    return 'F';
  }
  if (firstName.endsWith('ى') || firstName.endsWith('يا')) {
    if (['مصطفى','مرتضى','موسى','عيسى','يحيى','يحيا','زكريا','مهدى','مهدي'].includes(firstName)) return 'M';
    return 'F';
  }

  return 'M';
}

/* ─────────────────────────────────────────
   TYPES
───────────────────────────────────────── */
interface Rotation {
  num?: number;
  dept: string;
  start: string;
  end: string;
}

interface Student {
  name: string;
  phone?: string;
  university?: string;
  globalStartDate?: string;
  globalEndDate?: string;
  startDate?: string;
  endDate?: string;
  allRotations?: Rotation[];
  originalDepartment?: string;
  deptLabel?: string;
  department?: string;
  [key: string]: any;
}

interface StudentEntry { name: string; dept: string; student: Student }
interface CertRotation { training: string; section: string; from: string; to: string }

/* ─────────────────────────────────────────
   DEPT / TRANSLATION MAPS (ALL SPECIALTIES)
───────────────────────────────────────── */
const deptFormalName: Record<string, { training: string; section: string }> = {
  // أطباء الامتياز
  'جراحة':   { training: 'الجراحة العامة', section: 'الجراحة العامة' },
  'الجراحة': { training: 'الجراحة العامة', section: 'الجراحة العامة' },
  'نسائية':  { training: 'النسائية والتوليد', section: 'النسائية والتوليد' },
  'النسائية': { training: 'النسائية والتوليد', section: 'النسائية والتوليد' },
  'الاطفال': { training: 'طب الأطفال', section: 'طب الأطفال' },
  'اطفال':   { training: 'طب الأطفال', section: 'طب الأطفال' },
  'أطفال':   { training: 'طب الأطفال', section: 'طب الأطفال' },
  'الأطفال': { training: 'طب الأطفال', section: 'طب الأطفال' },
  'طب تدريب': { training: 'التدريب السريري الطبي', section: 'الأقسام الطبية والجراحية' },
  'طب تطوع': { training: 'التطوع الطبي السريري', section: 'الأقسام الطبية' },
  'الأطباء المتعاقدون': { training: 'العمل الطبي التخصصي', section: 'الأقسام الطبية والجراحية' },
  'الأطباء المتعاقدين مع الجامعات': { training: 'العمل الطبي التخصصي', section: 'الأقسام الطبية والجراحية' },

  // التمريض
  'التمريض': { training: 'التمريض العام', section: 'التمريض العام والأقسام التخصصية' },
  'تمريض': { training: 'التمريض العام', section: 'التمريض العام والأقسام التخصصية' },
  'تمريض تدريب': { training: 'التدريب التمريضي السريري', section: 'قسم التمريض' },
  'تمريض امتياز': { training: 'تمريض الامتياز السريري', section: 'قسم التمريض' },
  'تمريض تطوع': { training: 'التطوع التمريضي', section: 'قسم التمريض' },
  'تدريب تمريض الجامعات': { training: 'التدريب التمريضي الجامعي السريري', section: 'قسم التمريض والأقسام السريرية' },
  'تقديم طلبات لتدريب طلاب التمريض في الجامعات': { training: 'التدريب التمريضي الجامعي السريري', section: 'قسم التمريض' },
  'تدريب طلاب التمريض في الجامعات': { training: 'التدريب التمريضي الجامعي السريري', section: 'قسم التمريض' },

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

  // الإدارة والخدمات والتطوع
  'إدارة': { training: 'الإدارة والخدمات الصحية', section: 'الدائرة الإدارية' },
  'المحاسبة': { training: 'المحاسبة والتدقيق المالي', section: 'الدائرة المالية' },
  'سكرتارية طبية': { training: 'السكرتارية الطبية والسجلات', section: 'قسم السجلات الطبية والسكرتارية' },
  'المطبخ': { training: 'خدمات الإعاشة والتغذية العامة', section: 'قسم الإعاشة' },
  'العمل المجتمعي': { training: 'العمل المجتمعي والتطوع', section: 'دائرة العمل المجتمعي' },
  'المغادرين': { training: 'فترة التدريب الطبي المكتملة', section: 'الأقسام الطبية' }
};

const arToEnMap: Record<string, string> = {
  // Medicine
  'الجراحة العامة': 'General Surgery',
  'الجراحة': 'General Surgery',
  'جراحة عامة': 'General Surgery',
  'النسائية والتوليد': 'Obstetrics & Gynecology',
  'النسائية': 'Obstetrics & Gynecology',
  'نسائية': 'Obstetrics & Gynecology',
  'طب الأطفال': 'Pediatrics',
  'الاطفال': 'Pediatrics',
  'أطفال': 'Pediatrics',
  'اطفال': 'Pediatrics',
  'الأطفال': 'Pediatrics',
  'التدريب السريري الطبي': 'Clinical Medical Training',
  'التطوع الطبي السريري': 'Clinical Medical Volunteering',
  'التطوع الطبي': 'Medical Volunteering',
  'الأطباء المتعاقدون': 'Contracted Physicians',
  'العمل الطبي التخصصي': 'Specialized Medical Service',
  'الأقسام الطبية والجراحية': 'Medical & Surgical Wards',
  'الأقسام الطبية': 'Medical Departments',
  'جراحة تخصصية': 'Specialized Surgery',
  'جراحة أطفال': 'Pediatric Surgery',
  'تخدير': 'Anesthesia',
  'عظام': 'Orthopedic Surgery',

  // Nursing
  'التمريض العام': 'General Nursing',
  'التمريض': 'General Nursing',
  'تمريض': 'General Nursing',
  'التدريب التمريضي السريري': 'Clinical Nursing Training',
  'تمريض تدريب': 'Nursing Training',
  'تمريض امتياز': 'Internship Nursing',
  'تمريض الامتياز السريري': 'Clinical Internship Nursing',
  'التطوع التمريضي': 'Nursing Volunteering',
  'تمريض تطوع': 'Nursing Volunteering',
  'التدريب التمريضي الجامعي السريري': 'University Clinical Nursing Training',
  'تدريب تمريض الجامعات': 'University Nursing Training',
  'قسم التمريض': 'Nursing Department',
  'قسم التمريض والأقسام السريرية': 'Nursing & Clinical Wards',
  'التمريض العام والأقسام التخصصية': 'General Nursing & Specialized Units',

  // Allied Health
  'المختبرات الطبية والتحاليل': 'Medical Laboratory & Analysis',
  'المختبرات الطبية': 'Medical Laboratory',
  'مختبرات طبية': 'Medical Laboratory',
  'المختبر وبنك الدم': 'Laboratory & Blood Bank',
  'الأشعة والتصوير الطبي': 'Medical Imaging & Radiology',
  'الأشعة': 'Radiology & Medical Imaging',
  'أشعة': 'Radiology & Medical Imaging',
  'قسم الأشعة والتصوير التشخيصي': 'Radiology & Diagnostic Imaging',
  'العلاج الطبيعي والتأهيل الطبي': 'Physical Therapy & Medical Rehabilitation',
  'العلاج الطبيعي': 'Physical Therapy',
  'قسم العلاج الطبيعي والتأهيل': 'Physical Therapy & Rehabilitation Department',
  'العلاج الوظيفي والتأهيل': 'Occupational Therapy & Rehabilitation',
  'العلاج الوظيفي': 'Occupational Therapy',
  'قسم العلاج الوظيفي': 'Occupational Therapy Department',
  'التغذية السريرية والحميات': 'Clinical Nutrition & Dietetics',
  'التغذية': 'Clinical Nutrition',
  'تغذية': 'Clinical Nutrition',
  'قسم التغذية السريرية': 'Clinical Nutrition Department',
  'الصحة النفسية والدعم النفسي': 'Mental Health & Psychosocial Support',
  'الصحة النفسية': 'Mental Health',
  'قسم الصحة النفسية': 'Mental Health Department',
  'الخدمة الاجتماعية والعمل المجتمعي': 'Social Work & Community Service',
  'خدمة اجتماعية': 'Social Work',
  'قسم الخدمة الاجتماعية': 'Social Work Department',
  'الإسعاف والطوارئ': 'Emergency Medical Services (EMS)',
  'ضباط الإسعاف': 'Ambulance Officers & Paramedics',
  'دائرة الإسعاف والطوارئ': 'Emergency & EMS Directorate',

  // Administration
  'الإدارة والخدمات الصحية': 'Healthcare Administration & Services',
  'إدارة': 'Administration',
  'الدائرة الإدارية': 'Administrative Directorate',
  'المحاسبة والتدقيق المالي': 'Accounting & Financial Auditing',
  'المحاسبة': 'Accounting & Finance',
  'الدائرة المالية': 'Finance Department',
  'السكرتارية الطبية والسجلات': 'Medical Records & Secretarial Services',
  'سكرتارية طبية': 'Medical Secretarial Services',
  'قسم السجلات الطبية والسكرتارية': 'Medical Records & Archives Department',
  'خدمات الإعاشة والتغذية العامة': 'Catering & Hospitality Services',
  'المطبخ': 'Catering Department',
  'قسم الإعاشة': 'Catering Department',
  'العمل المجتمعي والتطوع': 'Community & Volunteer Work',
  'العمل المجتمعي': 'Community Work',
  'دائرة العمل المجتمعي': 'Community Work Directorate',
  'فترة التدريب الطبي المكتملة': 'Completed Clinical Internship Period'
};

const enToArMap: Record<string, string> = {
  'General Surgery': 'جراحة عامة',
  'Obstetrics & Gynecology': 'نسائية وتوليد',
  'Pediatrics': 'أطفال',
  'Specialized Surgery': 'جراحة تخصصية',
  'Pediatric Surgery': 'جراحة أطفال',
  'Anesthesia': 'تخدير',
  'Orthopedic Surgery': 'عظام',
  'General Nursing': 'تمريض عام',
  'Clinical Nursing Training': 'تدريب تمريضي سريري',
  'University Nursing Training': 'تدريب تمريض جامعات',
  'Medical Laboratory & Analysis': 'مختبرات طبية وتحاليل',
  'Radiology & Medical Imaging': 'أشعة وتصوير طبي',
  'Physical Therapy': 'علاج طبيعي',
  'Occupational Therapy': 'علاج وظيفي',
  'Clinical Nutrition': 'تغذية سريرية',
  'Mental Health': 'صحة نفسية',
  'Social Work': 'خدمة اجتماعية',
  'Emergency Medical Services (EMS)': 'إسعاف وطوارئ',
  'Administration': 'إدارة',
  'Accounting & Finance': 'محاسبة ومالية',
  'Medical Secretarial Services': 'سكرتارية طبية'
};

const translateTerm = (term: string, targetLang: 'ar' | 'en') => {
  if (!term) return term;
  const t = term.trim();
  if (targetLang === 'en') return arToEnMap[t] || t;
  return enToArMap[t] || t;
};

/* ─────────────────────────────────────────
   CERTIFICATE COMPONENT CONTENT
───────────────────────────────────────── */
function CertificateContent() {
  const searchParams = useSearchParams();
  const studentParam = searchParams.get('student');
  const deptParam = searchParams.get('dept');

  const [allStudents, setAllStudents] = useState<StudentEntry[]>([]);
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [showDropdown, setShowDropdown] = useState(false);
  const [certDate, setCertDate] = useState('');
  const [customRotations, setCustomRotations] = useState<CertRotation[]>([]);
  const [doctorName, setDoctorName] = useState('');
  const [gender, setGender] = useState<'M' | 'F'>('M');
  const [titleOption, setTitleOption] = useState<'auto' | 'doctor' | 'nurse' | 'specialist' | 'intern' | 'employee' | 'volunteer' | 'none'>('auto');
  const [isLoading, setIsLoading] = useState(true);
  const [lang, setLang] = useState<'ar' | 'en'>('ar');

  // Layout controls
  const [headerOffset, setHeaderOffset] = useState(65);
  const [fontSizeScale, setFontSizeScale] = useState(1.0);
  const [lineSpacing, setLineSpacing] = useState(2.0);
  const [showBismillah, setShowBismillah] = useState(true);
  const [showRecipient, setShowRecipient] = useState(false);
  const [recipientText, setRecipientText] = useState('السادة المحترمين');
  const [recipientMode, setRecipientMode] = useState<'none'|'niqaba'|'majlis'>('none');
  const [saveStatus, setSaveStatus] = useState<'idle'|'saving'|'saved'|'error'>('idle');
  const [savedCerts, setSavedCerts] = useState<any[]>([]);
  const [certsLoading, setCertsLoading] = useState(false);
  const [dateSizeScale, setDateSizeScale] = useState(1.0);
  const [signSizeScale, setSignSizeScale] = useState(1.0);

  const searchRef = useRef<HTMLDivElement>(null);

  // Derived recipient text based on mode
  const RECIPIENT_NIQABA = 'السادة نقابة الأطباء المحترمين';
  const RECIPIENT_MAJLIS = 'السادة المجلس الطبي الفلسطيني';
  const activeRecipient = recipientMode === 'niqaba' ? RECIPIENT_NIQABA
    : recipientMode === 'majlis' ? RECIPIENT_MAJLIS
    : '';

  // Persist settings
  useEffect(() => {
    const load = (k: string, def: any) => { const v = localStorage.getItem(k); return v !== null ? v : def; };
    setHeaderOffset(Number(load('cert_headerOffset', 65)));
    setFontSizeScale(Number(load('cert_fontSizeScale', 1.0)));
    setLineSpacing(Number(load('cert_lineSpacing', 2.0)));
    setShowBismillah(load('cert_showBismillah', 'true') === 'true');
    setShowRecipient(load('cert_showRecipient', 'false') === 'true');
    const rt = load('cert_recipientText', '');
    if (rt) setRecipientText(rt);
    const sl = load('cert_lang', 'ar');
    if (sl === 'ar' || sl === 'en') setLang(sl as 'ar' | 'en');
    setDateSizeScale(Number(load('cert_dateSizeScale', 1.0)));
    setSignSizeScale(Number(load('cert_signSizeScale', 1.0)));
    const rm = load('cert_recipientMode', 'none');
    if (rm === 'none' || rm === 'niqaba' || rm === 'majlis') setRecipientMode(rm as any);
  }, []);

  useEffect(() => {
    localStorage.setItem('cert_headerOffset', headerOffset.toString());
    localStorage.setItem('cert_fontSizeScale', fontSizeScale.toString());
    localStorage.setItem('cert_lineSpacing', lineSpacing.toString());
    localStorage.setItem('cert_showBismillah', showBismillah.toString());
    localStorage.setItem('cert_showRecipient', showRecipient.toString());
    localStorage.setItem('cert_recipientText', recipientText);
    localStorage.setItem('cert_lang', lang);
    localStorage.setItem('cert_dateSizeScale', dateSizeScale.toString());
    localStorage.setItem('cert_signSizeScale', signSizeScale.toString());
    localStorage.setItem('cert_recipientMode', recipientMode);
  }, [headerOffset, fontSizeScale, lineSpacing, showBismillah, showRecipient, recipientText, lang, dateSizeScale, signSizeScale, recipientMode]);

  // Today's date
  useEffect(() => {
    const today = new Date();
    const dd = String(today.getDate()).padStart(2, '0');
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const yyyy = today.getFullYear();
    setCertDate(`${dd}/${mm}/${yyyy}`);
    loadSavedCerts();
  }, []);

  // Load students from API
  useEffect(() => {
    const load = async () => {
      let data: any = null;
      try {
        const res = await fetch('/api/students');
        if (res.ok) data = await res.json();
      } catch {}
      if (!data) {
        try { const s = localStorage.getItem('studentsData'); if (s) data = JSON.parse(s); } catch {}
      }
      if (data && typeof data === 'object') {
        const list: StudentEntry[] = [];
        const seen = new Set<string>();
        for (const dept of Object.keys(data)) {
          if (!Array.isArray(data[dept])) continue;
          for (const s of data[dept]) {
            if (!s.name || seen.has(s.name + '_' + dept)) continue;
            seen.add(s.name + '_' + dept);
            list.push({ name: s.name, dept, student: { ...s, department: dept } });
          }
        }
        setAllStudents(list);

        // Auto-handle URL query parameters
        if (studentParam) {
          const decoded = decodeURIComponent(studentParam).trim();
          const found = list.find(e => e.name.trim() === decoded || e.name.includes(decoded));
          if (found) {
            selectStudent(found);
          } else {
            setDoctorName(decoded);
            setSearchTerm(decoded);
            setGender(detectGender(decoded));
            if (deptParam) {
              const d = decodeURIComponent(deptParam).trim();
              const formal = deptFormalName[d] || { training: d, section: d };
              setCustomRotations([{
                training: formal.training,
                section: formal.section,
                from: '',
                to: ''
              }]);
            }
          }
        } else if (deptParam) {
          const d = decodeURIComponent(deptParam).trim();
          const formal = deptFormalName[d] || { training: d, section: d };
          setCustomRotations([{
            training: formal.training,
            section: formal.section,
            from: '',
            to: ''
          }]);
        }
      }
      setIsLoading(false);
    };
    load();
  }, [studentParam, deptParam]);

  // Close dropdown on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
        setShowDropdown(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  /* ── filtered list ── */
  const filtered = searchTerm.trim().length > 0
    ? allStudents.filter(s => s.name.includes(searchTerm.trim()) || s.dept.includes(searchTerm.trim()))
    : (deptParam ? allStudents.filter(s => s.dept === deptParam) : allStudents);

  /* ── select a student from dropdown ── */
  const selectStudent = (entry: StudentEntry) => {
    const s = entry.student;
    setSelectedStudent(s);
    setSearchTerm(s.name);
    setDoctorName(s.name);
    setGender(detectGender(s.name));
    setShowDropdown(false);

    if (s.allRotations && Array.isArray(s.allRotations) && s.allRotations.length > 0) {
      setCustomRotations(s.allRotations.map((r: Rotation) => {
        const formal = deptFormalName[r.dept] || { training: r.dept, section: r.dept };
        const training = lang === 'ar'
          ? (formal?.training || r.dept)
          : (arToEnMap[formal?.training || r.dept] || r.dept);
        const section = lang === 'ar'
          ? (formal?.section || r.dept)
          : (arToEnMap[formal?.section || r.dept] || r.dept);
        return { training, section, from: r.start || '', to: r.end || '' };
      }));
    } else {
      const deptKey = entry.dept || s.department || s.originalDepartment || '';
      const formal = deptFormalName[deptKey] || { training: deptKey || 'التدريب السريري', section: deptKey || 'الأقسام السريرية' };
      const training = lang === 'ar'
        ? (formal?.training || deptKey)
        : (arToEnMap[formal?.training || deptKey] || deptKey);
      const section = lang === 'ar'
        ? (formal?.section || deptKey)
        : (arToEnMap[formal?.section || deptKey] || deptKey);
      setCustomRotations([{
        training,
        section,
        from: s.startDate || s.globalStartDate || '',
        to: s.endDate || s.globalEndDate || '',
      }]);
    }
  };

  const addRotation = () =>
    setCustomRotations(prev => [...prev, { training: '', section: '', from: '', to: '' }]);

  const removeRotation = (idx: number) =>
    setCustomRotations(prev => prev.filter((_, i) => i !== idx));

  const updateRotation = (idx: number, field: string, value: string) =>
    setCustomRotations(prev => prev.map((r, i) => i === idx ? { ...r, [field]: value } : r));

  /* ── dynamic title derivation ── */
  const isMale = gender === 'M';
  const isAr = lang === 'ar';

  const computedTitleAr = (() => {
    if (titleOption === 'doctor') return isMale ? 'الدكتور' : 'الدكتورة';
    if (titleOption === 'nurse') return isMale ? 'الممرض' : 'الممرضة';
    if (titleOption === 'specialist') return isMale ? 'الأخصائي' : 'الأخصائية';
    if (titleOption === 'intern') return isMale ? 'المتدرب' : 'المتدربة';
    if (titleOption === 'employee') return isMale ? 'الموظف' : 'الموظفة';
    if (titleOption === 'volunteer') return isMale ? 'المتطوع' : 'المتطوعة';
    if (titleOption === 'none') return '';
    // auto detect from dept
    const deptContext = (
      (selectedStudent?.department || selectedStudent?.originalDepartment || deptParam || '') + ' ' +
      customRotations.map(r => r.training + ' ' + r.section).join(' ')
    ).toLowerCase();
    if (deptContext.includes('تمريض') || deptContext.includes('nursing')) return isMale ? 'الممرض' : 'الممرضة';
    if (deptContext.includes('أشعة') || deptContext.includes('مختبر') || deptContext.includes('طبيعي') || deptContext.includes('وظيفي') || deptContext.includes('تغذية') || deptContext.includes('نفسية') || deptContext.includes('إسعاف')) return isMale ? 'الأخصائي' : 'الأخصائية';
    if (deptContext.includes('إدارة') || deptContext.includes('محاسبة') || deptContext.includes('سكرتارية') || deptContext.includes('مطبخ')) return isMale ? 'الموظف' : 'الموظفة';
    if (deptContext.includes('تطوع')) return isMale ? 'المتطوع' : 'المتطوعة';
    return isMale ? 'الدكتور' : 'الدكتورة';
  })();

  const computedTitleEn = (() => {
    if (titleOption === 'doctor') return 'Dr.';
    if (titleOption === 'nurse') return 'Nurse';
    if (titleOption === 'specialist') return 'Specialist';
    if (titleOption === 'intern') return 'Trainee';
    if (titleOption === 'employee') return 'Mr./Ms.';
    if (titleOption === 'volunteer') return 'Volunteer';
    if (titleOption === 'none') return '';
    // auto
    const deptContext = (
      (selectedStudent?.department || selectedStudent?.originalDepartment || deptParam || '') + ' ' +
      customRotations.map(r => r.training + ' ' + r.section).join(' ')
    ).toLowerCase();
    if (deptContext.includes('تمريض') || deptContext.includes('nursing')) return 'Nurse';
    if (deptContext.includes('أشعة') || deptContext.includes('مختبر') || deptContext.includes('طبيعي') || deptContext.includes('وظيفي') || deptContext.includes('تغذية') || deptContext.includes('نفسية') || deptContext.includes('إسعاف')) return 'Specialist';
    if (deptContext.includes('إدارة') || deptContext.includes('محاسبة') || deptContext.includes('سكرتارية') || deptContext.includes('مطبخ')) return 'Staff Member';
    if (deptContext.includes('تطوع')) return 'Volunteer';
    return 'Dr.';
  })();

  /* ── print ── */
  const handlePrint = () => {
    const rotCount = customRotations.length;
    let baseBismillah = 24, baseBody = 21, baseName = 34, baseRotFont = 19;
    let baseNameMb = 24, baseRotMb = 16, rotPadding = '14px 24px';
    if (rotCount > 2 && rotCount <= 4) {
      baseBismillah = 21; baseBody = 18; baseName = 28; baseRotFont = 16;
      baseNameMb = 18; baseRotMb = 12; rotPadding = '10px 18px';
    } else if (rotCount > 4) {
      baseBismillah = 18; baseBody = 15; baseName = 24; baseRotFont = 14;
      baseNameMb = 14; baseRotMb = 8; rotPadding = '8px 14px';
    }

    const bismillahSize  = `${baseBismillah * fontSizeScale}px`;
    const bodyFontSize   = `${baseBody * fontSizeScale}px`;
    const nameSize       = `${baseName * fontSizeScale}px`;
    const rotFontSize    = `${baseRotFont * fontSizeScale}px`;
    const nameMb         = `${baseNameMb * fontSizeScale}px`;
    const rotBlockMb     = `${baseRotMb * fontSizeScale}px`;
    const bodyLineHeight = lineSpacing.toString();

    const rotationsHtml = customRotations.map(rot => `
      <div class="cert-rotation-block">
        ${isAr
          ? `${isMale ? 'قد عمل' : 'قد عملت'} فترة التدريب (<strong>${rot.training || '...'}</strong>) في قسم (<strong>${rot.section || '...'}</strong>) ابتداء من تاريخ`
          : `Has completed a training period (<strong>${rot.training || '...'}</strong>) in the department of (<strong>${rot.section || '...'}</strong>) starting from`}
        <br/>
        <strong>${rot.from || '../../....'}</strong> ${isAr ? 'حتى' : 'to'} <strong>${rot.to || '../../....'}</strong>
      </div>
    `).join('');

    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = 'none';
    document.body.appendChild(iframe);

    const recipientLine = activeRecipient
      ? `<div style="text-align:center;margin-bottom:${rotBlockMb};"><span class="cert-recipient">${activeRecipient}</span></div>`
      : (showRecipient && recipientText
          ? `<p style="margin-bottom:${rotBlockMb};"><span style="font-weight:800;border-bottom:3px solid #1a1a1a;display:inline-block;padding-bottom:6px;">${recipientText}</span></p>`
          : '');

    const certHTML = `<!DOCTYPE html>
<html lang="${isAr ? 'ar' : 'en'}" dir="${isAr ? 'rtl' : 'ltr'}">
<head>
  <meta charset="UTF-8"/>
  <title>شهادة خبرة - ${doctorName}</title>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700;800&display=swap" rel="stylesheet"/>
  <style>
    @page { size: A4 portrait; margin: 0 !important; }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    html, body {
      width: 210mm; min-height: 297mm; background: white;
      font-family: 'Tajawal','Arial',sans-serif;
      direction: ${isAr ? 'rtl' : 'ltr'};
      color: #1a1a1a; line-height: ${bodyLineHeight};
      -webkit-print-color-adjust: exact; print-color-adjust: exact;
    }
    .page-wrap { width: 210mm; min-height: 297mm; padding: ${headerOffset}mm 20mm 20mm 20mm; }
    .cert-date-line { text-align: ${isAr ? 'left' : 'right'}; font-size: ${15 * fontSizeScale * dateSizeScale}px; font-weight: 600; margin-bottom: ${nameMb}; }
    .cert-content { text-align: center; }
    .cert-bismillah { font-size: ${bismillahSize}; font-weight: 700; margin-bottom: ${nameMb}; text-align: center; }
    .cert-recipient { font-size: ${baseBismillah * fontSizeScale * 0.85}px; font-weight: 800; margin-bottom: ${nameMb}; border-bottom: 2px solid #1a1a1a; display: inline-block; padding-bottom: 6px; }
    .cert-body { font-size: ${bodyFontSize}; line-height: ${bodyLineHeight}; text-align: center; }
    .cert-body strong { color: #8B1A2B; }
    .cert-doctor-name { font-size: ${nameSize}; font-weight: 800; color: #8B1A2B; margin: ${nameMb} 0; }
    .cert-rotation-block { margin: ${rotBlockMb} auto; padding: ${rotPadding}; background: #faf5f5; border-radius: 4px; max-width: 92%; text-align: center; font-size: ${rotFontSize}; }
    .cert-closing { margin-top: ${rotBlockMb}; font-size: ${bodyFontSize}; }
    .cert-signature { margin-top: 40px; text-align: ${isAr ? 'left' : 'right'}; }
    .cert-sig-role { font-size: ${20 * fontSizeScale * signSizeScale}px; color: #555; font-weight: 800; margin-bottom: 4px; }
    .cert-sig-name { font-size: ${20 * fontSizeScale * signSizeScale}px; font-weight: 800; color: #8B1A2B; }
  </style>
</head>
<body>
  <div class="page-wrap">
    <div class="cert-date-line">${isAr ? 'التاريخ :-' : 'Date:'} ${certDate}</div>
    <div class="cert-content">
      ${showBismillah ? `<div class="cert-bismillah">${isAr ? 'بسم الله الرحمن الرحيم' : 'In the name of Allah, the Most Gracious, the Most Merciful'}</div>` : ''}
      ${recipientLine}
      <div class="cert-body">
        <p style="margin-bottom:${rotBlockMb};">${isAr ? 'تشهد إدارة مستشفى الهلال الأحمر التخصصي /الخليل بأن' : 'The administration of PRCS Specialized Hospital / Hebron certifies that'}</p>
        <p class="cert-doctor-name">${isAr ? (computedTitleAr ? `${computedTitleAr} / ` : '') : (computedTitleEn ? `${computedTitleEn} ` : '')}${doctorName || '_______________'}</p>
        ${rotationsHtml}
        <p class="cert-closing">${isAr ? `وقد ${isMale ? 'كان' : 'كانت'} خلال فترة ${isMale ? 'عمله ملتزم وحسن' : 'عملها ملتزمة وحسنة'} السيرة والسلوك .` : `During this period, ${isMale ? 'he' : 'she'} demonstrated excellent commitment and professional conduct.`}</p>
        <p style="margin-top:${rotBlockMb};">${isAr ? 'هذا مع الاحترام .' : 'Sincerely,'}</p>
      </div>
    </div>
    <div class="cert-signature">
      <p class="cert-sig-role">${isAr ? 'المدير الطبي' : 'Medical Director'}</p>
      <p class="cert-sig-name">${isAr ? 'د. خالد السراحنه' : 'Dr. Khaled Al-Sarahneh'}</p>
    </div>
  </div>
</body>
</html>`;

    const iframeDoc = iframe.contentDocument || (iframe.contentWindow as any)?.document;
    if (!iframeDoc) { iframe.remove(); return; }

    iframeDoc.open();
    iframeDoc.write(certHTML);
    iframeDoc.close();

    setTimeout(() => {
      iframe.contentWindow?.focus();
      iframe.contentWindow?.print();
      setTimeout(() => { iframe.remove(); }, 2000);
    }, 600);
  };

  /* ── save to Supabase / D1 ── */
  const handleSave = async () => {
    if (!doctorName.trim()) return;
    setSaveStatus('saving');
    try {
      const res = await fetch('/api/certificates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          doctorName,
          gender,
          certDate,
          lang,
          rotations: customRotations,
          recipient: activeRecipient || recipientText || '',
        }),
      });
      const json = await res.json();
      if (json.success) {
        setSaveStatus('saved');
        setTimeout(() => setSaveStatus('idle'), 3000);
        loadSavedCerts();
      } else {
        setSaveStatus('error');
        setTimeout(() => setSaveStatus('idle'), 3000);
      }
    } catch {
      setSaveStatus('error');
      setTimeout(() => setSaveStatus('idle'), 3000);
    }
  };

  /* ── load saved certificates ── */
  const loadSavedCerts = async () => {
    setCertsLoading(true);
    try {
      const res = await fetch('/api/certificates');
      const json = await res.json();
      setSavedCerts(json.certificates || []);
    } catch {}
    setCertsLoading(false);
  };

  /* ── delete saved certificate ── */
  const handleDeleteCert = async (id: string) => {
    if (!confirm('تأكيد حذف هذه الشهادة؟')) return;
    try {
      await fetch('/api/certificates', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id }),
      });
      loadSavedCerts();
    } catch {}
  };

  /* ── load a saved cert into the form ── */
  const handleLoadCert = (cert: any) => {
    setDoctorName(cert.doctor_name || '');
    setSearchTerm(cert.doctor_name || '');
    setGender(cert.gender || 'M');
    setCertDate(cert.cert_date || '');
    setLang(cert.lang || 'ar');
    setCustomRotations(cert.rotations || []);
    if (cert.recipient) setRecipientText(cert.recipient);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

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

  const hasContent = doctorName.trim().length > 0;

  return (
    <div dir="rtl" style={{ fontFamily: 'Tajawal, sans-serif', background: '#f8f9fa', minHeight: '100vh', padding: '20px' }}>

      {/* Top Navigation */}
      <div style={{ maxWidth: '1050px', margin: '0 auto 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px' }}>
        <Link href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', color: '#8B1A2B', fontWeight: 800, textDecoration: 'none', fontSize: '1rem', background: 'white', padding: '10px 18px', borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
          ← رجوع للوحة التحكم الرئيسية
        </Link>
        {deptParam && (
          <div style={{ background: '#e0e7ff', color: '#4338ca', padding: '8px 16px', borderRadius: '12px', fontWeight: 800, fontSize: '0.9rem', display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>🏥 تصفية تابعة لقسم: <strong>{deptParam}</strong></span>
            <Link href="/certificate" style={{ color: '#dc2626', textDecoration: 'none', fontSize: '0.8rem', marginRight: '6px' }}>
              إلغاء التصفية ✕
            </Link>
          </div>
        )}
      </div>

      <div style={{ maxWidth: '1050px', margin: '0 auto', display: 'grid', gridTemplateColumns: '340px 1fr', gap: '22px', alignItems: 'start' }}>

        {/* ── LEFT PANEL ── */}
        <div style={{ background: 'white', borderRadius: '18px', padding: '22px', boxShadow: '0 4px 20px rgba(0,0,0,0.08)', position: 'sticky', top: '20px' }}>
          <h3 style={{ fontSize: '1.15rem', fontWeight: 900, color: '#8B1A2B', marginBottom: '18px', display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>📜</span>
            توليد شهادة خبرة لجميع الأقسام
          </h3>

          {/* ── SEARCH DROPDOWN ── */}
          <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '6px', color: '#334155' }}>
            🔍 ابحث عن المتدرب/الطبيب ({allStudents.length} مسجل):
          </label>
          <div ref={searchRef} style={{ position: 'relative', marginBottom: '16px' }}>
            <input
              type="text"
              placeholder="اكتب اسم المتدرب أو الطبيب..."
              value={searchTerm}
              onChange={e => {
                const val = e.target.value;
                setSearchTerm(val);
                setDoctorName(val);
                setGender(detectGender(val));
                setShowDropdown(true);
                if (!val.trim()) {
                  setSelectedStudent(null);
                  setCustomRotations([]);
                }
              }}
              onFocus={() => setShowDropdown(true)}
              style={{
                width: '100%', padding: '11px 14px', borderRadius: '10px',
                border: '2px solid #e0e0e0', fontFamily: 'Tajawal', fontSize: '0.95rem',
                outline: 'none', transition: 'border 0.2s',
              }}
              onMouseEnter={e => (e.currentTarget.style.borderColor = '#8B1A2B')}
              onMouseLeave={e => (e.currentTarget.style.borderColor = selectedStudent ? '#8B1A2B' : '#e0e0e0')}
            />
            {/* Dropdown */}
            {showDropdown && filtered.length > 0 && (
              <div style={{
                position: 'absolute', top: '100%', right: 0, left: 0, zIndex: 999,
                background: 'white', borderRadius: '10px', border: '1px solid #e0e0e0',
                boxShadow: '0 8px 30px rgba(0,0,0,0.15)', maxHeight: '280px', overflowY: 'auto',
                marginTop: '4px',
              }}>
                {filtered.slice(0, 50).map((entry, i) => (
                  <div
                    key={i}
                    onMouseDown={() => selectStudent(entry)}
                    style={{
                      padding: '10px 14px', cursor: 'pointer', display: 'flex',
                      justifyContent: 'space-between', alignItems: 'center',
                      borderBottom: i < filtered.length - 1 ? '1px solid #f5f5f5' : 'none',
                      transition: 'background 0.15s',
                    }}
                    onMouseEnter={e => (e.currentTarget.style.background = '#fdeced')}
                    onMouseLeave={e => (e.currentTarget.style.background = 'white')}
                  >
                    <span style={{ fontWeight: 700, fontSize: '0.9rem', color: '#1e293b' }}>{entry.name}</span>
                    <span style={{ fontSize: '0.75rem', color: '#8B1A2B', background: '#fdeced', padding: '2px 8px', borderRadius: '20px', fontWeight: 800 }}>
                      {entry.dept}
                    </span>
                  </div>
                ))}
                {filtered.length > 50 && (
                  <div style={{ padding: '8px 14px', fontSize: '0.8rem', color: '#888', textAlign: 'center' }}>
                    + {filtered.length - 50} آخرين... تابع الكتابة للتحديد
                  </div>
                )}
              </div>
            )}
            {showDropdown && searchTerm.trim().length > 0 && filtered.length === 0 && (
              <div style={{
                position: 'absolute', top: '100%', right: 0, left: 0, zIndex: 999,
                background: 'white', borderRadius: '10px', border: '1px solid #e0e0e0',
                boxShadow: '0 4px 15px rgba(0,0,0,0.1)', padding: '12px 14px',
                fontSize: '0.85rem', color: '#888', marginTop: '4px', textAlign: 'center',
              }}>
                لا توجد نتائج مطابقة — سيتم إصدار الشهادة بالاسم المكتوب
              </div>
            )}
          </div>

          {/* ── RECIPIENT TOGGLE — always visible ── */}
          <div style={{ marginBottom: '18px', background: '#fdf8f8', borderRadius: '12px', padding: '14px', border: '2px solid #f0dede' }}>
            <label style={{ fontSize: '0.85rem', fontWeight: 800, display: 'block', marginBottom: '10px', color: '#8B1A2B' }}>
              📨 الموجه إليه (يظهر بعد البسملة):
            </label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '7px' }}>
              {([
                { mode: 'none' as const,   label: '❌ بدون توجيه مخصص' },
                { mode: 'niqaba' as const, label: 'السادة نقابة الأطباء المحترمين' },
                { mode: 'majlis' as const, label: 'السادة المجلس الطبي الفلسطيني' },
              ]).map(({ mode, label }) => (
                <button
                  key={mode}
                  onClick={() => setRecipientMode(mode)}
                  style={{
                    padding: '9px 12px', borderRadius: '9px', border: '2px solid',
                    borderColor: recipientMode === mode ? '#8B1A2B' : '#ddd',
                    background: recipientMode === mode ? '#8B1A2B' : 'white',
                    color: recipientMode === mode ? 'white' : '#444',
                    fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.82rem',
                    cursor: 'pointer', textAlign: 'right', transition: 'all 0.18s',
                  }}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>

          {/* ── FORM (shown once any name is typed or selected) ── */}
          {hasContent && (
            <>
              {/* Doctor / Trainee Name */}
              <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '4px' }}>
                ✏️ {isAr ? 'الاسم بالشهادة:' : 'Name:'}
              </label>
              <input
                type="text"
                value={doctorName}
                onChange={e => { setDoctorName(e.target.value); setGender(detectGender(e.target.value)); }}
                style={{ width: '100%', padding: '10px', borderRadius: '10px', border: '1px solid #ddd', fontFamily: 'Tajawal', fontSize: '0.9rem', marginBottom: '14px' }}
              />

              {/* Title / Role Option */}
              <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '6px' }}>
                🏷️ اللقب المهني في الشهادة:
              </label>
              <select
                value={titleOption}
                onChange={e => setTitleOption(e.target.value as any)}
                style={{ width: '100%', padding: '9px', borderRadius: '10px', border: '1.5px solid #cbd5e1', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.88rem', marginBottom: '14px', background: 'white' }}
              >
                <option value="auto">✨ تلقائي حسب القسم (دكتور / ممرض / أخصائي / موظف)</option>
                <option value="doctor">طبيب / طبيبة (الدكتور / الدكتورة)</option>
                <option value="nurse">تمريض (الممرض / الممرضة)</option>
                <option value="specialist">أخصائي / أخصائية (مهن مساندة)</option>
                <option value="intern">متدرب / متدربة</option>
                <option value="employee">موظف / موظفة (إدارة وخدمات)</option>
                <option value="volunteer">متطوع / متطوعة</option>
                <option value="none">بدون أي لقب (الاسم مباشرة)</option>
              </select>

              {/* Gender */}
              <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '6px' }}>
                👤 صيغة المخاطبة:
                <span style={{ marginRight: '6px', color: '#8B1A2B', fontWeight: 800 }}>
                  {gender === 'M' ? `← مذكر (${computedTitleAr || 'هو'})` : `← مؤنث (${computedTitleAr || 'هي'})`}
                </span>
              </label>
              <div style={{ display: 'flex', gap: '10px', marginBottom: '14px' }}>
                {(['M', 'F'] as const).map(g => (
                  <label key={g} style={{
                    flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px',
                    background: gender === g ? (g === 'M' ? '#e8f4fd' : '#fdeced') : '#f5f5f5',
                    border: `2px solid ${gender === g ? (g === 'M' ? '#1e3a8a' : '#8B1A2B') : '#e0e0e0'}`,
                    padding: '8px', borderRadius: '8px', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem',
                    transition: 'all 0.2s',
                  }}>
                    <input type="radio" value={g} checked={gender === g} onChange={() => setGender(g)} style={{ accentColor: g === 'M' ? '#1e3a8a' : '#8B1A2B' }} />
                    {g === 'M' ? 'مذكر 👨‍⚕️' : 'مؤنث 👩‍⚕️'}
                  </label>
                ))}
              </div>

              {/* Date */}
              <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '4px' }}>📅 تاريخ إصدار الشهادة:</label>
              <input
                type="text"
                value={certDate}
                onChange={e => setCertDate(e.target.value)}
                style={{ width: '100%', padding: '10px', borderRadius: '10px', border: '1px solid #ddd', fontFamily: 'Tajawal', marginBottom: '14px' }}
              />

              {/* Language */}
              <label style={{ fontSize: '0.85rem', fontWeight: 700, display: 'block', marginBottom: '6px' }}>🌐 لغة الشهادة:</label>
              <div style={{ display: 'flex', gap: '8px', marginBottom: '14px' }}>
                {(['ar', 'en'] as const).map(l => (
                  <button key={l} onClick={() => {
                    setLang(l);
                    setCustomRotations(prev => prev.map(r => ({
                      ...r,
                      training: translateTerm(r.training, l),
                      section: translateTerm(r.section, l),
                    })));
                  }} style={{
                    flex: 1, padding: '9px', borderRadius: '8px', fontWeight: 700, cursor: 'pointer',
                    fontFamily: 'Tajawal', fontSize: '0.85rem',
                    border: `2px solid ${lang === l ? '#8B1A2B' : '#ddd'}`,
                    background: lang === l ? '#fdeced' : 'white', color: lang === l ? '#8B1A2B' : '#555',
                    transition: 'all 0.2s',
                  }}>
                    {l === 'ar' ? 'العربية 🇵🇸' : 'English 🇬🇧'}
                  </button>
                ))}
              </div>

              {/* Letterhead offset */}
              <label style={{ fontSize: '0.82rem', fontWeight: 700, display: 'block', marginBottom: '4px' }}>
                📏 ارتفاع رأسية الورقة: <strong style={{ color: '#8B1A2B' }}>{headerOffset}mm</strong>
              </label>
              <input type="range" min={0} max={220} step={5} value={headerOffset}
                onChange={e => setHeaderOffset(Number(e.target.value))}
                style={{ width: '100%', marginBottom: '14px', accentColor: '#8B1A2B' }} />

              {/* Typography Details */}
              <details style={{ background: '#f8f9fa', borderRadius: '10px', padding: '12px', marginBottom: '14px', border: '1px solid #e9ecef' }}>
                <summary style={{ fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer', color: '#495057' }}>🖌️ إعدادات الخط والتخطيط</summary>
                <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
                  {[
                    { label: 'حجم الخط العام', val: fontSizeScale, set: setFontSizeScale, color: '#8B1A2B' },
                    { label: 'حجم خط التاريخ', val: dateSizeScale, set: setDateSizeScale, color: '#4f46e5' },
                    { label: 'حجم توقيع الإدارة', val: signSizeScale, set: setSignSizeScale, color: '#059669' },
                  ].map(({ label, val, set, color }) => (
                    <div key={label}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                        <label style={{ fontSize: '0.78rem', fontWeight: 600 }}>{label}:</label>
                        <strong style={{ color, fontSize: '0.78rem' }}>{Math.round(val * 100)}%</strong>
                      </div>
                      <input type="range" min={0.5} max={3.0} step={0.05} value={val}
                        onChange={e => set(Number(e.target.value))}
                        style={{ width: '100%', accentColor: color }} />
                    </div>
                  ))}
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                      <label style={{ fontSize: '0.78rem', fontWeight: 600 }}>التباعد بين الأسطر:</label>
                      <strong style={{ color: '#1e3a8a', fontSize: '0.78rem' }}>{lineSpacing.toFixed(1)}</strong>
                    </div>
                    <input type="range" min={1.2} max={3.0} step={0.1} value={lineSpacing}
                      onChange={e => setLineSpacing(Number(e.target.value))}
                      style={{ width: '100%', accentColor: '#1e3a8a' }} />
                  </div>
                  <label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.82rem', cursor: 'pointer' }}>
                    <input type="checkbox" checked={showBismillah} onChange={e => setShowBismillah(e.target.checked)} style={{ accentColor: '#8B1A2B', width: '15px', height: '15px' }} />
                    إظهار (بسم الله الرحمن الرحيم)
                  </label>
                  <label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.82rem', cursor: 'pointer' }}>
                    <input type="checkbox" checked={showRecipient} onChange={e => setShowRecipient(e.target.checked)} style={{ accentColor: '#8B1A2B', width: '15px', height: '15px' }} />
                    إظهار الموجه إليه
                  </label>
                  {showRecipient && (
                    <div>
                      <input type="text" value={recipientText} onChange={e => setRecipientText(e.target.value)}
                        placeholder="السادة المحترمين..."
                        style={{ width: '100%', padding: '7px', borderRadius: '6px', border: '1px solid #ddd', fontFamily: 'Tajawal', fontSize: '0.82rem' }} />
                      <div style={{ display: 'flex', gap: '5px', flexWrap: 'wrap', marginTop: '5px' }}>
                        {isAr ? (
                          <>
                            <button onClick={() => setRecipientText('السادة المجلس الطبي الفلسطيني المحترمين')} style={chipStyle}>للمجلس الطبي</button>
                            <button onClick={() => setRecipientText('السادة نقابة الأطباء المحترمين')} style={chipStyle}>لنقابة الأطباء</button>
                            <button onClick={() => setRecipientText('السادة نقابة التمريض والقبالة المحترمين')} style={chipStyle}>لنقابة التمريض</button>
                            <button onClick={() => setRecipientText('السادة وزارة الصحة الفلسطينية المحترمين')} style={chipStyle}>لوزارة الصحة</button>
                          </>
                        ) : (
                          <>
                            <button onClick={() => setRecipientText('Palestine Medical Council')} style={chipStyle}>Medical Council</button>
                            <button onClick={() => setRecipientText('Palestinian Nursing Association')} style={chipStyle}>Nursing Association</button>
                            <button onClick={() => setRecipientText('Palestinian Ministry of Health')} style={chipStyle}>Ministry of Health</button>
                          </>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </details>

              {/* Rotations Editor */}
              <div style={{ marginBottom: '14px' }}>
                <label style={{ fontSize: '0.85rem', fontWeight: 800, display: 'block', marginBottom: '8px', color: '#1e293b' }}>
                  📋 الأقسام والدورات التدريبية المشمولة:
                </label>

                {/* ── Preset dept quick-add buttons ── */}
                <div style={{ background: '#f0f7ff', borderRadius: '12px', padding: '12px', marginBottom: '12px', border: '1px solid #d0e4f8' }}>
                  <div style={{ fontSize: '0.78rem', fontWeight: 800, color: '#1e3a8a', marginBottom: '8px' }}>⚡ إضافة سريعة للأقسام والتخصصات:</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>
                    {[
                      { ar: 'الجراحة العامة',     en: 'General Surgery',         emoji: '🏥' },
                      { ar: 'النسائية والتوليد',  en: 'Obstetrics & Gynecology', emoji: '👩‍⚕️' },
                      { ar: 'طب الأطفال',        en: 'Pediatrics',              emoji: '👶' },
                      { ar: 'الأطباء المتعاقدون', en: 'Contracted Physicians',   emoji: '🩺' },
                      { ar: 'التمريض العام',      en: 'General Nursing',         emoji: '💉' },
                      { ar: 'تدريب تمريض الجامعات', en: 'University Nursing Training', emoji: '🎓' },
                      { ar: 'العلاج الطبيعي',     en: 'Physical Therapy',        emoji: '🏃' },
                      { ar: 'المختبرات الطبية',   en: 'Medical Laboratory',      emoji: '🧪' },
                      { ar: 'الأشعة والتصوير الطبي', en: 'Medical Imaging & Radiology', emoji: '☢️' },
                      { ar: 'الإدارة والخدمات',   en: 'Administration',          emoji: '💼' },
                    ].map(dept => (
                      <button
                        key={dept.ar}
                        onClick={() => setCustomRotations(prev => [...prev, {
                          training: lang === 'ar' ? dept.ar : dept.en,
                          section:  lang === 'ar' ? dept.ar : dept.en,
                          from: '', to: '',
                        }])}
                        style={{
                          padding: '7px 6px', borderRadius: '8px', border: '1.5px solid #bfdbfe',
                          background: 'white', color: '#1e3a8a', fontFamily: 'Tajawal',
                          fontWeight: 700, fontSize: '0.76rem', cursor: 'pointer',
                          transition: 'all 0.15s', textAlign: 'center',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',
                        }}
                        onMouseEnter={e => { e.currentTarget.style.background = '#1e3a8a'; e.currentTarget.style.color = 'white'; }}
                        onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = '#1e3a8a'; }}
                      >
                        {dept.emoji} {lang === 'ar' ? dept.ar : dept.en}
                      </button>
                    ))}
                  </div>
                  <button
                    onClick={addRotation}
                    style={{
                      marginTop: '8px', width: '100%', padding: '7px', borderRadius: '8px',
                      border: '1.5px dashed #93c5fd', background: 'white', color: '#2563eb',
                      fontFamily: 'Tajawal', fontWeight: 800, fontSize: '0.8rem', cursor: 'pointer',
                    }}
                  >
                    + إضافة دورة/قسم مخصص يدوياً
                  </button>
                </div>

                {customRotations.map((rot, idx) => (
                  <div key={idx} style={{ background: '#f8fafc', borderRadius: '10px', padding: '12px', marginBottom: '10px', border: '1px solid #e2e8f0', position: 'relative' }}>
                    <button
                      onClick={() => removeRotation(idx)}
                      style={{
                        position: 'absolute', top: '8px', left: '8px',
                        background: '#fee2e2', border: 'none', borderRadius: '50%',
                        width: '24px', height: '24px', cursor: 'pointer',
                        color: '#dc2626', fontSize: '0.8rem', display: 'flex',
                        alignItems: 'center', justifyContent: 'center',
                      }}
                      title="حذف هذه الدورة"
                    >
                      ✕
                    </button>
                    <div style={{ fontSize: '0.75rem', fontWeight: 800, color: '#475569', marginBottom: '8px' }}>
                      الدورة / القسم #{idx + 1}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>
                      <div>
                        <small style={{ fontWeight: 700, display: 'block', marginBottom: '2px', fontSize: '0.75rem' }}>{isAr ? 'فترة التدريب:' : 'Training:'}</small>
                        <input type="text" value={rot.training} onChange={e => updateRotation(idx, 'training', e.target.value)}
                          style={{ width: '100%', padding: '6px 8px', borderRadius: '6px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.82rem' }} />
                      </div>
                      <div>
                        <small style={{ fontWeight: 700, display: 'block', marginBottom: '2px', fontSize: '0.75rem' }}>{isAr ? 'في قسم:' : 'Section:'}</small>
                        <input type="text" value={rot.section} onChange={e => updateRotation(idx, 'section', e.target.value)}
                          style={{ width: '100%', padding: '6px 8px', borderRadius: '6px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.82rem' }} />
                      </div>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
                      <div>
                        <small style={{ fontWeight: 700, display: 'block', marginBottom: '2px', fontSize: '0.75rem' }}>{isAr ? 'من تاريخ:' : 'From:'}</small>
                        <input type="text" value={rot.from} onChange={e => updateRotation(idx, 'from', e.target.value)}
                          placeholder="dd/mm/yyyy"
                          style={{ width: '100%', padding: '6px 8px', borderRadius: '6px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.82rem' }} />
                      </div>
                      <div>
                        <small style={{ fontWeight: 700, display: 'block', marginBottom: '2px', fontSize: '0.75rem' }}>{isAr ? 'حتى تاريخ:' : 'To:'}</small>
                        <input type="text" value={rot.to} onChange={e => updateRotation(idx, 'to', e.target.value)}
                          placeholder="dd/mm/yyyy"
                          style={{ width: '100%', padding: '6px 8px', borderRadius: '6px', border: '1px solid #cbd5e1', fontFamily: 'Tajawal', fontSize: '0.82rem' }} />
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Print Button */}
              <button onClick={handlePrint} style={{
                width: '100%', padding: '14px', borderRadius: '12px', border: 'none',
                background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', color: 'white',
                fontFamily: 'Tajawal', fontWeight: 800, fontSize: '1.05rem', cursor: 'pointer',
                boxShadow: '0 6px 20px rgba(139,26,43,0.35)', letterSpacing: '0.5px',
                marginBottom: '10px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px'
              }}>
                <span>🖨️</span>
                طباعة الشهادة الرسمية
              </button>

              {/* Save Button */}
              <button
                onClick={handleSave}
                disabled={saveStatus === 'saving' || !doctorName.trim()}
                style={{
                  width: '100%', padding: '14px', borderRadius: '12px', border: 'none',
                  background: saveStatus === 'saved'
                    ? 'linear-gradient(135deg, #16a34a, #15803d)'
                    : saveStatus === 'error'
                    ? 'linear-gradient(135deg, #dc2626, #b91c1c)'
                    : saveStatus === 'saving'
                    ? 'linear-gradient(135deg, #6b7280, #4b5563)'
                    : 'linear-gradient(135deg, #1d4ed8, #1e40af)',
                  color: 'white', fontFamily: 'Tajawal', fontWeight: 800,
                  fontSize: '1.05rem', cursor: saveStatus === 'saving' || !doctorName.trim() ? 'not-allowed' : 'pointer',
                  boxShadow: saveStatus === 'saved'
                    ? '0 6px 20px rgba(22,163,74,0.35)'
                    : '0 6px 20px rgba(29,78,216,0.35)',
                  letterSpacing: '0.5px',
                  transition: 'all 0.3s ease',
                  opacity: !doctorName.trim() ? 0.6 : 1,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px'
                }}
              >
                {saveStatus === 'saving' && '⏳ جاري الحفظ...'}
                {saveStatus === 'saved'  && '✅ تم الحفظ بنجاح!'}
                {saveStatus === 'error'  && '❌ خطأ في الحفظ'}
                {saveStatus === 'idle'   && '💾 حفظ الشهادة في الأرشيف'}
              </button>
            </>
          )}

          {!hasContent && (
            <div style={{ textAlign: 'center', padding: '30px 10px', color: '#94a3b8' }}>
              <div style={{ fontSize: '2.5rem', marginBottom: '10px' }}>🔍</div>
              <p style={{ fontSize: '0.92rem', fontWeight: 600 }}>ابحث عن اسم المتدرب أو الطبيب من أي قسم أعلاه للبدء</p>
            </div>
          )}
        </div>

        {/* ── RIGHT: LIVE PREVIEW ── */}
        <div style={{ background: 'white', borderRadius: '18px', padding: '45px', boxShadow: '0 4px 20px rgba(0,0,0,0.08)', border: '1px solid #e8e0e0', minHeight: '520px' }}>
          {!hasContent ? (
            <div style={{ textAlign: 'center', padding: '60px 20px', color: '#94a3b8' }}>
              <div style={{ fontSize: '4.5rem', marginBottom: '16px' }}>📄</div>
              <p style={{ fontSize: '1.2rem', fontWeight: 800, color: '#475569' }}>معاينة شهادة الخبرة ستظهر هنا مباشرة</p>
              <p style={{ fontSize: '0.9rem', marginTop: '8px' }}>اختر متدرباً أو طبيباً من القائمة اليسرى لمعاينة شهادته وطباعتها</p>
            </div>
          ) : (
            <div dir={isAr ? 'rtl' : 'ltr'}>
              {/* Date */}
              <div style={{ textAlign: isAr ? 'left' : 'right', marginBottom: '30px', fontSize: `${Math.max(14, 18 * fontSizeScale * dateSizeScale)}px`, fontWeight: 700 }}>
                {isAr ? 'التاريخ :-' : 'Date:'} {certDate}
              </div>

              {showBismillah && (
                <div style={{ textAlign: 'center', fontSize: `${22 * fontSizeScale}px`, fontWeight: 800, marginBottom: activeRecipient ? `${12 * fontSizeScale}px` : `${24 * fontSizeScale}px` }}>
                  {isAr ? 'بسم الله الرحمن الرحيم' : 'In the name of Allah, the Most Gracious, the Most Merciful'}
                </div>
              )}

              {/* Recipient line */}
              {activeRecipient && (
                <div style={{ textAlign: 'center', marginBottom: `${20 * fontSizeScale}px` }}>
                  <span style={{
                    fontWeight: 800, fontSize: `${19 * fontSizeScale}px`,
                    borderBottom: '2px solid #1a1a1a', display: 'inline-block', paddingBottom: '5px',
                  }}>
                    {activeRecipient}
                  </span>
                </div>
              )}

              <div style={{ fontSize: `${20 * fontSizeScale}px`, lineHeight: lineSpacing, textAlign: 'center' }}>
                {showRecipient && recipientText && !activeRecipient && (
                  <p style={{ marginBottom: `${16 * fontSizeScale}px` }}>
                    <span style={{ fontWeight: 800, fontSize: `${22 * fontSizeScale}px`, borderBottom: '3px solid #1a1a1a', display: 'inline-block', paddingBottom: '6px' }}>
                      {recipientText}
                    </span>
                  </p>
                )}

                <p style={{ marginBottom: `${20 * fontSizeScale}px` }}>
                  {isAr ? 'تشهد إدارة مستشفى الهلال الأحمر التخصصي /الخليل بأن' : 'The administration of PRCS Specialized Hospital / Hebron certifies that'}
                </p>

                <p style={{ fontSize: `${28 * fontSizeScale}px`, fontWeight: 800, color: '#8B1A2B', margin: `${24 * fontSizeScale}px 0` }}>
                  {isAr ? (computedTitleAr ? `${computedTitleAr} / ` : '') : (computedTitleEn ? `${computedTitleEn} ` : '')}{doctorName}
                </p>

                {customRotations.map((rot, idx) => (
                  <div key={idx} style={{ margin: `${14 * fontSizeScale}px auto`, padding: '14px 20px', background: '#faf5f5', borderRadius: '6px', maxWidth: '88%', textAlign: 'center', fontSize: `${18 * fontSizeScale}px`, border: '1px solid #fecdd3' }}>
                    {isAr
                      ? <>{isMale ? 'قد عمل' : 'قد عملت'} فترة التدريب (<strong>{rot.training || '...'}</strong>) في قسم (<strong>{rot.section || '...'}</strong>) ابتداء من تاريخ</>
                      : <>Has completed a training period (<strong>{rot.training || '...'}</strong>) in the department of (<strong>{rot.section || '...'}</strong>) starting from</>
                    }
                    <br />
                    <strong>{rot.from || '../../....'}</strong> {isAr ? 'حتى' : 'to'} <strong>{rot.to || '../../....'}</strong>
                  </div>
                ))}

                <p style={{ marginTop: `${20 * fontSizeScale}px` }}>
                  {isAr
                    ? `وقد ${isMale ? 'كان' : 'كانت'} خلال فترة ${isMale ? 'عمله ملتزم وحسن' : 'عملها ملتزمة وحسنة'} السيرة والسلوك .`
                    : `During this period, ${isMale ? 'he' : 'she'} demonstrated excellent commitment and professional conduct.`
                  }
                </p>
                <p style={{ marginTop: `${16 * fontSizeScale}px` }}>{isAr ? 'هذا مع الاحترام .' : 'Sincerely,'}</p>
              </div>

              {/* Signature */}
              <div style={{ marginTop: '45px', textAlign: isAr ? 'left' : 'right' }}>
                <p style={{ fontSize: `${20 * fontSizeScale * signSizeScale}px`, color: '#475569', fontWeight: 800, marginBottom: '4px' }}>
                  {isAr ? 'المدير الطبي' : 'Medical Director'}
                </p>
                <p style={{ fontSize: `${20 * fontSizeScale * signSizeScale}px`, fontWeight: 800, color: '#8B1A2B' }}>
                  {isAr ? 'د. خالد السراحنه' : 'Dr. Khaled Al-Sarahneh'}
                </p>
              </div>
            </div>
          )}
        </div>

      </div>

      {/* ── SAVED CERTIFICATES ARCHIVE ── */}
      <div style={{ maxWidth: '1050px', margin: '40px auto 0' }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          marginBottom: '16px', padding: '0 4px'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <h2 style={{ fontSize: '1.25rem', fontWeight: 900, color: '#1e293b', margin: 0 }}>
              💾 أرشيف الشهادات المحفوظة
            </h2>
            {savedCerts.length > 0 && (
              <span style={{
                background: '#8B1A2B', color: 'white', borderRadius: '20px',
                padding: '3px 12px', fontSize: '0.82rem', fontWeight: 800
              }}>
                {savedCerts.length}
              </span>
            )}
          </div>
          <button
            onClick={loadSavedCerts}
            style={{
              background: 'white', border: '1.5px solid #e0e0e0', borderRadius: '10px',
              padding: '8px 16px', cursor: 'pointer', fontFamily: 'Tajawal',
              fontSize: '0.85rem', fontWeight: 800, color: '#475569',
              display: 'flex', alignItems: 'center', gap: '6px',
              boxShadow: '0 2px 6px rgba(0,0,0,0.04)', transition: 'all 0.2s',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = '#8B1A2B'; e.currentTarget.style.color = '#8B1A2B'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = '#e0e0e0'; e.currentTarget.style.color = '#475569'; }}
          >
            🔄 تحديث القائمة
          </button>
        </div>

        {certsLoading && (
          <div style={{ textAlign: 'center', padding: '30px', color: '#94a3b8', fontSize: '0.95rem' }}>
            ⏳ جاري تحميل الشهادات...
          </div>
        )}

        {!certsLoading && savedCerts.length === 0 && (
          <div style={{
            textAlign: 'center', padding: '40px', background: 'white',
            borderRadius: '18px', border: '2px dashed #e2e8f0', color: '#94a3b8'
          }}>
            <div style={{ fontSize: '2.8rem', marginBottom: '10px' }}>📂</div>
            <p style={{ fontSize: '1rem', fontWeight: 700 }}>لا توجد شهادات محفوظة بعد</p>
            <p style={{ fontSize: '0.85rem', marginTop: '4px' }}>اضغط على "حفظ الشهادة في الأرشيف" لتخزين الشهادات للرجوع إليها لاحقاً</p>
          </div>
        )}

        {!certsLoading && savedCerts.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '16px', paddingBottom: '40px' }}>
            {savedCerts.map((cert: any) => {
              const certDate2 = cert.cert_date || '—';
              const createdAt = cert.created_at
                ? new Date(cert.created_at).toLocaleDateString('ar-SA', { year: 'numeric', month: 'short', day: 'numeric' })
                : '—';
              const rotCount = (cert.rotations || []).length;
              const depts = (cert.rotations || []).map((r: any) => r.section || r.training).filter(Boolean);

              return (
                <div key={cert.id} style={{
                  background: 'white', borderRadius: '16px',
                  boxShadow: '0 4px 15px rgba(0,0,0,0.06)',
                  border: '1px solid #f1f5f9', overflow: 'hidden',
                  transition: 'transform 0.2s, box-shadow 0.2s',
                }}
                onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.boxShadow = '0 8px 25px rgba(0,0,0,0.1)'; }}
                onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.06)'; }}
                >
                  <div style={{ background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', padding: '12px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ color: 'white', fontWeight: 800, fontSize: '0.95rem', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {cert.doctor_name}
                    </span>
                    <span style={{ color: 'rgba(255,255,255,0.85)', fontSize: '0.75rem', fontWeight: 700 }}>
                      {cert.lang === 'ar' ? '🇵🇸 عربي' : '🇬🇧 EN'}
                    </span>
                  </div>

                  <div style={{ padding: '16px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '10px', fontSize: '0.8rem', color: '#64748b' }}>
                      <span>📅 تاريخ الشهادة: <strong style={{ color: '#1e293b' }}>{certDate2}</strong></span>
                    </div>

                    {cert.recipient && (
                      <div style={{ fontSize: '0.8rem', color: '#475569', marginBottom: '10px', background: '#fdf8f8', padding: '6px 12px', borderRadius: '8px', border: '1px solid #f0dede' }}>
                        📨 {cert.recipient}
                      </div>
                    )}

                    {depts.length > 0 && (
                      <div style={{ marginBottom: '12px' }}>
                        <div style={{ fontSize: '0.75rem', fontWeight: 800, color: '#8B1A2B', marginBottom: '6px' }}>
                          🏥 الأقسام ({rotCount}):
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '5px' }}>
                          {depts.map((d: string, i: number) => (
                            <span key={i} style={{
                              background: '#fdeced', color: '#8B1A2B', fontSize: '0.72rem',
                              fontWeight: 700, padding: '3px 9px', borderRadius: '20px',
                            }}>{d}</span>
                          ))}
                        </div>
                      </div>
                    )}

                    <div style={{ fontSize: '0.75rem', color: '#94a3b8', marginBottom: '14px' }}>
                      💾 تاريخ الحفظ: {createdAt}
                    </div>

                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button
                        onClick={() => handleLoadCert(cert)}
                        style={{
                          flex: 1, padding: '9px', borderRadius: '8px', border: 'none',
                          background: 'linear-gradient(135deg, #1d4ed8, #1e40af)', color: 'white',
                          fontFamily: 'Tajawal', fontWeight: 800, fontSize: '0.85rem',
                          cursor: 'pointer', transition: 'opacity 0.2s',
                        }}
                        onMouseEnter={e => e.currentTarget.style.opacity = '0.9'}
                        onMouseLeave={e => e.currentTarget.style.opacity = '1'}
                      >
                        📂 تحميل وتعديل
                      </button>
                      <button
                        onClick={() => handleDeleteCert(cert.id)}
                        style={{
                          padding: '8px 14px', borderRadius: '8px',
                          border: '1.5px solid #fca5a5', background: 'white',
                          color: '#dc2626', fontFamily: 'Tajawal', fontWeight: 800,
                          fontSize: '0.85rem', cursor: 'pointer', transition: 'all 0.2s',
                        }}
                        onMouseEnter={e => { e.currentTarget.style.background = '#dc2626'; e.currentTarget.style.color = 'white'; }}
                        onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = '#dc2626'; }}
                        title="حذف الشهادة"
                      >
                        🗑️
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

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

const chipStyle: React.CSSProperties = {
  background: '#e2e8f0', border: 'none', padding: '4px 10px',
  borderRadius: '6px', fontSize: '0.74rem', cursor: 'pointer',
  fontFamily: 'Tajawal', color: '#334155', fontWeight: 700
};
