// WebAuthn utility functions

// Convert Base64URL string to ArrayBuffer
export function base64urlToBuffer(base64url: string): ArrayBuffer {
  const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')
  const padLen = (4 - (base64.length % 4)) % 4
  const padded = base64 + '='.repeat(padLen)
  const binary = atob(padded)
  const buffer = new ArrayBuffer(binary.length)
  const bytes = new Uint8Array(buffer)
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i)
  }
  return buffer
}

// Convert ArrayBuffer to Base64URL string
export function bufferToBase64url(buffer: ArrayBuffer): string {
  const bytes = new Uint8Array(buffer)
  let binary = ''
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i])
  }
  return btoa(binary)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '')
}

// Get CSRF token from meta tag
export function getCsrfToken(): string {
  const metaTag = document.querySelector<HTMLMetaElement>("meta[name='csrf-token']")
  if (!metaTag) {
    throw new Error('CSRF token meta tag not found')
  }
  return metaTag.getAttribute('content') || ''
}
