// QR encoding helpers shared by the login page.
//
// The heavy lifting lives in qrcode-generator (MIT, Kazuhiko Arase); this
// module only turns its module grid into a compact SVG path and keeps the
// rendering math testable outside of Vue.
import qrcode from 'qrcode-generator'

export type QrLevel = 'L' | 'M' | 'Q' | 'H'

export interface QrMatrix {
  /** Number of modules per side, excluding the quiet zone. */
  count: number
  /** Row major grid, `true` means a dark module. */
  modules: boolean[][]
}

/** Encodes text, returning null when the payload cannot be encoded. */
export function qrMatrix(text: string, level: QrLevel = 'M'): QrMatrix | null {
  if (!text) return null
  try {
    const qr = qrcode(0, level)
    qr.addData(text)
    qr.make()
    const count = qr.getModuleCount()
    const modules: boolean[][] = []
    for (let row = 0; row < count; row++) {
      const line: boolean[] = []
      for (let col = 0; col < count; col++) line.push(qr.isDark(row, col))
      modules.push(line)
    }
    return { count, modules }
  } catch {
    return null
  }
}

/**
 * Builds one SVG path for the whole symbol. Horizontal runs are merged so the
 * DOM stays small, and every rectangle lands on whole module coordinates.
 */
export function qrPath(matrix: QrMatrix, margin = 3): { size: number; path: string } {
  const parts: string[] = []
  for (let row = 0; row < matrix.count; row++) {
    let col = 0
    while (col < matrix.count) {
      if (!matrix.modules[row][col]) {
        col++
        continue
      }
      let run = 1
      while (col + run < matrix.count && matrix.modules[row][col + run]) run++
      const x = col + margin
      const y = row + margin
      parts.push(`M${x} ${y}h${run}v1h-${run}z`)
      col += run
    }
  }
  return { size: matrix.count + margin * 2, path: parts.join('') }
}

/**
 * Integer pixel size per module. Rendering each module on a whole number of
 * device independent pixels is what keeps the symbol crisp on every zoom level;
 * the callers size the frame from the result, so the symbol is never clipped.
 */
export function qrCellSize(size: number, count: number): number {
  return Math.max(2, Math.round(size / Math.max(1, count)))
}
