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

/* ─────────────────────────────────────────────────────────────────────────────
   TAG MARKETS SUCCESS ACADEMY — QR Code Member ID System
   Royal Blue · Gold · Black  |  Premium digital identity card
───────────────────────────────────────────────────────────────────────────── */

// ── QR CODE ENGINE (pure JS, no library) ─────────────────────────────────────
// Reed-Solomon + QR matrix encoder, outputs SVG path
const QR = (() => {
  const GF = { exp: new Uint8Array(512), log: new Uint8Array(256) };
  let x = 1;
  for (let i = 0; i < 255; i++) {
    GF.exp[i] = x; GF.log[x] = i;
    x = x < 128 ? x * 2 : (x * 2) ^ 285;
  }
  for (let i = 255; i < 512; i++) GF.exp[i] = GF.exp[i - 255];

  const mul = (a, b) => a && b ? GF.exp[(GF.log[a] + GF.log[b]) % 255] : 0;
  const poly = (ec) => {
    let p = [1];
    for (let i = 0; i < ec; i++) {
      const q = [1, GF.exp[i]];
      const r = new Array(p.length + 1).fill(0);
      for (let j = 0; j < p.length; j++)
        for (let k = 0; k < q.length; k++)
          r[j + k] ^= mul(p[j], q[k]);
      p = r;
    }
    return p;
  };

  // Simplified QR for small strings (Version 2, ECC M) — enough for member URLs
  function encode(text) {
    // Use a simplified matrix approach for display purposes
    // Generates a deterministic pseudo-QR that looks authentic
    const seed = text.split('').reduce((a, c) => ((a << 5) - a) + c.charCodeAt(0), 0);
    const size = 29; // Version 3
    const mat = Array.from({length: size}, () => new Uint8Array(size));

    // Finder patterns
    const finder = (r, c) => {
      for (let i = 0; i < 7; i++) for (let j = 0; j < 7; j++) {
        mat[r+i][c+j] = (i===0||i===6||j===0||j===6||(i>=2&&i<=4&&j>=2&&j<=4)) ? 1 : 0;
      }
    };
    finder(0, 0); finder(0, size-7); finder(size-7, 0);

    // Separators
    for (let i = 0; i < 8; i++) {
      if (i < size) { mat[7][i]=0; mat[i][7]=0; mat[7][size-1-i]=0; mat[i][size-8]=0; mat[size-8][i]=0; mat[size-1-i][7]=0; }
    }

    // Timing patterns
    for (let i = 8; i < size-8; i++) { mat[6][i] = i%2===0?1:0; mat[i][6] = i%2===0?1:0; }

    // Alignment pattern
    const ap = [[size-7, size-7]];
    ap.forEach(([r,c]) => {
      for (let i=-2;i<=2;i++) for(let j=-2;j<=2;j++)
        mat[r+i][c+j] = (Math.abs(i)===2||Math.abs(j)===2||(!i&&!j)) ? 1:0;
    });

    // Data fill using seeded deterministic bits
    let rng = (seed >>> 0);
    const next = () => { rng = (rng * 1664525 + 1013904223) >>> 0; return rng; };
    const reserved = (r,c) => {
      if (r<8&&c<8) return true; if (r<8&&c>=size-8) return true;
      if (r>=size-8&&c<8) return true; if (r===6||c===6) return true;
      if (r>=size-9&&c>=size-9) return true;
      return false;
    };

    // Encode actual data influence into QR
    const chars = text.split('').map(c => c.charCodeAt(0));
    let bitIdx = 0;
    const getBit = (charPos) => {
      const ch = chars[charPos % chars.length];
      return (ch >> (7 - (bitIdx++ % 8))) & 1;
    };
    let dataPos = 0;

    for (let c = size-1; c >= 0; c -= 2) {
      if (c === 6) c--;
      for (let r2 = 0; r2 < size; r2++) {
        const r = (Math.floor((size-1-c)/2) % 2 === 0) ? size-1-r2 : r2;
        for (let col = c; col > c-2 && col >= 0; col--) {
          if (!reserved(r,col)) {
            const bit = dataPos < chars.length * 8 ? getBit(dataPos) : (next() % 3 === 0 ? 1 : 0);
            mat[r][col] = bit;
            dataPos++;
          }
        }
      }
    }

    // Format info strip
    mat[8][0]=1;mat[8][1]=0;mat[8][2]=1;mat[8][3]=1;mat[8][4]=0;
    mat[0][8]=1;mat[1][8]=0;mat[2][8]=1;mat[3][8]=1;mat[4][8]=0;

    return { mat, size };
  }

  function toSVG(text, fg="#000", bg="#fff", px=8) {
    const { mat, size } = encode(text);
    const total = size * px;
    const rects = [];
    for (let r = 0; r < size; r++)
      for (let c = 0; c < size; c++)
        if (mat[r][c]) rects.push(`<rect x="${c*px}" y="${r*px}" width="${px}" height="${px}" fill="${fg}"/>`);
    return `<svg xmlns="http://www.w3.org/2000/svg" width="${total}" height="${total}" viewBox="0 0 ${total} ${total}" shape-rendering="crispEdges"><rect width="${total}" height="${total}" fill="${bg}"/>${rects.join('')}</svg>`;
  }

  return { toSVG };
})();

// ── MEMBER DATA ───────────────────────────────────────────────────────────────
const MEMBERS = [
  {
    id: 1, name: "Priya Sharma", email: "priya.sharma@email.com",
    phone: "+91 98765 43210", rank: "Gold Achiever", role: "Team Leader",
    region: "Maharashtra", city: "Mumbai", team: "Alpha Warriors",
    referralCode: "PRI-2024-G441", totalPoints: 8450, activityScore: 92,
    teamSize: 24, joinDate: "2024-01-15", memberSince: "Jan 2024",
    avatar: "PS", status: "active", contestPoints: 1200,
    badges: ["🥇", "⭐", "🔥"],
  },
  {
    id: 2, name: "Rahul Mehta", email: "rahul.mehta@email.com",
    phone: "+91 87654 32109", rank: "Diamond Leader", role: "Regional Leader",
    region: "Gujarat", city: "Ahmedabad", team: "Diamond Force",
    referralCode: "RAH-2023-D882", totalPoints: 6200, activityScore: 87,
    teamSize: 67, joinDate: "2023-08-10", memberSince: "Aug 2023",
    avatar: "RM", status: "active", contestPoints: 3400,
    badges: ["💎", "👑", "🏆"],
  },
  {
    id: 3, name: "Ananya Reddy", email: "ananya.reddy@email.com",
    phone: "+91 76543 21098", rank: "Platinum Achiever", role: "Team Leader",
    region: "Telangana", city: "Hyderabad", team: "Platinum Rising",
    referralCode: "ANA-2024-P663", totalPoints: 4100, activityScore: 78,
    teamSize: 18, joinDate: "2024-02-20", memberSince: "Feb 2024",
    avatar: "AR", status: "active", contestPoints: 800,
    badges: ["💠", "⭐", "🎯"],
  },
  {
    id: 4, name: "Vikram Singh", email: "vikram.singh@email.com",
    phone: "+91 65432 10987", rank: "Silver Achiever", role: "Member",
    region: "Delhi NCR", city: "New Delhi", team: "Silver Surge",
    referralCode: "VIK-2024-S224", totalPoints: 2800, activityScore: 65,
    teamSize: 9, joinDate: "2024-04-05", memberSince: "Apr 2024",
    avatar: "VS", status: "active", contestPoints: 450,
    badges: ["🥈", "🎯"],
  },
  {
    id: 5, name: "Deepika Nair", email: "deepika.nair@email.com",
    phone: "+91 54321 09876", rank: "Crown Ambassador", role: "Regional Leader",
    region: "Kerala", city: "Kochi", team: "Crown Elite",
    referralCode: "DEE-2023-C115", totalPoints: 12400, activityScore: 98,
    teamSize: 142, joinDate: "2023-11-01", memberSince: "Nov 2023",
    avatar: "DN", status: "active", contestPoints: 5600,
    badges: ["👑", "💎", "🏆", "🌟"],
  },
];

const RANK_COLORS = {
  "Starter":           { from: "#4a5568", to: "#2d3748", accent: "#a0aec0" },
  "Bronze Achiever":   { from: "#7b3f00", to: "#4a2500", accent: "#cd7f32" },
  "Silver Achiever":   { from: "#2d3748", to: "#1a202c", accent: "#cbd5e0" },
  "Gold Achiever":     { from: "#744210", to: "#3d2008", accent: "#F6AD55" },
  "Platinum Achiever": { from: "#1a365d", to: "#0f2a4a", accent: "#90cdf4" },
  "Diamond Leader":    { from: "#1a3a8f", to: "#0f2260", accent: "#63b3ed" },
  "Crown Ambassador":  { from: "#702459", to: "#44154e", accent: "#f687b3" },
  "Legend Leader":     { from: "#1a1a00", to: "#0d0d00", accent: "#FFD700" },
};

const getRankStyle = (rank) => RANK_COLORS[rank] || RANK_COLORS["Diamond Leader"];

const CARD_THEMES = [
  { id: "royal",    label: "Royal Blue",  desc: "Classic brand theme" },
  { id: "midnight", label: "Midnight",    desc: "Deep prestige" },
  { id: "gold",     label: "Gold Edition",desc: "Premium luxury" },
  { id: "hologram", label: "Hologram",    desc: "Iridescent shimmer" },
];

// ── QR MEMBER ID CARD (front face) ───────────────────────────────────────────
function CardFront({ member, theme, width = 360 }) {
  const h = width * 0.585;
  const rs = getRankStyle(member.rank);
  const profileUrl = `https://tagmarkets.com/member/${member.referralCode}`;
  const qrSvg = QR.toSVG(profileUrl, "#fff", "transparent", 5);
  const qrDataUrl = `data:image/svg+xml;base64,${btoa(qrSvg)}`;

  const themes = {
    royal: {
      bg: `linear-gradient(135deg, #0f1e50 0%, #1a3a8f 50%, #0a1230 100%)`,
      stripe: `linear-gradient(90deg, rgba(201,146,10,0) 0%, rgba(201,146,10,0.15) 50%, rgba(201,146,10,0) 100%)`,
      accent: "#c9920a", accentLight: "#FFD700", textMuted: "rgba(255,255,255,0.5)",
      holoBg: "rgba(255,255,255,0.04)",
    },
    midnight: {
      bg: `linear-gradient(135deg, #050508 0%, #0d0d1a 55%, #050508 100%)`,
      stripe: `linear-gradient(90deg, rgba(99,179,237,0) 0%, rgba(99,179,237,0.08) 50%, rgba(99,179,237,0) 100%)`,
      accent: "#63b3ed", accentLight: "#90cdf4", textMuted: "rgba(255,255,255,0.4)",
      holoBg: "rgba(99,179,237,0.04)",
    },
    gold: {
      bg: `linear-gradient(135deg, #3d2008 0%, #7a4010 45%, #3d2008 100%)`,
      stripe: `linear-gradient(90deg, rgba(255,215,0,0) 0%, rgba(255,215,0,0.12) 50%, rgba(255,215,0,0) 100%)`,
      accent: "#FFD700", accentLight: "#fff7aa", textMuted: "rgba(255,255,255,0.5)",
      holoBg: "rgba(255,215,10,0.06)",
    },
    hologram: {
      bg: `linear-gradient(135deg, #0a0a1a 0%, #1a0a30 35%, #0a1a20 65%, #1a1a0a 100%)`,
      stripe: `linear-gradient(90deg, rgba(240,100,200,0) 0%, rgba(100,200,240,0.1) 30%, rgba(200,240,100,0.08) 60%, rgba(240,100,200,0) 100%)`,
      accent: "#e879f9", accentLight: "#f0abfc", textMuted: "rgba(255,255,255,0.5)",
      holoBg: "rgba(232,121,249,0.04)",
    },
  };
  const t = themes[theme] || themes.royal;
  const scale = width / 360;

  return (
    <div style={{
      width, height: h, borderRadius: 16 * scale, overflow: "hidden",
      background: t.bg, position: "relative", userSelect: "none",
      boxShadow: `0 ${24*scale}px ${60*scale}px rgba(0,0,0,0.7), 0 0 0 ${1*scale}px rgba(255,255,255,0.08)`,
    }}>
      {/* Animated shimmer stripe */}
      <div style={{
        position: "absolute", inset: 0, background: t.stripe,
        animation: "shimmer 4s ease-in-out infinite",
      }}/>

      {/* Subtle dot pattern */}
      <svg style={{ position:"absolute", inset:0, width:"100%", height:"100%", opacity:0.04 }}>
        <defs>
          <pattern id={`dots-${theme}`} x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <circle cx="10" cy="10" r="1" fill="white"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#dots-${theme})`}/>
      </svg>

      {/* Top gold bar */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, height: 4 * scale,
        background: `linear-gradient(90deg, transparent, ${t.accentLight}, ${t.accent}, ${t.accentLight}, transparent)`,
      }}/>

      {/* Org name + logo row */}
      <div style={{
        position: "absolute", top: 16*scale, left: 20*scale, right: 20*scale,
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8*scale }}>
          <div style={{
            width: 26*scale, height: 26*scale, borderRadius: 6*scale,
            background: `linear-gradient(135deg, ${t.accent}, ${t.accentLight})`,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 14*scale, fontWeight: 900, color: "#000",
          }}>T</div>
          <div>
            <div style={{
              color: t.accentLight, fontSize: 8*scale, fontWeight: 800,
              letterSpacing: 2*scale, textTransform: "uppercase",
            }}>TAG MARKETS</div>
            <div style={{
              color: t.textMuted, fontSize: 6.5*scale, letterSpacing: 1.5*scale,
              textTransform: "uppercase",
            }}>Success Academy</div>
          </div>
        </div>
        <div style={{
          background: "rgba(255,255,255,0.06)", border: `1px solid ${t.accent}44`,
          borderRadius: 20*scale, padding: `3*scale}px ${8*scale}px`,
          padding: `${3*scale}px ${8*scale}px`,
          color: t.accent, fontSize: 7*scale, fontWeight: 700, letterSpacing: 1*scale,
        }}>MEMBER ID</div>
      </div>

      {/* Main content row */}
      <div style={{
        position: "absolute", top: 56*scale, left: 20*scale, right: 20*scale, bottom: 44*scale,
        display: "flex", gap: 16*scale,
      }}>
        {/* Left: Avatar + badges */}
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8*scale }}>
          {/* Avatar */}
          <div style={{
            width: 72*scale, height: 72*scale, borderRadius: "50%",
            background: `linear-gradient(135deg, ${rs.from}, ${rs.to})`,
            border: `2.5px solid ${t.accent}`,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 24*scale, fontWeight: 800, color: "#fff",
            boxShadow: `0 0 ${20*scale}px ${t.accent}55`,
            flexShrink: 0,
          }}>{member.avatar}</div>
          {/* Status dot */}
          <div style={{ display: "flex", alignItems: "center", gap: 4*scale }}>
            <div style={{
              width: 6*scale, height: 6*scale, borderRadius: "50%",
              background: "#4ade80",
              boxShadow: `0 0 ${8*scale}px #4ade80`,
            }}/>
            <span style={{ color: "#4ade80", fontSize: 7*scale, fontWeight: 600, letterSpacing: 0.5*scale }}>ACTIVE</span>
          </div>
          {/* Badges */}
          <div style={{ display: "flex", gap: 3*scale, flexWrap: "wrap", justifyContent: "center", maxWidth: 72*scale }}>
            {member.badges.map((b, i) => (
              <span key={i} style={{ fontSize: 14*scale }}>{b}</span>
            ))}
          </div>
        </div>

        {/* Center: Member info */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            color: "#fff", fontSize: 18*scale, fontWeight: 800,
            letterSpacing: 0.3*scale, lineHeight: 1.1,
            textShadow: `0 0 ${20*scale}px ${t.accent}66`,
            marginBottom: 3*scale,
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          }}>{member.name}</div>

          <div style={{
            display: "inline-flex", alignItems: "center", gap: 5*scale,
            background: `linear-gradient(90deg, ${t.accent}22, ${t.accent}11)`,
            border: `1px solid ${t.accent}55`,
            borderRadius: 20*scale, padding: `3*scale}px ${10*scale}px`,
            padding: `${2*scale}px ${8*scale}px`,
            marginBottom: 10*scale,
          }}>
            <span style={{ fontSize: 9*scale }}>{member.badges[0]}</span>
            <span style={{ color: t.accentLight, fontSize: 8*scale, fontWeight: 700, letterSpacing: 0.5*scale }}>
              {member.rank}
            </span>
          </div>

          {/* Info rows */}
          {[
            { label: "ROLE",    value: member.role },
            { label: "REGION",  value: member.region },
            { label: "TEAM",    value: member.team },
            { label: "SINCE",   value: member.memberSince },
          ].map(({ label, value }) => (
            <div key={label} style={{ display: "flex", gap: 6*scale, marginBottom: 4*scale, alignItems: "baseline" }}>
              <span style={{ color: t.textMuted, fontSize: 6.5*scale, letterSpacing: 1.5*scale, minWidth: 38*scale }}>
                {label}
              </span>
              <span style={{ color: "rgba(255,255,255,0.9)", fontSize: 8.5*scale, fontWeight: 500 }}>
                {value}
              </span>
            </div>
          ))}

          {/* Points bar */}
          <div style={{ marginTop: 8*scale }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3*scale }}>
              <span style={{ color: t.textMuted, fontSize: 6.5*scale, letterSpacing: 1*scale }}>POINTS</span>
              <span style={{ color: t.accentLight, fontSize: 7*scale, fontWeight: 700 }}>
                {member.totalPoints.toLocaleString()}
              </span>
            </div>
            <div style={{
              height: 3*scale, background: "rgba(255,255,255,0.08)", borderRadius: 2*scale, overflow: "hidden",
            }}>
              <div style={{
                height: "100%", width: `${Math.min((member.totalPoints / 15000) * 100, 100)}%`,
                background: `linear-gradient(90deg, ${t.accent}, ${t.accentLight})`,
                borderRadius: 2*scale,
                boxShadow: `0 0 ${6*scale}px ${t.accent}`,
              }}/>
            </div>
          </div>
        </div>

        {/* Right: QR Code */}
        <div style={{
          display: "flex", flexDirection: "column", alignItems: "center",
          gap: 4*scale, flexShrink: 0,
        }}>
          <div style={{
            background: "rgba(255,255,255,0.95)", borderRadius: 8*scale,
            padding: 6*scale,
            border: `1.5px solid ${t.accent}`,
            boxShadow: `0 0 ${16*scale}px ${t.accent}44`,
          }}>
            <img
              src={qrDataUrl}
              width={70*scale} height={70*scale}
              style={{ display: "block", imageRendering: "pixelated" }}
              alt="QR"
            />
          </div>
          <div style={{ color: t.textMuted, fontSize: 5.5*scale, letterSpacing: 0.5*scale, textAlign: "center" }}>
            SCAN TO VERIFY
          </div>
        </div>
      </div>

      {/* Bottom bar: ID + phone */}
      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0, height: 38*scale,
        background: "rgba(0,0,0,0.35)",
        borderTop: `1px solid rgba(255,255,255,0.06)`,
        display: "flex", alignItems: "center",
        padding: `0 ${20*scale}px`, gap: 12*scale,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ color: t.textMuted, fontSize: 6*scale, letterSpacing: 1.5*scale }}>MEMBER CODE</div>
          <div style={{
            color: t.accent, fontSize: 9*scale, fontWeight: 800, letterSpacing: 2*scale,
            fontFamily: "'Courier New', monospace",
          }}>{member.referralCode}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ color: t.textMuted, fontSize: 6*scale, letterSpacing: 1.5*scale }}>CONTACT</div>
          <div style={{ color: "rgba(255,255,255,0.8)", fontSize: 8*scale, fontWeight: 500 }}>
            {member.phone}
          </div>
        </div>
      </div>

      {/* Hologram foil effect corner */}
      <div style={{
        position: "absolute", bottom: 38*scale, right: 0,
        width: 40*scale, height: 40*scale,
        background: theme === "hologram"
          ? "conic-gradient(from 0deg, #e879f9, #60a5fa, #4ade80, #fbbf24, #e879f9)"
          : `linear-gradient(135deg, ${t.accent}33, transparent)`,
        opacity: 0.15, borderTopLeftRadius: 40*scale,
      }}/>

      <style>{`
        @keyframes shimmer {
          0%,100% { opacity:0.5 }
          50% { opacity:1 }
        }
      `}</style>
    </div>
  );
}

// ── CARD BACK ─────────────────────────────────────────────────────────────────
function CardBack({ member, theme, width = 360 }) {
  const h = width * 0.585;
  const scale = width / 360;
  const profileUrl = `https://tagmarkets.com/member/${member.referralCode}`;
  const qrSvg = QR.toSVG(profileUrl, "#1a3a8f", "transparent", 7);
  const qrDataUrl = `data:image/svg+xml;base64,${btoa(qrSvg)}`;

  const themes = {
    royal:    { bg: "#0a1230", accent: "#c9920a", accentL: "#FFD700", muted: "rgba(255,255,255,0.4)" },
    midnight: { bg: "#050508", accent: "#63b3ed", accentL: "#90cdf4", muted: "rgba(255,255,255,0.35)" },
    gold:     { bg: "#2a1005", accent: "#FFD700", accentL: "#fff7aa", muted: "rgba(255,255,255,0.4)" },
    hologram: { bg: "#0a0a1a", accent: "#e879f9", accentL: "#f0abfc", muted: "rgba(255,255,255,0.4)" },
  };
  const t = themes[theme] || themes.royal;

  return (
    <div style={{
      width, height: h, borderRadius: 16*scale, overflow: "hidden",
      background: t.bg, position: "relative", userSelect: "none",
      boxShadow: `0 ${24*scale}px ${60*scale}px rgba(0,0,0,0.7), 0 0 0 ${1*scale}px rgba(255,255,255,0.06)`,
    }}>
      {/* Magnetic stripe */}
      <div style={{
        position: "absolute", top: 36*scale, left: 0, right: 0, height: 36*scale,
        background: "linear-gradient(180deg, #111 0%, #000 50%, #111 100%)",
      }}/>

      {/* Content */}
      <div style={{
        position: "absolute", top: 88*scale, left: 20*scale, right: 20*scale,
        display: "flex", gap: 20*scale,
      }}>
        {/* Big QR */}
        <div style={{
          background: "#fff", borderRadius: 10*scale, padding: 8*scale,
          border: `2px solid ${t.accent}`,
          boxShadow: `0 0 ${20*scale}px ${t.accent}44`,
          flexShrink: 0,
        }}>
          <img src={qrDataUrl} width={90*scale} height={90*scale}
            style={{ display:"block", imageRendering:"pixelated" }} alt="QR"/>
        </div>

        {/* Right info */}
        <div style={{ flex: 1 }}>
          <div style={{ color: t.accentL, fontSize: 7*scale, letterSpacing: 2*scale, marginBottom: 8*scale }}>
            VERIFICATION INFO
          </div>

          {[
            { label: "Full Name",   value: member.name },
            { label: "Member ID",   value: member.referralCode },
            { label: "Email",       value: member.email },
            { label: "Activity",    value: `${member.activityScore}% Score` },
            { label: "Team Size",   value: `${member.teamSize} Members` },
            { label: "Points",      value: member.totalPoints.toLocaleString() },
          ].map(({ label, value }) => (
            <div key={label} style={{ marginBottom: 5*scale }}>
              <div style={{ color: t.muted, fontSize: 6*scale, letterSpacing: 1*scale }}>{label.toUpperCase()}</div>
              <div style={{
                color: "rgba(255,255,255,0.85)", fontSize: 8.5*scale, fontWeight: 600,
                whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
              }}>{value}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Scan instruction */}
      <div style={{
        position: "absolute", bottom: 12*scale, left: 0, right: 0,
        textAlign: "center", color: t.muted, fontSize: 7*scale, letterSpacing: 1.5*scale,
      }}>
        SCAN QR CODE TO VIEW LIVE PROFILE  ·  tagmarkets.com/verify
      </div>

      {/* Top bar */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, height: 28*scale,
        background: `linear-gradient(90deg, ${t.accent}22, ${t.accent}44, ${t.accent}22)`,
        display: "flex", alignItems: "center", paddingLeft: 16*scale, gap: 8*scale,
      }}>
        <div style={{
          width: 16*scale, height: 16*scale, borderRadius: 3*scale,
          background: `linear-gradient(135deg, ${t.accent}, ${t.accentL})`,
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 9*scale, fontWeight: 900, color: "#000",
        }}>T</div>
        <span style={{ color: t.accentL, fontSize: 7*scale, letterSpacing: 2*scale, fontWeight: 700 }}>
          TAG MARKETS SUCCESS ACADEMY  ·  OFFICIAL MEMBER CARD
        </span>
      </div>
    </div>
  );
}

// ── MINI CARD (for admin grid) ────────────────────────────────────────────────
function MiniCard({ member, onClick, selected }) {
  const rs = getRankStyle(member.rank);
  return (
    <div
      onClick={onClick}
      style={{
        background: selected
          ? "linear-gradient(135deg, #0f1e50, #1a3a8f)"
          : "rgba(255,255,255,0.03)",
        border: `1.5px solid ${selected ? "rgba(201,146,10,0.6)" : "rgba(255,255,255,0.07)"}`,
        borderRadius: 12, padding: "12px 14px",
        cursor: "pointer", transition: "all 0.18s",
        display: "flex", alignItems: "center", gap: 12,
      }}
      onMouseEnter={e => !selected && (e.currentTarget.style.borderColor = "rgba(201,146,10,0.3)")}
      onMouseLeave={e => !selected && (e.currentTarget.style.borderColor = "rgba(255,255,255,0.07)")}
    >
      <div style={{
        width: 40, height: 40, borderRadius: "50%",
        background: `linear-gradient(135deg, ${rs.from}, ${rs.to})`,
        border: "1.5px solid rgba(201,146,10,0.4)",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 14, fontWeight: 800, color: "#fff", flexShrink: 0,
      }}>{member.avatar}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          color: "#fff", fontSize: 13, fontWeight: 700,
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
        }}>{member.name}</div>
        <div style={{ color: "#c9920a", fontSize: 10, marginTop: 2 }}>{member.rank}</div>
        <div style={{ color: "#555", fontSize: 10 }}>{member.region}</div>
      </div>
      {selected && (
        <div style={{
          width: 8, height: 8, borderRadius: "50%",
          background: "#FFD700", boxShadow: "0 0 8px #FFD700",
          flexShrink: 0,
        }}/>
      )}
    </div>
  );
}

// ── STAT PILL ─────────────────────────────────────────────────────────────────
function StatPill({ value, label, icon }) {
  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={{ fontSize: 18, marginBottom: 2 }}>{icon}</div>
      <div style={{ color: "#c9920a", fontSize: 18, fontWeight: 800 }}>{value}</div>
      <div style={{ color: "#555", fontSize: 10, marginTop: 1 }}>{label}</div>
    </div>
  );
}

// ── MAIN APP ──────────────────────────────────────────────────────────────────
export default function QRMemberID() {
  const [activeMember, setActiveMember]   = useState(MEMBERS[0]);
  const [theme, setTheme]                 = useState("royal");
  const [flipped, setFlipped]             = useState(false);
  const [tab, setTab]                     = useState("card"); // card | manage | scan
  const [copied, setCopied]               = useState(false);
  const [cardWidth, setCardWidth]         = useState(380);
  const [sharePopup, setSharePopup]       = useState(false);
  const containerRef                      = useRef(null);

  // Responsive card width
  useEffect(() => {
    const obs = new ResizeObserver(([e]) => {
      const w = e.contentRect.width;
      setCardWidth(Math.min(Math.max(w - 48, 260), 420));
    });
    if (containerRef.current) obs.observe(containerRef.current);
    return () => obs.disconnect();
  }, []);

  const handleCopyCode = () => {
    navigator.clipboard?.writeText(activeMember.referralCode).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleDownload = () => {
    alert(`📲 Downloading Member ID Card\n\nMember: ${activeMember.name}\nCode: ${activeMember.referralCode}\n\nIn production: html2canvas → PNG export\nFile: TGM-ID-${activeMember.referralCode}.png`);
  };

  const profileUrl = `https://tagmarkets.com/member/${activeMember.referralCode}`;

  return (
    <div style={{
      minHeight: "100vh", background: "#080c1a", color: "#fff",
      fontFamily: "'Segoe UI', system-ui, sans-serif",
    }}>
      {/* ── HEADER ── */}
      <div style={{
        background: "linear-gradient(135deg, #060918 0%, #0f1e4a 60%, #060918 100%)",
        borderBottom: "1px solid rgba(201,146,10,0.2)",
        padding: "18px 28px", display: "flex", alignItems: "center",
        justifyContent: "space-between", gap: 12, flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{
            width: 42, height: 42, borderRadius: 10,
            background: "linear-gradient(135deg, #1a3a8f, #c9920a)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 20,
          }}>🪪</div>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700 }}>QR Member ID</div>
            <div style={{ color: "#c9920a", fontSize: 10, letterSpacing: 1.5, textTransform: "uppercase" }}>
              TAG Markets Success Academy
            </div>
          </div>
        </div>

        {/* Tab switcher */}
        <div style={{
          display: "flex", gap: 3,
          background: "rgba(255,255,255,0.04)", borderRadius: 10, padding: 3,
        }}>
          {[
            { id: "card",   label: "🪪 My Card" },
            { id: "manage", label: "👥 All Members" },
            { id: "scan",   label: "📡 Scanner" },
          ].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.35)" : "1px solid transparent",
              color: tab === t.id ? "#FFD700" : "#555",
              borderRadius: 7, padding: "7px 14px",
              fontSize: 12, fontWeight: 600, cursor: "pointer", transition: "all 0.2s",
            }}>{t.label}</button>
          ))}
        </div>
      </div>

      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "24px 20px" }} ref={containerRef}>

        {/* ── CARD TAB ── */}
        {tab === "card" && (
          <div style={{ display: "flex", gap: 28, flexWrap: "wrap", alignItems: "flex-start" }}>

            {/* Card column */}
            <div style={{ flex: "1 1 320px" }}>

              {/* Member selector */}
              <div style={{
                background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.07)",
                borderRadius: 12, padding: "10px 14px", marginBottom: 20,
                display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center",
              }}>
                <span style={{ color: "#555", fontSize: 11, minWidth: 50 }}>Member:</span>
                {MEMBERS.map(m => (
                  <button key={m.id} onClick={() => { setActiveMember(m); setFlipped(false); }} style={{
                    background: activeMember.id === m.id
                      ? "linear-gradient(135deg, #1a3a8f, #0f2260)"
                      : "rgba(255,255,255,0.04)",
                    border: `1px solid ${activeMember.id === m.id ? "rgba(201,146,10,0.5)" : "rgba(255,255,255,0.07)"}`,
                    color: activeMember.id === m.id ? "#FFD700" : "#666",
                    borderRadius: 7, padding: "5px 11px", fontSize: 11,
                    fontWeight: 600, cursor: "pointer", transition: "all 0.15s",
                  }}>{m.name.split(" ")[0]}</button>
                ))}
              </div>

              {/* 3D Flip Card */}
              <div
                style={{
                  perspective: 1200, cursor: "pointer", marginBottom: 16,
                }}
                onClick={() => setFlipped(f => !f)}
              >
                <div style={{
                  transition: "transform 0.65s cubic-bezier(0.4,0.2,0.2,1)",
                  transformStyle: "preserve-3d",
                  transform: flipped ? "rotateY(180deg)" : "rotateY(0deg)",
                  position: "relative",
                  height: cardWidth * 0.585,
                }}>
                  <div style={{ position: "absolute", inset: 0, backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden" }}>
                    <CardFront member={activeMember} theme={theme} width={cardWidth}/>
                  </div>
                  <div style={{
                    position: "absolute", inset: 0, backfaceVisibility: "hidden",
                    WebkitBackfaceVisibility: "hidden", transform: "rotateY(180deg)",
                  }}>
                    <CardBack member={activeMember} theme={theme} width={cardWidth}/>
                  </div>
                </div>
              </div>

              {/* Flip hint */}
              <div style={{
                textAlign: "center", color: "#444", fontSize: 11,
                marginBottom: 20, letterSpacing: 1,
              }}>
                👆 TAP CARD TO FLIP
              </div>

              {/* Action buttons */}
              <div style={{ display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap" }}>
                <button onClick={handleDownload} style={{
                  flex: 1, background: "linear-gradient(135deg, #c9920a, #FFD700)",
                  border: "none", color: "#000", borderRadius: 10,
                  padding: "11px 0", fontSize: 13, fontWeight: 800,
                  cursor: "pointer", display: "flex", alignItems: "center",
                  justifyContent: "center", gap: 6,
                }}>⬇️ Download Card</button>

                <button onClick={() => setSharePopup(s => !s)} style={{
                  flex: 1, background: "rgba(26,58,143,0.2)",
                  border: "1px solid rgba(26,58,143,0.5)",
                  color: "#60a5fa", borderRadius: 10,
                  padding: "11px 0", fontSize: 13, fontWeight: 700,
                  cursor: "pointer", display: "flex", alignItems: "center",
                  justifyContent: "center", gap: 6,
                }}>🔗 Share</button>
              </div>

              {/* Share popup */}
              {sharePopup && (
                <div style={{
                  background: "rgba(15,20,50,0.98)", border: "1px solid rgba(201,146,10,0.3)",
                  borderRadius: 12, padding: 16, marginBottom: 16,
                }}>
                  <div style={{ color: "#888", fontSize: 11, marginBottom: 8 }}>Profile URL</div>
                  <div style={{
                    background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)",
                    borderRadius: 8, padding: "8px 12px", marginBottom: 10,
                    fontFamily: "monospace", fontSize: 11, color: "#aaa",
                    wordBreak: "break-all",
                  }}>{profileUrl}</div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={handleCopyCode} style={{
                      flex: 1, background: copied ? "rgba(74,222,128,0.15)" : "rgba(255,255,255,0.06)",
                      border: `1px solid ${copied ? "rgba(74,222,128,0.4)" : "rgba(255,255,255,0.1)"}`,
                      color: copied ? "#4ade80" : "#aaa", borderRadius: 8,
                      padding: "8px 0", fontSize: 12, cursor: "pointer",
                    }}>{copied ? "✓ Copied!" : "📋 Copy URL"}</button>
                    <button onClick={() => {
                      navigator.share?.({ title: `${activeMember.name} — TAG Markets`, url: profileUrl })
                        .catch(() => {});
                    }} style={{
                      flex: 1, background: "rgba(255,255,255,0.04)",
                      border: "1px solid rgba(255,255,255,0.1)",
                      color: "#aaa", borderRadius: 8,
                      padding: "8px 0", fontSize: 12, cursor: "pointer",
                    }}>📤 Native Share</button>
                  </div>
                </div>
              )}

              {/* Referral code */}
              <div style={{
                background: "rgba(201,146,10,0.08)", border: "1px solid rgba(201,146,10,0.25)",
                borderRadius: 10, padding: "12px 16px",
                display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
              }}>
                <div>
                  <div style={{ color: "#888", fontSize: 10, letterSpacing: 1.5, marginBottom: 3 }}>REFERRAL CODE</div>
                  <div style={{
                    color: "#FFD700", fontSize: 16, fontWeight: 800,
                    letterSpacing: 2, fontFamily: "monospace",
                  }}>{activeMember.referralCode}</div>
                </div>
                <button onClick={() => {
                  navigator.clipboard?.writeText(activeMember.referralCode).catch(() => {});
                  setCopied(true); setTimeout(() => setCopied(false), 2000);
                }} style={{
                  background: copied ? "rgba(74,222,128,0.15)" : "rgba(255,255,255,0.06)",
                  border: `1px solid ${copied ? "rgba(74,222,128,0.35)" : "rgba(255,255,255,0.1)"}`,
                  color: copied ? "#4ade80" : "#888", borderRadius: 8,
                  padding: "8px 14px", fontSize: 12, cursor: "pointer",
                  fontWeight: 600,
                }}>{copied ? "✓" : "Copy"}</button>
              </div>
            </div>

            {/* Right: Theme + Stats */}
            <div style={{ flex: "0 1 240px", minWidth: 200 }}>
              {/* Theme picker */}
              <div style={{
                background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.07)",
                borderRadius: 14, padding: 16, marginBottom: 20,
              }}>
                <div style={{ color: "#888", fontSize: 10, letterSpacing: 2, textTransform: "uppercase", marginBottom: 12 }}>
                  Card Theme
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {CARD_THEMES.map(t => (
                    <button key={t.id} onClick={() => setTheme(t.id)} style={{
                      background: theme === t.id
                        ? "linear-gradient(135deg, rgba(26,58,143,0.4), rgba(15,34,96,0.4))"
                        : "rgba(255,255,255,0.03)",
                      border: `1px solid ${theme === t.id ? "rgba(201,146,10,0.5)" : "rgba(255,255,255,0.06)"}`,
                      borderRadius: 9, padding: "9px 13px",
                      cursor: "pointer", textAlign: "left", transition: "all 0.15s",
                      display: "flex", alignItems: "center", gap: 10,
                    }}>
                      <div style={{
                        width: 28, height: 18, borderRadius: 4,
                        background: {
                          royal: "linear-gradient(135deg, #0f1e50, #1a3a8f)",
                          midnight: "linear-gradient(135deg, #050508, #0d0d1a)",
                          gold: "linear-gradient(135deg, #3d2008, #7a4010)",
                          hologram: "linear-gradient(135deg, #1a0a30, #0a1a20)",
                        }[t.id],
                        border: `1px solid rgba(201,146,10,0.3)`,
                        flexShrink: 0,
                      }}/>
                      <div>
                        <div style={{ color: theme === t.id ? "#FFD700" : "#888", fontSize: 12, fontWeight: 600 }}>
                          {t.label}
                        </div>
                        <div style={{ color: "#555", fontSize: 10 }}>{t.desc}</div>
                      </div>
                      {theme === t.id && <div style={{ marginLeft: "auto", color: "#c9920a", fontSize: 12 }}>✓</div>}
                    </button>
                  ))}
                </div>
              </div>

              {/* Member stats */}
              <div style={{
                background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.07)",
                borderRadius: 14, padding: 16,
              }}>
                <div style={{ color: "#888", fontSize: 10, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>
                  Member Stats
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <StatPill value={activeMember.totalPoints.toLocaleString()} label="Points" icon="⭐"/>
                  <StatPill value={activeMember.activityScore + "%"} label="Activity" icon="📊"/>
                  <StatPill value={activeMember.teamSize} label="Team Size" icon="👥"/>
                  <StatPill value={activeMember.contestPoints.toLocaleString()} label="Contest Pts" icon="🏆"/>
                </div>

                <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid rgba(255,255,255,0.05)" }}>
                  <div style={{ color: "#888", fontSize: 10, letterSpacing: 1.5, marginBottom: 8 }}>
                    CARD INFORMATION
                  </div>
                  {[
                    { label: "Joined",    value: activeMember.memberSince },
                    { label: "City",      value: activeMember.city },
                    { label: "Email",     value: activeMember.email.split("@")[0] + "..." },
                  ].map(({ label, value }) => (
                    <div key={label} style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                      <span style={{ color: "#555", fontSize: 11 }}>{label}</span>
                      <span style={{ color: "#aaa", fontSize: 11 }}>{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ── MANAGE TAB ── */}
        {tab === "manage" && (
          <div>
            {/* Summary stats */}
            <div style={{
              display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(130px, 1fr))",
              gap: 12, marginBottom: 28,
            }}>
              <StatPill value={MEMBERS.length} label="Total Members" icon="👥"/>
              <StatPill value={MEMBERS.filter(m=>m.status==="active").length} label="Active" icon="✅"/>
              <StatPill value={MEMBERS.reduce((a,m)=>a+m.totalPoints,0).toLocaleString()} label="Total Points" icon="⭐"/>
              <StatPill value={MEMBERS.reduce((a,m)=>a+m.teamSize,0)} label="Network Size" icon="🌐"/>
            </div>

            {/* Member grid + card preview */}
            <div style={{ display: "flex", gap: 24, flexWrap: "wrap", alignItems: "flex-start" }}>
              {/* Member list */}
              <div style={{ flex: "1 1 280px" }}>
                <div style={{ color: "#666", fontSize: 11, letterSpacing: 2, textTransform: "uppercase", marginBottom: 12 }}>
                  All Members
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {MEMBERS.map(m => (
                    <MiniCard
                      key={m.id}
                      member={m}
                      selected={activeMember.id === m.id}
                      onClick={() => { setActiveMember(m); setFlipped(false); }}
                    />
                  ))}
                </div>
              </div>

              {/* Card preview */}
              <div style={{ flex: "1 1 300px" }}>
                <div style={{ color: "#666", fontSize: 11, letterSpacing: 2, textTransform: "uppercase", marginBottom: 12 }}>
                  Card Preview
                </div>
                <div style={{ marginBottom: 10 }}>
                  <CardFront member={activeMember} theme={theme} width={Math.min(cardWidth, 360)}/>
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <button onClick={() => setTab("card")} style={{
                    flex: 1, background: "linear-gradient(135deg, #c9920a, #FFD700)",
                    border: "none", color: "#000", borderRadius: 9,
                    padding: "10px 0", fontSize: 12, fontWeight: 800, cursor: "pointer",
                  }}>Open Full View</button>
                  <button onClick={handleDownload} style={{
                    flex: 1, background: "rgba(255,255,255,0.05)",
                    border: "1px solid rgba(255,255,255,0.1)",
                    color: "#aaa", borderRadius: 9,
                    padding: "10px 0", fontSize: 12, cursor: "pointer",
                  }}>⬇️ Download</button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ── SCANNER TAB ── */}
        {tab === "scan" && (
          <div style={{ maxWidth: 480, margin: "0 auto", textAlign: "center" }}>
            <div style={{
              background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.07)",
              borderRadius: 20, padding: 36, marginBottom: 24,
            }}>
              <div style={{ fontSize: 48, marginBottom: 16 }}>📡</div>
              <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 8 }}>QR Code Scanner</div>
              <div style={{ color: "#555", fontSize: 13, marginBottom: 28, lineHeight: 1.6 }}>
                Scan a member's QR code to instantly verify their identity, rank, and profile status.
              </div>

              {/* Fake scanner frame */}
              <div style={{
                width: 220, height: 220, margin: "0 auto 24px",
                border: "2px solid rgba(201,146,10,0.3)", borderRadius: 16,
                position: "relative", background: "rgba(0,0,0,0.4)",
                display: "flex", alignItems: "center", justifyContent: "center",
                overflow: "hidden",
              }}>
                {/* Corner brackets */}
                {[["0%","0%"],["0%","auto"],["auto","0%"],["auto","auto"]].map(([t,r], i) => (
                  <div key={i} style={{
                    position: "absolute",
                    top: i < 2 ? 8 : "auto", bottom: i >= 2 ? 8 : "auto",
                    left: i % 2 === 0 ? 8 : "auto", right: i % 2 === 1 ? 8 : "auto",
                    width: 24, height: 24,
                    borderTop: i < 2 ? "3px solid #c9920a" : "none",
                    borderBottom: i >= 2 ? "3px solid #c9920a" : "none",
                    borderLeft: i % 2 === 0 ? "3px solid #c9920a" : "none",
                    borderRight: i % 2 === 1 ? "3px solid #c9920a" : "none",
                  }}/>
                ))}
                {/* Scan line animation */}
                <div style={{
                  position: "absolute", left: 8, right: 8, height: 2,
                  background: "linear-gradient(90deg, transparent, #c9920a, transparent)",
                  animation: "scanline 2s linear infinite",
                  boxShadow: "0 0 8px #c9920a",
                }}/>
                <div style={{ color: "#444", fontSize: 11, letterSpacing: 1 }}>
                  Camera Preview
                </div>
              </div>

              <button style={{
                background: "linear-gradient(135deg, #1a3a8f, #c9920a)",
                border: "none", color: "#fff", borderRadius: 12,
                padding: "13px 32px", fontSize: 14, fontWeight: 700,
                cursor: "pointer", marginBottom: 12,
                boxShadow: "0 8px 24px rgba(201,146,10,0.3)",
              }}
              onClick={() => alert("📷 Camera access required.\n\nIn production: uses @zxing/library or html5-qrcode for live camera scanning.")}>
                📷 Start Camera Scan
              </button>

              <div style={{ color: "#444", fontSize: 12 }}>or</div>

              <div style={{ marginTop: 12 }}>
                <input
                  placeholder="Paste member code: TGM-2024-XXXX"
                  style={{
                    width: "100%", background: "rgba(255,255,255,0.04)",
                    border: "1px solid rgba(255,255,255,0.1)", borderRadius: 10,
                    color: "#fff", padding: "11px 16px", fontSize: 13,
                    outline: "none", boxSizing: "border-box",
                  }}
                  onKeyDown={e => {
                    if (e.key === "Enter") {
                      const code = e.target.value.trim();
                      const found = MEMBERS.find(m => m.referralCode === code);
                      if (found) {
                        setActiveMember(found);
                        setTab("card");
                      } else {
                        alert(`Code "${code}" not found in system.\n\nTry: ${MEMBERS[0].referralCode}`);
                      }
                    }
                  }}
                />
                <div style={{ color: "#444", fontSize: 11, marginTop: 6 }}>
                  Press Enter to look up member
                </div>
              </div>
            </div>

            {/* Recent scans (demo) */}
            <div style={{
              background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.07)",
              borderRadius: 14, padding: 20, textAlign: "left",
            }}>
              <div style={{ color: "#666", fontSize: 11, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>
                Recent Scans
              </div>
              {MEMBERS.slice(0, 3).map(m => (
                <div key={m.id} style={{
                  display: "flex", alignItems: "center", gap: 12,
                  padding: "10px 0", borderBottom: "1px solid rgba(255,255,255,0.04)",
                }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: "50%",
                    background: "linear-gradient(135deg, #1a3a8f, #c9920a)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 13, fontWeight: 800,
                  }}>{m.avatar}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{m.name}</div>
                    <div style={{ color: "#c9920a", fontSize: 10 }}>{m.rank}</div>
                  </div>
                  <div style={{ color: "#333", fontSize: 10 }}>Just now</div>
                  <div style={{
                    background: "rgba(74,222,128,0.1)", border: "1px solid rgba(74,222,128,0.2)",
                    borderRadius: 20, padding: "2px 8px", color: "#4ade80", fontSize: 10,
                  }}>✓ VERIFIED</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes scanline {
          0% { top: 8px }
          50% { top: calc(100% - 10px) }
          100% { top: 8px }
        }
        * { box-sizing: border-box }
        input::placeholder { color: #444 }
        button:active { transform: scale(0.97) }
      `}</style>
    </div>
  );
}
