import React, { useState, useEffect, useRef } from 'react';
import QRCode from 'qrcode';
import {
  X,
  QrCode,
  Download,
  Printer,
  ShieldCheck,
  CheckCircle2,
  AlertTriangle,
  Camera,
  Share2,
  Copy,
  Check,
  UserCheck,
  Building,
  RefreshCw,
  Sparkles,
  ExternalLink,
  Scissors,
  Eye,
  CreditCard,
  FileCheck,
  HelpCircle,
  Layers,
  Phone,
  MapPin,
  Award,
} from 'lucide-react';
import { User, FeePayment } from '../types';

interface StudentIDCardModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: User;
  studentFee?: FeePayment;
}

export const StudentIDCardModal: React.FC<StudentIDCardModalProps> = ({
  isOpen,
  onClose,
  user,
  studentFee,
}) => {
  const [activeTab, setActiveTab] = useState<'digital' | 'printable'>('printable');
  const [qrCodeDataUrl, setQrCodeDataUrl] = useState<string>('');
  const [copied, setCopied] = useState(false);
  const [customPhotoUrl, setCustomPhotoUrl] = useState<string | null>(null);
  const [isVerifying, setIsVerifying] = useState(false);
  const [scanResult, setScanResult] = useState<any | null>(null);
  const [includeBackSide, setIncludeBackSide] = useState(true);
  const [printColorMode, setPrintColorMode] = useState<'color' | 'bw'>('color');
  const [showPrintTips, setShowPrintTips] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const studentId = user.studentId || 'STC/2026/ICT-108';
  const studentName = user.name || 'Chimwemwe Phiri';
  const courseTitle = studentFee?.courseName || user.title || 'ICT - Systems Support (City & Guilds)';
  const totalTuition = studentFee?.totalAmountDue || studentFee?.totalTuitionDue || 180000;
  const amountPaid = studentFee?.totalPaid || 126000;
  const balanceDue = studentFee?.balanceDue ?? (totalTuition - amountPaid);
  const isFullyPaid = balanceDue <= 0;
  const isMinPaid = amountPaid >= totalTuition * 0.7;

  // Determine Registration Status
  let regStatusText = 'OFFICIALLY REGISTERED';
  let regStatusColor = 'bg-emerald-500 text-slate-950';
  let feeStatusBadge = '70% Minimum Tuition Cleared';

  if (isFullyPaid) {
    regStatusText = 'FULLY CLEARED & ADMITTED';
    regStatusColor = 'bg-emerald-400 text-slate-950 font-bold';
    feeStatusBadge = '100% Tuition Fully Settled';
  } else if (!isMinPaid) {
    regStatusText = 'PROVISIONAL REGISTRATION';
    regStatusColor = 'bg-amber-400 text-slate-950 font-bold';
    feeStatusBadge = 'Pending 70% Initial Deposit';
  }

  // QR Payload
  const qrPayload = {
    iss: 'Soche Technical College Admissions & Registry',
    std_id: studentId,
    name: studentName,
    intake: 'July - December 2026 Intake',
    term_start: '2026-07-13',
    term_end: '2026-12-18',
    programme: courseTitle,
    mode: 'Day-Release / Regular',
    status: regStatusText,
    fee_clearance: isFullyPaid ? '100% Cleared' : `Partial (MK ${amountPaid.toLocaleString()} Paid)`,
    verified_at: new Date().toISOString(),
    security_hash: `STC-SEC-${studentId.replace(/[^a-zA-Z0-9]/g, '')}-2026`,
  };

  useEffect(() => {
    if (isOpen) {
      QRCode.toDataURL(
        JSON.stringify(qrPayload, null, 2),
        {
          errorCorrectionLevel: 'H',
          margin: 1,
          width: 320,
          color: {
            dark: '#0f172a',
            light: '#ffffff',
          },
        },
        (err, url) => {
          if (!err && url) {
            setQrCodeDataUrl(url);
          }
        }
      );
    }
  }, [isOpen, studentId, studentName, courseTitle, isFullyPaid, amountPaid]);

  if (!isOpen) return null;

  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setCustomPhotoUrl(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleCopyVerification = () => {
    navigator.clipboard.writeText(
      `SOCHE TECHNICAL COLLEGE DIGITAL ID VERIFICATION\nStudent ID: ${studentId}\nName: ${studentName}\nIntake: July - December 2026 Intake\nProgramme: ${courseTitle}\nRegistration Status: ${regStatusText}\nFee Status: ${feeStatusBadge}\nValid Through: December 2026\nSecurity Hash: ${qrPayload.security_hash}`
    );
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleSimulateScan = () => {
    setIsVerifying(true);
    setTimeout(() => {
      setScanResult(qrPayload);
      setIsVerifying(false);
    }, 600);
  };

  const handlePrintCard = () => {
    // Ensure we are in printable mode when printing
    setActiveTab('printable');
    setTimeout(() => {
      window.print();
    }, 100);
  };

  const handleDownloadQr = () => {
    if (!qrCodeDataUrl) return;
    const a = document.createElement('a');
    a.href = qrCodeDataUrl;
    a.download = `STC_ID_QR_${studentId.replace(/\//g, '_')}.png`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  const currentPhoto =
    customPhotoUrl ||
    user.avatarUrl ||
    'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=400&auto=format&fit=crop&q=80';

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-slate-950/80 backdrop-blur-xs overflow-y-auto">
      
      {/* SCREEN UI CONTAINER (Hidden on actual print) */}
      <div className="relative w-full max-w-3xl bg-white rounded-3xl shadow-2xl border border-slate-200 overflow-hidden my-auto animate-in fade-in zoom-in-95 duration-150 no-print">
        
        {/* Top Modal Navigation Header */}
        <div className="bg-slate-900 px-6 py-4 flex flex-wrap items-center justify-between text-white border-b border-slate-800 gap-3">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-lg bg-emerald-600 flex items-center justify-center font-black text-xs text-white shadow-xs">
              STC
            </div>
            <div>
              <h2 className="text-sm font-bold tracking-tight text-white flex items-center gap-2">
                Official Student Identification
                <span className="bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 text-[10px] font-mono px-2 py-0.5 rounded-full">
                  July – Dec 2026
                </span>
              </h2>
              <p className="text-[11px] text-slate-400">High-Resolution Physical Print & Digital Smart Pass</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {/* View Mode Toggle Buttons */}
            <div className="bg-slate-800 p-1 rounded-xl flex items-center border border-slate-700 text-xs font-semibold">
              <button
                onClick={() => setActiveTab('printable')}
                className={`px-3 py-1.5 rounded-lg transition flex items-center gap-1.5 ${
                  activeTab === 'printable'
                    ? 'bg-emerald-600 text-white shadow'
                    : 'text-slate-300 hover:text-white'
                }`}
              >
                <Printer className="w-3.5 h-3.5" />
                <span>Print-Ready ID</span>
              </button>

              <button
                onClick={() => setActiveTab('digital')}
                className={`px-3 py-1.5 rounded-lg transition flex items-center gap-1.5 ${
                  activeTab === 'digital'
                    ? 'bg-emerald-600 text-white shadow'
                    : 'text-slate-300 hover:text-white'
                }`}
              >
                <CreditCard className="w-3.5 h-3.5" />
                <span>Digital Smart Pass</span>
              </button>
            </div>

            <button
              onClick={onClose}
              className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition ml-1"
              aria-label="Close"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Modal Body Scroll Area */}
        <div className="p-4 sm:p-6 space-y-6 max-h-[80vh] overflow-y-auto">
          
          {/* ======================================================== */}
          {/* TAB 1: PRINT-READY PHYSICAL ID CARD VIEW */}
          {/* ======================================================== */}
          {activeTab === 'printable' && (
            <div className="space-y-6">
              
              {/* Print Controls Bar */}
              <div className="bg-slate-50 border border-slate-200 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3 text-xs">
                <div className="flex flex-wrap items-center gap-4">
                  
                  {/* Side Selector */}
                  <label className="flex items-center gap-2 font-medium text-slate-700 cursor-pointer select-none">
                    <input
                      type="checkbox"
                      checked={includeBackSide}
                      onChange={(e) => setIncludeBackSide(e.target.checked)}
                      className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4 cursor-pointer"
                    />
                    <span>Include Card Back (Foldable Wallet Card)</span>
                  </label>

                  {/* Color Mode */}
                  <div className="flex items-center gap-1.5">
                    <span className="text-slate-500 text-[11px]">Mode:</span>
                    <select
                      value={printColorMode}
                      onChange={(e) => setPrintColorMode(e.target.value as 'color' | 'bw')}
                      className="bg-white border border-slate-300 text-slate-700 py-1 px-2.5 rounded-lg text-xs font-semibold focus:outline-none focus:border-emerald-500"
                    >
                      <option value="color">Full Official Color (300 DPI)</option>
                      <option value="bw">Eco-Black & White</option>
                    </select>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setShowPrintTips(!showPrintTips)}
                    className="px-3 py-1.5 text-slate-600 hover:text-slate-900 font-semibold flex items-center gap-1 transition"
                  >
                    <HelpCircle className="w-3.5 h-3.5" />
                    <span>Lamination Guide</span>
                  </button>

                  <button
                    onClick={handlePrintCard}
                    className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl shadow transition flex items-center gap-2 text-xs"
                  >
                    <Printer className="w-4 h-4" />
                    <span>Print Physical Copy</span>
                  </button>
                </div>
              </div>

              {/* Lamination & Printing Instructions Banner */}
              {showPrintTips && (
                <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 text-xs text-amber-900 space-y-2 animate-in fade-in duration-150">
                  <h4 className="font-bold flex items-center gap-1.5 text-amber-950">
                    <Layers className="w-4 h-4 text-amber-700" />
                    Printing & Lamination Specifications (Standard ISO CR-80 Format):
                  </h4>
                  <ul className="list-disc pl-5 space-y-1 text-[11px] text-amber-800">
                    <li><strong>Paper Scale:</strong> Set your print dialog scale to <strong>100% / Actual Size</strong> (Do NOT select "Fit to Page").</li>
                    <li><strong>Card Dimensions:</strong> Standard CR-80 pocket size: <strong>85.6 mm × 53.98 mm</strong> (3.375" × 2.125").</li>
                    <li><strong>Paper Type:</strong> Recommend 200–250 gsm heavy matte paper or photo cardstock.</li>
                    <li><strong>Assembly:</strong> Cut along outer corner crop marks (<Scissors className="w-3 h-3 inline text-amber-700" />), fold along the center dotted line, and seal in a 5–7 mil laminating pouch.</li>
                  </ul>
                </div>
              )}

              {/* LIVE PHYSICAL CARD PREVIEW CONTAINER */}
              <div className="p-6 bg-slate-200 rounded-2xl border-2 border-dashed border-slate-300 flex flex-col items-center justify-center">
                <span className="text-[11px] font-bold text-slate-600 uppercase tracking-widest mb-4 flex items-center gap-1.5">
                  <Scissors className="w-3.5 h-3.5 text-slate-500" />
                  Cut & Fold Preview (Actual Card Size Ratio)
                </span>

                {/* Physical Card Sheet Preview */}
                <div className={`flex flex-col md:flex-row items-center justify-center gap-6 bg-white p-6 rounded-2xl shadow-lg border border-slate-300 max-w-full ${
                  printColorMode === 'bw' ? 'grayscale contrast-125' : ''
                }`}>
                  
                  {/* FRONT SIDE */}
                  <div className="w-[325px] h-[205px] bg-white rounded-xl border-2 border-slate-800 shadow-md relative overflow-hidden flex flex-col justify-between p-3 select-none text-slate-900">
                    
                    {/* Top Malawi Flag Stripe */}
                    <div className="absolute top-0 left-0 right-0 h-1.5 flex">
                      <div className="flex-1 bg-black" />
                      <div className="flex-1 bg-red-600" />
                      <div className="flex-1 bg-emerald-600" />
                    </div>

                    {/* Card Header */}
                    <div className="flex items-start justify-between gap-2 pt-1 border-b border-slate-200 pb-1.5">
                      <div className="flex items-center gap-2">
                        <div className="w-9 h-9 rounded-lg bg-slate-950 border border-emerald-600 flex items-center justify-center text-emerald-400 font-black text-xs shrink-0 shadow-xs">
                          STC
                        </div>
                        <div>
                          <span className="text-[7.5px] font-bold text-slate-600 uppercase tracking-tight block">
                            Republic of Malawi • Ministry of Labour
                          </span>
                          <h3 className="text-xs font-black uppercase text-slate-950 tracking-tight font-serif leading-none">
                            Soche Technical College
                          </h3>
                          <span className="text-[8px] font-bold text-emerald-700 tracking-wide uppercase">
                            Student Identity Card
                          </span>
                        </div>
                      </div>

                      <div className="text-right shrink-0">
                        <span className="text-[7px] font-mono text-slate-500 uppercase block">Intake</span>
                        <span className="text-[8.5px] font-mono font-bold bg-slate-100 px-1 py-0.5 rounded border border-slate-300">
                          2026-II
                        </span>
                      </div>
                    </div>

                    {/* Card Body */}
                    <div className="grid grid-cols-12 gap-2 items-center my-auto">
                      {/* Photo */}
                      <div className="col-span-4 flex flex-col items-center">
                        <div className="relative">
                          <img
                            src={currentPhoto}
                            alt={studentName}
                            className="w-18 h-22 object-cover rounded-md border-2 border-slate-800 shadow-xs bg-slate-100"
                          />
                          <div className="absolute bottom-0 inset-x-0 bg-slate-900/80 text-[6.5px] text-white text-center font-mono py-0.2">
                            VALID
                          </div>
                        </div>
                      </div>

                      {/* Info */}
                      <div className="col-span-8 space-y-1 text-left">
                        <div>
                          <span className="text-[7px] text-slate-500 uppercase font-bold block leading-tight">Student Name</span>
                          <h4 className="text-[11px] font-black text-slate-900 uppercase truncate leading-tight">
                            {studentName}
                          </h4>
                        </div>

                        <div className="grid grid-cols-2 gap-1">
                          <div>
                            <span className="text-[7px] text-slate-500 uppercase font-bold block leading-tight">Student ID</span>
                            <span className="font-mono font-black text-[9.5px] text-emerald-800 leading-tight">
                              {studentId}
                            </span>
                          </div>
                          <div>
                            <span className="text-[7px] text-slate-500 uppercase font-bold block leading-tight">Expires</span>
                            <span className="font-mono font-bold text-[9px] text-slate-800 leading-tight">
                              DEC 2026
                            </span>
                          </div>
                        </div>

                        <div>
                          <span className="text-[7px] text-slate-500 uppercase font-bold block leading-tight">Course / Programme</span>
                          <p className="text-[8.5px] font-semibold text-slate-800 truncate leading-tight">
                            {courseTitle}
                          </p>
                        </div>

                        <div className="pt-0.5 flex items-center justify-between">
                          <span className={`text-[7px] font-black px-1.5 py-0.5 rounded uppercase tracking-wider ${
                            isFullyPaid ? 'bg-emerald-100 text-emerald-900 border border-emerald-300' : 'bg-amber-100 text-amber-900 border border-amber-300'
                          }`}>
                            {regStatusText}
                          </span>

                          <div className="w-7 h-7 bg-white p-0.5 border border-slate-300 rounded shadow-xs shrink-0">
                            {qrCodeDataUrl ? (
                              <img src={qrCodeDataUrl} alt="QR" className="w-full h-full object-contain" />
                            ) : (
                              <QrCode className="w-full h-full text-slate-400" />
                            )}
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Card Footer Bar */}
                    <div className="border-t border-slate-200 pt-1 flex items-center justify-between text-[7px] text-slate-500 font-mono">
                      <span>STC/SEC-REG-2026</span>
                      <span className="font-bold text-slate-700 uppercase">FRONT FACE</span>
                      <span>LIMBE • MALAWI</span>
                    </div>

                    {/* Corner crop mark guides */}
                    <div className="absolute top-1 left-1 text-[8px] text-slate-400 font-mono pointer-events-none">┌</div>
                    <div className="absolute top-1 right-1 text-[8px] text-slate-400 font-mono pointer-events-none">┐</div>
                    <div className="absolute bottom-1 left-1 text-[8px] text-slate-400 font-mono pointer-events-none">└</div>
                    <div className="absolute bottom-1 right-1 text-[8px] text-slate-400 font-mono pointer-events-none">┘</div>
                  </div>

                  {/* BACK SIDE (IF ENABLED) */}
                  {includeBackSide && (
                    <div className="w-[325px] h-[205px] bg-slate-50 rounded-xl border-2 border-slate-800 shadow-md relative overflow-hidden flex flex-col justify-between p-3 select-none text-slate-900">
                      
                      {/* Magnetic Stripe Simulator */}
                      <div className="absolute top-0 left-0 right-0 h-5 bg-slate-950 flex items-center justify-end px-3">
                        <span className="text-[6.5px] font-mono text-slate-400">STC MAGNETIC SMART CODE</span>
                      </div>

                      {/* Back Header */}
                      <div className="pt-5 border-b border-slate-200 pb-1 flex items-center justify-between">
                        <span className="text-[7.5px] font-black uppercase text-slate-800">
                          INSTITUTIONAL REGULATIONS & GUARDIAN DETAILS
                        </span>
                        <span className="text-[7px] font-bold text-emerald-800">ACCREDITED</span>
                      </div>

                      {/* Back Content */}
                      <div className="space-y-1.5 text-[7.5px] text-slate-700 leading-tight my-auto">
                        <p className="italic text-slate-600">
                          1. This card is property of Soche Technical College and is non-transferable.
                        </p>
                        <p>
                          2. Must be presented for library borrowing, computer lab access, and all end-of-term examinations.
                        </p>
                        <div className="bg-white p-1.5 rounded border border-slate-200 space-y-0.5">
                          <div className="flex justify-between font-mono text-[7px]">
                            <span className="text-slate-500">Official Bank:</span>
                            <strong className="text-slate-900">National Bank of Malawi</strong>
                          </div>
                          <div className="flex justify-between font-mono text-[7px]">
                            <span className="text-slate-500">Account No:</span>
                            <strong className="text-emerald-800">1003452219 (Customs Road)</strong>
                          </div>
                          <div className="flex justify-between font-mono text-[7px]">
                            <span className="text-slate-500">Campus Contact:</span>
                            <span className="text-slate-800">+265 1 845 384 / +265 882 497 114</span>
                          </div>
                        </div>

                        {/* Stamp & Authorized Signature */}
                        <div className="flex items-center justify-between pt-1">
                          <div className="border border-red-500 text-red-600 px-2 py-0.5 rounded text-[7px] font-black uppercase transform -rotate-3">
                            OFFICIAL REGISTRY STAMP 2026
                          </div>
                          <div className="text-right">
                            <div className="w-20 border-b border-slate-800 mb-0.5" />
                            <span className="text-[6.5px] font-mono text-slate-600 block uppercase">College Registrar</span>
                          </div>
                        </div>
                      </div>

                      {/* Card Back Footer */}
                      <div className="border-t border-slate-200 pt-1 flex items-center justify-between text-[7px] text-slate-500 font-mono">
                        <span>Private Bag 515, Limbe</span>
                        <span className="font-bold text-slate-700 uppercase">BACK FACE</span>
                        <span>sochetech.org</span>
                      </div>

                      {/* Corner crop mark guides */}
                      <div className="absolute top-1 left-1 text-[8px] text-slate-400 font-mono pointer-events-none">┌</div>
                      <div className="absolute top-1 right-1 text-[8px] text-slate-400 font-mono pointer-events-none">┐</div>
                      <div className="absolute bottom-1 left-1 text-[8px] text-slate-400 font-mono pointer-events-none">└</div>
                      <div className="absolute bottom-1 right-1 text-[8px] text-slate-400 font-mono pointer-events-none">┘</div>
                    </div>
                  )}

                </div>

                {/* Fold instruction hint */}
                {includeBackSide && (
                  <p className="text-[10px] text-slate-500 font-mono mt-3 text-center">
                    - - - - - - - - - - - - - - - - - - - FOLD ALONG CENTER LINE AFTER PRINTING - - - - - - - - - - - - - - - - - - -
                  </p>
                )}
              </div>

              {/* Photo customization trigger in print tab */}
              <div className="flex flex-wrap items-center justify-between gap-3 bg-slate-50 p-3.5 rounded-xl border border-slate-200 text-xs">
                <div className="flex items-center gap-2">
                  <img src={currentPhoto} alt="Student" className="w-9 h-9 rounded-lg object-cover border border-slate-300" />
                  <div>
                    <span className="font-bold text-slate-800 block">Student Identity Photo</span>
                    <span className="text-[11px] text-slate-500">Passport-style portrait for physical printing</span>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    className="px-3 py-1.5 bg-white hover:bg-slate-100 border border-slate-300 text-slate-800 font-semibold rounded-lg transition flex items-center gap-1.5 text-xs shadow-xs"
                  >
                    <Camera className="w-3.5 h-3.5 text-slate-600" />
                    <span>Upload New Photo</span>
                  </button>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handlePhotoUpload}
                    className="hidden"
                  />
                </div>
              </div>

            </div>
          )}

          {/* ======================================================== */}
          {/* TAB 2: DIGITAL SMART PASS & LIVE SCANNER VIEW */}
          {/* ======================================================== */}
          {activeTab === 'digital' && (
            <div className="space-y-6">
              
              {/* THE DIGITAL ID CARD CANVAS */}
              <div className="relative bg-gradient-to-br from-slate-900 via-slate-900 to-slate-950 text-white rounded-2xl p-5 sm:p-6 shadow-xl border-2 border-emerald-500/40 overflow-hidden">
                <div className="absolute top-0 right-0 w-64 h-64 bg-emerald-500/5 rounded-full blur-3xl pointer-events-none" />
                <div className="absolute -bottom-10 -left-10 w-48 h-48 bg-blue-500/5 rounded-full blur-2xl pointer-events-none" />
                
                {/* Card Header */}
                <div className="border-b border-slate-700/80 pb-3 flex items-start justify-between gap-3 relative z-10">
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 rounded-xl bg-slate-950 border-2 border-emerald-400 flex items-center justify-center shadow-inner">
                      <span className="font-black text-emerald-400 text-lg tracking-tighter">STC</span>
                    </div>
                    <div>
                      <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest block">
                        Republic of Malawi • Ministry of Labour
                      </span>
                      <h3 className="text-base sm:text-lg font-black tracking-tight uppercase text-white font-serif">
                        Soche Technical College
                      </h3>
                      <span className="text-[10px] text-emerald-400 font-semibold tracking-wide">
                        CONTINUING EDUCATION PROGRAMMES • DIGITAL SMART PASS
                      </span>
                    </div>
                  </div>

                  <div className="text-right shrink-0">
                    <span className="text-[9px] font-mono text-slate-400 block uppercase">Intake Session</span>
                    <span className="text-xs font-bold text-white font-mono bg-slate-800 px-2 py-0.5 rounded border border-slate-700">
                      2026-II (JUL–DEC)
                    </span>
                  </div>
                </div>

                {/* Card Content Grid */}
                <div className="pt-4 grid grid-cols-1 sm:grid-cols-12 gap-4 items-center relative z-10">
                  
                  {/* Photo & Upload Trigger */}
                  <div className="sm:col-span-4 flex flex-col items-center text-center space-y-2">
                    <div className="relative group">
                      <img
                        src={currentPhoto}
                        alt={studentName}
                        className="w-28 h-32 sm:w-32 sm:h-36 object-cover rounded-xl border-2 border-emerald-400 shadow-md bg-slate-800"
                      />
                      
                      <button
                        onClick={() => fileInputRef.current?.click()}
                        className="absolute inset-0 bg-slate-950/70 text-white rounded-xl opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-center gap-1 text-[11px] font-semibold cursor-pointer"
                      >
                        <Camera className="w-5 h-5 text-emerald-400" />
                        <span>Change Photo</span>
                      </button>
                    </div>

                    <div className="space-y-0.5">
                      <span className={`inline-block px-2.5 py-0.5 rounded-full text-[10px] font-black uppercase tracking-wider ${regStatusColor}`}>
                        {regStatusText}
                      </span>
                      <p className="text-[9px] text-slate-400 font-mono">
                        Valid: Jul 2026 – Dec 2026
                      </p>
                    </div>
                  </div>

                  {/* Student Metadata */}
                  <div className="sm:col-span-5 space-y-2.5 text-left text-xs">
                    <div>
                      <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">
                        Student Full Name
                      </span>
                      <strong className="text-sm sm:text-base font-bold text-white block">
                        {studentName}
                      </strong>
                    </div>

                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">
                          Student ID No.
                        </span>
                        <span className="font-mono font-bold text-emerald-400 text-xs">
                          {studentId}
                        </span>
                      </div>
                      <div>
                        <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">
                          Study Mode
                        </span>
                        <span className="text-slate-200 font-medium text-[11px]">
                          Day-Release
                        </span>
                      </div>
                    </div>

                    <div>
                      <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">
                        Enrolled Programme & Level
                      </span>
                      <p className="text-slate-200 font-medium text-[11px] leading-tight">
                        {courseTitle}
                      </p>
                    </div>

                    <div>
                      <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">
                        Financial Clearance Status
                      </span>
                      <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-300">
                        <CheckCircle2 className="w-3.5 h-3.5" />
                        {feeStatusBadge}
                      </span>
                    </div>
                  </div>

                  {/* High-Resolution QR Code */}
                  <div className="sm:col-span-3 flex flex-col items-center justify-center p-2 bg-white rounded-xl shadow-inner text-slate-900 text-center">
                    {qrCodeDataUrl ? (
                      <img
                        src={qrCodeDataUrl}
                        alt="Digital Student Identification QR Code"
                        className="w-24 h-24 sm:w-28 sm:h-28 object-contain"
                      />
                    ) : (
                      <div className="w-24 h-24 bg-slate-100 flex items-center justify-center animate-pulse">
                        <QrCode className="w-8 h-8 text-slate-400" />
                      </div>
                    )}
                    <span className="text-[8px] font-mono font-bold text-slate-700 tracking-tighter uppercase mt-0.5">
                      Scan to Verify
                    </span>
                    <span className="text-[7px] font-mono text-slate-500 uppercase">
                      STC/2026-SEC
                    </span>
                  </div>

                </div>

                {/* Card Footer Bar */}
                <div className="mt-4 pt-3 border-t border-slate-800 flex items-center justify-between text-[10px] text-slate-400 relative z-10">
                  <span className="font-mono">National Bank Customs Road Service Centre A/C 1003452219</span>
                  <span className="font-semibold text-emerald-400 flex items-center gap-1">
                    <ShieldCheck className="w-3.5 h-3.5" />
                    Accredited Institutional Credential
                  </span>
                </div>

              </div>

              {/* Actions & Live Simulator */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 text-xs">
                <button
                  onClick={() => fileInputRef.current?.click()}
                  className="p-2.5 bg-slate-100 hover:bg-slate-200 text-slate-800 rounded-xl font-semibold flex items-center justify-center gap-1.5 transition border border-slate-300"
                >
                  <Camera className="w-3.5 h-3.5 text-slate-600" />
                  <span>Upload Photo</span>
                </button>

                <button
                  onClick={handleDownloadQr}
                  className="p-2.5 bg-slate-100 hover:bg-slate-200 text-slate-800 rounded-xl font-semibold flex items-center justify-center gap-1.5 transition border border-slate-300"
                >
                  <Download className="w-3.5 h-3.5 text-slate-600" />
                  <span>Save QR Code</span>
                </button>

                <button
                  onClick={handleCopyVerification}
                  className="p-2.5 bg-slate-100 hover:bg-slate-200 text-slate-800 rounded-xl font-semibold flex items-center justify-center gap-1.5 transition border border-slate-300"
                >
                  {copied ? (
                    <>
                      <Check className="w-3.5 h-3.5 text-emerald-600" />
                      <span className="text-emerald-700">Copied Info</span>
                    </>
                  ) : (
                    <>
                      <Copy className="w-3.5 h-3.5 text-slate-600" />
                      <span>Copy ID Data</span>
                    </>
                  )}
                </button>

                <button
                  onClick={handleSimulateScan}
                  className="p-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold flex items-center justify-center gap-1.5 transition shadow"
                >
                  <QrCode className="w-3.5 h-3.5" />
                  <span>Test Scanner</span>
                </button>
              </div>

              {/* Live Scanner Verification Results Simulation */}
              {scanResult && (
                <div className="p-4 bg-emerald-50 border-2 border-emerald-300 rounded-2xl space-y-2.5 animate-in fade-in duration-200">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <ShieldCheck className="w-5 h-5 text-emerald-700" />
                      <h4 className="text-xs font-bold text-emerald-950 uppercase tracking-wide">
                        Gate & Exam Room Verification Successful
                      </h4>
                    </div>
                    <span className="text-[10px] font-mono bg-emerald-200 text-emerald-900 font-bold px-2 py-0.5 rounded">
                      AUTHENTIC
                    </span>
                  </div>

                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
                    <div className="bg-white p-2.5 rounded-lg border border-emerald-200">
                      <span className="text-[10px] text-slate-500 block uppercase font-semibold">Student ID</span>
                      <strong className="font-mono text-slate-900">{scanResult.std_id}</strong>
                    </div>
                    <div className="bg-white p-2.5 rounded-lg border border-emerald-200">
                      <span className="text-[10px] text-slate-500 block uppercase font-semibold">Name</span>
                      <strong className="text-slate-900 truncate block">{scanResult.name}</strong>
                    </div>
                    <div className="bg-white p-2.5 rounded-lg border border-emerald-200">
                      <span className="text-[10px] text-slate-500 block uppercase font-semibold">Academic Intake</span>
                      <span className="text-slate-800 font-medium text-[11px] block">{scanResult.intake}</span>
                    </div>
                    <div className="bg-white p-2.5 rounded-lg border border-emerald-200">
                      <span className="text-[10px] text-slate-500 block uppercase font-semibold">Clearance</span>
                      <span className="text-emerald-700 font-bold text-[11px] block">{scanResult.fee_clearance}</span>
                    </div>
                  </div>

                  <p className="text-[11px] text-slate-600 leading-normal">
                    Card validated against Soche Technical College Central Registry. Eligible for campus access, laboratory entry, library borrowing, and July – December 2026 examinations.
                  </p>
                </div>
              )}

            </div>
          )}

        </div>

        {/* Modal Footer Controls */}
        <div className="bg-slate-100 px-6 py-3 border-t border-slate-200 flex flex-wrap items-center justify-between text-xs gap-3">
          <span className="text-slate-500 text-[11px]">
            Soche Technical College • Private Bag 515, Limbe, Malawi
          </span>

          <div className="flex items-center gap-2">
            <button
              onClick={handlePrintCard}
              className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white font-bold rounded-xl transition flex items-center gap-1.5 shadow-xs"
            >
              <Printer className="w-3.5 h-3.5" />
              <span>Print Physical ID (100% Scale)</span>
            </button>
            
            <button
              onClick={onClose}
              className="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-800 font-semibold rounded-xl transition"
            >
              Close
            </button>
          </div>
        </div>

      </div>

      {/* ======================================================== */}
      {/* ISOLATED PRINT-ONLY SHEET (Rendered exclusively by @media print) */}
      {/* ======================================================== */}
      <div id="printable-id-sheet" className="hidden print:block text-black bg-white font-sans">
        
        {/* Print Sheet Header Instructions */}
        <div className="border-b-2 border-black pb-3 mb-6 flex justify-between items-end">
          <div>
            <h1 className="text-lg font-black uppercase font-serif tracking-tight">
              SOCHE TECHNICAL COLLEGE • OFFICIAL STUDENT IDENTITY CARD
            </h1>
            <p className="text-xs text-gray-700 font-medium">
              Ministry of Labour & Manpower Development • Continuing Education Programmes (July – December 2026)
            </p>
          </div>
          <div className="text-right text-[10px] font-mono">
            <span>PRINT DATE: {new Date().toLocaleDateString('en-GB')}</span>
            <br />
            <span>FORMAT: ISO/IEC 7810 ID-1 (CR-80 STANDARD)</span>
          </div>
        </div>

        {/* 100% SCALE VERIFICATION GUIDE BOX */}
        <div className="mb-6 p-2 border border-gray-400 rounded flex items-center justify-between text-[9px] text-gray-600 bg-gray-50">
          <span>📐 <strong>Scale Verification Gauge:</strong> If printed at 100% (No Scale), this ruler measure exactly 2.0 inches (50.8 mm):</span>
          <div className="w-[192px] h-3 border-x border-b border-black text-[8px] font-mono text-center flex items-center justify-between px-1">
            <span>0"</span>
            <span>1"</span>
            <span>2"</span>
          </div>
        </div>

        {/* PRINTABLE CARDS CONTAINER */}
        <div className="flex flex-row items-center justify-center gap-6 my-4">
          
          {/* PRINTABLE FRONT FACE (Exact ISO 85.6mm x 54mm = approx 325px x 205px at standard display DPI) */}
          <div className="w-[325px] h-[205px] bg-white border-2 border-black rounded-lg relative overflow-hidden flex flex-col justify-between p-3 box-border">
            
            {/* Malawi Flag Header Bar */}
            <div className="absolute top-0 left-0 right-0 h-1.5 flex">
              <div className="flex-1 bg-black" />
              <div className="flex-1 bg-red-600" />
              <div className="flex-1 bg-emerald-600" />
            </div>

            {/* Front Header */}
            <div className="flex items-start justify-between gap-2 pt-1 border-b border-black pb-1">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-black text-white font-black text-xs flex items-center justify-center rounded">
                  STC
                </div>
                <div>
                  <span className="text-[7px] font-bold text-gray-700 uppercase tracking-tight block">
                    Republic of Malawi • Ministry of Labour
                  </span>
                  <h2 className="text-[11px] font-black uppercase font-serif text-black leading-none">
                    Soche Technical College
                  </h2>
                  <span className="text-[7.5px] font-bold text-emerald-800 tracking-wider uppercase block">
                    Student Identity Card
                  </span>
                </div>
              </div>

              <div className="text-right">
                <span className="text-[6.5px] font-mono text-gray-600 uppercase block">Session</span>
                <span className="text-[8px] font-mono font-black border border-black px-1 py-0.2 rounded">
                  2026-II
                </span>
              </div>
            </div>

            {/* Front Body */}
            <div className="grid grid-cols-12 gap-2 items-center my-auto">
              {/* Photo */}
              <div className="col-span-4 flex flex-col items-center">
                <img
                  src={currentPhoto}
                  alt={studentName}
                  className="w-18 h-22 object-cover border-2 border-black rounded shadow-none"
                />
              </div>

              {/* Metadata */}
              <div className="col-span-8 space-y-1 text-left">
                <div>
                  <span className="text-[6.5px] text-gray-600 uppercase font-bold block leading-tight">Student Full Name</span>
                  <h3 className="text-[11px] font-black text-black uppercase leading-tight truncate">
                    {studentName}
                  </h3>
                </div>

                <div className="grid grid-cols-2 gap-1">
                  <div>
                    <span className="text-[6.5px] text-gray-600 uppercase font-bold block leading-tight">Student ID</span>
                    <span className="font-mono font-black text-[9px] text-black leading-tight">
                      {studentId}
                    </span>
                  </div>
                  <div>
                    <span className="text-[6.5px] text-gray-600 uppercase font-bold block leading-tight">Valid Through</span>
                    <span className="font-mono font-bold text-[8.5px] text-black leading-tight">
                      31 DEC 2026
                    </span>
                  </div>
                </div>

                <div>
                  <span className="text-[6.5px] text-gray-600 uppercase font-bold block leading-tight">Programme of Study</span>
                  <p className="text-[8px] font-bold text-gray-900 truncate leading-tight">
                    {courseTitle}
                  </p>
                </div>

                <div className="pt-0.5 flex items-center justify-between">
                  <span className="text-[7px] font-black border border-black px-1.5 py-0.2 uppercase">
                    {regStatusText}
                  </span>

                  <div className="w-7 h-7 bg-white p-0.5 border border-black rounded shrink-0">
                    {qrCodeDataUrl && (
                      <img src={qrCodeDataUrl} alt="QR" className="w-full h-full object-contain" />
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Front Footer */}
            <div className="border-t border-black pt-0.5 flex items-center justify-between text-[6.5px] font-mono text-gray-700">
              <span>SECURITY: {qrPayload.security_hash}</span>
              <span className="font-bold text-black uppercase">FRONT FACE</span>
              <span>LIMBE, MALAWI</span>
            </div>

            {/* Corner Crop Marks */}
            <div className="absolute top-0.5 left-0.5 text-[8px] font-mono leading-none">┌</div>
            <div className="absolute top-0.5 right-0.5 text-[8px] font-mono leading-none">┐</div>
            <div className="absolute bottom-0.5 left-0.5 text-[8px] font-mono leading-none">└</div>
            <div className="absolute bottom-0.5 right-0.5 text-[8px] font-mono leading-none">┘</div>
          </div>

          {/* PRINTABLE BACK FACE (IF INCLUDED) */}
          {includeBackSide && (
            <div className="w-[325px] h-[205px] bg-white border-2 border-black rounded-lg relative overflow-hidden flex flex-col justify-between p-3 box-border">
              
              {/* Magnetic Stripe Bar */}
              <div className="absolute top-0 left-0 right-0 h-4.5 bg-black flex items-center justify-between px-3">
                <span className="text-[6px] font-mono text-white">SOCHE TECHNICAL COLLEGE</span>
                <span className="text-[6px] font-mono text-white">SMART ID # {studentId}</span>
              </div>

              {/* Back Header */}
              <div className="pt-4 border-b border-black pb-0.5 flex items-center justify-between">
                <span className="text-[7px] font-black uppercase text-black">
                  CARD CONDITIONS & CAMPUS POLICIES
                </span>
                <span className="text-[6.5px] font-bold text-gray-700">STC/REG/2026</span>
              </div>

              {/* Back Info */}
              <div className="space-y-1 text-[7px] text-gray-800 leading-tight my-auto">
                <p>1. This card is property of Soche Technical College. Unauthorized possession or alteration is strictly prohibited.</p>
                <p>2. Must be presented at college gates, laboratories, library services, and for entrance to examinations.</p>
                
                <div className="border border-black p-1 rounded space-y-0.5 bg-gray-50 text-[6.5px] font-mono">
                  <div className="flex justify-between">
                    <span>College Account:</span>
                    <strong>National Bank (Customs Road) #1003452219</strong>
                  </div>
                  <div className="flex justify-between">
                    <span>Registry Tel:</span>
                    <span>+265 1 845 384 / +265 882 497 114</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Postal:</span>
                    <span>Private Bag 515, Limbe, Republic of Malawi</span>
                  </div>
                </div>

                <div className="flex items-center justify-between pt-1">
                  <div className="border-2 border-red-600 text-red-600 px-1.5 py-0.2 rounded text-[6.5px] font-black uppercase tracking-wider">
                    OFFICIALLY VALIDATED 2026
                  </div>
                  <div className="text-right">
                    <div className="w-18 border-b border-black mb-0.5" />
                    <span className="text-[6px] font-mono uppercase text-gray-700 block">Registrar Signature</span>
                  </div>
                </div>
              </div>

              {/* Back Footer */}
              <div className="border-t border-black pt-0.5 flex items-center justify-between text-[6.5px] font-mono text-gray-700">
                <span>If found, return to STC Registry</span>
                <span className="font-bold text-black uppercase">BACK FACE</span>
                <span>www.sochetech.org</span>
              </div>

              {/* Corner Crop Marks */}
              <div className="absolute top-0.5 left-0.5 text-[8px] font-mono leading-none">┌</div>
              <div className="absolute top-0.5 right-0.5 text-[8px] font-mono leading-none">┐</div>
              <div className="absolute bottom-0.5 left-0.5 text-[8px] font-mono leading-none">└</div>
              <div className="absolute bottom-0.5 right-0.5 text-[8px] font-mono leading-none">┘</div>
            </div>
          )}

        </div>

        {/* Assembly Cut & Laminate Guidelines for Print Sheet */}
        <div className="mt-8 pt-4 border-t border-gray-300 text-[9px] text-gray-600 space-y-1">
          <p className="font-bold text-black uppercase flex items-center gap-1">
            ✂ ASSEMBLY INSTRUCTIONS:
          </p>
          <ol className="list-decimal pl-4 space-y-0.5 text-[8.5px]">
            <li>Cut out both Front and Back faces along the outer corner crop marks.</li>
            <li>Fold along the central alignment line back-to-back, or paste together using adhesive.</li>
            <li>Insert into a standard 54 mm × 86 mm (CR-80) ID card laminating pouch (5 to 7 mil heat seal).</li>
          </ol>
        </div>

      </div>

    </div>
  );
};
