// ============================================================
// ATHAR — QR / barcode preview component
// Pseudo-random 21x21 pattern with 3 position markers.
// Deterministic per seed so each perfume shows a stable QR.
// ============================================================

function mulberry32(seed) {
  let s = seed >>> 0;
  return function () {
    s = (s + 0x6D2B79F5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function buildQRPattern(seed, N) {
  const rng = mulberry32(seed * 9973 + 17);
  const grid = Array.from({ length: N }, () => Array(N).fill(false));
  const markers = [[0, 0], [N - 7, 0], [0, N - 7]];

  // 7x7 position markers (outer ring + inner 3x3 core)
  for (const [mx, my] of markers) {
    for (let y = 0; y < 7; y++) {
      for (let x = 0; x < 7; x++) {
        const onBorder = x === 0 || x === 6 || y === 0 || y === 6;
        const inCore = x >= 2 && x <= 4 && y >= 2 && y <= 4;
        grid[my + y][mx + x] = onBorder || inCore;
      }
    }
  }

  // Timing patterns (lines of alternating modules)
  for (let i = 8; i < N - 8; i++) {
    grid[6][i] = i % 2 === 0;
    grid[i][6] = i % 2 === 0;
  }

  const inMarker = (x, y) =>
    markers.some(
      ([mx, my]) => x >= mx && x < mx + 8 && y >= my && y < my + 8
    );

  // Data modules — pseudo-random
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) {
      if (inMarker(x, y)) continue;
      if (x === 6 || y === 6) continue; // timing rows
      grid[y][x] = rng() > 0.52;
    }
  }

  // Small alignment block bottom-right (typical of small QRs)
  const ax = N - 9, ay = N - 9;
  if (ax >= 0 && ay >= 0) {
    for (let y = 0; y < 5; y++) {
      for (let x = 0; x < 5; x++) {
        const onBorder = x === 0 || x === 4 || y === 0 || y === 4;
        const core = x === 2 && y === 2;
        grid[ay + y][ax + x] = onBorder || core;
      }
    }
  }

  return grid;
}

function AtharQR({ seed = 7, size = 140, color = '#13100A' }) {
  const N = 25;
  const grid = React.useMemo(() => buildQRPattern(seed, N), [seed]);
  const cells = [];
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) {
      if (grid[y][x]) {
        cells.push(
          <rect
            key={`${x}-${y}`}
            x={x} y={y}
            width="1" height="1"
            fill={color}
          />
        );
      }
    }
  }
  return (
    <svg
      viewBox={`0 0 ${N} ${N}`}
      width={size}
      height={size}
      role="img"
      aria-label="QR code preview"
      shapeRendering="crispEdges"
      style={{ display: 'block' }}
    >
      {cells}
    </svg>
  );
}

window.AtharQR = AtharQR;
