"use client";

import { useState, useEffect, useMemo } from "react";
import Link from "next/link";
import { QRCodeSVG } from "qrcode.react";
import { 
  ArrowRight, 
  Printer, 
  Download, 
  Share2, 
  Check, 
  Copy, 
  Filter, 
  Globe, 
  Sparkles,
  QrCode,
  GraduationCap,
  Stethoscope,
  HeartPulse,
  Activity,
  Layers,
  Search
} from "lucide-react";

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

const defaultCategories: CategoryItem[] = [
  // ── 1. الجامعات والمدربون السريريون والأطباء المتعاقدون ──
  {
    id: "university-nursing-trainers",
    name: "تدريب طلاب التمريض في الجامعات",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#0284c7",
    badge: "مدرب سريري — تمريض",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة التمريض في الجامعات داخل أقسام المستشفى"
  },
  {
    id: "contracted-doctors",
    name: "الأطباء المتعاقدين مع الجامعات",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#4338ca",
    badge: "أطباء متعاقدون",
    desc: "خاص بالأطباء المشرفين والمتعاقدين مع الجامعات لتدريب الطلبة في الأقسام الطبية"
  },
  {
    id: "radiology-trainers",
    name: "مدربي أشعة (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#7c3aed",
    badge: "مدرب سريري — أشعة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة الأشعة والتصوير الطبي من الجامعات"
  },
  {
    id: "physical-therapy-trainers",
    name: "مدربي علاج طبيعي (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#059669",
    badge: "مدرب سريري — علاج طبيعي",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة العلاج الطبيعي والتأهيل الحركي"
  },
  {
    id: "lab-trainers",
    name: "مدربي مختبرات (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#0891b2",
    badge: "مدرب سريري — مختبرات",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة العلوم الطبية المخبرية"
  },
  {
    id: "pharmacy-trainers",
    name: "مدربي صيدلة (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#b45309",
    badge: "مدرب سريري — صيدلة",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة كليات الصيدلة السريرية"
  },
  {
    id: "occupational-therapy-trainers",
    name: "مدربي علاج وظيفي (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#0f766e",
    badge: "مدرب سريري — علاج وظيفي",
    desc: "خاص بالمدربين والمشرفين لتدريب وتأهيل اختصاصيي العلاج الوظيفي"
  },
  {
    id: "nutrition-trainers",
    name: "مدربي تغذية (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#16a34a",
    badge: "مدرب سريري — تغذية",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة التغذية السريرية والعلاجية"
  },
  {
    id: "medical-engineering-trainers",
    name: "مدربي هندسة طبية (التدريب السريري والجامعات)",
    group: "universities",
    groupName: "كادر الجامعات والمدربين",
    color: "#1d4ed8",
    badge: "مدرب سريري — هندسة طبية",
    desc: "خاص بالمدربين والمشرفين لتدريب طلبة الهندسة والأجهزة الطبية"
  },

  // ── 2. أطباء الامتياز والطب البشري ──
  {
    id: "internship",
    name: "المتقدمين للإمتياز (طب وجراحة)",
    group: "internship",
    groupName: "أطباء الامتياز",
    color: "#1e3a8a",
    badge: "برنامج الامتياز الطبي",
    desc: "أطباء الامتياز لخريجي كليات الطب البشري (نظام 5+2 و 6+1)"
  },
  {
    id: "medical-training",
    name: "طب تدريب سريري",
    group: "internship",
    groupName: "أطباء الامتياز",
    color: "#0284c7",
    badge: "تدريب سريري",
    desc: "برنامج التدريب السريري لطلبة كليات الطب البشري"
  },
  {
    id: "volunteer-medicine",
    name: "طب تطوع",
    group: "volunteer",
    groupName: "التطوع",
    color: "#d97706",
    badge: "التطوع الطبي",
    desc: "برنامج التطوع الطبي في مختلف العيادات والأقسام"
  },

  // ── 3. التمريض ──
  {
    id: "nursing-training",
    name: "تمريض تدريب",
    group: "nursing",
    groupName: "التمريض والتدريب",
    color: "#db2777",
    badge: "تدريب عملي",
    desc: "برنامج التدريب العملي والميداني لطلبة وخريجي كليات التمريض"
  },
  {
    id: "nursing-internship",
    name: "تمريض امتياز",
    group: "nursing",
    groupName: "التمريض والتدريب",
    color: "#9333ea",
    badge: "امتياز تمريض",
    desc: "برنامج سنة الامتياز لخريجي التمريض لتطوير الكفاءات السريرية"
  },
  {
    id: "nursing",
    name: "التمريض العام",
    group: "nursing",
    groupName: "التمريض والتدريب",
    color: "#e11d48",
    badge: "طاقم التمريض",
    desc: "تقديم طلبات الالتحاق والتدريب لكادر التمريض التخصصي"
  },
  {
    id: "volunteer-nursing",
    name: "تمريض تطوع",
    group: "volunteer",
    groupName: "التطوع",
    color: "#0d9488",
    badge: "التطوع التمريضي",
    desc: "فرص التطوع لطلبة وخريجي التمريض لاكتساب الخبرة الميدانية"
  },

  // ── 4. الإسعاف والمهن الطبية المساندة ──
  {
    id: "ambulance-officers",
    name: "تدريب ضباط الإسعاف",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#ea580c",
    badge: "الإسعاف والطوارئ",
    desc: "برنامج التدريب العملي لضباط وفنيي الإسعاف وطوارئ المستشفى"
  },
  {
    id: "physical-therapy-training",
    name: "علاج طبيعي تدريب",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#16a34a",
    badge: "تدريب عملي",
    desc: "برنامج التدريب العملي والميداني لطلاب العلاج الطبيعي والتأهيل"
  },
  {
    id: "physical-therapy-internship",
    name: "علاج طبيعي امتياز",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#059669",
    badge: "سنة الامتياز",
    desc: "برنامج سنة الامتياز لخريجي العلاج الطبيعي والتأهيل الحركي"
  },
  {
    id: "occupational-therapy",
    name: "العلاج الوظيفي",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#0f766e",
    badge: "التأهيل الوظيفي",
    desc: "برنامج تدريب وتأهيل اختصاصيي العلاج الوظيفي والتأهيل العصبي"
  },
  {
    id: "radiology",
    name: "أشعة وتصوير طبي",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#475569",
    badge: "التصوير الطبي",
    desc: "تدريب فنيي الأشعة والتصوير الطبقي والرنين والموجات الصوتية"
  },
  {
    id: "nutrition",
    name: "تغذية سريرية",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#65a30d",
    badge: "التغذية العلاجية",
    desc: "برنامج التدريب لأخصائيي التغذية السريرية والحميات الغذائية"
  },
  {
    id: "medical-labs",
    name: "مختبرات طبية وتحاليل",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#7c3aed",
    badge: "المختبرات والتحاليل",
    desc: "برنامج التدريب في المختبرات الطبية وبنك الدم ومطابقة العينات"
  },
  {
    id: "biomedical-engineering",
    name: "هندسة طبية وأجهزة",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#0284c7",
    badge: "الهندسة الطبية",
    desc: "برنامج التدريب في صيانة ومعايرة الأجهزة والمعدات السريرية"
  },
  {
    id: "psychological-counseling",
    name: "إرشاد وصحة نفسية",
    group: "allied",
    groupName: "الإسعاف والتأهيل",
    color: "#059669",
    badge: "إرشاد وصحة نفسية",
    desc: "برنامج التدريب والتأهيل الميداني في الإرشاد النفسي والصحة النفسية والدعم النفسي الاجتماعي"
  },

  // ── 5. الإدارة والخدمات ──
  {
    id: "admin",
    name: "الإدارة والسكرتاريا",
    group: "admin",
    groupName: "الإدارة والخدمات",
    color: "#334155",
    badge: "الكوادر الإدارية",
    desc: "التقديم للتدريب الإداري والشؤون المؤسسية"
  },
  {
    id: "medical-sec",
    name: "سكرتارية طبية وسجلات",
    group: "admin",
    groupName: "الإدارة والخدمات",
    color: "#4f46e5",
    badge: "السجلات الطبية",
    desc: "قسم السكرتارية الطبية وإدارة السجلات والتوثيق الصحي"
  },
  {
    id: "accounting",
    name: "المحاسبة والمالية",
    group: "admin",
    groupName: "الإدارة والخدمات",
    color: "#6d28d9",
    badge: "الشؤون المالية",
    desc: "تدريب وتأهيل الكوادر المالية والمحاسبية والتأمين الصحي"
  },
  {
    id: "kitchen",
    name: "المطبخ والخدمات الفندقية",
    group: "admin",
    groupName: "الإدارة والخدمات",
    color: "#c2410c",
    badge: "الإعاشة الفندقية",
    desc: "خدمات الإعاشة وتغذية المرضى والكوادر الطبية"
  },

  // ── 6. العمل المجتمعي والتطوع ──
  {
    id: "social-service",
    name: "خدمة اجتماعية",
    group: "volunteer",
    groupName: "التطوع والمجتمع",
    color: "#78350f",
    badge: "الدعم الاجتماعي",
    desc: "تقديم الخدمات الاجتماعية والدعم الإنساني للمرضى وعائلاتهم"
  },
  {
    id: "community-work",
    name: "العمل المجتمعي",
    group: "volunteer",
    groupName: "التطوع والمجتمع",
    color: "#0f766e",
    badge: "المبادرات المجتمعية",
    desc: "المشاركة في الأنشطة المجتمعية والتوعوية والحملات الصحية"
  }
];

export default function PrintQRPage() {
  const [categories, setCategories] = useState<CategoryItem[]>(defaultCategories);
  const [selectedGroup, setSelectedGroup] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [copiedId, setCopiedId] = useState<string | null>(null);

  // SMART BASE URL:
  // If running locally, mobile phones scanning the QR code cannot access localhost.
  // We default to the live production server (https://crescent.livestimes.com) on localhost
  // so scanning any QR code with a phone works immediately!
  const [useProductionDomain, setUseProductionDomain] = useState(true);
  const [currentOrigin, setCurrentOrigin] = useState("https://crescent.livestimes.com");

  useEffect(() => {
    if (typeof window !== "undefined") {
      setCurrentOrigin(window.location.origin);
    }

    // Fetch dynamic categories
    fetch("/api/categories")
      .then((res) => res.json())
      .then((data) => {
        if (data && Array.isArray(data.categories) && data.categories.length > 0) {
          const custom: CategoryItem[] = data.categories.map((c: any) => ({
            id: c.id,
            name: c.name,
            group: (c.group as any) || "allied",
            groupName: c.groupName || "أقسام إضافية",
            color: "#6366f1",
            badge: c.badge || "استمارة تقديم",
            desc: c.desc || `برنامج التقديم والتدريب في قسم ${c.name}`
          }));

          setCategories((prev) => {
            const existingIds = new Set(prev.map((p) => p.id));
            const newOnes = custom.filter((c) => !existingIds.has(c.id));
            return [...prev, ...newOnes];
          });
        } else {
          try {
            const local = localStorage.getItem("customCategories");
            if (local) {
              const parsed = JSON.parse(local);
              setCategories((prev) => {
                const existingIds = new Set(prev.map((p) => p.id));
                const newOnes = parsed.filter((c: any) => !existingIds.has(c.id));
                return [...prev, ...newOnes];
              });
            }
          } catch {}
        }
      })
      .catch(() => {
        try {
          const local = localStorage.getItem("customCategories");
          if (local) {
            const parsed = JSON.parse(local);
            setCategories((prev) => {
              const existingIds = new Set(prev.map((p) => p.id));
              const newOnes = parsed.filter((c: any) => !existingIds.has(c.id));
              return [...prev, ...newOnes];
            });
          }
        } catch {}
      });
  }, []);

  const isLocal = useMemo(() => {
    return (
      currentOrigin.includes("localhost") ||
      currentOrigin.includes("127.0.0.1") ||
      currentOrigin.includes("192.168.")
    );
  }, [currentOrigin]);

  const activeBaseUrl = useMemo(() => {
    if (isLocal && useProductionDomain) {
      return "https://crescent.livestimes.com";
    }
    return currentOrigin;
  }, [isLocal, useProductionDomain, currentOrigin]);

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

  const filteredCategories = useMemo(() => {
    return categories.filter((cat) => {
      const matchGroup = selectedGroup === "all" || cat.group === selectedGroup;
      const q = searchQuery.trim().toLowerCase();
      const matchSearch =
        !q ||
        cat.name.toLowerCase().includes(q) ||
        cat.groupName.toLowerCase().includes(q) ||
        (cat.desc && cat.desc.toLowerCase().includes(q));
      return matchGroup && matchSearch;
    });
  }, [categories, selectedGroup, searchQuery]);

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

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

  return (
    <div style={{ minHeight: "100vh", background: "#0b1329", color: "#f8fafc", fontFamily: "Tajawal, sans-serif", padding: "24px 20px 80px" }}>
      {/* ── Top Header Bar (No Print) ── */}
      <div className="no-print" style={{ maxWidth: "1400px", margin: "0 auto 28px" }}>
        
        {/* Breadcrumb & Navigation */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "16px", marginBottom: "20px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "12px", flexWrap: "wrap" }}>
            <Link
              href="/"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "8px",
                padding: "10px 20px",
                background: "rgba(255,255,255,0.08)",
                border: "1px solid rgba(255,255,255,0.15)",
                borderRadius: "14px",
                color: "#e2e8f0",
                textDecoration: "none",
                fontWeight: 800,
                fontSize: "0.9rem",
                transition: "all 0.2s"
              }}
            >
              <ArrowRight size={18} />
              العودة للوحة التحكم
            </Link>

            <Link
              href="/trainers-qr"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "8px",
                padding: "10px 20px",
                background: "linear-gradient(135deg, #ffd700 0%, #f59e0b 100%)",
                border: "1.5px solid #ffd700",
                borderRadius: "14px",
                color: "#0f172a",
                textDecoration: "none",
                fontWeight: 900,
                fontSize: "0.9rem",
                boxShadow: "0 4px 15px rgba(245,158,11,0.35)"
              }}
              title="الانتقال لصفحة طباعة مخصصة ومستقلة لكادر المدربين فقط"
            >
              <GraduationCap size={18} />
              ⭐ صفحة مخصصة لطباعة رموز المدربين
            </Link>

            <Link
              href="/recruitment"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "8px",
                padding: "10px 20px",
                background: "linear-gradient(135deg, #059669 0%, #10b981 100%)",
                border: "1.5px solid rgba(255,215,0,0.6)",
                borderRadius: "14px",
                color: "white",
                textDecoration: "none",
                fontWeight: 900,
                fontSize: "0.9rem",
                boxShadow: "0 4px 15px rgba(16,185,129,0.3)"
              }}
            >
              <QrCode size={18} />
              بوابة تقديم الطلبات والـ QR التفاعلية
            </Link>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: "12px", flexWrap: "wrap" }}>
            <button
              onClick={() => window.print()}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "10px",
                padding: "12px 30px",
                background: "linear-gradient(135deg, #7c3aed 0%, #4f46e5 100%)",
                border: "1.5px solid rgba(255,255,255,0.3)",
                borderRadius: "14px",
                color: "white",
                fontWeight: 900,
                fontSize: "1.05rem",
                cursor: "pointer",
                boxShadow: "0 6px 25px rgba(124,58,237,0.45)",
                fontFamily: "Tajawal, sans-serif"
              }}
            >
              <Printer size={20} />
              طباعة كافة رموز الـ QR (A4)
            </button>
          </div>
        </div>

        {/* Hero Title Box */}
        <div style={{
          background: "linear-gradient(135deg, rgba(30, 41, 59, 0.9) 0%, rgba(15, 23, 42, 0.95) 100%)",
          border: "1.5px solid rgba(255, 215, 0, 0.35)",
          borderRadius: "24px",
          padding: "26px 30px",
          boxShadow: "0 10px 30px rgba(0,0,0,0.4)",
          position: "relative",
          overflow: "hidden"
        }}>
          <div style={{ position: "absolute", top: "-40px", left: "-40px", width: "160px", height: "160px", background: "rgba(255, 215, 0, 0.1)", borderRadius: "50%", filter: "blur(40px)" }} />
          
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "20px", position: "relative", zIndex: 1 }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "8px" }}>
                <span style={{ fontSize: "1.8rem" }}>📱</span>
                <h1 style={{ fontSize: "1.8rem", fontWeight: 900, color: "#ffffff", margin: 0 }}>
                  دليل وطباعة كافة رموز الـ QR لجميع برامج التدريب والتعاقد
                </h1>
                <span style={{ background: "rgba(255,215,0,0.15)", color: "#fbbf24", border: "1px solid rgba(255,215,0,0.4)", padding: "3px 12px", borderRadius: "20px", fontSize: "0.82rem", fontWeight: 800 }}>
                  {filteredCategories.length} استمارة جاهزة
                </span>
              </div>
              <p style={{ color: "#94a3b8", fontSize: "0.95rem", margin: 0, lineHeight: 1.6 }}>
                رموز QR عالية الدقة تتيح للطلبة والأطباء والمدربين مسح الرمز بكاميرا الهاتف وتعبئة استمارة التقديم الرسمية مباشرة من أي مكان.
              </p>
            </div>

            {/* Smart URL / Domain Status Pill */}
            <div style={{
              background: "rgba(15, 23, 42, 0.8)",
              border: "1px solid rgba(56, 189, 248, 0.3)",
              borderRadius: "16px",
              padding: "12px 18px",
              display: "flex",
              flexDirection: "column",
              gap: "6px"
            }}>
              <div style={{ fontSize: "0.78rem", color: "#94a3b8", display: "flex", alignItems: "center", gap: "6px" }}>
                <Globe size={14} color="#38bdf8" />
                <span>نطاق الربط لرموز الـ QR:</span>
              </div>
              <div style={{ fontSize: "0.85rem", fontWeight: 800, color: "#38bdf8", direction: "ltr", fontFamily: "monospace" }}>
                {activeBaseUrl}
              </div>
              {isLocal && (
                <div style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "4px" }}>
                  <button
                    onClick={() => setUseProductionDomain(!useProductionDomain)}
                    style={{
                      background: useProductionDomain ? "rgba(16,185,129,0.2)" : "rgba(239,68,68,0.2)",
                      border: `1px solid ${useProductionDomain ? "#10b981" : "#ef4444"}`,
                      color: useProductionDomain ? "#6ee7b7" : "#fca5a5",
                      borderRadius: "8px",
                      padding: "4px 10px",
                      fontSize: "0.72rem",
                      fontWeight: 800,
                      cursor: "pointer",
                      fontFamily: "Tajawal"
                    }}
                    title="التبديل بين رابط المستشفى المباشر والرابط المحلي"
                  >
                    {useProductionDomain ? "✅ رابط مباشر (يعمل بالهواتف)" : "⚠️ رابط محلي (Localhost)"}
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Search & Filter Tabs */}
          <div style={{ marginTop: "24px", display: "flex", flexDirection: "column", gap: "14px", position: "relative", zIndex: 1 }}>
            {/* Search Input */}
            <div style={{ maxWidth: "420px", position: "relative" }}>
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="🔍 ابحث عن قسم أو استمارة أو تخصص..."
                style={{
                  width: "100%",
                  padding: "10px 16px 10px 38px",
                  background: "rgba(255,255,255,0.07)",
                  border: "1px solid rgba(255,255,255,0.2)",
                  borderRadius: "12px",
                  color: "#ffffff",
                  fontSize: "0.9rem",
                  fontFamily: "Tajawal",
                  outline: "none"
                }}
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  style={{
                    position: "absolute",
                    left: "12px",
                    top: "50%",
                    transform: "translateY(-50%)",
                    background: "transparent",
                    border: "none",
                    color: "#94a3b8",
                    cursor: "pointer"
                  }}
                >✕</button>
              )}
            </div>

            {/* Filter Pills */}
            <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
              {filterTabs.map((tab) => (
                <button
                  key={tab.key}
                  onClick={() => setSelectedGroup(tab.key)}
                  style={{
                    padding: "7px 16px",
                    borderRadius: "20px",
                    border: selectedGroup === tab.key ? "1.5px solid #38bdf8" : "1px solid rgba(255,255,255,0.12)",
                    background: selectedGroup === tab.key ? "rgba(56, 189, 248, 0.18)" : "rgba(255,255,255,0.05)",
                    color: selectedGroup === tab.key ? "#38bdf8" : "#cbd5e1",
                    fontSize: "0.84rem",
                    fontWeight: 800,
                    cursor: "pointer",
                    fontFamily: "Tajawal",
                    transition: "all 0.2s"
                  }}
                >
                  {tab.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ── Printable Hospital Banner (Appears ONLY during print) ── */}
      <div className="print-only" style={{ display: "none", textAlign: "center", marginBottom: "25px", borderBottom: "2px solid #0f172a", paddingBottom: "15px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "0 20px" }}>
          <img src="/prcs-logo.png" alt="الهلال الأحمر" style={{ height: "65px" }} />
          <div>
            <h2 style={{ fontSize: "1.4rem", fontWeight: 900, margin: 0, color: "#000" }}>جمعية الهلال الأحمر الفلسطيني التخصصي — الخليل</h2>
            <div style={{ fontSize: "1rem", fontWeight: 800, color: "#64748b", marginTop: "4px" }}>دائرة التعليم الطبي والتدريب السريري — رموز QR الرسمية لتقديم الطلبات</div>
          </div>
          <div style={{ fontSize: "0.8rem", color: "#64748b", textAlign: "left" }}>
            تاريخ الطباعة: {new Date().toLocaleDateString("ar-EG")}
          </div>
        </div>
      </div>

      {/* ── QR Cards Grid ── */}
      <div style={{
        maxWidth: "1400px",
        margin: "0 auto",
        display: "grid",
        gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
        gap: "22px"
      }}>
        {filteredCategories.map((cat) => {
          const applyUrl = `${activeBaseUrl}/apply/${cat.id}`;

          return (
            <div
              key={cat.id}
              className="qr-print-card"
              style={{
                background: "linear-gradient(180deg, rgba(30, 41, 59, 0.8) 0%, rgba(15, 23, 42, 0.95) 100%)",
                border: `2px solid ${cat.color}66`,
                borderRadius: "22px",
                padding: "20px 18px",
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                textAlign: "center",
                gap: "14px",
                boxShadow: "0 10px 30px rgba(0,0,0,0.3)",
                position: "relative",
                pageBreakInside: "avoid",
                breakInside: "avoid"
              }}
            >
              {/* Top Accent Strip */}
              <div style={{
                position: "absolute",
                top: 0,
                left: "20px",
                right: "20px",
                height: "4px",
                background: cat.color,
                borderRadius: "0 0 4px 4px"
              }} />

              {/* Group Name & Badge */}
              <div style={{ width: "100%", display: "flex", justifyContent: "space-between", alignItems: "center", gap: "8px", marginTop: "4px" }}>
                <span style={{ fontSize: "0.75rem", color: "#94a3b8", fontWeight: 700 }}>{cat.groupName}</span>
                <span style={{
                  fontSize: "0.72rem",
                  background: `${cat.color}22`,
                  color: cat.color,
                  border: `1px solid ${cat.color}55`,
                  borderRadius: "8px",
                  padding: "2px 8px",
                  fontWeight: 800
                }}>
                  {cat.badge}
                </span>
              </div>

              {/* Title */}
              <h3 style={{
                fontSize: "1.08rem",
                fontWeight: 900,
                color: "#ffffff",
                margin: 0,
                minHeight: "44px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                lineHeight: 1.3
              }}>
                {cat.name}
              </h3>

              {/* High-Resolution QR SVG Frame */}
              <div
                style={{
                  background: "#ffffff",
                  padding: "14px",
                  borderRadius: "18px",
                  boxShadow: "0 8px 24px rgba(0,0,0,0.35)",
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  border: `3px solid ${cat.color}`
                }}
              >
                <QRCodeSVG
                  id={`qr-svg-${cat.id}`}
                  value={applyUrl}
                  size={165}
                  level="H"
                  includeMargin={false}
                  fgColor="#0f172a"
                />
              </div>

              {/* Scan Text */}
              <div style={{ fontSize: "0.82rem", fontWeight: 800, color: cat.color }}>
                امسح الرمز بكاميرا الجوال للتقديم 📲
              </div>

              {/* Direct Link Box */}
              <div
                onClick={() => handleCopy(cat.id, applyUrl)}
                style={{
                  width: "100%",
                  background: "rgba(255,255,255,0.05)",
                  border: "1px solid rgba(255,255,255,0.12)",
                  borderRadius: "10px",
                  padding: "6px 10px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: "6px",
                  cursor: "pointer",
                  transition: "all 0.2s"
                }}
                title="اضغط لنسخ الرابط المباشر"
              >
                <span style={{
                  fontSize: "0.7rem",
                  color: "#94a3b8",
                  direction: "ltr",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                  fontFamily: "monospace",
                  flex: 1
                }}>
                  {applyUrl}
                </span>
                <span style={{
                  fontSize: "0.72rem",
                  color: copiedId === cat.id ? "#34d399" : "#38bdf8",
                  fontWeight: 800,
                  display: "flex",
                  alignItems: "center",
                  gap: "4px"
                }}>
                  {copiedId === cat.id ? <><Check size={12} /> تم</> : <><Copy size={12} /> نسخ</>}
                </span>
              </div>

              {/* Utility Action Buttons (No Print) */}
              <div className="no-print" style={{ width: "100%", display: "flex", gap: "8px", marginTop: "auto" }}>
                <a
                  href={`/apply/${cat.id}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    flex: 1,
                    padding: "8px",
                    background: "rgba(255,255,255,0.08)",
                    border: "1px solid rgba(255,255,255,0.15)",
                    borderRadius: "10px",
                    color: "#e2e8f0",
                    fontSize: "0.78rem",
                    fontWeight: 800,
                    textDecoration: "none",
                    textAlign: "center"
                  }}
                >
                  فتح النموذج ↗
                </a>

                <button
                  type="button"
                  onClick={() => handleDownloadSingleQR(cat.id, cat.name)}
                  style={{
                    flex: 1,
                    padding: "8px",
                    background: `linear-gradient(135deg, ${cat.color} 0%, #1e293b 100%)`,
                    border: "1px solid rgba(255,255,255,0.2)",
                    borderRadius: "10px",
                    color: "white",
                    fontSize: "0.78rem",
                    fontWeight: 800,
                    cursor: "pointer",
                    display: "inline-flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: "6px",
                    fontFamily: "Tajawal"
                  }}
                  title="تنزيل رمز QR بدقة عالية كصورة PNG"
                >
                  <Download size={13} />
                  <span>تنزيل PNG</span>
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* ── Print Media Stylesheet ── */}
      <style>{`
        @media print {
          .no-print { display: none !important; }
          .print-only { display: block !important; }
          body, html {
            background: #ffffff !important;
            color: #000000 !important;
            margin: 0 !important;
            padding: 0 !important;
          }
          .qr-print-card {
            background: #ffffff !important;
            color: #000000 !important;
            border: 2px solid #cbd5e1 !important;
            box-shadow: none !important;
            page-break-inside: avoid !important;
            break-inside: avoid !important;
            margin-bottom: 16px !important;
            padding: 14px !important;
          }
          .qr-print-card h3 {
            color: #0f172a !important;
          }
          .qr-print-card span {
            color: #334155 !important;
          }
        }
      `}</style>
    </div>
  );
}
