'use strict';

/**
 * MVG Offline QR generator (Byte mode)
 *
 * - Pure JS (ES module), no network calls.
 * - Intended for printable audit summaries: embeds a QR that encodes the Approval ID + re-verify path.
 * - Implements QR Code Model 2 (ISO/IEC 18004) essentials: RS blocks + BCH format/version + masking.
 *
 * Notes:
 * - This is a minimal, self-contained implementation for MVG verifiers (not a general-purpose QR toolkit).
 * - All inputs are encoded as UTF-8 in 8-bit byte mode.
 */

// Error correction level bits used in QR format information.
// (Matches QR standard: M=0, L=1, H=2, Q=3)
const ECC = Object.freeze({ M: 0, L: 1, H: 2, Q: 3 });

// RS block table offset mapping.
// In the RS block table, entries are ordered per version as: L, M, Q, H.
const RS_BLOCK_OFFSET = Object.freeze({ [ECC.L]: 0, [ECC.M]: 1, [ECC.Q]: 2, [ECC.H]: 3 });

// Padding bytes (per QR spec)
const PAD0 = 236;
const PAD1 = 17;

// BCH constants (per QR spec)
const G15 = 1335;
const G18 = 7973;
const G15_MASK = 21522;

const RS_BLOCK_TABLE = [[1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12, 7, 37, 13], [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16]];

const PATTERN_POSITION_TABLE = [[], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170]];


const EXP_TABLE = new Array(256).fill(0);
const LOG_TABLE = new Array(256).fill(0);
(function initGfTables(){
  for (let i = 0; i < 8; i++) EXP_TABLE[i] = 1 << i;
  for (let i = 8; i < 256; i++) {
    EXP_TABLE[i] = (EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]) & 0xff;
  }
  for (let i = 0; i < 255; i++) {
    LOG_TABLE[EXP_TABLE[i]] = i;
  }
})();

function mod(n, m) {
  return ((n % m) + m) % m;
}

function glog(n) {
  if (n < 1) throw new Error(`glog({n})`);
  return LOG_TABLE[n];
}

function gexp(n) {
  return EXP_TABLE[mod(n, 255)];
}

function bchDigit(data) {
  let digit = 0;
  let d = data >>> 0;
  while (d !== 0) {
    digit += 1;
    d = d >>> 1;
  }
  return digit;
}

function bchTypeInfo(data) {
  let d = (data << 10) >>> 0;
  while (bchDigit(d) - bchDigit(G15) >= 0) {
    d = (d ^ (G15 << (bchDigit(d) - bchDigit(G15)))) >>> 0;
  }
  return (((data << 10) | d) ^ G15_MASK) >>> 0;
}

function bchTypeNumber(data) {
  let d = (data << 12) >>> 0;
  while (bchDigit(d) - bchDigit(G18) >= 0) {
    d = (d ^ (G18 << (bchDigit(d) - bchDigit(G18)))) >>> 0;
  }
  return ((data << 12) | d) >>> 0;
}

function maskFunc(pattern) {
  switch (pattern) {
    case 0: return (i, j) => ((i + j) % 2) === 0;
    case 1: return (i, j) => (i % 2) === 0;
    case 2: return (i, j) => (j % 3) === 0;
    case 3: return (i, j) => ((i + j) % 3) === 0;
    case 4: return (i, j) => ((Math.floor(i / 2) + Math.floor(j / 3)) % 2) === 0;
    case 5: return (i, j) => (((i * j) % 2) + ((i * j) % 3)) === 0;
    case 6: return (i, j) => ((((i * j) % 2) + ((i * j) % 3)) % 2) === 0;
    case 7: return (i, j) => ((((i * j) % 3) + ((i + j) % 2)) % 2) === 0;
    default: throw new Error(`Bad mask pattern: ${pattern}`);
  }
}

function lengthInBitsByte(version) {
  // Byte mode length field width depends on version range.
  // v1-9: 8 bits, v10-40: 16 bits
  return version < 10 ? 8 : 16;
}

function rsBlocks(version, eccBits) {
  const offset = RS_BLOCK_OFFSET[eccBits];
  if (offset === undefined) throw new Error('Bad ecc bits');
  const rs = RS_BLOCK_TABLE[(version - 1) * 4 + offset];
  const blocks = [];
  for (let i = 0; i < rs.length; i += 3) {
    const count = rs[i];
    const totalCount = rs[i + 1];
    const dataCount = rs[i + 2];
    for (let j = 0; j < count; j++) {
      blocks.push({ totalCount, dataCount });
    }
  }
  return blocks;
}

class BitBuffer {
  constructor() {
    this.buffer = [];
    this.length = 0;
  }
  get(index) {
    const bufIndex = Math.floor(index / 8);
    return (((this.buffer[bufIndex] >>> (7 - (index % 8))) & 1) === 1);
  }
  put(num, length) {
    for (let i = 0; i < length; i++) {
      this.putBit((((num >>> (length - i - 1)) & 1) === 1));
    }
  }
  putBit(bit) {
    const bufIndex = Math.floor(this.length / 8);
    if (this.buffer.length <= bufIndex) this.buffer.push(0);
    if (bit) this.buffer[bufIndex] = (this.buffer[bufIndex] | (0x80 >>> (this.length % 8))) & 0xff;
    this.length += 1;
  }
}

function polyNormalize(num) {
  let offset = 0;
  while (offset < num.length && num[offset] === 0) offset++;
  const out = num.slice(offset);
  return out.length ? out : [0];
}

function polyMultiply(p, q) {
  const num = new Array(p.length + q.length - 1).fill(0);
  for (let i = 0; i < p.length; i++) {
    const a = p[i];
    if (!a) continue;
    for (let j = 0; j < q.length; j++) {
      const b = q[j];
      if (!b) continue;
      num[i + j] = (num[i + j] ^ gexp(glog(a) + glog(b))) & 0xff;
    }
  }
  return polyNormalize(num);
}

function polyMod(dividend, divisor) {
  let result = polyNormalize(dividend);
  const div = polyNormalize(divisor);
  while (result.length >= div.length && !(result.length === 1 && result[0] === 0)) {
    const ratio = glog(result[0]) - glog(div[0]);
    const num = [];
    for (let i = 0; i < div.length; i++) {
      const a = result[i] || 0;
      const b = div[i] || 0;
      const term = b ? gexp(glog(b) + ratio) : 0;
      num[i] = (a ^ term) & 0xff;
    }
    if (result.length > div.length) {
      num.push(...result.slice(div.length));
    }
    result = polyNormalize(num);
  }
  return result;
}

function createBytes(bitBuffer, blocks) {
  let offset = 0;
  let maxDcCount = 0;
  let maxEcCount = 0;

  const dcdata = new Array(blocks.length);
  const ecdata = new Array(blocks.length);

  for (let r = 0; r < blocks.length; r++) {
    const dcCount = blocks[r].dataCount;
    const ecCount = blocks[r].totalCount - dcCount;

    maxDcCount = Math.max(maxDcCount, dcCount);
    maxEcCount = Math.max(maxEcCount, ecCount);

    const dc = new Array(dcCount);
    for (let i = 0; i < dcCount; i++) {
      dc[i] = (bitBuffer.buffer[i + offset] ?? 0) & 0xff;
    }
    offset += dcCount;
    dcdata[r] = dc;

    // Generator polynomial
    let rsPoly = [1];
    for (let i = 0; i < ecCount; i++) {
      rsPoly = polyMultiply(rsPoly, [1, gexp(i)]);
    }

    const rawPoly = dc.concat(new Array(ecCount).fill(0));
    const modPoly = polyMod(rawPoly, rsPoly);

    const ec = new Array(ecCount).fill(0);
    for (let i = 0; i < ecCount; i++) {
      const modIndex = i + modPoly.length - ecCount;
      ec[i] = (modIndex >= 0) ? (modPoly[modIndex] & 0xff) : 0;
    }
    ecdata[r] = ec;
  }

  const totalCodeCount = blocks.reduce((s, b) => s + b.totalCount, 0);
  const data = new Array(totalCodeCount);
  let index = 0;

  for (let i = 0; i < maxDcCount; i++) {
    for (let r = 0; r < blocks.length; r++) {
      if (i < dcdata[r].length) {
        data[index++] = dcdata[r][i];
      }
    }
  }

  for (let i = 0; i < maxEcCount; i++) {
    for (let r = 0; r < blocks.length; r++) {
      if (i < ecdata[r].length) {
        data[index++] = ecdata[r][i];
      }
    }
  }

  return data;
}

function createData(version, eccBits, bytes) {
  const buffer = new BitBuffer();

  // Mode: 8-bit byte (0100)
  buffer.put(4, 4);

  // Length field
  buffer.put(bytes.length, lengthInBitsByte(version));

  // Data
  for (const b of bytes) buffer.put(b, 8);

  // Capacity
  const blocks = rsBlocks(version, eccBits);
  const bitLimit = blocks.reduce((s, b) => s + b.dataCount * 8, 0);
  if (buffer.length > bitLimit) throw new Error('QR data overflow');

  // Terminator (up to 4 zeros)
  const terminator = Math.min(bitLimit - buffer.length, 4);
  for (let i = 0; i < terminator; i++) buffer.putBit(false);

  // Pad to byte boundary
  const delimit = buffer.length % 8;
  if (delimit) {
    for (let i = 0; i < (8 - delimit); i++) buffer.putBit(false);
  }

  // Pad bytes
  const bytesToFill = (bitLimit - buffer.length) / 8;
  for (let i = 0; i < bytesToFill; i++) {
    buffer.put((i % 2 === 0) ? PAD0 : PAD1, 8);
  }

  return createBytes(buffer, blocks);
}

function setupPositionProbe(modules, modulesCount, row, col) {
  for (let r = -1; r < 8; r++) {
    if (row + r <= -1 || modulesCount <= row + r) continue;
    for (let c = -1; c < 8; c++) {
      if (col + c <= -1 || modulesCount <= col + c) continue;
      const isDark =
        ((0 <= r && r <= 6) && (c === 0 || c === 6)) ||
        ((0 <= c && c <= 6) && (r === 0 || r === 6)) ||
        ((2 <= r && r <= 4) && (2 <= c && c <= 4));
      modules[row + r][col + c] = isDark;
    }
  }
}

function setupTimingPattern(modules, modulesCount) {
  for (let r = 8; r < modulesCount - 8; r++) {
    if (modules[r][6] !== null) continue;
    modules[r][6] = (r % 2 === 0);
  }
  for (let c = 8; c < modulesCount - 8; c++) {
    if (modules[6][c] !== null) continue;
    modules[6][c] = (c % 2 === 0);
  }
}

function setupPositionAdjustPattern(modules, version) {
  const pos = PATTERN_POSITION_TABLE[version - 1] || [];
  for (let i = 0; i < pos.length; i++) {
    const row = pos[i];
    for (let j = 0; j < pos.length; j++) {
      const col = pos[j];
      if (modules[row][col] !== null) continue;
      for (let r = -2; r <= 2; r++) {
        for (let c = -2; c <= 2; c++) {
          const isDark = (r === -2 || r === 2 || c === -2 || c === 2 || (r === 0 && c === 0));
          modules[row + r][col + c] = isDark;
        }
      }
    }
  }
}

function setupTypeNumber(modules, modulesCount, version, test) {
  const bits = bchTypeNumber(version);
  for (let i = 0; i < 18; i++) {
    const mod = (!test && (((bits >>> i) & 1) === 1));
    modules[Math.floor(i / 3)][(i % 3) + modulesCount - 8 - 3] = mod;
  }
  for (let i = 0; i < 18; i++) {
    const mod = (!test && (((bits >>> i) & 1) === 1));
    modules[(i % 3) + modulesCount - 8 - 3][Math.floor(i / 3)] = mod;
  }
}

function setupTypeInfo(modules, modulesCount, eccBits, maskPattern, test) {
  const data = ((eccBits << 3) | maskPattern) >>> 0;
  const bits = bchTypeInfo(data);

  // vertical
  for (let i = 0; i < 15; i++) {
    const modBit = (!test && (((bits >>> i) & 1) === 1));
    if (i < 6) modules[i][8] = modBit;
    else if (i < 8) modules[i + 1][8] = modBit;
    else modules[modulesCount - 15 + i][8] = modBit;
  }

  // horizontal
  for (let i = 0; i < 15; i++) {
    const modBit = (!test && (((bits >>> i) & 1) === 1));
    if (i < 8) modules[8][modulesCount - i - 1] = modBit;
    else if (i < 9) modules[8][15 - i - 1 + 1] = modBit;
    else modules[8][15 - i - 1] = modBit;
  }

  // fixed module
  modules[modulesCount - 8][8] = (!test);
}

function mapData(modules, modulesCount, data, maskPattern) {
  let inc = -1;
  let row = modulesCount - 1;
  let bitIndex = 7;
  let byteIndex = 0;

  const mask = maskFunc(maskPattern);
  const dataLen = data.length;

  for (let col = modulesCount - 1; col > 0; col -= 2) {
    if (col <= 6) col -= 1;

    const colRange = [col, col - 1];

    while (true) {
      for (const c of colRange) {
        if (modules[row][c] === null) {
          let dark = false;
          if (byteIndex < dataLen) {
            dark = ((((data[byteIndex] >>> bitIndex) & 1) === 1));
          }
          if (mask(row, c)) dark = !dark;

          modules[row][c] = dark;

          bitIndex -= 1;
          if (bitIndex === -1) {
            byteIndex += 1;
            bitIndex = 7;
          }
        }
      }

      row += inc;

      if (row < 0 || modulesCount <= row) {
        row -= inc;
        inc = -inc;
        break;
      }
    }
  }
}

function makeImpl(version, eccBits, dataCodewords, maskPattern, test) {
  const modulesCount = version * 4 + 17;
  const modules = new Array(modulesCount);
  for (let r = 0; r < modulesCount; r++) modules[r] = new Array(modulesCount).fill(null);

  setupPositionProbe(modules, modulesCount, 0, 0);
  setupPositionProbe(modules, modulesCount, modulesCount - 7, 0);
  setupPositionProbe(modules, modulesCount, 0, modulesCount - 7);

  setupPositionAdjustPattern(modules, version);
  setupTimingPattern(modules, modulesCount);

  setupTypeInfo(modules, modulesCount, eccBits, maskPattern, test);

  if (version >= 7) setupTypeNumber(modules, modulesCount, version, test);

  mapData(modules, modulesCount, dataCodewords, maskPattern);

  return modules;
}

function lostPoint(modules) {
  const modulesCount = modules.length;
  let lost = 0;
  lost += lostPointLevel1(modules, modulesCount);
  lost += lostPointLevel2(modules, modulesCount);
  lost += lostPointLevel3(modules, modulesCount);
  lost += lostPointLevel4(modules, modulesCount);
  return lost;
}

function lostPointLevel1(modules, modulesCount) {
  let lost = 0;
  const container = new Array(modulesCount + 1).fill(0);

  // rows
  for (let row = 0; row < modulesCount; row++) {
    const thisRow = modules[row];
    let previousColor = thisRow[0];
    let length = 0;
    for (let col = 0; col < modulesCount; col++) {
      if (thisRow[col] === previousColor) {
        length += 1;
      } else {
        if (length >= 5) container[length] += 1;
        length = 1;
        previousColor = thisRow[col];
      }
    }
    if (length >= 5) container[length] += 1;
  }

  // cols
  for (let col = 0; col < modulesCount; col++) {
    let previousColor = modules[0][col];
    let length = 0;
    for (let row = 0; row < modulesCount; row++) {
      if (modules[row][col] === previousColor) {
        length += 1;
      } else {
        if (length >= 5) container[length] += 1;
        length = 1;
        previousColor = modules[row][col];
      }
    }
    if (length >= 5) container[length] += 1;
  }

  for (let eachLength = 5; eachLength <= modulesCount; eachLength++) {
    lost += container[eachLength] * (eachLength - 2);
  }
  return lost;
}

function lostPointLevel2(modules, modulesCount) {
  let lost = 0;
  for (let row = 0; row < modulesCount - 1; row++) {
    const thisRow = modules[row];
    const nextRow = modules[row + 1];
    for (let col = 0; col < modulesCount - 1; col++) {
      const topRight = thisRow[col + 1];
      if (topRight !== nextRow[col + 1]) {
        col += 1; // skip one
        continue;
      }
      if (topRight !== thisRow[col]) continue;
      if (topRight !== nextRow[col]) continue;
      lost += 3;
    }
  }
  return lost;
}

function lostPointLevel3(modules, modulesCount) {
  let lost = 0;
  const modulesRangeShort = modulesCount - 10;

  // rows
  for (let row = 0; row < modulesCount; row++) {
    const thisRow = modules[row];
    for (let col = 0; col < modulesRangeShort; col++) {
      const cond =
        (!thisRow[col + 1] &&
          thisRow[col + 4] &&
          !thisRow[col + 5] &&
          thisRow[col + 6] &&
          !thisRow[col + 9] &&
          ((thisRow[col + 0] &&
            thisRow[col + 2] &&
            thisRow[col + 3] &&
            !thisRow[col + 7] &&
            !thisRow[col + 8] &&
            !thisRow[col + 10]) ||
           (!thisRow[col + 0] &&
            !thisRow[col + 2] &&
            !thisRow[col + 3] &&
            thisRow[col + 7] &&
            thisRow[col + 8] &&
            thisRow[col + 10])));
      if (cond) lost += 40;
      if (thisRow[col + 10]) col += 1; // horspool-like skip
    }
  }

  // cols
  for (let col = 0; col < modulesCount; col++) {
    for (let row = 0; row < modulesRangeShort; row++) {
      const cond =
        (!modules[row + 1][col] &&
          modules[row + 4][col] &&
          !modules[row + 5][col] &&
          modules[row + 6][col] &&
          !modules[row + 9][col] &&
          ((modules[row + 0][col] &&
            modules[row + 2][col] &&
            modules[row + 3][col] &&
            !modules[row + 7][col] &&
            !modules[row + 8][col] &&
            !modules[row + 10][col]) ||
           (!modules[row + 0][col] &&
            !modules[row + 2][col] &&
            !modules[row + 3][col] &&
            modules[row + 7][col] &&
            modules[row + 8][col] &&
            modules[row + 10][col])));
      if (cond) lost += 40;
      if (modules[row + 10][col]) row += 1;
    }
  }

  return lost;
}

function lostPointLevel4(modules, modulesCount) {
  let darkCount = 0;
  for (let r = 0; r < modulesCount; r++) {
    for (let c = 0; c < modulesCount; c++) {
      if (modules[r][c]) darkCount += 1;
    }
  }
  const percent = darkCount / (modulesCount * modulesCount);
  const rating = Math.floor(Math.abs(percent * 100 - 50) / 5);
  return rating * 10;
}

function bestMaskPattern(version, eccBits, dataCodewords) {
  let minLost = null;
  let best = 0;
  for (let i = 0; i < 8; i++) {
    const testModules = makeImpl(version, eccBits, dataCodewords, i, true);
    const lp = lostPoint(testModules);
    if (minLost === null || lp < minLost) {
      minLost = lp;
      best = i;
    }
  }
  return best;
}

function bestFitVersion(eccBits, bytes) {
  // needed bits: mode(4) + lengthField + data
  for (let version = 1; version <= 40; version++) {
    const lengthBits = lengthInBitsByte(version);
    const needed = 4 + lengthBits + (bytes.length * 8);
    const blocks = rsBlocks(version, eccBits);
    const bitLimit = blocks.reduce((s, b) => s + b.dataCount * 8, 0);
    if (needed <= bitLimit) return version;
  }
  throw new Error('QR data too large');
}

export function qrMatrix(text, { ecl = 'M', maskPattern = null } = {}) {
  const eccBits = ECC[String(ecl || 'M').toUpperCase()] ?? ECC.M;
  const bytes = new TextEncoder().encode(String(text ?? ''));

  const version = bestFitVersion(eccBits, bytes);
  const dataCodewords = createData(version, eccBits, bytes);

  const mask = (maskPattern === null || maskPattern === undefined)
    ? bestMaskPattern(version, eccBits, dataCodewords)
    : (Number(maskPattern) & 7);

  return makeImpl(version, eccBits, dataCodewords, mask, false);
}

export function qrSvg(text, { size = 104, margin = 4, ecl = 'M', maskPattern = null } = {}) {
  const modules = qrMatrix(text, { ecl, maskPattern });
  const n = modules.length;
  const m = Math.max(0, Number(margin) || 0);
  const view = n + m * 2;
  const px = Math.max(32, Number(size) || 104);

  let rects = '';
  for (let r = 0; r < n; r++) {
    for (let c = 0; c < n; c++) {
      if (!modules[r][c]) continue;
      rects += `<rect x="${c + m}" y="${r + m}" width="1" height="1"/>`;
    }
  }

  // Inline SVG keeps printing crisp (no raster blur).
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${view} ${view}" shape-rendering="crispEdges" role="img" aria-label="Approval ID QR">
` +
    `<rect width="100%" height="100%" fill="#fff"/>
` +
    `<g fill="#000">${rects}</g>
` +
    `</svg>`;
}

export function shortCodeFromSha256Id(id) {
  if (!id) return '—';
  let s = String(id).trim();
  if (!s || s === '—') return '—';
  if (s.startsWith('sha256:')) s = s.slice('sha256:'.length);
  s = s.replace(/[^0-9a-fA-F]/g, '');
  if (!s) return '—';
  s = s.toUpperCase().slice(0, 16);
  const groups = [];
  for (let i = 0; i < s.length; i += 4) groups.push(s.slice(i, i + 4));
  return groups.join('-');
}
