import { useState, useRef, useEffect } from "react";

// ─── THEME ────────────────────────────────────────────────────────────────────
const T = {
  royalBlue: "#1a3a8f",
  royalDark: "#0f2260",
  royalLight: "#2451c7",
  gold: "#c9920a",
  goldLight: "#f0c040",
  goldBright: "#FFD700",
  white: "#ffffff",
  offWhite: "#f8f6f0",
  black: "#080c1a",
  gray: "#1e1e2e",
  muted: "#7a7a9a",
};

// ─── DATA ─────────────────────────────────────────────────────────────────────
const MODULES = [
  { id: 1,  title: "Mindset & Vision",           icon: "🧠", subtitle: "Foundation for Success",          color: "#1a3a8f" },
  { id: 2,  title: "TAG Markets Fundamentals",   icon: "🏢", subtitle: "Products, Services & Model",      color: "#0f2260" },
  { id: 3,  title: "List Building Mastery",      icon: "📋", subtitle: "Build Your Prospect Pipeline",    color: "#1a5276" },
  { id: 4,  title: "Invitation Skills",          icon: "📞", subtitle: "Phone, WhatsApp & Social",        color: "#1a3a8f" },
  { id: 5,  title: "Presentation Skills",        icon: "🎤", subtitle: "Zoom, Storytelling & Confidence", color: "#0f2260" },
  { id: 6,  title: "Follow-Up Mastery",          icon: "🔄", subtitle: "Objection Handling & Closing",    color: "#1a5276" },
  { id: 7,  title: "Social Media Marketing",     icon: "📱", subtitle: "Facebook, Instagram & Reels",     color: "#1a3a8f" },
  { id: 8,  title: "Personal Branding",          icon: "⭐", subtitle: "Profile, Content & Authority",    color: "#0f2260" },
  { id: 9,  title: "Customer Acquisition",       icon: "🎯", subtitle: "Lead Conversion & Retention",     color: "#1a5276" },
  { id: 10, title: "Leadership & Duplication",   icon: "👑", subtitle: "Coaching & Team Building",        color: "#0f2260" },
];

const SPECIAL_CERTS = [
  { id: "master",   title: "Master Affiliate Marketer",  icon: "🏆", subtitle: "Complete Academy Graduate", color: "#c9920a" },
  { id: "thailand", title: "Thailand Achievers Club",    icon: "🌴", subtitle: "Elite Performance Award",   color: "#1a3a8f" },
  { id: "dubai",    title: "Dubai Achievers Club",       icon: "🌆", subtitle: "Diamond Excellence Award",  color: "#0f2260" },
  { id: "leader",   title: "Certified Team Leader",      icon: "💎", subtitle: "Leadership Certification",  color: "#6b21a8" },
];

const SAMPLE_MEMBERS = [
  { id: 1, name: "Priya Sharma",    rank: "Gold Achiever",     region: "Maharashtra", completedModules: [1,2,3,4,5,6,7,8,9,10], points: 8450, joinDate: "2025-01-15" },
  { id: 2, name: "Rahul Mehta",     rank: "Diamond Leader",    region: "Gujarat",     completedModules: [1,2,3,4,5,6,7,8],     points: 6200, joinDate: "2025-03-10" },
  { id: 3, name: "Ananya Reddy",    rank: "Platinum Achiever", region: "Telangana",   completedModules: [1,2,3,4,5,6],         points: 4100, joinDate: "2025-02-20" },
  { id: 4, name: "Vikram Singh",    rank: "Silver Achiever",   region: "Delhi NCR",   completedModules: [1,2,3,4],             points: 2800, joinDate: "2025-04-05" },
  { id: 5, name: "Deepika Nair",    rank: "Crown Ambassador",  region: "Kerala",      completedModules: [1,2,3,4,5,6,7,8,9],  points: 12400, joinDate: "2024-11-01" },
];

function formatDate(d) {
  const date = d ? new Date(d) : new Date();
  return date.toLocaleDateString("en-IN", { day: "numeric", month: "long", year: "numeric" });
}

function generateCertId(memberId, certType) {
  const hash = ((memberId * 7 + certType.length * 13) % 9000) + 1000;
  return `TGM-${new Date().getFullYear()}-${hash}`;
}

// ─── CERTIFICATE CANVAS (rendered to DOM, screenshot-able) ───────────────────
function CertificateCanvas({ member, certType, certData, scale = 1 }) {
  const isModule = typeof certType === "number";
  const module   = isModule ? MODULES.find(m => m.id === certType) : null;
  const special  = !isModule ? SPECIAL_CERTS.find(s => s.id === certType) : null;
  const cert     = module || special;
  const certId   = generateCertId(member.id, String(certType));
  const issueDate = formatDate(certData?.issueDate);

  const W = 960, H = 680;
  const sw = W * scale, sh = H * scale;

  return (
    <div data-cert-canvas="true" style={{
      width: sw, height: sh, position: "relative", overflow: "hidden",
      background: "#0a0e1f", fontFamily: "'Georgia', 'Times New Roman', serif",
      boxShadow: "0 30px 80px rgba(0,0,0,0.6)",
      transform: "translateZ(0)",
    }}>
      {/* Deep background */}
      <svg style={{ position:"absolute", inset:0, width:"100%", height:"100%" }} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
        {/* Navy gradient base */}
        <defs>
          <radialGradient id="bg1" cx="25%" cy="30%" r="60%">
            <stop offset="0%" stopColor="#0f2260" stopOpacity="1"/>
            <stop offset="100%" stopColor="#060918" stopOpacity="1"/>
          </radialGradient>
          <radialGradient id="glow1" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="#c9920a" stopOpacity="0.08"/>
            <stop offset="100%" stopColor="#c9920a" stopOpacity="0"/>
          </radialGradient>
          <linearGradient id="borderGrad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#FFD700"/>
            <stop offset="30%" stopColor="#c9920a"/>
            <stop offset="60%" stopColor="#FFD700"/>
            <stop offset="100%" stopColor="#c9920a"/>
          </linearGradient>
          <linearGradient id="innerBorder" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#c9920a" stopOpacity="0.4"/>
            <stop offset="50%" stopColor="#FFD700" stopOpacity="0.6"/>
            <stop offset="100%" stopColor="#c9920a" stopOpacity="0.4"/>
          </linearGradient>
          <filter id="glow">
            <feGaussianBlur stdDeviation="3" result="blur"/>
            <feComposite in="SourceGraphic" in2="blur" operator="over"/>
          </filter>
        </defs>

        {/* Base bg */}
        <rect width={W} height={H} fill="url(#bg1)"/>
        <rect width={W} height={H} fill="url(#glow1)"/>

        {/* Corner ornaments - top left */}
        <g opacity="0.7">
          <path d="M0,0 L120,0 L120,8 L8,8 L8,120 L0,120 Z" fill="url(#borderGrad)"/>
          <path d="M16,16 L100,16 L100,22 L22,22 L22,100 L16,100 Z" fill="url(#innerBorder)"/>
          <circle cx="20" cy="20" r="5" fill="#FFD700" opacity="0.8"/>
          <circle cx="100" cy="20" r="3" fill="#c9920a" opacity="0.6"/>
          <circle cx="20" cy="100" r="3" fill="#c9920a" opacity="0.6"/>
        </g>

        {/* Corner ornaments - top right */}
        <g opacity="0.7">
          <path d={`M${W},0 L${W-120},0 L${W-120},8 L${W-8},8 L${W-8},120 L${W},120 Z`} fill="url(#borderGrad)"/>
          <path d={`M${W-16},16 L${W-100},16 L${W-100},22 L${W-22},22 L${W-22},100 L${W-16},100 Z`} fill="url(#innerBorder)"/>
          <circle cx={W-20} cy="20" r="5" fill="#FFD700" opacity="0.8"/>
          <circle cx={W-100} cy="20" r="3" fill="#c9920a" opacity="0.6"/>
          <circle cx={W-20} cy="100" r="3" fill="#c9920a" opacity="0.6"/>
        </g>

        {/* Corner ornaments - bottom left */}
        <g opacity="0.7">
          <path d={`M0,${H} L120,${H} L120,${H-8} L8,${H-8} L8,${H-120} L0,${H-120} Z`} fill="url(#borderGrad)"/>
          <path d={`M16,${H-16} L100,${H-16} L100,${H-22} L22,${H-22} L22,${H-100} L16,${H-100} Z`} fill="url(#innerBorder)"/>
          <circle cx="20" cy={H-20} r="5" fill="#FFD700" opacity="0.8"/>
        </g>

        {/* Corner ornaments - bottom right */}
        <g opacity="0.7">
          <path d={`M${W},${H} L${W-120},${H} L${W-120},${H-8} L${W-8},${H-8} L${W-8},${H-120} L${W},${H-120} Z`} fill="url(#borderGrad)"/>
          <path d={`M${W-16},${H-16} L${W-100},${H-16} L${W-100},${H-22} L${W-22},${H-22} L${W-22},${H-100} L${W-16},${H-100} Z`} fill="url(#innerBorder)"/>
          <circle cx={W-20} cy={H-20} r="5" fill="#FFD700" opacity="0.8"/>
        </g>

        {/* Decorative horizontal lines */}
        <line x1="40" y1={H/2-1} x2="200" y2={H/2-1} stroke="#c9920a" strokeWidth="0.5" opacity="0.3"/>
        <line x1={W-40} y1={H/2-1} x2={W-200} y2={H/2-1} stroke="#c9920a" strokeWidth="0.5" opacity="0.3"/>

        {/* Subtle geometric background pattern */}
        {[...Array(6)].map((_, i) => (
          <circle key={i} cx={W/2} cy={H/2}
            r={80 + i*60} stroke="#c9920a" strokeWidth="0.3"
            fill="none" opacity={0.04 + i*0.01}/>
        ))}

        {/* Side decorative bars */}
        <rect x="0" y={H*0.3} width="3" height={H*0.4} fill="url(#borderGrad)" opacity="0.5"/>
        <rect x={W-3} y={H*0.3} width="3" height={H*0.4} fill="url(#borderGrad)" opacity="0.5"/>
      </svg>

      {/* Content layer */}
      <div style={{
        position: "absolute", inset: 0, display: "flex", flexDirection: "column",
        alignItems: "center", justifyContent: "center", padding: `${32*scale}px ${80*scale}px`,
        gap: 0,
      }}>

        {/* TOP: Organization name */}
        <div style={{
          color: T.goldLight, fontSize: 11*scale, letterSpacing: 6*scale,
          fontFamily: "'Georgia', serif", textTransform: "uppercase",
          marginBottom: 10*scale, opacity: 0.9,
        }}>
          TAG MARKETS SUCCESS ACADEMY
        </div>

        {/* Divider line with diamond */}
        <div style={{ display:"flex", alignItems:"center", gap: 12*scale, marginBottom: 16*scale }}>
          <div style={{ width: 60*scale, height: 1, background: `linear-gradient(to right, transparent, ${T.gold})` }}/>
          <div style={{ width: 8*scale, height: 8*scale, background: T.goldBright, transform: "rotate(45deg)" }}/>
          <div style={{ width: 60*scale, height: 1, background: `linear-gradient(to left, transparent, ${T.gold})` }}/>
        </div>

        {/* Certificate of Completion */}
        <div style={{
          color: "#e8d5a3", fontSize: 13*scale, letterSpacing: 8*scale,
          textTransform: "uppercase", marginBottom: 14*scale, opacity: 0.8,
          fontStyle: "italic",
        }}>
          Certificate of Completion
        </div>

        {/* Module icon */}
        <div style={{
          fontSize: 40*scale, marginBottom: 12*scale,
          filter: `drop-shadow(0 0 ${12*scale}px rgba(255,215,0,0.5))`,
          lineHeight: 1,
        }}>
          {cert?.icon}
        </div>

        {/* THIS IS TO CERTIFY */}
        <div style={{
          color: T.muted, fontSize: 10*scale, letterSpacing: 3*scale,
          textTransform: "uppercase", marginBottom: 8*scale,
        }}>
          This is to certify that
        </div>

        {/* Member name */}
        <div style={{
          color: T.white, fontSize: 36*scale, fontWeight: "bold",
          letterSpacing: 2*scale, textAlign: "center",
          textShadow: `0 0 ${30*scale}px rgba(201,146,10,0.4)`,
          marginBottom: 4*scale, lineHeight: 1.1,
        }}>
          {member.name}
        </div>

        {/* Rank */}
        <div style={{
          color: T.goldLight, fontSize: 11*scale, letterSpacing: 3*scale,
          marginBottom: 18*scale, opacity: 0.85,
        }}>
          {member.rank}  ·  {member.region}
        </div>

        {/* Divider */}
        <div style={{
          width: 300*scale, height: 1,
          background: `linear-gradient(to right, transparent, ${T.gold}, transparent)`,
          marginBottom: 18*scale, opacity: 0.4,
        }}/>

        {/* Has successfully completed */}
        <div style={{
          color: "#c8c8d8", fontSize: 11*scale, textAlign: "center",
          marginBottom: 10*scale, lineHeight: 1.6,
        }}>
          has successfully completed
        </div>

        {/* Module/Certificate title */}
        <div style={{
          color: T.goldBright, fontSize: 22*scale, fontWeight: "bold",
          letterSpacing: 1*scale, textAlign: "center", marginBottom: 4*scale,
          textShadow: `0 0 ${20*scale}px rgba(255,215,0,0.3)`,
        }}>
          {isModule ? `Module ${certType}: ${cert.title}` : cert?.title}
        </div>

        {/* Subtitle */}
        <div style={{
          color: "#9aaabb", fontSize: 10*scale, letterSpacing: 2*scale,
          marginBottom: 28*scale, textTransform: "uppercase",
        }}>
          {cert?.subtitle}
        </div>

        {/* Bottom row: signatures + date + cert ID */}
        <div style={{
          display: "flex", width: "100%", justifyContent: "space-between",
          alignItems: "flex-end", maxWidth: 700*scale,
        }}>
          {/* Issuer signature */}
          <div style={{ textAlign: "center" }}>
            <div style={{
              width: 100*scale, height: 1,
              background: `linear-gradient(to right, transparent, ${T.gold}, transparent)`,
              marginBottom: 4*scale,
            }}/>
            <div style={{ color: "#aab", fontSize: 8.5*scale, letterSpacing: 1*scale }}>
              ACADEMY DIRECTOR
            </div>
            <div style={{ color: T.gold, fontSize: 7.5*scale, letterSpacing: 0.5*scale, opacity: 0.7 }}>
              TAG Markets Global
            </div>
          </div>

          {/* Center seal */}
          <div style={{ textAlign: "center" }}>
            <div style={{
              width: 56*scale, height: 56*scale, borderRadius: "50%",
              border: `2px solid ${T.gold}`, display: "flex",
              flexDirection: "column", alignItems: "center", justifyContent: "center",
              background: "rgba(201,146,10,0.08)",
              boxShadow: `0 0 ${20*scale}px rgba(201,146,10,0.2)`,
              marginBottom: 4*scale,
            }}>
              <div style={{ fontSize: 20*scale }}>🏅</div>
            </div>
            <div style={{
              color: T.gold, fontSize: 7*scale, letterSpacing: 2*scale,
              textTransform: "uppercase", opacity: 0.8,
            }}>
              Verified
            </div>
          </div>

          {/* Date & cert ID */}
          <div style={{ textAlign: "center" }}>
            <div style={{
              width: 100*scale, height: 1,
              background: `linear-gradient(to right, transparent, ${T.gold}, transparent)`,
              marginBottom: 4*scale,
            }}/>
            <div style={{ color: "#aab", fontSize: 8.5*scale, letterSpacing: 1*scale }}>
              {issueDate}
            </div>
            <div style={{ color: T.gold, fontSize: 7.5*scale, letterSpacing: 0.5*scale, opacity: 0.7 }}>
              {certId}
            </div>
          </div>
        </div>

      </div>
    </div>
  );
}

// ─── MINI CERTIFICATE CARD (list view) ───────────────────────────────────────
function CertCard({ member, certType, onPreview, earned }) {
  const isModule = typeof certType === "number";
  const cert = isModule ? MODULES.find(m => m.id === certType) : SPECIAL_CERTS.find(s => s.id === certType);

  return (
    <div
      onClick={() => earned && onPreview({ member, certType })}
      style={{
        background: earned
          ? "linear-gradient(135deg, #0f1a3a 0%, #1a2a5a 100%)"
          : "rgba(255,255,255,0.03)",
        border: `1px solid ${earned ? "rgba(201,146,10,0.4)" : "rgba(255,255,255,0.07)"}`,
        borderRadius: 12, padding: "14px 16px",
        cursor: earned ? "pointer" : "default",
        transition: "all 0.2s",
        position: "relative", overflow: "hidden",
        opacity: earned ? 1 : 0.45,
      }}
      onMouseEnter={e => earned && (e.currentTarget.style.borderColor = "rgba(201,146,10,0.8)")}
      onMouseLeave={e => earned && (e.currentTarget.style.borderColor = "rgba(201,146,10,0.4)")}
    >
      {earned && (
        <div style={{
          position: "absolute", top: 0, right: 0,
          background: "linear-gradient(135deg, rgba(201,146,10,0.3), transparent)",
          width: 60, height: 60, borderRadius: "0 12px 0 60px",
        }}/>
      )}
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ fontSize: 24, lineHeight: 1 }}>{cert?.icon}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            color: earned ? T.goldLight : "#666", fontSize: 12,
            fontWeight: 600, marginBottom: 2,
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          }}>
            {isModule ? `Module ${certType}` : cert?.title}
          </div>
          <div style={{ color: "#888", fontSize: 11 }}>
            {isModule ? cert?.title : cert?.subtitle}
          </div>
        </div>
        {earned ? (
          <div style={{
            background: "rgba(201,146,10,0.15)", border: "1px solid rgba(201,146,10,0.4)",
            borderRadius: 20, padding: "2px 8px",
            color: T.goldLight, fontSize: 10, fontWeight: 700,
            whiteSpace: "nowrap",
          }}>✓ EARNED</div>
        ) : (
          <div style={{
            background: "rgba(255,255,255,0.04)", borderRadius: 20, padding: "2px 8px",
            color: "#555", fontSize: 10,
          }}>LOCKED</div>
        )}
      </div>
    </div>
  );
}

// ─── MODAL OVERLAY ────────────────────────────────────────────────────────────
function Modal({ children, onClose }) {
  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 1000,
        background: "rgba(0,0,0,0.85)", backdropFilter: "blur(8px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 20,
      }}
    >
      <div onClick={e => e.stopPropagation()} style={{ position: "relative" }}>
        {children}
        <button
          onClick={onClose}
          style={{
            position: "absolute", top: -14, right: -14,
            width: 32, height: 32, borderRadius: "50%",
            background: "#1a1a2e", border: "1px solid rgba(201,146,10,0.4)",
            color: T.goldLight, fontSize: 16, cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}
        >×</button>
      </div>
    </div>
  );
}

// ─── STATS BAR ────────────────────────────────────────────────────────────────
function StatBadge({ value, label, color }) {
  return (
    <div style={{
      background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)",
      borderRadius: 10, padding: "10px 16px", textAlign: "center",
    }}>
      <div style={{ color: color || T.goldLight, fontSize: 22, fontWeight: 700 }}>{value}</div>
      <div style={{ color: "#666", fontSize: 11, marginTop: 2 }}>{label}</div>
    </div>
  );
}

// ─── MAIN APP ─────────────────────────────────────────────────────────────────
export default function TagMarketsCertificates() {
  const [selectedMember, setSelectedMember] = useState(SAMPLE_MEMBERS[0]);
  const [preview, setPreview]               = useState(null);   // { member, certType }
  const [tab, setTab]                       = useState("member"); // member | admin
  const [copied, setCopied]                 = useState(false);
  const [downloading, setDownloading]       = useState(false);
  const [searchQuery, setSearchQuery]       = useState("");
  const [filterStatus, setFilterStatus]     = useState("all");

  const certRef = useRef(null);

  // Determine earned certs for selected member
  const earnedModules  = selectedMember.completedModules || [];
  const earnedSpecial  = [];
  if (earnedModules.length === 10) earnedSpecial.push("master");
  if (selectedMember.points >= 10000) earnedSpecial.push("thailand");
  if (selectedMember.points >= 15000) earnedSpecial.push("dubai");
  if (["Diamond Leader","Crown Ambassador","Legend Leader"].includes(selectedMember.rank)) earnedSpecial.push("leader");

  const totalEarned = earnedModules.length + earnedSpecial.length;

  // Download: uses html2canvas + jsPDF loaded dynamically from CDN
  const handleDownload = async () => {
    setDownloading(true);
    const isModule = typeof preview.certType === "number";
    const cert = isModule
      ? MODULES.find(m => m.id === preview.certType)
      : SPECIAL_CERTS.find(s => s.id === preview.certType);
    const filename = `TGM-Certificate-${preview.member.name.replace(/\s+/g,"-")}-${(cert?.title||"cert").replace(/\s+/g,"-")}`;

    try {
      // Load html2canvas if not present
      if (!window.html2canvas) {
        await new Promise((res, rej) => {
          const s = document.createElement("script");
          s.src = "https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js";
          s.onload = res; s.onerror = rej;
          document.head.appendChild(s);
        });
      }
      // Load jsPDF if not present
      if (!window.jspdf) {
        await new Promise((res, rej) => {
          const s = document.createElement("script");
          s.src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js";
          s.onload = res; s.onerror = rej;
          document.head.appendChild(s);
        });
      }

      // Find the certificate canvas element inside the modal
      const el = certRef.current?.querySelector?.("[data-cert-canvas]") || certRef.current;
      if (!el) throw new Error("Certificate element not found");

      // Reset any scale transforms temporarily for clean capture
      const origTransform = el.style.transform;
      el.style.transform = "none";

      const canvas = await window.html2canvas(el, {
        scale: 2,
        useCORS: true,
        backgroundColor: null,
        logging: false,
        allowTaint: true,
      });

      el.style.transform = origTransform;

      // Option 1: Download as PNG
      const link = document.createElement("a");
      link.download = filename + ".png";
      link.href = canvas.toDataURL("image/png");
      link.click();

      // Option 2: Also offer PDF
      const { jsPDF } = window.jspdf;
      const pdf = new jsPDF({ orientation: "landscape", unit: "px", format: [canvas.width / 2, canvas.height / 2] });
      pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0, canvas.width / 2, canvas.height / 2);
      pdf.save(filename + ".pdf");

    } catch (err) {
      console.error("Download error:", err);
      // Graceful fallback: open print dialog with the certificate
      const printWin = window.open("", "_blank", "width=1000,height=720");
      if (printWin) {
        const el = certRef.current;
        printWin.document.write(`<!DOCTYPE html><html><head><title>${filename}</title>
          <style>*{margin:0;padding:0;box-sizing:border-box;}body{background:#fff;}@media print{body{-webkit-print-color-adjust:exact;print-color-adjust:exact;}}</style>
          </head><body>${el ? el.innerHTML : "<p>Certificate</p>"}</body></html>`);
        printWin.document.close();
        setTimeout(() => { printWin.focus(); printWin.print(); }, 400);
      } else {
        alert(`📜 To save: Right-click the certificate → "Save as image"\nOr use Ctrl+P to print.\n\nFilename: ${filename}`);
      }
    } finally {
      setDownloading(false);
    }
  };

  const handleCopyId = () => {
    const id = generateCertId(preview.member.id, String(preview.certType));
    navigator.clipboard?.writeText(id).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  // Filter members for admin view
  const filteredMembers = SAMPLE_MEMBERS.filter(m => {
    const q = searchQuery.toLowerCase();
    const matchQ = m.name.toLowerCase().includes(q) || m.region.toLowerCase().includes(q);
    const earnedCount = m.completedModules.length;
    const matchF = filterStatus === "all"
      ? true
      : filterStatus === "complete" ? earnedCount === 10
      : filterStatus === "partial"  ? (earnedCount > 0 && earnedCount < 10)
      : earnedCount === 0;
    return matchQ && matchF;
  });

  return (
    <div style={{
      minHeight: "100vh", background: T.black, color: T.white,
      fontFamily: "'Segoe UI', system-ui, sans-serif",
    }}>

      {/* ── HEADER ── */}
      <div style={{
        background: "linear-gradient(135deg, #060918 0%, #0f1e4a 50%, #060918 100%)",
        borderBottom: "1px solid rgba(201,146,10,0.2)",
        padding: "20px 32px", display: "flex", alignItems: "center",
        justifyContent: "space-between", gap: 16,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 10,
            background: "linear-gradient(135deg, #1a3a8f, #c9920a)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 22,
          }}>🏅</div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, color: T.white, letterSpacing: 0.3 }}>
              Digital Certificates
            </div>
            <div style={{ color: T.gold, fontSize: 11, letterSpacing: 1, textTransform: "uppercase" }}>
              TAG Markets Success Academy
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{
          display: "flex", gap: 4,
          background: "rgba(255,255,255,0.04)", borderRadius: 10, padding: 4,
        }}>
          {[
            { id: "member", label: "🎓 My Certificates" },
            { id: "admin",  label: "⚙️ Admin View" },
          ].map(t => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              style={{
                background: tab === t.id ? "linear-gradient(135deg, #1a3a8f, #0f2260)" : "transparent",
                border: tab === t.id ? "1px solid rgba(201,146,10,0.3)" : "1px solid transparent",
                color: tab === t.id ? T.goldLight : "#666",
                borderRadius: 7, padding: "7px 16px",
                fontSize: 12, fontWeight: 600, cursor: "pointer",
                transition: "all 0.2s",
              }}
            >{t.label}</button>
          ))}
        </div>
      </div>

      <div style={{ maxWidth: 1100, margin: "0 auto", padding: "28px 24px" }}>

        {/* ─── MEMBER VIEW ─── */}
        {tab === "member" && (
          <div>
            {/* Member selector */}
            <div style={{
              background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)",
              borderRadius: 14, padding: 20, marginBottom: 24,
              display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap",
            }}>
              <div style={{ color: "#888", fontSize: 12, fontWeight: 600, minWidth: 80 }}>
                VIEW AS:
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", flex: 1 }}>
                {SAMPLE_MEMBERS.map(m => (
                  <button
                    key={m.id}
                    onClick={() => setSelectedMember(m)}
                    style={{
                      background: selectedMember.id === m.id
                        ? "linear-gradient(135deg, #1a3a8f, #0f2260)"
                        : "rgba(255,255,255,0.04)",
                      border: `1px solid ${selectedMember.id === m.id ? "rgba(201,146,10,0.5)" : "rgba(255,255,255,0.08)"}`,
                      color: selectedMember.id === m.id ? T.goldLight : "#888",
                      borderRadius: 8, padding: "6px 14px", fontSize: 12,
                      cursor: "pointer", transition: "all 0.2s",
                    }}
                  >{m.name}</button>
                ))}
              </div>
            </div>

            {/* Member stats */}
            <div style={{
              background: "linear-gradient(135deg, #0a0e1f, #0f1e4a)",
              border: "1px solid rgba(201,146,10,0.2)", borderRadius: 16,
              padding: 24, marginBottom: 28,
              display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap",
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: "50%",
                background: "linear-gradient(135deg, #1a3a8f, #c9920a)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 22, fontWeight: 700, color: T.white,
              }}>
                {selectedMember.name.split(" ").map(w => w[0]).join("")}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 20, fontWeight: 700 }}>{selectedMember.name}</div>
                <div style={{ color: T.gold, fontSize: 12, marginTop: 2 }}>
                  {selectedMember.rank} · {selectedMember.region}
                </div>
              </div>
              <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                <StatBadge value={totalEarned} label="Certificates" color={T.goldLight}/>
                <StatBadge value={earnedModules.length + "/10"} label="Modules" color="#60a5fa"/>
                <StatBadge value={selectedMember.points.toLocaleString()} label="Points" color="#4ade80"/>
              </div>
            </div>

            {/* Progress bar */}
            <div style={{ marginBottom: 28 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                <div style={{ color: "#aaa", fontSize: 12 }}>Academy Completion Progress</div>
                <div style={{ color: T.goldLight, fontSize: 12, fontWeight: 700 }}>
                  {Math.round((earnedModules.length / 10) * 100)}%
                </div>
              </div>
              <div style={{
                height: 8, background: "rgba(255,255,255,0.06)", borderRadius: 4, overflow: "hidden",
              }}>
                <div style={{
                  height: "100%", borderRadius: 4,
                  width: `${(earnedModules.length / 10) * 100}%`,
                  background: "linear-gradient(90deg, #1a3a8f, #c9920a, #FFD700)",
                  transition: "width 0.6s ease",
                  boxShadow: "0 0 8px rgba(201,146,10,0.5)",
                }}/>
              </div>
            </div>

            {/* Module certificates */}
            <div style={{ marginBottom: 8 }}>
              <div style={{
                color: "#aaa", fontSize: 11, letterSpacing: 2, textTransform: "uppercase",
                marginBottom: 14,
              }}>
                Module Certificates (10)
              </div>
              <div style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
                gap: 10,
              }}>
                {MODULES.map(m => (
                  <CertCard
                    key={m.id}
                    member={selectedMember}
                    certType={m.id}
                    earned={earnedModules.includes(m.id)}
                    onPreview={setPreview}
                  />
                ))}
              </div>
            </div>

            {/* Special certificates */}
            <div style={{ marginTop: 28 }}>
              <div style={{
                color: "#aaa", fontSize: 11, letterSpacing: 2, textTransform: "uppercase",
                marginBottom: 14,
              }}>
                Special Achievement Certificates (4)
              </div>
              <div style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
                gap: 10,
              }}>
                {SPECIAL_CERTS.map(s => (
                  <CertCard
                    key={s.id}
                    member={selectedMember}
                    certType={s.id}
                    earned={earnedSpecial.includes(s.id)}
                    onPreview={setPreview}
                  />
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ─── ADMIN VIEW ─── */}
        {tab === "admin" && (
          <div>
            {/* Stats overview */}
            <div style={{
              display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
              gap: 12, marginBottom: 28,
            }}>
              <StatBadge value={SAMPLE_MEMBERS.length} label="Total Members" color={T.goldLight}/>
              <StatBadge
                value={SAMPLE_MEMBERS.filter(m => m.completedModules.length === 10).length}
                label="Full Graduates" color="#4ade80"
              />
              <StatBadge
                value={SAMPLE_MEMBERS.reduce((a, m) => a + m.completedModules.length, 0)}
                label="Certs Issued" color="#60a5fa"
              />
              <StatBadge
                value={Math.round(SAMPLE_MEMBERS.reduce((a,m)=>a+m.completedModules.length,0)/SAMPLE_MEMBERS.length*10)+"%"}
                label="Avg Completion" color="#f472b6"
              />
            </div>

            {/* Filter bar */}
            <div style={{
              display: "flex", gap: 10, marginBottom: 20, flexWrap: "wrap",
            }}>
              <input
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                placeholder="Search by name or region..."
                style={{
                  flex: 1, minWidth: 180, background: "rgba(255,255,255,0.04)",
                  border: "1px solid rgba(255,255,255,0.1)", borderRadius: 8,
                  color: T.white, padding: "8px 14px", fontSize: 12,
                  outline: "none",
                }}
              />
              {["all", "complete", "partial", "none"].map(f => (
                <button
                  key={f}
                  onClick={() => setFilterStatus(f)}
                  style={{
                    background: filterStatus === f ? "rgba(201,146,10,0.15)" : "rgba(255,255,255,0.04)",
                    border: `1px solid ${filterStatus === f ? "rgba(201,146,10,0.5)" : "rgba(255,255,255,0.08)"}`,
                    color: filterStatus === f ? T.goldLight : "#666",
                    borderRadius: 8, padding: "8px 14px", fontSize: 11,
                    fontWeight: 600, cursor: "pointer", textTransform: "capitalize",
                  }}
                >{f === "all" ? "All Members" : f === "complete" ? "✓ Complete" : f === "partial" ? "◑ Partial" : "○ None"}</button>
              ))}
            </div>

            {/* Member table */}
            <div style={{
              background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.07)",
              borderRadius: 14, overflow: "hidden",
            }}>
              {/* Header */}
              <div style={{
                display: "grid", gridTemplateColumns: "2fr 1.5fr 1fr 2fr 80px",
                padding: "12px 20px",
                borderBottom: "1px solid rgba(255,255,255,0.06)",
                color: "#555", fontSize: 11, letterSpacing: 1, textTransform: "uppercase",
              }}>
                <div>Member</div>
                <div>Rank</div>
                <div>Points</div>
                <div>Module Progress</div>
                <div>Actions</div>
              </div>

              {filteredMembers.map((m, i) => {
                const pct = Math.round((m.completedModules.length / 10) * 100);
                return (
                  <div
                    key={m.id}
                    style={{
                      display: "grid", gridTemplateColumns: "2fr 1.5fr 1fr 2fr 80px",
                      padding: "14px 20px", alignItems: "center",
                      borderBottom: i < filteredMembers.length - 1
                        ? "1px solid rgba(255,255,255,0.04)" : "none",
                      transition: "background 0.15s",
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.03)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{
                        width: 34, height: 34, borderRadius: "50%",
                        background: "linear-gradient(135deg, #1a3a8f, #c9920a)",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontSize: 13, fontWeight: 700, flexShrink: 0,
                      }}>
                        {m.name.split(" ").map(w => w[0]).join("")}
                      </div>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600 }}>{m.name}</div>
                        <div style={{ color: "#666", fontSize: 11 }}>{m.region}</div>
                      </div>
                    </div>

                    <div>
                      <div style={{ color: T.goldLight, fontSize: 12, fontWeight: 600 }}>
                        {m.rank}
                      </div>
                    </div>

                    <div style={{ color: "#aaa", fontSize: 13 }}>
                      {m.points.toLocaleString()}
                    </div>

                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{
                          flex: 1, height: 6, background: "rgba(255,255,255,0.06)",
                          borderRadius: 3, overflow: "hidden",
                        }}>
                          <div style={{
                            height: "100%", borderRadius: 3,
                            width: `${pct}%`,
                            background: pct === 100
                              ? "linear-gradient(90deg, #4ade80, #22c55e)"
                              : "linear-gradient(90deg, #1a3a8f, #c9920a)",
                          }}/>
                        </div>
                        <div style={{ color: "#888", fontSize: 11, minWidth: 50 }}>
                          {m.completedModules.length}/10 ({pct}%)
                        </div>
                      </div>
                      <div style={{ display: "flex", gap: 3, marginTop: 5, flexWrap: "wrap" }}>
                        {MODULES.map(mod => (
                          <div
                            key={mod.id}
                            title={`Module ${mod.id}: ${mod.title}`}
                            style={{
                              width: 14, height: 14, borderRadius: 3,
                              background: m.completedModules.includes(mod.id)
                                ? "linear-gradient(135deg, #1a3a8f, #c9920a)"
                                : "rgba(255,255,255,0.06)",
                              fontSize: 8, display: "flex", alignItems: "center",
                              justifyContent: "center", color: "#fff",
                              cursor: "pointer",
                            }}
                            onClick={() => m.completedModules.includes(mod.id) && setPreview({ member: m, certType: mod.id })}
                          >
                            {m.completedModules.includes(mod.id) ? "✓" : mod.id}
                          </div>
                        ))}
                      </div>
                    </div>

                    <div>
                      <button
                        onClick={() => {
                          setSelectedMember(m);
                          setTab("member");
                        }}
                        style={{
                          background: "rgba(26,58,143,0.2)", border: "1px solid rgba(26,58,143,0.4)",
                          color: "#60a5fa", borderRadius: 7, padding: "5px 10px",
                          fontSize: 11, cursor: "pointer",
                        }}
                      >View All</button>
                    </div>
                  </div>
                );
              })}

              {filteredMembers.length === 0 && (
                <div style={{ textAlign: "center", padding: 40, color: "#555" }}>
                  No members match your filter.
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* ─── PREVIEW MODAL ─── */}
      {preview && (
        <Modal onClose={() => setPreview(null)}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 16 }}>
            {/* Scale certificate to fit viewport */}
            <div ref={certRef} style={{ transform: "scale(0.62)", transformOrigin: "top center", marginBottom: -220 }}>
              <CertificateCanvas
                member={preview.member}
                certType={preview.certType}
                certData={{}}
                scale={1}
              />
            </div>

            {/* Action buttons */}
            <div style={{
              display: "flex", gap: 10, flexWrap: "wrap", justifyContent: "center",
              marginTop: 4,
            }}>
              <button
                onClick={handleDownload}
                disabled={downloading}
                style={{
                  background: "linear-gradient(135deg, #c9920a, #FFD700)",
                  border: "none", color: T.black, borderRadius: 10,
                  padding: "10px 22px", fontSize: 13, fontWeight: 700,
                  cursor: downloading ? "wait" : "pointer",
                  display: "flex", alignItems: "center", gap: 6,
                }}
              >
                {downloading ? "⏳ Preparing..." : "⬇️ Download PNG + PDF"}
              </button>

              <button
                onClick={() => {
                  const el = certRef.current;
                  if (!el) return;
                  const pw = window.open("","_blank","width=1000,height=720");
                  if (pw) {
                    pw.document.write(`<!DOCTYPE html><html><head><title>Certificate</title>
                      <style>*{margin:0;padding:0}body{background:#fff;display:flex;align-items:center;justify-content:center;min-height:100vh;}
                      @media print{body{-webkit-print-color-adjust:exact;print-color-adjust:exact;}}</style>
                      </head><body>${el.innerHTML}</body></html>`);
                    pw.document.close();
                    setTimeout(()=>{pw.focus();pw.print();},400);
                  }
                }}
                style={{
                  background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.12)",
                  color: T.white, borderRadius: 10,
                  padding: "10px 22px", fontSize: 13, cursor: "pointer",
                  display: "flex", alignItems: "center", gap: 6,
                }}
              >
                🖨️ Print
              </button>

              <button
                onClick={handleCopyId}
                style={{
                  background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.12)",
                  color: copied ? "#4ade80" : T.white, borderRadius: 10,
                  padding: "10px 22px", fontSize: 13, cursor: "pointer",
                  display: "flex", alignItems: "center", gap: 6,
                }}
              >
                {copied ? "✓ Copied!" : "📋 Copy Cert ID"}
              </button>

              <button
                onClick={() => {
                  const isModule = typeof preview.certType === "number";
                  const cert = isModule
                    ? MODULES.find(m => m.id === preview.certType)
                    : SPECIAL_CERTS.find(s => s.id === preview.certType);
                  alert(`🔗 Share link copied!\nhttps://tagmarkets.com/verify/${generateCertId(preview.member.id, String(preview.certType))}`);
                }}
                style={{
                  background: "rgba(26,58,143,0.2)", border: "1px solid rgba(26,58,143,0.4)",
                  color: "#60a5fa", borderRadius: 10,
                  padding: "10px 22px", fontSize: 13, cursor: "pointer",
                  display: "flex", alignItems: "center", gap: 6,
                }}
              >
                🔗 Share Link
              </button>
            </div>

            {/* Verification ID */}
            <div style={{
              background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)",
              borderRadius: 8, padding: "8px 16px",
              color: "#888", fontSize: 11,
              display: "flex", gap: 8, alignItems: "center",
            }}>
              <span>Verification ID:</span>
              <span style={{ color: T.gold, fontWeight: 700 }}>
                {generateCertId(preview.member.id, String(preview.certType))}
              </span>
              <span>·</span>
              <span>Issued: {formatDate()}</span>
            </div>
          </div>
        </Modal>
      )}

    </div>
  );
}