"use client";

import { useState, useEffect, useMemo } from "react";
import Link from "next/link";
import { QRCodeSVG } from "qrcode.react";
import { 
  ArrowRight, 
  Printer, 
  Download, 
  Check, 
  Copy, 
  Sparkles, 
  QrCode, 
  GraduationCap, 
  Search, 
  ExternalLink, 
  PlusCircle, 
  Edit3, 
  Trash2, 
  RotateCcw, 
  X, 
  Palette, 
  Smile,
  Layers
} from "lucide-react";

export interface TrainerCategory {
  id: string;
  name: string;
  specialty?: string;
  color: string;
  badge: string;
  desc: string;
  icon: string;
  isCustom?: boolean;
}

const COLOR_PRESETS = [
  { label: "أزرق طبي", val: "#0284c7" },
  { label: "نيلي ملكي", val: "#4338ca" },
  { label: "بنفسجي", val: "#7c3aed" },
  { label: "زمردي", val: "#059669" },
  { label: "كهرماني", val: "#d97706" },
  { label: "سماوي", val: "#0891b2" },
  { label: "برتقالي", val: "#ea580c" },
  { label: "أخضر", val: "#16a34a" },
  { label: "أزرق حبري", val: "#4f46e5" },
  { label: "ياقوتي", val: "#be123c" },
];

const EMOJI_PRESETS = [
  "🩺", "👨‍⚕️", "☢️", "🏃‍♂️", "🔬", "💊", "🤲", "🥗", "⚙️", "🎓", "💉", "🧬", "🩹", "📋", "🏥", "🫀", "🧠", "👶"
];

const defaultTrainers: TrainerCategory[] = [
  {
    id: "university-nursing-trainers",
    name: "تدريب طلاب التمريض في الجامعات",
    specialty: "تمريض سريري جامعي",
    color: "#0284c7",
    badge: "مدرب سريري — تمريض",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة التمريض في الجامعات الشريكة داخل أقسام المستشفى",
    icon: "🩺"
  },
  {
    id: "contracted-doctors",
    name: "الأطباء المتعاقدون مع الجامعات الشريكة",
    specialty: "أطباء استشاريون وأخصائيون متعاقدون",
    color: "#4338ca",
    badge: "أطباء متعاقدون مع الجامعات",
    desc: "خاص بالأطباء المشرفين والمتعاقدين مع الجامعات لتدريب الطلبة في الأقسام والعيادات التخصصية",
    icon: "👨‍⚕️"
  },
  {
    id: "radiology-trainers",
    name: "مدربو الأشعة والتصوير الطبي",
    specialty: "أشعة وتصوير طبي سريري",
    color: "#7c3aed",
    badge: "مدرب سريري — أشعة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة الأشعة والتصوير الطبي من الجامعات الشريكة",
    icon: "☢️"
  },
  {
    id: "physical-therapy-trainers",
    name: "مدربو العلاج الطبيعي والتأهيل الحركي",
    specialty: "علاج طبيعي وتأهيل سريري",
    color: "#059669",
    badge: "مدرب سريري — علاج طبيعي",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة العلاج الطبيعي والتأهيل الحركي في أقسام المستشفى",
    icon: "🏃‍♂️"
  },
  {
    id: "lab-trainers",
    name: "مدربو المختبرات والتحاليل الطبية",
    specialty: "علوم طبية مخبرية وتحاليل سريرية",
    color: "#d97706",
    badge: "مدرب سريري — مختبرات",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة العلوم الطبية المخبرية في أقسام المستشفى ومختبراته",
    icon: "🔬"
  },
  {
    id: "pharmacy-trainers",
    name: "مدربو الصيدلة السريرية",
    specialty: "صيدلة سريرية ومستشفيات",
    color: "#0891b2",
    badge: "مدرب سريري — صيدلة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة كليات الصيدلة السريرية داخل أقسام المستشفى والصيدلية",
    icon: "💊"
  },
  {
    id: "occupational-therapy-trainers",
    name: "مدربو العلاج الوظيفي",
    specialty: "علاج وتأهيل وظيفي سريري",
    color: "#ea580c",
    badge: "مدرب سريري — علاج وظيفي",
    desc: "خاص بالمدربين والمشرفين لتدريب وتأهيل اختصاصيي العلاج الوظيفي للجامعات الشريكة",
    icon: "🤲"
  },
  {
    id: "nutrition-trainers",
    name: "مدربو التغذية السريرية والعلاجية",
    specialty: "تغذية سريرية وعلاجية",
    color: "#16a34a",
    badge: "مدرب سريري — تغذية",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة التغذية السريرية والعلاجية والحميات داخل المستشفى",
    icon: "🥗"
  },
  {
    id: "medical-engineering-trainers",
    name: "مدربو الهندسة الطبية والأجهزة الحيوية",
    specialty: "هندسة أجهزة طبية وسريرية",
    color: "#4f46e5",
    badge: "مدرب سريري — هندسة طبية",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة الهندسة الطبية والأجهزة الحيوية في المستشفى",
    icon: "⚙️"
  }
];

const STORAGE_KEY = "crescent_trainers_list_v3";

export default function TrainersQRPrintPage() {
  const [trainers, setTrainers] = useState<TrainerCategory[]>(defaultTrainers);
  const [searchQuery, setSearchQuery] = useState("");
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [printDate, setPrintDate] = useState("");

  // Modal State for Add & Edit
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingTrainerId, setEditingTrainerId] = useState<string | null>(null);
  const [formName, setFormName] = useState("");
  const [formBadge, setFormBadge] = useState("");
  const [formDesc, setFormDesc] = useState("");
  const [formColor, setFormColor] = useState("#0284c7");
  const [formIcon, setFormIcon] = useState("🩺");
  const [formCustomId, setFormCustomId] = useState("");
  const [saveSuccessMsg, setSaveSuccessMsg] = useState<string | null>(null);

  // Initialize and load saved trainers from storage and API
  useEffect(() => {
    const today = new Date().toLocaleDateString("ar-EG", {
      year: "numeric",
      month: "long",
      day: "numeric"
    });
    setPrintDate(today);

    // 1. Try loading from localStorage first
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const parsed = JSON.parse(saved);
        if (Array.isArray(parsed) && parsed.length > 0) {
          setTrainers(parsed);
        }
      }
    } catch {}

    // 2. Load from /api/categories for any extra departments
    const loadApi = async () => {
      try {
        const res = await fetch("/api/categories");
        if (res.ok) {
          const data = await res.json();
          const cats = data.categories || [];
          if (Array.isArray(cats) && cats.length > 0) {
            const apiTrainers = cats.filter((c: any) => 
              c.group === 'universities' || 
              c.id.includes('trainer') || 
              (c.name && (c.name.includes('مدرب') || c.name.includes('جامع')))
            );

            if (apiTrainers.length > 0) {
              setTrainers(prev => {
                const map = new Map<string, TrainerCategory>();
                prev.forEach(t => map.set(t.id, t));
                apiTrainers.forEach((c: any) => {
                  if (!map.has(c.id)) {
                    map.set(c.id, {
                      id: c.id,
                      name: c.name,
                      specialty: c.badge || "كادر التدريب الجامعي",
                      color: c.color || "#0284c7",
                      badge: c.badge || "مدرب معتمد",
                      desc: c.desc || "نموذج اعتماد وتدريب للجامعات الشريكة",
                      icon: c.icon || "🎓",
                      isCustom: true
                    });
                  }
                });
                const combined = Array.from(map.values());
                try { localStorage.setItem(STORAGE_KEY, JSON.stringify(combined)); } catch {}
                return combined;
              });
            }
          }
        }
      } catch {}
    };
    loadApi();
  }, []);

  // Save changes helper
  const saveTrainers = (updated: TrainerCategory[]) => {
    setTrainers(updated);
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
    } catch {}
  };

  // Filtered trainers
  const filteredTrainers = useMemo(() => {
    if (!searchQuery.trim()) return trainers;
    const q = searchQuery.toLowerCase().trim();
    return trainers.filter(t => 
      t.name.toLowerCase().includes(q) ||
      (t.specialty && t.specialty.toLowerCase().includes(q)) ||
      t.desc.toLowerCase().includes(q) ||
      t.badge.toLowerCase().includes(q)
    );
  }, [trainers, searchQuery]);

  // Production domain for QR codes
  const getTrainerUrl = (id: string) => `https://crescent.livestimes.com/apply/${id}`;

  const handleCopy = (id: string) => {
    const url = getTrainerUrl(id);
    navigator.clipboard.writeText(url);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleDownloadSingleQR = (id: string, name: string) => {
    const svg = document.getElementById(`trainer-qr-${id}`);
    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_مدرب_${name.replace(/[\/\s]/g, "_")}.png`;
        a.href = canvas.toDataURL("image/png");
        a.click();
      }
    };
    img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData)));
  };

  // Open Modal for New Trainer
  const handleOpenAddModal = () => {
    setEditingTrainerId(null);
    setFormName("");
    setFormBadge("مدرب سريري");
    setFormDesc("");
    setFormColor("#0284c7");
    setFormIcon("🩺");
    setFormCustomId("");
    setSaveSuccessMsg(null);
    setIsModalOpen(true);
  };

  // Open Modal for Editing Existing Trainer
  const handleOpenEditModal = (t: TrainerCategory) => {
    setEditingTrainerId(t.id);
    setFormName(t.name);
    setFormBadge(t.badge);
    setFormDesc(t.desc);
    setFormColor(t.color || "#0284c7");
    setFormIcon(t.icon || "🩺");
    setFormCustomId(t.id);
    setSaveSuccessMsg(null);
    setIsModalOpen(true);
  };

  // Delete / Remove Trainer Card
  const handleDeleteTrainer = async (id: string, name: string) => {
    if (!confirm(`هل أنت متأكد من حذف أو إخفاء بطاقة (${name}) من قائمة الطباعة؟`)) {
      return;
    }
    const updated = trainers.filter(t => t.id !== id);
    saveTrainers(updated);

    // Also inform API
    try {
      await fetch("/api/categories", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id })
      });
    } catch {}
  };

  // Reset to Defaults
  const handleResetDefaults = () => {
    if (confirm("هل تريد إعادة ضبط القائمة إلى التخصصات الـ 9 الأصلية المعتمدة؟")) {
      saveTrainers(defaultTrainers);
      try {
        localStorage.removeItem(STORAGE_KEY);
      } catch {}
    }
  };

  // Save Modal Form (Create or Edit)
  const handleSaveModal = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formName.trim()) {
      alert("يرجى إدخال اسم المدرب أو التخصص");
      return;
    }

    const trimmedName = formName.trim();
    let finalId = editingTrainerId;

    if (!finalId) {
      finalId = formCustomId.trim()
        ? formCustomId.trim().toLowerCase().replace(/[^\w-]/g, "")
        : trimmedName.toLowerCase().replace(/[^\w\u0621-\u064A\s-]/g, "").replace(/\s+/g, "-");
      
      if (!finalId) finalId = `trainer-${Date.now()}`;
    }

    const updatedItem: TrainerCategory = {
      id: finalId,
      name: trimmedName,
      specialty: formBadge.trim() || "مدرب سريري",
      badge: formBadge.trim() || "مدرب سريري",
      desc: formDesc.trim() || `خاص بالمدربين والمشرفين لتدريب طلبة ${trimmedName} لدى المستشفى والجامعات الشريكة`,
      color: formColor,
      icon: formIcon,
      isCustom: true
    };

    let newTrainersList: TrainerCategory[] = [];
    if (editingTrainerId) {
      // Edit existing
      newTrainersList = trainers.map(t => t.id === editingTrainerId ? updatedItem : t);
    } else {
      // Add new
      newTrainersList = [updatedItem, ...trainers.filter(t => t.id !== finalId)];
    }

    saveTrainers(newTrainersList);

    // Sync with backend API
    try {
      await fetch("/api/categories", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: finalId,
          name: trimmedName,
          group: "universities",
          groupName: "كادر الجامعات والمدربين",
          badge: updatedItem.badge,
          desc: updatedItem.desc,
          color: formColor,
          icon: formIcon
        })
      });
    } catch {}

    setSaveSuccessMsg(editingTrainerId ? "تم تعديل البطاقة بنجاح!" : "تمت إضافة البطاقة ورمز QR بنجاح!");
    setTimeout(() => {
      setIsModalOpen(false);
      setSaveSuccessMsg(null);
    }, 1200);
  };

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

  return (
    <div className="trainers-page-wrapper" dir="rtl" style={{
      minHeight: "100vh",
      background: "linear-gradient(135deg, #090e17 0%, #0f172a 50%, #1e293b 100%)",
      color: "#f8fafc",
      fontFamily: "Tajawal, sans-serif",
      padding: "16px 14px 80px"
    }}>
      <style jsx global>{`
        @media print {
          @page {
            size: A4;
            margin: 10mm 8mm;
          }
          body {
            background: #ffffff !important;
            color: #000000 !important;
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
          }
          .trainers-page-wrapper {
            background: #ffffff !important;
            color: #000000 !important;
            padding: 0 !important;
          }
          .no-print {
            display: none !important;
          }
          .print-header {
            display: flex !important;
            border-bottom: 2px solid #0f172a !important;
            padding-bottom: 12px !important;
            margin-bottom: 16px !important;
          }
          .trainer-card {
            background: #ffffff !important;
            border: 1.5px solid #cbd5e1 !important;
            color: #0f172a !important;
            box-shadow: none !important;
            page-break-inside: avoid !important;
            break-inside: avoid !important;
            margin-bottom: 12px !important;
          }
          .trainer-banner {
            color: #ffffff !important;
            print-color-adjust: exact !important;
            -webkit-print-color-adjust: exact !important;
          }
          .print-only-footer {
            display: block !important;
          }
        }
        @media screen {
          .print-header {
            display: none;
          }
          .print-only-footer {
            display: none;
          }
        }
      `}</style>

      <div style={{ maxWidth: "1400px", margin: "0 auto" }}>

        {/* ══════════════════════════════════════════════════════════
            OFFICIAL PRINT HEADER (Shown ONLY when printing to paper)
        ══════════════════════════════════════════════════════════ */}
        <div className="print-header" style={{
          alignItems: "center",
          justifyContent: "space-between",
          gap: "16px",
          width: "100%",
          direction: "rtl"
        }}>
          {/* Right: Hospital Logo & Name */}
          <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
            <img 
              src="/prcs-logo.png" 
              alt="شعار الهلال الأحمر الفلسطيني" 
              style={{ width: "65px", height: "65px", objectFit: "contain" }}
              onError={(e) => { (e.target as HTMLElement).style.display = 'none'; }}
            />
            <div>
              <div style={{ fontSize: "1.1rem", fontWeight: 900, color: "#b91c1c" }}>
                جمعية الهلال الأحمر الفلسطيني
              </div>
              <div style={{ fontSize: "1rem", fontWeight: 800, color: "#0f172a" }}>
                مستشفى الهلال الأحمر التخصصي — الخليل
              </div>
              <div style={{ fontSize: "0.8rem", color: "#64748b", fontWeight: 600 }}>
                Palestinian Red Crescent Society Specialized Hospital
              </div>
            </div>
          </div>

          {/* Center: Document Title */}
          <div style={{ textAlign: "center" }}>
            <div style={{
              display: "inline-block",
              background: "#fef3c7",
              border: "1.5px solid #d97706",
              padding: "4px 14px",
              borderRadius: "20px",
              fontSize: "0.85rem",
              fontWeight: 900,
              color: "#92400e",
              marginBottom: "4px"
            }}>
              دليل ورموز الاستجابة السريعة المعتمدة (QR Codes)
            </div>
            <div style={{ fontSize: "1.05rem", fontWeight: 900, color: "#0f172a" }}>
              كادر المدربين والمشرفين السريريين والأطباء المتعاقدون
            </div>
            <div style={{ fontSize: "0.75rem", color: "#64748b" }}>
              تاريخ الطباعة: {printDate}
            </div>
          </div>

          {/* Left: Supervisor Info */}
          <div style={{ display: "flex", alignItems: "center", gap: "10px", textAlign: "left" }}>
            <img 
              src="/supervisor.png" 
              alt="أ. نسرين عابدين" 
              style={{ 
                width: "55px", 
                height: "55px", 
                borderRadius: "50%", 
                objectFit: "cover",
                border: "2px solid #b91c1c"
              }}
            />
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: "0.78rem", color: "#b91c1c", fontWeight: 800 }}>
                مديرة وحدة التطوير والتدريب
              </div>
              <div style={{ fontSize: "0.92rem", fontWeight: 900, color: "#0f172a" }}>
                أ. نسرين عابدين (أم خالد)
              </div>
              <div style={{ fontSize: "0.72rem", color: "#64748b" }}>
                التعليم الطبي والجامعات
              </div>
            </div>
          </div>
        </div>

        {/* ══════════════════════════════════════════════════════════
            ON-SCREEN CONTROL BAR & HEADER (Hidden on print)
        ══════════════════════════════════════════════════════════ */}
        <div className="no-print" style={{
          background: "rgba(255,255,255,0.04)",
          backdropFilter: "blur(15px)",
          padding: "12px 18px",
          borderRadius: "16px",
          border: "1px solid rgba(255,255,255,0.1)",
          marginBottom: "16px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: "12px"
        }}>
          {/* Navigation Links */}
          <div style={{ display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" }}>
            <Link
              href="/recruitment"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "6px",
                padding: "8px 14px",
                background: "rgba(255,255,255,0.08)",
                color: "#e2e8f0",
                borderRadius: "10px",
                textDecoration: "none",
                fontWeight: 800,
                fontSize: "0.85rem",
                border: "1px solid rgba(255,255,255,0.15)"
              }}
            >
              <ArrowRight size={15} />
              بوابة التقديم العامة
            </Link>

            <Link
              href="/"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "6px",
                padding: "8px 14px",
                background: "rgba(16, 185, 129, 0.15)",
                color: "#6ee7b7",
                borderRadius: "10px",
                textDecoration: "none",
                fontWeight: 800,
                fontSize: "0.85rem",
                border: "1px solid rgba(16, 185, 129, 0.3)"
              }}
            >
              الرئيسية
            </Link>

            <Link
              href="/print-qr"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "6px",
                padding: "8px 14px",
                background: "rgba(56, 189, 248, 0.12)",
                color: "#38bdf8",
                borderRadius: "10px",
                textDecoration: "none",
                fontWeight: 700,
                fontSize: "0.85rem",
                border: "1px solid rgba(56, 189, 248, 0.25)"
              }}
            >
              <QrCode size={15} />
              طباعة كافة الأقسام (25+)
            </Link>
          </div>

          {/* Action Buttons: Add New Category & Master Print */}
          <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap" }}>
            {/* ➕ ADD NEW CATEGORY BUTTON (Requested by user) */}
            <button
              onClick={handleOpenAddModal}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "8px",
                padding: "10px 20px",
                background: "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)",
                color: "#ffffff",
                borderRadius: "12px",
                border: "1.5px solid rgba(255,255,255,0.3)",
                fontWeight: 900,
                fontSize: "0.9rem",
                cursor: "pointer",
                boxShadow: "0 4px 18px rgba(99, 102, 241, 0.45)",
                fontFamily: "Tajawal",
                transition: "all 0.2s"
              }}
            >
              <PlusCircle size={18} />
              ➕ إضافة استمارة ورمز QR لقسم جديد
            </button>

            {/* Print Button */}
            <button
              onClick={handlePrint}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "8px",
                padding: "10px 22px",
                borderRadius: "12px",
                border: "none",
                background: "linear-gradient(135deg, #ffd700 0%, #f59e0b 100%)",
                color: "#0f172a",
                fontWeight: 900,
                fontSize: "0.95rem",
                cursor: "pointer",
                boxShadow: "0 4px 18px rgba(245, 158, 11, 0.4)",
                fontFamily: "Tajawal",
                transition: "all 0.2s"
              }}
            >
              <Printer size={18} />
              🖨️ طباعة الصفحة المخصصة (A4)
            </button>

            {/* Reset Defaults button */}
            <button
              onClick={handleResetDefaults}
              title="إعادة التخصصات الأصلية"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "6px",
                padding: "8px 12px",
                background: "rgba(255,255,255,0.06)",
                color: "#94a3b8",
                borderRadius: "10px",
                border: "1px solid rgba(255,255,255,0.1)",
                fontWeight: 700,
                fontSize: "0.8rem",
                cursor: "pointer",
                fontFamily: "Tajawal"
              }}
            >
              <RotateCcw size={14} />
              استعادة الأصل
            </button>
          </div>
        </div>

        {/* ══════════════════════════════════════════════════════════
            HERO INTRO SECTION (On Screen)
        ══════════════════════════════════════════════════════════ */}
        <div className="no-print" style={{
          textAlign: "center",
          padding: "18px 20px 22px",
          background: "radial-gradient(ellipse at center, rgba(30, 58, 138, 0.45) 0%, rgba(15, 23, 42, 0.8) 70%)",
          borderRadius: "20px",
          border: "1.5px solid rgba(255, 215, 0, 0.3)",
          marginBottom: "16px",
          boxShadow: "0 8px 30px rgba(0,0,0,0.35)"
        }}>
          <div style={{
            display: "inline-flex",
            alignItems: "center",
            gap: "8px",
            padding: "5px 16px",
            background: "rgba(255, 215, 0, 0.15)",
            borderRadius: "30px",
            border: "1.5px solid rgba(255, 215, 0, 0.4)",
            color: "#ffd700",
            fontSize: "0.85rem",
            fontWeight: 800,
            marginBottom: "10px"
          }}>
            <Sparkles size={16} />
            لوحة تفاعلية بالكامل: يمكنك إضافة أي قسم، وتعديل وتخصيص أي بطاقة بحرية تامة!
          </div>

          <h1 style={{
            fontSize: "1.85rem",
            fontWeight: 900,
            color: "#ffffff",
            margin: "0 0 8px 0",
            textShadow: "0 2px 10px rgba(0,0,0,0.5)"
          }}>
            رموز الـ QR المعتمدة للمدربين والجامعات (قابلة للإضافة والتعديل)
          </h1>

          <p style={{
            fontSize: "0.92rem",
            color: "#cbd5e1",
            maxWidth: "850px",
            margin: "0 auto 16px",
            lineHeight: "1.6"
          }}>
            اضغط على <strong>"➕ إضافة استمارة ورمز QR لقسم جديد"</strong> لإضافة أي تخصص تريده، أو اضغط على <strong>"تعديل ✏️"</strong> على أي بطاقة لتغيير اسمها، شارتها، لونها، أو أيقونتها في أي وقت!
          </p>

          {/* Quick Stats Pill */}
          <div style={{
            display: "inline-flex",
            alignItems: "center",
            gap: "14px",
            background: "rgba(15, 23, 42, 0.7)",
            padding: "8px 18px",
            borderRadius: "14px",
            border: "1px solid rgba(255,255,255,0.12)",
            fontSize: "0.84rem",
            color: "#e2e8f0",
            flexWrap: "wrap",
            justifyContent: "center"
          }}>
            <span>🎓 <strong>{trainers.length}</strong> تخصصات مدرجة حالياً</span>
            <span style={{ color: "rgba(255,255,255,0.2)" }}>|</span>
            <span>✏️ قابلة للتعديل والحذف والإضافة الفورية</span>
            <span style={{ color: "rgba(255,255,255,0.2)" }}>|</span>
            <span>📱 روابط مشفرة ومبرمجة للهواتف الذكية بنسبة 100%</span>
            <span style={{ color: "rgba(255,255,255,0.2)" }}>|</span>
            <span>🖨️ جاهزة للطباعة على ورق A4</span>
          </div>

          {/* Search Box */}
          <div style={{ maxWidth: "480px", margin: "14px auto 0", 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)",
                color: "white",
                fontSize: "0.88rem",
                fontFamily: "Tajawal",
                outline: "none"
              }}
            />
            {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",
                  fontSize: "0.75rem"
                }}
              >
                ✕
              </button>
            )}
          </div>
        </div>

        {/* ══════════════════════════════════════════════════════════
            TRAINERS CARDS GRID
        ══════════════════════════════════════════════════════════ */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(310px, 1fr))",
          gap: "16px",
          alignItems: "stretch"
        }}>
          {filteredTrainers.map((t) => {
            const applyUrl = getTrainerUrl(t.id);
            return (
              <div 
                key={t.id}
                className="trainer-card"
                style={{
                  background: "linear-gradient(180deg, rgba(30, 41, 59, 0.75) 0%, rgba(15, 23, 42, 0.9) 100%)",
                  backdropFilter: "blur(20px)",
                  borderRadius: "20px",
                  border: "1px solid rgba(255, 255, 255, 0.12)",
                  overflow: "hidden",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "space-between",
                  boxShadow: "0 10px 25px -5px rgba(0,0,0,0.35)",
                  transition: "all 0.25s ease",
                  position: "relative"
                }}
              >
                {/* Header Banner */}
                <div 
                  className="trainer-banner"
                  style={{
                    background: t.color,
                    padding: "14px 16px",
                    color: "white",
                    display: "flex",
                    alignItems: "center",
                    gap: "12px",
                    position: "relative",
                    overflow: "hidden"
                  }}
                >
                  <div style={{
                    width: "44px",
                    height: "44px",
                    borderRadius: "12px",
                    background: "rgba(255,255,255,0.22)",
                    backdropFilter: "blur(10px)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: "1.4rem",
                    flexShrink: 0,
                    border: "1px solid rgba(255,255,255,0.35)",
                    boxShadow: "0 4px 10px rgba(0,0,0,0.2)"
                  }}>
                    {t.icon || "🎓"}
                  </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: "12px", 
                      marginBottom: "4px",
                      border: "1px solid rgba(255,255,255,0.35)"
                    }}>
                      {t.badge}
                    </div>
                    <h3 style={{ fontSize: "1.05rem", fontWeight: 900, margin: 0, lineHeight: "1.3" }}>
                      {t.name}
                    </h3>
                  </div>

                  {/* EDIT & DELETE QUICK ACTION ICONS (Hidden on print) */}
                  <div className="no-print" style={{ display: "flex", gap: "6px", zIndex: 2 }}>
                    <button
                      onClick={() => handleOpenEditModal(t)}
                      title="تعديل بيانات هذه البطاقة"
                      style={{
                        background: "rgba(255,255,255,0.2)",
                        border: "1px solid rgba(255,255,255,0.4)",
                        color: "#ffffff",
                        borderRadius: "8px",
                        width: "30px",
                        height: "30px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        cursor: "pointer",
                        transition: "all 0.2s"
                      }}
                    >
                      <Edit3 size={14} />
                    </button>

                    <button
                      onClick={() => handleDeleteTrainer(t.id, t.name)}
                      title="حذف / إخفاء هذه البطاقة"
                      style={{
                        background: "rgba(239, 68, 68, 0.3)",
                        border: "1px solid rgba(239, 68, 68, 0.6)",
                        color: "#fca5a5",
                        borderRadius: "8px",
                        width: "30px",
                        height: "30px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        cursor: "pointer",
                        transition: "all 0.2s"
                      }}
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                </div>

                {/* Card Body */}
                <div style={{ padding: "16px", flex: 1, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
                  <p style={{
                    fontSize: "0.82rem",
                    color: "#cbd5e1",
                    lineHeight: "1.5",
                    marginBottom: "12px",
                    minHeight: "36px"
                  }}>
                    {t.desc}
                  </p>

                  {/* QR Code Container (Pure white frame for 100% scan accuracy) */}
                  <div style={{
                    background: "#ffffff",
                    borderRadius: "16px",
                    padding: "14px 10px 10px",
                    textAlign: "center",
                    boxShadow: "0 6px 20px rgba(0,0,0,0.25)",
                    marginBottom: "12px",
                    border: "1px solid rgba(0,0,0,0.08)"
                  }}>
                    <QRCodeSVG 
                      id={`trainer-qr-${t.id}`}
                      value={applyUrl}
                      size={155}
                      level="H"
                      includeMargin={false}
                    />

                    <div style={{
                      fontSize: "0.74rem",
                      color: "#0f172a",
                      fontWeight: 800,
                      marginTop: "8px",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: "4px"
                    }}>
                      <span>📲</span>
                      <span>امسح الرمز لتقديم النموذج مباشرة</span>
                    </div>

                    <div style={{
                      fontSize: "0.68rem",
                      color: "#475569",
                      marginTop: "3px",
                      direction: "ltr",
                      fontFamily: "monospace",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap",
                      padding: "2px 6px",
                      background: "#f1f5f9",
                      borderRadius: "6px"
                    }}>
                      {applyUrl}
                    </div>
                  </div>

                  {/* Screen Actions (Hidden on Print) */}
                  <div className="no-print" style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                    <div style={{ display: "flex", gap: "6px" }}>
                      <button
                        onClick={() => handleCopy(t.id)}
                        style={{
                          flex: 1,
                          padding: "8px 10px",
                          borderRadius: "10px",
                          border: "1px solid rgba(255,255,255,0.15)",
                          background: copiedId === t.id ? "#059669" : "rgba(255,255,255,0.08)",
                          color: "white",
                          fontSize: "0.8rem",
                          fontWeight: 700,
                          cursor: "pointer",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          gap: "5px",
                          fontFamily: "Tajawal"
                        }}
                      >
                        {copiedId === t.id ? <><Check size={13} /> تم النسخ</> : <><Copy size={13} /> نسخ الرابط</>}
                      </button>

                      <button
                        onClick={() => handleDownloadSingleQR(t.id, t.name)}
                        style={{
                          flex: 1,
                          padding: "8px 10px",
                          borderRadius: "10px",
                          border: "1px solid rgba(56, 189, 248, 0.4)",
                          background: "rgba(56, 189, 248, 0.12)",
                          color: "#38bdf8",
                          fontSize: "0.8rem",
                          fontWeight: 700,
                          cursor: "pointer",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          gap: "5px",
                          fontFamily: "Tajawal"
                        }}
                        title="تنزيل رمز QR بصيغة PNG فائقة الدقة للطباعة"
                      >
                        <Download size={13} />
                        تنزيل QR بدقة 1000px
                      </button>
                    </div>

                    <div style={{ display: "flex", gap: "6px" }}>
                      <button
                        onClick={() => handleOpenEditModal(t)}
                        style={{
                          flex: 1,
                          padding: "8px 10px",
                          borderRadius: "10px",
                          border: "1px solid rgba(255, 215, 0, 0.4)",
                          background: "rgba(255, 215, 0, 0.1)",
                          color: "#fef08a",
                          fontSize: "0.8rem",
                          fontWeight: 800,
                          cursor: "pointer",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          gap: "5px",
                          fontFamily: "Tajawal"
                        }}
                      >
                        <Edit3 size={13} />
                        تعديل البطاقة
                      </button>

                      <a
                        href={applyUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{
                          flex: 1.3,
                          padding: "8px 10px",
                          borderRadius: "10px",
                          background: "linear-gradient(135deg, #1d4ed8 0%, #2563eb 100%)",
                          color: "white",
                          textDecoration: "none",
                          fontWeight: 800,
                          fontSize: "0.8rem",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          gap: "5px",
                          boxShadow: "0 4px 12px rgba(37, 99, 235, 0.3)",
                          border: "1px solid rgba(255, 255, 255, 0.15)"
                        }}
                      >
                        <ExternalLink size={13} />
                        فتح النموذج ↗
                      </a>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* ══════════════════════════════════════════════════════════
            MODAL: ADD & EDIT TRAINER / DEPARTMENT CARD
        ══════════════════════════════════════════════════════════ */}
        {isModalOpen && (
          <div style={{
            position: "fixed",
            inset: 0,
            background: "rgba(0, 0, 0, 0.78)",
            backdropFilter: "blur(8px)",
            zIndex: 9999,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: "16px",
            direction: "rtl"
          }}>
            <div style={{
              background: "#0f172a",
              border: "2px solid rgba(99, 102, 241, 0.6)",
              borderRadius: "24px",
              maxWidth: "580px",
              width: "100%",
              maxHeight: "92vh",
              overflowY: "auto",
              padding: "26px",
              color: "#f8fafc",
              boxShadow: "0 25px 60px -15px rgba(0,0,0,0.8), 0 0 30px rgba(99, 102, 241, 0.3)",
              fontFamily: "Tajawal, sans-serif"
            }}>
              {/* Header */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "18px" }}>
                <div>
                  <div style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: "6px",
                    padding: "4px 12px",
                    background: "rgba(99, 102, 241, 0.18)",
                    borderRadius: "20px",
                    color: "#a5b4fc",
                    fontSize: "0.8rem",
                    fontWeight: 800,
                    marginBottom: "6px"
                  }}>
                    <Sparkles size={14} /> {editingTrainerId ? "تعديل بطاقة قائمة" : "إضافة بطاقة واستمارة جديدة"}
                  </div>
                  <h3 style={{ fontSize: "1.35rem", fontWeight: 900, color: "#ffffff", margin: 0 }}>
                    {editingTrainerId ? "تعديل بطاقة المدرب / القسم" : "إضافة استمارة ورمز QR لقسم جديد"}
                  </h3>
                  <p style={{ color: "#94a3b8", fontSize: "0.82rem", marginTop: "4px", margin: 0 }}>
                    قم بضبط الاسم والشارة والألوان والأيقونة وسيتم تحديث وحفظ البطاقة ورمز QR فوراً
                  </p>
                </div>

                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  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 */}
              {saveSuccessMsg && (
                <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: "16px",
                  display: "flex",
                  alignItems: "center",
                  gap: "10px"
                }}>
                  <Check size={18} />
                  {saveSuccessMsg}
                </div>
              )}

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

                {/* 2. الشارة (Badge) */}
                <div style={{ marginBottom: "14px" }}>
                  <label style={{ display: "block", fontWeight: 800, fontSize: "0.88rem", color: "#e2e8f0", marginBottom: "6px" }}>
                    الشارة والصفة السريرية (Badge)
                  </label>
                  <input
                    type="text"
                    placeholder="مثال: مدرب سريري — تخدير"
                    value={formBadge}
                    onChange={(e) => setFormBadge(e.target.value)}
                    style={{
                      width: "100%",
                      padding: "11px 14px",
                      background: "rgba(255,255,255,0.05)",
                      border: "1.5px solid rgba(255,255,255,0.15)",
                      borderRadius: "12px",
                      color: "white",
                      fontSize: "0.92rem",
                      fontFamily: "Tajawal",
                      outline: "none",
                      boxSizing: "border-box"
                    }}
                  />
                </div>

                {/* 3. الوصف */}
                <div style={{ marginBottom: "14px" }}>
                  <label style={{ display: "block", fontWeight: 800, fontSize: "0.88rem", color: "#e2e8f0", marginBottom: "6px" }}>
                    الوصف المختصر المطبوع على البطاقة
                  </label>
                  <textarea
                    rows={2}
                    placeholder="خاص بالمدربين والمشرفين لتدريب طلبة هذا القسم في أقسام المستشفى والجامعات الشريكة..."
                    value={formDesc}
                    onChange={(e) => setFormDesc(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.86rem",
                      fontFamily: "Tajawal",
                      outline: "none",
                      resize: "none",
                      boxSizing: "border-box"
                    }}
                  />
                </div>

                {/* 4. اختيار الأيقونة واللون */}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px", marginBottom: "16px" }}>
                  {/* الأيقونة */}
                  <div>
                    <label style={{ display: "block", fontWeight: 800, fontSize: "0.85rem", color: "#e2e8f0", marginBottom: "6px" }}>
                      الأيقونة التعبيرية:
                    </label>
                    <div style={{ display: "flex", gap: "6px", flexWrap: "wrap", maxHeight: "80px", overflowY: "auto", padding: "6px", background: "rgba(255,255,255,0.03)", borderRadius: "10px", border: "1px solid rgba(255,255,255,0.1)" }}>
                      {EMOJI_PRESETS.map((em) => (
                        <button
                          key={em}
                          type="button"
                          onClick={() => setFormIcon(em)}
                          style={{
                            width: "32px",
                            height: "32px",
                            borderRadius: "8px",
                            border: formIcon === em ? "2px solid #ffd700" : "1px solid rgba(255,255,255,0.1)",
                            background: formIcon === em ? "rgba(255,215,0,0.25)" : "transparent",
                            fontSize: "1.1rem",
                            cursor: "pointer",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center"
                          }}
                        >
                          {em}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* اللون */}
                  <div>
                    <label style={{ display: "block", fontWeight: 800, fontSize: "0.85rem", color: "#e2e8f0", marginBottom: "6px" }}>
                      اللون المميز للبطاقة:
                    </label>
                    <div style={{ display: "flex", gap: "6px", flexWrap: "wrap", maxHeight: "80px", overflowY: "auto", padding: "6px", background: "rgba(255,255,255,0.03)", borderRadius: "10px", border: "1px solid rgba(255,255,255,0.1)" }}>
                      {COLOR_PRESETS.map((c) => (
                        <button
                          key={c.val}
                          type="button"
                          onClick={() => setFormColor(c.val)}
                          title={c.label}
                          style={{
                            width: "28px",
                            height: "28px",
                            borderRadius: "50%",
                            background: c.val,
                            border: formColor === c.val ? "3px solid #ffffff" : "1px solid rgba(255,255,255,0.2)",
                            cursor: "pointer",
                            boxShadow: formColor === c.val ? "0 0 10px #ffffff" : "none"
                          }}
                        />
                      ))}
                    </div>
                  </div>
                </div>

                {/* Preview Box */}
                {formName.trim() && (
                  <div style={{
                    padding: "12px",
                    background: "rgba(99, 102, 241, 0.1)",
                    borderRadius: "12px",
                    border: "1px dashed rgba(99, 102, 241, 0.4)",
                    marginBottom: "18px",
                    fontSize: "0.82rem",
                    color: "#c7d2fe"
                  }}>
                    <div>🔗 <strong>رابط التقديم المباشر:</strong> {getTrainerUrl(editingTrainerId || formName.trim().toLowerCase().replace(/[^\w\u0621-\u064A\s-]/g, "").replace(/\s+/g, "-"))}</div>
                    <div style={{ marginTop: "4px" }}>📱 <strong>رمز QR:</strong> سيتم إنشاؤه وتحديثه فور الحفظ ليكون جاهزاً للطباعة والمسح المباشر.</div>
                  </div>
                )}

                {/* Modal Action Buttons */}
                <div style={{ display: "flex", gap: "10px", justifyContent: "flex-end" }}>
                  <button
                    type="button"
                    onClick={() => setIsModalOpen(false)}
                    style={{
                      padding: "10px 18px",
                      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"
                    style={{
                      padding: "10px 24px",
                      background: "linear-gradient(135deg, #4f46e5 0%, #6366f1 100%)",
                      color: "white",
                      borderRadius: "12px",
                      border: "none",
                      fontWeight: 900,
                      fontSize: "0.92rem",
                      cursor: "pointer",
                      boxShadow: "0 4px 15px rgba(99, 102, 241, 0.4)",
                      fontFamily: "Tajawal"
                    }}
                  >
                    {editingTrainerId ? "حفظ التعديلات ✨" : "إضافة البطاقة والرمز الآن ➕"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* ══════════════════════════════════════════════════════════
            PRINT ONLY OFFICIAL FOOTER
        ══════════════════════════════════════════════════════════ */}
        <div className="print-only-footer" style={{
          marginTop: "20px",
          paddingTop: "12px",
          borderTop: "2px solid #0f172a",
          fontSize: "0.75rem",
          color: "#475569",
          textAlign: "center"
        }}>
          <div>
            <strong>مستشفى الهلال الأحمر الفلسطيني التخصصي — الخليل</strong> | وحدة التطوير والتدريب والتعليم الطبي المستمر
          </div>
          <div>
            هذه الوثيقة رسمية ومحدثة إلكترونياً. مسح أي رمز QR يوجه المتقدم مباشرة إلى البوابة الإلكترونية المعتمدة لحفظ الطلبات في قاعدة بيانات المستشفى.
          </div>
        </div>

      </div>
    </div>
  );
}
