// Real QR generator using qrcode-generator (loaded as a global `qrcode` in index.html).
// Default vanaf deze versie: QR codes openen de QRJam webplayer, met de Spotify
// track-url als parameter. Zet window.QRJAM_QR_MODE = "spotify" als je bewust
// weer direct naar Spotify wilt linken.

function spotifyUrl(track) {
  return `https://open.spotify.com/track/${track.spotifyId || track.id}`;
}

function qrjamPlayerUrl(track) {
  const base = window.QRJAM_PLAYER_BASE_URL || "https://www.qrjam.nl/speel/";
  const url = new URL(base, window.location.origin);
  url.searchParams.set("spotify", spotifyUrl(track));
  if (track.id) url.searchParams.set("t", track.id);
  return url.toString();
}

function qrPayloadUrl(track) {
  const mode = window.QRJAM_QR_MODE || "webplayer";
  return mode === "spotify" ? spotifyUrl(track) : qrjamPlayerUrl(track);
}

// Cache so React re-renders don't re-encode the same QR
const QR_CACHE = new Map();
function getQrMatrix(data) {
  if (QR_CACHE.has(data)) return QR_CACHE.get(data);
  // Type 0 = auto, Error correction "M" → ~15% recovery, good balance.
  const qr = qrcode(0, "M");
  qr.addData(data);
  qr.make();
  const n = qr.getModuleCount();
  const mat = [];
  for (let r = 0; r < n; r++) {
    const row = [];
    for (let c = 0; c < n; c++) row.push(qr.isDark(r, c));
    mat.push(row);
  }
  QR_CACHE.set(data, mat);
  return mat;
}

function PseudoQR({ seed, track, size = 200, fg = "#000", bg = "#fff", style = {} }) {
  // `seed` is the legacy prop used by card styles that don't pass `track`.
  // When we have a track, encode the QRJam webplayer url; otherwise fall back to
  // an id-based payload so dev tests still get a visible code.
  const payload = track ? qrPayloadUrl(track) : `qrjam://${seed || "x"}`;
  let matrix;
  try {
    matrix = getQrMatrix(payload);
  } catch (e) {
    // qrcode-generator hasn't loaded yet on initial render — render an empty
    // square that will be replaced on the next paint.
    return <div style={{ width: size, height: size, background: bg, ...style }} />;
  }
  const N = matrix.length;
  const cell = size / N;

  // Collect dark rects as one path d-string — fewer DOM nodes than per-cell rects.
  let d = "";
  for (let r = 0; r < N; r++) {
    for (let c = 0; c < N; c++) {
      if (matrix[r][c]) {
        const x = c * cell;
        const y = r * cell;
        d += `M${x} ${y}h${cell + 0.3}v${cell + 0.3}h-${cell + 0.3}z`;
      }
    }
  }

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}
         style={{ display: "block", background: bg, ...style }}
         role="img" aria-label={payload}>
      <rect width={size} height={size} fill={bg} />
      <path d={d} fill={fg} />
    </svg>
  );
}

window.PseudoQR = PseudoQR;
window.spotifyUrl = spotifyUrl;
window.qrjamPlayerUrl = qrjamPlayerUrl;
