"use client";

import { useState, useMemo, useEffect, useCallback } from "react";
import Link from "next/link";
import { QRCodeSVG } from "qrcode.react";
import { 
  ArrowRight, Stethoscope, Activity, Utensils, Briefcase, 
  Calculator, HeartPulse, HandHeart, GraduationCap, Apple, 
  Scan, Users, QrCode, Download, Copy, Check, Siren, Heart,
  Search, Sparkles, Printer, Home, UserCheck, ShieldCheck, ChevronDown,
  Globe, ExternalLink, Layers, PlusCircle, X, Edit3, Trash2
} from "lucide-react";

interface CategoryItem {
  id: string;
  name: string;
  group: 'universities' | 'internship' | 'nursing' | 'allied' | 'admin' | 'volunteer';
  groupName: string;
  icon: any;
  color: string;
  badge: string;
  desc: string;
}

const categories: CategoryItem[] = [
  // 1. Universities & Contracted Doctors & All Clinical Trainers (Top Priority)
  { 
    id: "university-nursing-trainers", 
    name: "تقديم طلبات لتدريب طلاب التمريض في الجامعات", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: HeartPulse, 
    color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)",
    badge: "جديد — الجامعات الشريكة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة التمريض في الجامعات داخل أقسام المستشفى"
  },
  { 
    id: "contracted-doctors", 
    name: "الأطباء المتعاقدين مع الجامعات", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: Stethoscope, 
    color: "linear-gradient(135deg, #4338ca 0%, #312e81 100%)",
    badge: "جديد — الأطباء المتعاقدون",
    desc: "خاص بالأطباء المشرفين والمتعاقدين مع الجامعات لتدريب الطلبة في الأقسام الطبية"
  },
  { 
    id: "radiology-trainers", 
    name: "مدربي أشعة (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: Scan, 
    color: "linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%)",
    badge: "مدرب سريري — أشعة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة الأشعة والتصوير الطبي من الجامعات الشريكة"
  },
  { 
    id: "physical-therapy-trainers", 
    name: "مدربي علاج طبيعي (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: Activity, 
    color: "linear-gradient(135deg, #059669 0%, #047857 100%)",
    badge: "مدرب سريري — علاج طبيعي",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة العلاج الطبيعي والتأهيل الحركي"
  },
  { 
    id: "lab-trainers", 
    name: "مدربي مختبرات (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: Activity, 
    color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)",
    badge: "مدرب سريري — مختبرات",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة العلوم الطبية المخبرية في أقسام المستشفى"
  },
  { 
    id: "pharmacy-trainers", 
    name: "مدربي صيدلة (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: HeartPulse, 
    color: "linear-gradient(135deg, #b45309 0%, #78350f 100%)",
    badge: "مدرب سريري — صيدلة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة كليات الصيدلة السريرية"
  },
  { 
    id: "occupational-therapy-trainers", 
    name: "مدربي علاج وظيفي (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: HandHeart, 
    color: "linear-gradient(135deg, #0f766e 0%, #115e59 100%)",
    badge: "مدرب سريري — علاج وظيفي",
    desc: "خاص بالمدربين والمشرفين لتدريب وتأهيل اختصاصيي العلاج الوظيفي"
  },
  { 
    id: "nutrition-trainers", 
    name: "مدربي تغذية (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: Apple, 
    color: "linear-gradient(135deg, #16a34a 0%, #15803d 100%)",
    badge: "مدرب سريري — تغذية",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة التغذية السريرية والعلاجية"
  },
  { 
    id: "medical-engineering-trainers", 
    name: "مدربي هندسة طبية (التدريب السريري والجامعات)", 
    group: 'universities',
    groupName: "الجامعات والمشرفين",
    icon: Activity, 
    color: "linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%)",
    badge: "مدرب سريري — هندسة طبية",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة الهندسة والأجهزة الطبية السريرية"
  },

  // 2. Internship & Medical
  { 
    id: "internship", 
    name: "المتقدمين للإمتياز (طب وجراحة)", 
    group: 'internship',
    groupName: "أطباء الامتياز",
    icon: GraduationCap, 
    color: "linear-gradient(135deg, #0284c7 0%, #1e40af 100%)",
    badge: "برنامج الامتياز الطبي",
    desc: "أطباء الامتياز لخريجي كليات الطب البشري (نظام 5+2 و 6+1)"
  },
  { 
    id: "medical-training", 
    name: "طب تدريب سريري", 
    group: 'internship',
    groupName: "أطباء الامتياز والتدريب",
    icon: Stethoscope, 
    color: "linear-gradient(135deg, #0369a1 0%, #0284c7 100%)",
    badge: "تدريب سريري",
    desc: "برنامج التدريب السريري التخصصي لطلبة كليات الطب البشري"
  },
  { 
    id: "volunteer-medicine", 
    name: "طب تطوع", 
    group: 'volunteer',
    groupName: "التطوع",
    icon: HandHeart, 
    color: "linear-gradient(135deg, #d97706 0%, #b45309 100%)",
    badge: "التطوع الطبي",
    desc: "برنامج التطوع الطبي في مختلف الأقسام والعيادات التخصصية"
  },

  // 3. Nursing
  { 
    id: "nursing", 
    name: "التمريض العام", 
    group: 'nursing',
    groupName: "التمريض والتدريب",
    icon: HeartPulse, 
    color: "linear-gradient(135deg, #e11d48 0%, #be123c 100%)",
    badge: "طاقم التمريض",
    desc: "تقديم طلبات الالتحاق والتدريب لكادر التمريض التخصصي"
  },
  { 
    id: "nursing-training", 
    name: "تمريض تدريب", 
    group: 'nursing',
    groupName: "التمريض والتدريب",
    icon: Stethoscope, 
    color: "linear-gradient(135deg, #db2777 0%, #9d174d 100%)",
    badge: "تدريب عملي",
    desc: "برامج التدريب الميداني والعملي لطلبة وخريجي كليات التمريض"
  },
  { 
    id: "nursing-internship", 
    name: "تمريض امتياز", 
    group: 'nursing',
    groupName: "التمريض والتدريب",
    icon: Stethoscope, 
    color: "linear-gradient(135deg, #9333ea 0%, #6b21a8 100%)",
    badge: "سنة الامتياز التمريضي",
    desc: "برنامج سنة الامتياز لخريجي التمريض لتطوير الكفاءات السريرية"
  },
  { 
    id: "volunteer-nursing", 
    name: "تمريض تطوع", 
    group: 'volunteer',
    groupName: "التطوع",
    icon: HandHeart, 
    color: "linear-gradient(135deg, #0d9488 0%, #0f766e 100%)",
    badge: "التطوع التمريضي",
    desc: "فرص التطوع لطلبة وخريجي التمريض لاكتساب الخبرة الميدانية"
  },

  // 4. Paramedics & Allied Health
  { 
    id: "ambulance-officers", 
    name: "تدريب ضباط الإسعاف", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Siren, 
    color: "linear-gradient(135deg, #ea580c 0%, #c2410c 100%)",
    badge: "الإسعاف والطوارئ",
    desc: "برنامج التدريب العملي لضباط وفنيي الإسعاف وطوارئ المستشفى"
  },
  { 
    id: "physical-therapy-training", 
    name: "علاج طبيعي تدريب", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Activity, 
    color: "linear-gradient(135deg, #16a34a 0%, #15803d 100%)",
    badge: "تدريب عملي",
    desc: "برنامج التدريب العملي والميداني لطلاب العلاج الطبيعي والتأهيل الحركي"
  },
  { 
    id: "physical-therapy-internship", 
    name: "علاج طبيعي امتياز", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Activity, 
    color: "linear-gradient(135deg, #059669 0%, #047857 100%)",
    badge: "سنة الامتياز",
    desc: "برنامج سنة الامتياز لخريجي العلاج الطبيعي والتأهيل الحركي"
  },
  { 
    id: "occupational-therapy", 
    name: "العلاج الوظيفي", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Activity, 
    color: "linear-gradient(135deg, #059669 0%, #047857 100%)",
    badge: "التأهيل الوظيفي",
    desc: "برنامج تدريب وتأهيل اختصاصيي العلاج الوظيفي والتأهيل"
  },
  { 
    id: "radiology", 
    name: "أشعة", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Scan, 
    color: "linear-gradient(135deg, #475569 0%, #334155 100%)",
    badge: "التصوير الطبي",
    desc: "تدريب فنيي الأشعة والتصوير الطبقي والرنين"
  },
  { 
    id: "nutrition", 
    name: "تغذية سريرية", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Apple, 
    color: "linear-gradient(135deg, #65a30d 0%, #4d7c0f 100%)",
    badge: "التغذية العلاجية",
    desc: "برنامج التدريب لأخصائيي التغذية السريرية والحميات"
  },
  { 
    id: "medical-labs", 
    name: "مختبرات طبية وتحاليل", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Activity, 
    color: "linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)",
    badge: "المختبرات والتحاليل",
    desc: "برنامج التدريب في المختبرات الطبية وبنك الدم ومطابقة العينات"
  },
  { 
    id: "biomedical-engineering", 
    name: "هندسة طبية وأجهزة", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل",
    icon: Activity, 
    color: "linear-gradient(135deg, #0284c7 0%, #0369a1 100%)",
    badge: "الهندسة الطبية",
    desc: "برنامج التدريب في صيانة ومعايرة الأجهزة والمعدات السريرية"
  },
  { 
    id: "psychological-counseling", 
    name: "إرشاد وصحة نفسية", 
    group: 'allied',
    groupName: "الإسعاف والتأهيل والمهن المساندة",
    icon: Activity, 
    color: "linear-gradient(135deg, #059669 0%, #10b981 100%)",
    badge: "إرشاد وصحة نفسية",
    desc: "برنامج التدريب والتأهيل الميداني في الإرشاد النفسي والصحة النفسية والدعم النفسي الاجتماعي"
  },
  { 
    id: "social-service", 
    name: "خدمة اجتماعية", 
    group: 'volunteer',
    groupName: "التطوع والخدمات",
    icon: Users, 
    color: "linear-gradient(135deg, #78350f 0%, #451a03 100%)",
    badge: "الدعم النفسي والاجتماعي",
    desc: "تقديم الخدمات الاجتماعية والدعم الإنساني للمرضى وعائلاتهم"
  },
  { 
    id: "community-work", 
    name: "العمل المجتمعي", 
    group: 'volunteer',
    groupName: "التطوع والخدمات",
    icon: Heart, 
    color: "linear-gradient(135deg, #0f766e 0%, #115e59 100%)",
    badge: "المبادرات المجتمعية",
    desc: "المشاركة في الأنشطة المجتمعية والتوعوية والحملات الصحية"
  },

  // 5. Admin & Support
  { 
    id: "admin", 
    name: "الإدارة والسكرتاريا", 
    group: 'admin',
    groupName: "الإدارة والخدمات المساندة",
    icon: Briefcase, 
    color: "linear-gradient(135deg, #334155 0%, #1e293b 100%)",
    badge: "الكوادر الإدارية",
    desc: "التقديم للتدريب الإداري والسكرتاريا الطبية"
  },
  { 
    id: "medical-sec", 
    name: "سكرتارية طبية وسجلات", 
    group: 'admin',
    groupName: "الإدارة والخدمات المساندة",
    icon: Briefcase, 
    color: "linear-gradient(135deg, #4f46e5 0%, #4338ca 100%)",
    badge: "السجلات الطبية",
    desc: "قسم السكرتارية الطبية وإدارة السجلات والتوثيق الصحي"
  },
  { 
    id: "accounting", 
    name: "المحاسبة والمالية", 
    group: 'admin',
    groupName: "الإدارة والخدمات المساندة",
    icon: Calculator, 
    color: "linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%)",
    badge: "الشؤون المالية",
    desc: "تدريب وتأهيل الكوادر المالية والمحاسبية والتأمين الصحي"
  },
  { 
    id: "kitchen", 
    name: "المطبخ والخدمات الفندقية", 
    group: 'admin',
    groupName: "الإدارة والخدمات المساندة",
    icon: Utensils, 
    color: "linear-gradient(135deg, #c2410c 0%, #9a3412 100%)",
    badge: "الإعاشة الفندقية",
    desc: "خدمات الإعاشة الفندقية وتغذية المرضى والكوادر الطبية"
  },
];

export default function RecruitmentHub() {
  const [selectedTab, setSelectedTab] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [customCategories, setCustomCategories] = useState<CategoryItem[]>([]);

  // Fetch custom categories on mount
  useEffect(() => {
    fetch('/api/categories')
      .then(res => res.json())
      .then(data => {
        if (data && Array.isArray(data.categories) && data.categories.length > 0) {
          const mapped: CategoryItem[] = data.categories.map((c: any) => ({
            id: c.id,
            name: c.name,
            group: c.group || 'allied',
            groupName: c.groupName || 'أقسام إضافية',
            icon: Layers,
            color: 'linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)',
            badge: c.badge || 'استمارة تقديم',
            desc: c.desc || `برنامج التقديم والتدريب في قسم ${c.name}`
          }));
          setCustomCategories(mapped);
          try { localStorage.setItem('customCategories', JSON.stringify(mapped)); } catch {}
        } else {
          try {
            const local = localStorage.getItem('customCategories');
            if (local) setCustomCategories(JSON.parse(local));
          } catch {}
        }
      })
      .catch(() => {
        try {
          const local = localStorage.getItem('customCategories');
          if (local) setCustomCategories(JSON.parse(local));
        } catch {}
      });
  }, []);

  const allCategories = useMemo(() => {
    const customMap = new Map<string, CategoryItem>();
    customCategories.forEach(c => customMap.set(c.id, c));
    const merged = categories.map(c => customMap.has(c.id) ? customMap.get(c.id)! : c);
    const defaultIds = new Set(categories.map(c => c.id));
    customCategories.forEach(c => {
      if (!defaultIds.has(c.id)) {
        merged.push(c);
      }
    });
    return merged;
  }, [customCategories]);

  const filterTabs = useMemo(() => [
    { key: 'all', label: `🌟 كافة النماذج (${allCategories.length})` },
    { key: 'universities', label: `🎓 تدريب الجامعات والأطباء والمدربين (${allCategories.filter(c => c.group === 'universities').length})` },
    { key: 'internship', label: `🩺 أطباء الامتياز (${allCategories.filter(c => c.group === 'internship').length})` },
    { key: 'nursing', label: `💉 التمريض والتدريب (${allCategories.filter(c => c.group === 'nursing').length})` },
    { key: 'allied', label: `🚑 الإسعاف والتأهيل والأشعة (${allCategories.filter(c => c.group === 'allied').length})` },
    { key: 'admin', label: `💼 الإدارة والمالية والمطبخ (${allCategories.filter(c => c.group === 'admin').length})` },
    { key: 'volunteer', label: `🤝 التطوع والمجتمع (${allCategories.filter(c => c.group === 'volunteer').length})` },
  ], [allCategories]);

  // Modal State for adding/editing department application & QR code
  const [showAddCategoryModal, setShowAddCategoryModal] = useState(false);
  const [editingCatId, setEditingCatId] = useState<string | null>(null);
  const [newDeptName, setNewDeptName] = useState('');
  const [newDeptGroup, setNewDeptGroup] = useState<'universities' | 'allied' | 'nursing' | 'internship' | 'admin' | 'volunteer'>('universities');
  const [newDeptBadge, setNewDeptBadge] = useState('');
  const [newDeptDesc, setNewDeptDesc] = useState('');
  const [isCreatingCategory, setIsCreatingCategory] = useState(false);
  const [addCategorySuccess, setAddCategorySuccess] = useState<string | null>(null);

  const handleOpenEditCategory = (cat: CategoryItem) => {
    setEditingCatId(cat.id);
    setNewDeptName(cat.name);
    setNewDeptGroup(cat.group);
    setNewDeptBadge(cat.badge);
    setNewDeptDesc(cat.desc);
    setShowAddCategoryModal(true);
  };

  const handleDeleteCategory = async (catId: string, catName: string) => {
    if (!confirm(`هل أنت متأكد من حذف أو إخفاء استمارة (${catName})؟`)) return;
    setCustomCategories(prev => {
      const updated = prev.filter(c => c.id !== catId);
      try { localStorage.setItem('customCategories', JSON.stringify(updated)); } catch {}
      return updated;
    });
    try {
      await fetch('/api/categories', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: catId })
      });
    } catch {}
  };

  // Default to showing all QR codes so all cards in every row have identical, symmetric, balanced heights
  const [expandedQRs, setExpandedQRs] = useState<Record<string, boolean>>(() => {
    const init: Record<string, boolean> = {};
    categories.forEach(c => { init[c.id] = true; });
    return init;
  });
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [allQRsExpanded, setAllQRsExpanded] = useState(true);

  // When allCategories changes, ensure all QR codes default to expanded
  useEffect(() => {
    setExpandedQRs(prev => {
      const updated = { ...prev };
      allCategories.forEach(c => {
        if (updated[c.id] === undefined) updated[c.id] = true;
      });
      return updated;
    });
  }, [allCategories]);

  const toggleAllQRs = () => {
    const next = !allQRsExpanded;
    setAllQRsExpanded(next);
    const updated: Record<string, boolean> = {};
    allCategories.forEach(c => { updated[c.id] = next; });
    setExpandedQRs(updated);
  };

  const toggleQR = (id: string) => {
    setExpandedQRs(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const [useOnlineDomain, setUseOnlineDomain] = useState(true);
  const isLocalEnvironment = typeof window !== 'undefined' && (
    window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1' ||
    window.location.hostname.startsWith('192.168.') ||
    window.location.hostname.startsWith('10.')
  );
  const baseUrl = (isLocalEnvironment && useOnlineDomain)
    ? 'https://crescent.livestimes.com'
    : (typeof window !== 'undefined' ? window.location.origin : 'https://crescent.livestimes.com');

  const filteredCategories = useMemo(() => {
    return allCategories.filter(cat => {
      const matchesTab = selectedTab === 'all' || cat.group === selectedTab || (selectedTab === 'volunteer' && cat.group === 'volunteer');
      const matchesSearch = !searchQuery.trim() || 
        cat.name.includes(searchQuery.trim()) || 
        cat.groupName.includes(searchQuery.trim()) ||
        cat.desc.includes(searchQuery.trim());
      return matchesTab && matchesSearch;
    });
  }, [allCategories, selectedTab, searchQuery]);

  const handleCopyLink = (catId: string) => {
    const url = `${baseUrl}/apply/${catId}`;
    navigator.clipboard.writeText(url).then(() => {
      setCopiedId(catId);
      setTimeout(() => setCopiedId(null), 2000);
    });
  };

  const handleCreateCategory = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newDeptName.trim()) {
      alert('يرجى إدخال اسم القسم');
      return;
    }
    setIsCreatingCategory(true);
    try {
      const slug = editingCatId || newDeptName.trim()
        .toLowerCase()
        .replace(/[^\w\u0621-\u064A\s-]/g, '')
        .replace(/\s+/g, '-');

      const groupNames: Record<string, string> = {
        universities: 'الجامعات والمشرفين',
        allied: 'الإسعاف والتأهيل والأشعة',
        nursing: 'التمريض والتدريب',
        internship: 'أطباء الامتياز',
        admin: 'الإدارة والمالية والمطبخ',
        volunteer: 'التطوع والمجتمع'
      };

      const payload = {
        id: slug || `dept-${Date.now()}`,
        name: newDeptName.trim(),
        group: newDeptGroup,
        groupName: groupNames[newDeptGroup] || 'أقسام إضافية',
        badge: newDeptBadge.trim() || (newDeptGroup === 'universities' ? 'مدرب سريري' : 'استمارة تدريب'),
        desc: newDeptDesc.trim() || `برنامج التقديم والتدريب الرسمي لقسم ${newDeptName.trim()} لدى المستشفى والجامعات الشريكة`
      };

      await fetch('/api/categories', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const existingCat = allCategories.find(c => c.id === payload.id);
      const newCatItem: CategoryItem = {
        ...payload,
        icon: existingCat?.icon || Layers,
        color: existingCat?.color || 'linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)'
      };

      setCustomCategories(prev => {
        const updated = [...prev.filter(c => c.id !== newCatItem.id), newCatItem];
        try { localStorage.setItem('customCategories', JSON.stringify(updated)); } catch {}
        return updated;
      });

      setExpandedQRs(prev => ({ ...prev, [newCatItem.id]: true }));
      setAddCategorySuccess(editingCatId 
        ? `تم بنجاح تعديل وحفظ بيانات الاستمارة (${newDeptName.trim()})!` 
        : `تم بنجاح إضافة الاستمارة ورمز الـ QR لقسم (${newDeptName.trim()})!`
      );
      setTimeout(() => {
        setAddCategorySuccess(null);
        setShowAddCategoryModal(false);
        setEditingCatId(null);
        setNewDeptName('');
        setNewDeptBadge('');
        setNewDeptDesc('');
      }, 1500);
    } catch (err: any) {
      alert('حدث خطأ أثناء حفظ القسم: ' + err?.message);
    } finally {
      setIsCreatingCategory(false);
    }
  };

  const handleDownloadFullCard = (catId: string, catName: string) => {
    if (catId === 'university-nursing-trainers') {
      const a = document.createElement('a');
      a.href = '/cards/card_university_nursing_trainers.png';
      a.download = 'بطاقة_تدريب_طلاب_التمريض_بالجامعات_QR.png';
      a.click();
      return;
    }
    if (catId === 'contracted-doctors') {
      const a = document.createElement('a');
      a.href = '/cards/card_contracted_doctors.png';
      a.download = 'بطاقة_الأطباء_المتعاقدون_مع_الجامعات_QR.png';
      a.click();
      return;
    }
    handleDownloadQR(catId, catName);
  };

  const handleDownloadQR = (catId: string, catName: string) => {
    const svg = document.getElementById(`qr-${catId}`);
    if (!svg) return;
    const svgData = new XMLSerializer().serializeToString(svg);
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    img.onload = () => {
      canvas.width = 1000;
      canvas.height = 1000;
      if (ctx) {
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, 1000, 1000);
        ctx.drawImage(img, 100, 100, 800, 800);
        const a = document.createElement('a');
        a.download = `QR_${catName.replace(/[\/\s]/g, '_')}.png`;
        a.href = canvas.toDataURL('image/png');
        a.click();
      }
    };
    img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #090e17 0%, #0f172a 50%, #1e293b 100%)',
      color: '#f8fafc',
      fontFamily: 'Tajawal, sans-serif',
      direction: 'rtl',
      padding: '14px 14px 60px'
    }}>
      <div style={{ maxWidth: '1400px', margin: '0 auto' }}>

        {/* ══════════════════════════════════════════════════════════
            TOP NAVIGATION & SUPERVISOR BADGE
        ══════════════════════════════════════════════════════════ */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: '12px',
          marginBottom: '14px',
          flexWrap: 'wrap',
          background: 'rgba(255,255,255,0.04)',
          backdropFilter: 'blur(15px)',
          padding: '10px 16px',
          borderRadius: '16px',
          border: '1px solid rgba(255,255,255,0.1)'
        }}>
          {/* Back Buttons */}
          <div style={{ display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
            <Link
              href="/"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                padding: '10px 18px',
                background: 'linear-gradient(135deg, #059669 0%, #10b981 100%)',
                color: 'white',
                borderRadius: '12px',
                textDecoration: 'none',
                fontWeight: 800,
                fontSize: '0.9rem',
                boxShadow: '0 4px 15px rgba(16, 185, 129, 0.3)',
                border: '1px solid rgba(255,255,255,0.2)'
              }}
            >
              <Home size={18} />
              الرئيسية
            </Link>

            <Link
              href="/trainers-qr"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                padding: '10px 18px',
                background: 'linear-gradient(135deg, #312e81 0%, #4338ca 100%)',
                color: '#ffffff',
                borderRadius: '12px',
                textDecoration: 'none',
                fontWeight: 900,
                fontSize: '0.86rem',
                border: '1.5px solid #ffd700',
                boxShadow: '0 4px 15px rgba(255, 215, 0, 0.25)'
              }}
              title="صفحة طباعة مستقلة ومخصصة لرموز QR لكادر المدربين والمشرفين والأطباء المتعاقدين"
            >
              <GraduationCap size={17} color="#ffd700" />
              🖨️ طباعة رموز الـ QR الخاصة بالمدربين
            </Link>

            <Link
              href="/print-qr"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                padding: '10px 18px',
                background: 'rgba(255,215,0,0.15)',
                color: '#ffd700',
                borderRadius: '12px',
                textDecoration: 'none',
                fontWeight: 700,
                fontSize: '0.85rem',
                border: '1px solid rgba(255,215,0,0.3)'
              }}
            >
              <Printer size={16} />
              طباعة كافة رموز QR
            </Link>

            <a
              href="/cards/poster_universities_and_contracted_doctors.png"
              download="بوستر_نماذج_تدريب_الجامعات_والأطباء_المتعاقدون_QR.png"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                padding: '10px 18px',
                background: 'linear-gradient(135deg, #ffd700 0%, #f59e0b 100%)',
                color: '#0f172a',
                borderRadius: '12px',
                textDecoration: 'none',
                fontWeight: 900,
                fontSize: '0.85rem',
                boxShadow: '0 4px 15px rgba(245, 158, 11, 0.35)',
                border: '1px solid #ffd700'
              }}
            >
              <Download size={16} />
              تحميل بوستر النماذج المشترك (PNG)
            </a>

            <Link
              href="/admin/applications"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                padding: '10px 18px',
                background: 'rgba(255,255,255,0.08)',
                color: '#e2e8f0',
                borderRadius: '12px',
                textDecoration: 'none',
                fontWeight: 700,
                fontSize: '0.85rem',
                border: '1px solid rgba(255,255,255,0.15)'
              }}
            >
              <ShieldCheck size={16} />
              إدارة وأرشيف الطلبات
            </Link>

            {/* ➕ Add New Department Application & QR Code */}
            <button
              type="button"
              onClick={() => setShowAddCategoryModal(true)}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '8px',
                padding: '10px 18px',
                background: 'linear-gradient(135deg, #6366f1 0%, #4338ca 100%)',
                color: '#ffffff',
                borderRadius: '12px',
                border: '1.5px solid rgba(255,255,255,0.3)',
                fontWeight: 900,
                fontSize: '0.88rem',
                cursor: 'pointer',
                boxShadow: '0 4px 15px rgba(99, 102, 241, 0.4)',
                fontFamily: 'Tajawal'
              }}
            >
              <PlusCircle size={17} />
              ➕ إضافة استمارة ورمز QR لقسم جديد
            </button>
          </div>

          {/* Supervisor Badge */}
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.9) 0%, rgba(30, 41, 59, 0.85) 100%)',
            padding: '6px 16px 6px 10px',
            borderRadius: '40px',
            border: '2px solid rgba(255, 215, 0, 0.75)',
            boxShadow: '0 0 15px rgba(255, 215, 0, 0.25), 0 4px 15px rgba(0,0,0,0.3)'
          }}>
            <img 
              src="/supervisor.png" 
              alt="أ. نسرين عابدين"
              style={{
                width: '58px',
                height: '58px',
                borderRadius: '50%',
                objectFit: 'cover',
                objectPosition: 'center top',
                border: '2.5px solid #ffd700',
                boxShadow: '0 0 10px rgba(255, 215, 0, 0.5)',
                background: '#ffffff'
              }}
            />
            <div>
              <div style={{ fontSize: '0.78rem', color: '#ffd700', fontWeight: 800, marginBottom: '1px' }}>
                مديرة وحدة التطوير والتدريب
              </div>
              <div style={{ fontSize: '1.05rem', fontWeight: 900, color: '#ffffff' }}>
                أ. نسرين عابدين (أم خالد)
              </div>
              <div style={{ fontSize: '0.74rem', color: '#94a3b8', fontWeight: 600 }}>
                مستشفى الهلال الأحمر التخصصي
              </div>
            </div>
          </div>
        </div>

        {/* ══════════════════════════════════════════════════════════
            HERO TITLE & INTRO
        ══════════════════════════════════════════════════════════ */}
        <div style={{
          textAlign: 'center',
          padding: '14px 16px 18px',
          background: 'radial-gradient(ellipse at center, rgba(30, 58, 138, 0.35) 0%, rgba(15, 23, 42, 0) 70%)',
          borderRadius: '20px',
          marginBottom: '14px'
        }}>
          <div style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: '6px',
            padding: '4px 12px',
            background: 'rgba(255, 215, 0, 0.12)',
            borderRadius: '20px',
            border: '1px solid rgba(255, 215, 0, 0.3)',
            color: '#ffd700',
            fontSize: '0.8rem',
            fontWeight: 800,
            marginBottom: '8px'
          }}>
            <Sparkles size={14} />
            البوابة الإلكترونية الموحدة لتقديم طلبات التدريب والتعاقد
          </div>

          <h1 style={{
            fontSize: '1.8rem',
            fontWeight: 900,
            color: '#ffffff',
            margin: '0 0 6px 0',
            textShadow: '0 2px 10px rgba(0,0,0,0.5)'
          }}>
            بوابة تقديم الطلبات والتدريب
          </h1>

          <p style={{
            fontSize: '0.88rem',
            color: '#94a3b8',
            maxWidth: '680px',
            margin: '0 auto 14px',
            lineHeight: '1.5'
          }}>
            اختر التخصص أو النموذج المناسب لتعبئة طلبك مباشرة أو مسح رمز QR عبر كاميرا الجوال للتقديم الفوري.
          </p>

          {/* Search Bar */}
          <div style={{
            maxWidth: '520px',
            margin: '0 auto',
            position: 'relative'
          }}>
            <Search 
              size={18} 
              color="#94a3b8" 
              style={{
                position: 'absolute',
                right: '16px',
                top: '50%',
                transform: 'translateY(-50%)'
              }}
            />
            <input 
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="ابحث عن اسم القسم، التخصص، أو نوع التدريب..."
              style={{
                width: '100%',
                padding: '10px 46px 10px 16px',
                borderRadius: '12px',
                border: '1.5px solid rgba(255,255,255,0.15)',
                background: 'rgba(15, 23, 42, 0.85)',
                backdropFilter: 'blur(10px)',
                color: 'white',
                fontSize: '0.9rem',
                fontFamily: 'Tajawal',
                outline: 'none',
                boxShadow: '0 4px 15px rgba(0,0,0,0.2)',
                transition: 'all 0.3s'
              }}
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                style={{
                  position: 'absolute',
                  left: '14px',
                  top: '50%',
                  transform: 'translateY(-50%)',
                  background: 'rgba(255,255,255,0.1)',
                  border: 'none',
                  color: '#94a3b8',
                  borderRadius: '50%',
                  width: '22px',
                  height: '22px',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '0.75rem'
                }}
              >
                ✕
              </button>
            )}
          </div>
        </div>

        {/* ══════════════════════════════════════════════════════════
            CATEGORY FILTER TABS
        ══════════════════════════════════════════════════════════ */}
        <div style={{
          display: 'flex',
          gap: '8px',
          overflowX: 'auto',
          paddingBottom: '6px',
          marginBottom: '12px',
          scrollbarWidth: 'none'
        }}>
          {filterTabs.map(tab => {
            const isActive = selectedTab === tab.key;
            return (
              <button
                key={tab.key}
                onClick={() => setSelectedTab(tab.key)}
                style={{
                  padding: '7px 16px',
                  borderRadius: '12px',
                  border: isActive ? '1.5px solid #ffd700' : '1px solid rgba(255,255,255,0.1)',
                  background: isActive ? 'linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%)' : 'rgba(255,255,255,0.05)',
                  color: isActive ? '#ffffff' : '#94a3b8',
                  fontWeight: isActive ? 800 : 600,
                  fontSize: '0.84rem',
                  cursor: 'pointer',
                  whiteSpace: 'nowrap',
                  transition: 'all 0.2s',
                  boxShadow: isActive ? '0 3px 12px rgba(59, 130, 246, 0.35)' : 'none',
                  fontFamily: 'Tajawal'
                }}
              >
                {tab.label}
              </button>
            );
          })}
        </div>

        {/* ══════════════════════════════════════════════════════════
            GRID TOOLBAR: ITEM COUNT & MASTER QR TOGGLE
        ══════════════════════════════════════════════════════════ */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          flexWrap: 'wrap',
          gap: '10px',
          marginBottom: '14px',
          padding: '8px 14px',
          background: 'rgba(255, 255, 255, 0.03)',
          borderRadius: '14px',
          border: '1px solid rgba(255, 255, 255, 0.08)'
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            fontSize: '0.86rem',
            color: '#94a3b8',
            fontWeight: 600
          }}>
            <Layers size={16} color="#38bdf8" />
            <span>عرض <strong style={{ color: '#ffffff' }}>{filteredCategories.length}</strong> نموذج معتمد للتقديم</span>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
            {isLocalEnvironment && (
              <div style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '6px',
                background: 'rgba(15, 23, 42, 0.6)',
                border: '1px solid rgba(56, 189, 248, 0.3)',
                padding: '4px 10px',
                borderRadius: '10px',
                fontSize: '0.75rem',
                color: '#38bdf8'
              }}>
                <Globe size={12} />
                <span>الـ QR مبرمج للهواتف:</span>
                <button
                  type="button"
                  onClick={() => setUseOnlineDomain(!useOnlineDomain)}
                  style={{
                    background: useOnlineDomain ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)',
                    border: `1px solid ${useOnlineDomain ? '#10b981' : '#ef4444'}`,
                    color: useOnlineDomain ? '#6ee7b7' : '#fca5a5',
                    borderRadius: '6px',
                    padding: '2px 6px',
                    fontSize: '0.7rem',
                    fontWeight: 800,
                    cursor: 'pointer',
                    fontFamily: 'Tajawal'
                  }}
                  title="التبديل بين رابط المستشفى المباشر والرابط المحلي"
                >
                  {useOnlineDomain ? '✅ مباشر' : '⚠️ محلي'}
                </button>
              </div>
            )}

            <button
              onClick={toggleAllQRs}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '6px',
                padding: '7px 14px',
                borderRadius: '10px',
                border: allQRsExpanded ? '1px solid rgba(56, 189, 248, 0.4)' : '1px solid rgba(255, 255, 255, 0.15)',
                background: allQRsExpanded ? 'rgba(56, 189, 248, 0.12)' : 'rgba(255, 255, 255, 0.06)',
                color: allQRsExpanded ? '#38bdf8' : '#e2e8f0',
                fontWeight: 700,
                fontSize: '0.82rem',
                cursor: 'pointer',
                transition: 'all 0.2s ease',
                fontFamily: 'Tajawal'
              }}
            >
              <QrCode size={15} />
              {allQRsExpanded ? 'إخفاء كافة رموز الـ QR (عرض مختصر)' : 'إظهار كافة رموز الـ QR لجميع النماذج'}
            </button>
          </div>
        </div>

        {/* ══════════════════════════════════════════════════════════
            APPLICATIONS GRID (CARDS)
        ══════════════════════════════════════════════════════════ */}
        {filteredCategories.length === 0 ? (
          <div style={{
            textAlign: 'center',
            padding: '50px 20px',
            background: 'rgba(255,255,255,0.03)',
            borderRadius: '20px',
            border: '1px dashed rgba(255,255,255,0.15)'
          }}>
            <div style={{ fontSize: '42px', marginBottom: '12px' }}>🔍</div>
            <h3 style={{ fontSize: '1.2rem', color: '#e2e8f0', marginBottom: '6px' }}>لم يتم العثور على نماذج تطابق بحثك</h3>
            <p style={{ color: '#94a3b8', fontSize: '0.9rem' }}>جرب كتابة كلمات بحث أخرى أو اختر "كافة النماذج"</p>
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(310px, 1fr))',
            gap: '16px',
            alignItems: 'stretch'
          }}>
            {filteredCategories.map((cat) => {
              const isExpanded = !!expandedQRs[cat.id];
              const applyUrl = `${baseUrl}/apply/${cat.id}`;
              const Icon = cat.icon;

              return (
                <div 
                  key={cat.id}
                  style={{
                    background: 'linear-gradient(180deg, rgba(30, 41, 59, 0.75) 0%, rgba(15, 23, 42, 0.9) 100%)',
                    backdropFilter: 'blur(20px)',
                    borderRadius: '24px',
                    border: isExpanded ? '1px solid rgba(255, 255, 255, 0.16)' : '1px solid rgba(255, 255, 255, 0.08)',
                    overflow: 'hidden',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    boxShadow: isExpanded 
                      ? '0 16px 40px -10px rgba(0,0,0,0.5), 0 0 20px rgba(56, 189, 248, 0.08)' 
                      : '0 10px 30px -10px rgba(0,0,0,0.35)',
                    transition: 'all 0.3s cubic-bezier(0.16, 1, 0.3, 1)',
                    position: 'relative'
                  }}
                  onMouseOver={(e) => {
                    e.currentTarget.style.transform = 'translateY(-5px)';
                    e.currentTarget.style.boxShadow = '0 20px 45px -8px rgba(0,0,0,0.55), 0 0 25px rgba(56, 189, 248, 0.15)';
                    e.currentTarget.style.borderColor = 'rgba(56, 189, 248, 0.4)';
                  }}
                  onMouseOut={(e) => {
                    e.currentTarget.style.transform = 'translateY(0)';
                    e.currentTarget.style.boxShadow = isExpanded 
                      ? '0 16px 40px -10px rgba(0,0,0,0.5), 0 0 20px rgba(56, 189, 248, 0.08)' 
                      : '0 10px 30px -10px rgba(0,0,0,0.35)';
                    e.currentTarget.style.borderColor = isExpanded ? 'rgba(255, 255, 255, 0.16)' : 'rgba(255, 255, 255, 0.08)';
                  }}
                >
                  {/* Top Color Banner */}
                  <div style={{
                    background: cat.color,
                    padding: '12px 16px',
                    color: 'white',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '12px',
                    position: 'relative',
                    overflow: 'hidden'
                  }}>
                    {/* Decorative Ambient Shapes */}
                    <div style={{ position: 'absolute', top: '-25px', right: '-25px', width: '90px', height: '90px', background: 'rgba(255,255,255,0.15)', borderRadius: '50%', filter: 'blur(4px)' }} />
                    <div style={{ position: 'absolute', bottom: '-20px', left: '-20px', width: '70px', height: '70px', background: 'rgba(0,0,0,0.15)', borderRadius: '50%' }} />

                    {/* Icon Squircle */}
                    <div style={{
                      width: '42px',
                      height: '42px',
                      borderRadius: '12px',
                      background: 'rgba(255,255,255,0.22)',
                      backdropFilter: 'blur(12px)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      flexShrink: 0,
                      border: '1px solid rgba(255,255,255,0.35)',
                      boxShadow: '0 4px 12px rgba(0,0,0,0.2)'
                    }}>
                      <Icon size={22} color="#ffffff" />
                    </div>

                    <div style={{ flex: 1, zIndex: 1 }}>
                      <div style={{ 
                        fontSize: '0.72rem', 
                        fontWeight: 800, 
                        background: 'rgba(255,255,255,0.2)', 
                        backdropFilter: 'blur(8px)',
                        color: '#ffffff',
                        display: 'inline-block', 
                        padding: '2px 8px', 
                        borderRadius: '14px', 
                        marginBottom: '4px',
                        border: '1px solid rgba(255,255,255,0.35)',
                        letterSpacing: '0.2px'
                      }}>
                        {cat.badge}
                      </div>
                      <h3 style={{ fontSize: '1.05rem', fontWeight: 800, margin: 0, lineHeight: '1.3', textShadow: '0 1px 3px rgba(0,0,0,0.2)' }}>
                        {cat.name}
                      </h3>
                    </div>

                    {/* Quick Edit & Delete Actions */}
                    <div style={{ display: 'flex', gap: '5px', zIndex: 2 }}>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleOpenEditCategory(cat);
                        }}
                        title="تعديل هذه الاستمارة"
                        style={{
                          background: 'rgba(255,255,255,0.2)',
                          border: '1px solid rgba(255,255,255,0.4)',
                          color: '#ffffff',
                          borderRadius: '8px',
                          width: '28px',
                          height: '28px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          cursor: 'pointer'
                        }}
                      >
                        <Edit3 size={13} />
                      </button>

                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteCategory(cat.id, cat.name);
                        }}
                        title="حذف / إخفاء هذه الاستمارة"
                        style={{
                          background: 'rgba(239, 68, 68, 0.3)',
                          border: '1px solid rgba(239, 68, 68, 0.6)',
                          color: '#fca5a5',
                          borderRadius: '8px',
                          width: '28px',
                          height: '28px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          cursor: 'pointer'
                        }}
                      >
                        <Trash2 size={13} />
                      </button>
                    </div>
                  </div>

                  {/* Body Content */}
                  <div style={{ padding: '14px 16px', flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                    <p style={{
                      fontSize: '0.84rem',
                      color: '#cbd5e1',
                      lineHeight: '1.5',
                      marginBottom: '12px',
                      minHeight: '34px'
                    }}>
                      {cat.desc}
                    </p>

                    {/* QR Code Collapsible Drawer */}
                    {isExpanded && (
                      <div style={{
                        background: 'rgba(15, 23, 42, 0.75)',
                        backdropFilter: 'blur(16px)',
                        borderRadius: '16px',
                        padding: '12px 10px',
                        border: '1px solid rgba(255, 255, 255, 0.1)',
                        marginBottom: '12px',
                        textAlign: 'center',
                        boxShadow: 'inset 0 2px 8px rgba(0,0,0,0.2)'
                      }}>
                        {/* High Quality QR Frame */}
                        <div style={{
                          padding: '8px',
                          background: '#ffffff',
                          borderRadius: '14px',
                          display: 'inline-block',
                          boxShadow: '0 8px 24px rgba(0,0,0,0.35)',
                          marginBottom: '6px'
                        }}>
                          <QRCodeSVG 
                            id={`qr-${cat.id}`} 
                            value={applyUrl} 
                            size={140} 
                            level="H" 
                            includeMargin={false} 
                          />
                        </div>

                        <div style={{
                          fontSize: '0.74rem',
                          color: '#94a3b8',
                          fontWeight: 600,
                          marginBottom: '10px'
                        }}>
                          امسح الرمز بكاميرا الجوال للتقديم المباشر 📲
                        </div>

                        {/* Interactive Click-to-Copy URL Pill (Fixes Ugly Text Wrapping) */}
                        <div 
                          onClick={() => handleCopyLink(cat.id)}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            gap: '8px',
                            marginBottom: '14px',
                            padding: '8px 12px',
                            background: 'rgba(255, 255, 255, 0.05)',
                            border: '1px solid rgba(255, 255, 255, 0.12)',
                            borderRadius: '12px',
                            cursor: 'pointer',
                            transition: 'all 0.2s',
                          }}
                          title="اضغط لنسخ الرابط المباشر"
                        >
                          <div style={{ display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0, flex: 1 }}>
                            <Globe size={14} color="#38bdf8" style={{ flexShrink: 0 }} />
                            <span style={{
                              fontSize: '0.75rem',
                              color: '#cbd5e1',
                              direction: 'ltr',
                              whiteSpace: 'nowrap',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                              fontFamily: 'monospace'
                            }}>
                              {applyUrl}
                            </span>
                          </div>

                          <span style={{
                            fontSize: '0.75rem',
                            fontWeight: 800,
                            color: copiedId === cat.id ? '#34d399' : '#38bdf8',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '4px',
                            flexShrink: 0,
                            background: copiedId === cat.id ? 'rgba(52, 211, 153, 0.15)' : 'rgba(56, 189, 248, 0.15)',
                            padding: '3px 8px',
                            borderRadius: '8px',
                            border: copiedId === cat.id ? '1px solid rgba(52, 211, 153, 0.3)' : '1px solid rgba(56, 189, 248, 0.3)'
                          }}>
                            {copiedId === cat.id ? <><Check size={12} /> تم النسخ!</> : <><Copy size={12} /> نسخ</>}
                          </span>
                        </div>

                        {/* QR Utility Buttons */}
                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                          <button
                            onClick={() => handleCopyLink(cat.id)}
                            style={{
                              flex: 1,
                              padding: '9px 12px',
                              borderRadius: '11px',
                              border: '1px solid rgba(255, 255, 255, 0.15)',
                              background: copiedId === cat.id ? '#059669' : 'rgba(255, 255, 255, 0.08)',
                              color: 'white',
                              cursor: 'pointer',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              gap: '6px',
                              fontSize: '0.82rem',
                              fontWeight: 700,
                              fontFamily: 'Tajawal',
                              transition: 'all 0.2s'
                            }}
                          >
                            {copiedId === cat.id ? <><Check size={14} /> تم النسخ!</> : <><Copy size={14} /> نسخ الرابط</>}
                          </button>

                          <button
                            onClick={() => handleDownloadQR(cat.id, cat.name)}
                            style={{
                              flex: 1,
                              padding: '9px 12px',
                              borderRadius: '11px',
                              border: '1px solid rgba(56, 189, 248, 0.4)',
                              background: 'rgba(56, 189, 248, 0.12)',
                              color: '#38bdf8',
                              cursor: 'pointer',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              gap: '6px',
                              fontSize: '0.82rem',
                              fontWeight: 700,
                              fontFamily: 'Tajawal',
                              transition: 'all 0.2s'
                            }}
                          >
                            <Download size={14} />
                            تنزيل QR
                          </button>
                        </div>

                        {/* Radiant Gold Full Branded Card Button */}
                        <button
                          onClick={() => handleDownloadFullCard(cat.id, cat.name)}
                          style={{
                            width: '100%',
                            marginTop: '8px',
                            padding: '8px 12px',
                            borderRadius: '10px',
                            border: 'none',
                            background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                            color: '#0f172a',
                            cursor: 'pointer',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: '6px',
                            fontSize: '0.82rem',
                            fontWeight: 900,
                            fontFamily: 'Tajawal',
                            transition: 'all 0.25s ease',
                            boxShadow: '0 3px 12px rgba(245, 158, 11, 0.3)'
                          }}
                          onMouseOver={(e) => {
                            e.currentTarget.style.filter = 'brightness(1.08)';
                            e.currentTarget.style.transform = 'scale(1.01)';
                          }}
                          onMouseOut={(e) => {
                            e.currentTarget.style.filter = 'none';
                            e.currentTarget.style.transform = 'scale(1)';
                          }}
                        >
                          <Download size={14} />
                          تحميل البطاقة كصورة (PNG جاهزة للإرسال)
                        </button>
                      </div>
                    )}

                    {/* Primary Card Actions */}
                    <div style={{ display: 'flex', gap: '8px', marginTop: 'auto' }}>
                      <Link
                        href={`/apply/${cat.id}`}
                        style={{
                          flex: 1,
                          padding: '10px 14px',
                          borderRadius: '12px',
                          background: 'linear-gradient(135deg, #1d4ed8 0%, #2563eb 100%)',
                          color: 'white',
                          textDecoration: 'none',
                          fontWeight: 800,
                          fontSize: '0.88rem',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          gap: '6px',
                          boxShadow: '0 4px 14px rgba(37, 99, 235, 0.3)',
                          border: '1px solid rgba(255, 255, 255, 0.15)',
                          transition: 'all 0.2s ease'
                        }}
                        onMouseOver={(e) => {
                          e.currentTarget.style.filter = 'brightness(1.1)';
                          e.currentTarget.style.boxShadow = '0 6px 18px rgba(37, 99, 235, 0.45)';
                        }}
                        onMouseOut={(e) => {
                          e.currentTarget.style.filter = 'none';
                          e.currentTarget.style.boxShadow = '0 4px 14px rgba(37, 99, 235, 0.3)';
                        }}
                      >
                        تقديم الطلب الآن ✨
                      </Link>

                      <button
                        onClick={() => toggleQR(cat.id)}
                        style={{
                          padding: '10px 14px',
                          borderRadius: '12px',
                          border: isExpanded ? '1px solid rgba(56, 189, 248, 0.35)' : '1px solid rgba(255, 255, 255, 0.12)',
                          background: isExpanded ? 'rgba(56, 189, 248, 0.12)' : 'rgba(255, 255, 255, 0.06)',
                          color: isExpanded ? '#38bdf8' : '#cbd5e1',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          gap: '6px',
                          fontSize: '0.82rem',
                          fontWeight: 700,
                          fontFamily: 'Tajawal',
                          transition: 'all 0.2s ease'
                        }}
                        title={isExpanded ? 'إخفاء رمز QR' : 'عرض رمز QR للتقديم عبر الهاتف'}
                      >
                        <QrCode size={16} />
                        {isExpanded ? 'إخفاء' : 'QR'}
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* ══════════════════════════════════════════════════════════
            BOTTOM BANNER
        ══════════════════════════════════════════════════════════ */}
        <div style={{
          marginTop: '50px',
          background: 'linear-gradient(135deg, rgba(30, 58, 138, 0.6) 0%, rgba(15, 23, 42, 0.8) 100%)',
          borderRadius: '24px',
          padding: '30px 25px',
          border: '1px solid rgba(255, 215, 0, 0.3)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: '20px',
          flexWrap: 'wrap'
        }}>
          <div>
            <h3 style={{ fontSize: '1.3rem', fontWeight: 800, color: '#ffffff', marginBottom: '6px' }}>
              هل ترغب في طباعة جميع رموز الـ QR للتعليق في الأقسام؟
            </h3>
            <p style={{ color: '#94a3b8', fontSize: '0.9rem', margin: 0 }}>
              تم تجهيز صفحة طباعة قياسية A4 تحتوي على كافة رموز QR لجميع البرامج والنماذج الـ 18 لتسهيل التقديم السريع.
            </p>
          </div>

          <Link
            href="/print-qr"
            style={{
              padding: '14px 26px',
              borderRadius: '14px',
              background: 'linear-gradient(135deg, #ffd700 0%, #d97706 100%)',
              color: '#0f172a',
              textDecoration: 'none',
              fontWeight: 900,
              fontSize: '0.95rem',
              display: 'inline-flex',
              alignItems: 'center',
              gap: '10px',
              boxShadow: '0 8px 25px rgba(255, 215, 0, 0.4)',
              transition: 'all 0.3s'
            }}
          >
            <Printer size={18} />
            فتح صفحة طباعة الرموز (A4)
          </Link>
        </div>

        {/* Footer */}
        <div style={{
          textAlign: 'center',
          marginTop: '40px',
          color: 'rgba(255,255,255,0.5)',
          fontSize: '0.85rem'
        }}>
          مستشفى الهلال الأحمر التخصصي — وحدة التطوير والتدريب © {new Date().getFullYear()}
        </div>

        {/* ══════════════════════════════════════════════════════════
            MODAL: إضافة استمارة ورمز QR لقسم جديد
        ══════════════════════════════════════════════════════════ */}
        {showAddCategoryModal && (
          <div style={{
            position: 'fixed',
            inset: 0,
            background: 'rgba(0, 0, 0, 0.75)',
            backdropFilter: 'blur(8px)',
            zIndex: 9999,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '20px'
          }}>
            <div style={{
              background: '#0f172a',
              border: '2px solid rgba(99, 102, 241, 0.5)',
              borderRadius: '24px',
              maxWidth: '560px',
              width: '100%',
              padding: '28px',
              color: '#f8fafc',
              boxShadow: '0 25px 60px -15px rgba(0,0,0,0.8), 0 0 30px rgba(99, 102, 241, 0.3)',
              direction: 'rtl',
              fontFamily: 'Tajawal, sans-serif'
            }}>
              {/* Modal Header */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '20px' }}>
                <div>
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', padding: '4px 12px', background: 'rgba(99, 102, 241, 0.15)', borderRadius: '20px', color: '#818cf8', fontSize: '0.82rem', fontWeight: 800, marginBottom: '6px' }}>
                    <Sparkles size={14} /> {editingCatId ? 'تعديل قسم واستمارة' : 'إضافة قسم واستمارة فورية'}
                  </div>
                  <h3 style={{ fontSize: '1.35rem', fontWeight: 900, color: '#ffffff', margin: 0 }}>
                    {editingCatId ? 'تعديل الاستمارة ورمز الـ QR' : 'إضافة استمارة ورمز QR لقسم جديد'}
                  </h3>
                  <p style={{ color: '#94a3b8', fontSize: '0.85rem', marginTop: '4px', margin: 0 }}>
                    {editingCatId ? 'عدّل اسم القسم أو الشارة أو الوصف وسيتم التحديث فوراً' : 'أدخل اسم القسم وسيقوم النظام بإنشاء الاستمارة ورابط التقديم ورمز الـ QR وحفظه تلقائياً'}
                  </p>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    setShowAddCategoryModal(false);
                    setEditingCatId(null);
                    setNewDeptName('');
                    setNewDeptBadge('');
                    setNewDeptDesc('');
                  }}
                  style={{
                    background: 'rgba(255,255,255,0.08)',
                    border: 'none',
                    color: '#94a3b8',
                    width: '36px',
                    height: '36px',
                    borderRadius: '50%',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                  }}
                >
                  <X size={18} />
                </button>
              </div>

              {/* Success Notification */}
              {addCategorySuccess && (
                <div style={{
                  padding: '12px 16px',
                  background: 'rgba(16, 185, 129, 0.2)',
                  border: '1px solid #10b981',
                  borderRadius: '12px',
                  color: '#34d399',
                  fontWeight: 800,
                  fontSize: '0.9rem',
                  marginBottom: '18px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '10px'
                }}>
                  <Check size={18} />
                  {addCategorySuccess}
                </div>
              )}

              {/* Form */}
              <form onSubmit={handleCreateCategory}>
                {/* 1. اسم القسم */}
                <div style={{ marginBottom: '16px' }}>
                  <label style={{ display: 'block', fontWeight: 800, fontSize: '0.9rem', color: '#e2e8f0', marginBottom: '6px' }}>
                    اسم القسم / التخصص <span style={{ color: '#ef4444' }}>*</span>
                  </label>
                  <input
                    type="text"
                    required
                    placeholder="مثال: مدربي تخدير، أو عناية حثيثة، أو هندسة طبية..."
                    value={newDeptName}
                    onChange={(e) => setNewDeptName(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '12px 14px',
                      background: 'rgba(255,255,255,0.05)',
                      border: '1.5px solid rgba(255,255,255,0.15)',
                      borderRadius: '12px',
                      color: 'white',
                      fontSize: '0.95rem',
                      fontFamily: 'Tajawal',
                      outline: 'none',
                      boxSizing: 'border-box'
                    }}
                  />
                </div>

                {/* 2. نوع وتصنيف القسم */}
                <div style={{ marginBottom: '16px' }}>
                  <label style={{ display: 'block', fontWeight: 800, fontSize: '0.9rem', color: '#e2e8f0', marginBottom: '6px' }}>
                    المجموعة / التصنيف
                  </label>
                  <select
                    value={newDeptGroup}
                    onChange={(e: any) => setNewDeptGroup(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '12px 14px',
                      background: '#1e293b',
                      border: '1.5px solid rgba(255,255,255,0.15)',
                      borderRadius: '12px',
                      color: 'white',
                      fontSize: '0.92rem',
                      fontFamily: 'Tajawal',
                      outline: 'none',
                      boxSizing: 'border-box'
                    }}
                  >
                    <option value="universities">🎓 تدريب الجامعات والمشرفين (مدرب سريري / جامعات شريكة)</option>
                    <option value="allied">🚑 الإسعاف والتأهيل والأشعة (مهن طبية مساندة)</option>
                    <option value="nursing">💉 التمريض والتدريب السريري</option>
                    <option value="internship">🩺 أطباء الامتياز والطب البشري</option>
                    <option value="admin">💼 الإدارة والمالية والمطبخ</option>
                    <option value="volunteer">🤝 التطوع والخدمات المجتمعية</option>
                  </select>
                </div>

                {/* 3. شارة القسم */}
                <div style={{ marginBottom: '16px' }}>
                  <label style={{ display: 'block', fontWeight: 800, fontSize: '0.9rem', color: '#e2e8f0', marginBottom: '6px' }}>
                    الشارة المكتوبة على البطاقة (Badge)
                  </label>
                  <input
                    type="text"
                    placeholder={newDeptGroup === 'universities' ? 'مثال: مدرب سريري' : 'مثال: تدريب عملي'}
                    value={newDeptBadge}
                    onChange={(e) => setNewDeptBadge(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '12px 14px',
                      background: 'rgba(255,255,255,0.05)',
                      border: '1.5px solid rgba(255,255,255,0.15)',
                      borderRadius: '12px',
                      color: 'white',
                      fontSize: '0.95rem',
                      fontFamily: 'Tajawal',
                      outline: 'none',
                      boxSizing: 'border-box'
                    }}
                  />
                </div>

                {/* 4. وصف مختصر */}
                <div style={{ marginBottom: '22px' }}>
                  <label style={{ display: 'block', fontWeight: 800, fontSize: '0.9rem', color: '#e2e8f0', marginBottom: '6px' }}>
                    وصف مختصر للبرنامج / التقديم
                  </label>
                  <textarea
                    rows={2}
                    placeholder="خاص بالتقديم والتدريب للكوادر والطلبة داخل أقسام المستشفى..."
                    value={newDeptDesc}
                    onChange={(e) => setNewDeptDesc(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '10px 14px',
                      background: 'rgba(255,255,255,0.05)',
                      border: '1.5px solid rgba(255,255,255,0.15)',
                      borderRadius: '12px',
                      color: 'white',
                      fontSize: '0.9rem',
                      fontFamily: 'Tajawal',
                      outline: 'none',
                      resize: 'none',
                      boxSizing: 'border-box'
                    }}
                  />
                </div>

                {/* Live Preview Info */}
                {newDeptName.trim() && (
                  <div style={{
                    padding: '12px',
                    background: 'rgba(99, 102, 241, 0.1)',
                    borderRadius: '12px',
                    border: '1px dashed rgba(99, 102, 241, 0.4)',
                    marginBottom: '20px',
                    fontSize: '0.85rem',
                    color: '#c7d2fe'
                  }}>
                    <div>🔗 <strong>رابط الاستمارة المباشر:</strong> {baseUrl}/apply/{newDeptName.trim().toLowerCase().replace(/[^\w\u0621-\u064A\s-]/g, '').replace(/\s+/g, '-')}</div>
                    <div style={{ marginTop: '4px' }}>📱 <strong>رمز QR:</strong> سيتم توليد الرمز تلقائياً فوراً وإتاحته للتحميل والمسح.</div>
                  </div>
                )}

                {/* Buttons */}
                <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
                  <button
                    type="button"
                    onClick={() => {
                      setShowAddCategoryModal(false);
                      setEditingCatId(null);
                      setNewDeptName('');
                      setNewDeptBadge('');
                      setNewDeptDesc('');
                    }}
                    style={{
                      padding: '10px 20px',
                      background: 'rgba(255,255,255,0.1)',
                      color: '#cbd5e1',
                      borderRadius: '12px',
                      border: '1px solid rgba(255,255,255,0.15)',
                      fontWeight: 700,
                      cursor: 'pointer',
                      fontFamily: 'Tajawal'
                    }}
                  >
                    إلغاء
                  </button>
                  <button
                    type="submit"
                    disabled={isCreatingCategory}
                    style={{
                      padding: '10px 24px',
                      background: 'linear-gradient(135deg, #6366f1 0%, #4338ca 100%)',
                      color: 'white',
                      borderRadius: '12px',
                      border: 'none',
                      fontWeight: 800,
                      cursor: isCreatingCategory ? 'wait' : 'pointer',
                      boxShadow: '0 4px 15px rgba(99, 102, 241, 0.4)',
                      fontFamily: 'Tajawal',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '8px'
                    }}
                  >
                    {isCreatingCategory ? 'جاري الحفظ...' : (editingCatId ? '✨ حفظ التعديلات فوراً' : '✨ إنشاء الاستمارة ورمز الـ QR فوراً')}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

      </div>
    </div>
  );
}
