/**
 * QR Data Encoder/Decoder
 * Handles encoding and decoding of calculator data for QR codes
 */

import { QRCalculatorData } from '../types';

/**
 * Encode calculator data to Base64 string for QR code
 * @param data Calculator data to encode
 * @returns Base64-encoded JSON string
 */
export function encodeQRData(data: QRCalculatorData): string {
  try {
    // Convert data to JSON string
    const jsonString = JSON.stringify(data);

    // Encode to Base64 (URL-safe)
    const base64 = btoa(jsonString);

    // Make URL-safe by replacing characters
    const urlSafe = base64
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=/g, '');

    return urlSafe;
  } catch (error) {
    console.error('Error encoding QR data:', error);
    throw new Error('Failed to encode QR data');
  }
}

/**
 * Decode Base64 string from QR code back to calculator data
 * @param encoded Base64-encoded string
 * @returns Decoded calculator data or null if invalid
 */
export function decodeQRData(encoded: string): QRCalculatorData | null {
  try {
    // Restore Base64 padding and special characters
    let base64 = encoded
      .replace(/-/g, '+')
      .replace(/_/g, '/');

    // Add padding if needed
    while (base64.length % 4) {
      base64 += '=';
    }

    // Decode from Base64
    const jsonString = atob(base64);

    // Parse JSON
    const data = JSON.parse(jsonString) as QRCalculatorData;

    // Basic validation - ensure calculationType exists
    if (!data.calculationType || !['fuel', 'distance', 'custom'].includes(data.calculationType)) {
      console.error('Invalid calculator type in QR data');
      return null;
    }

    return data;
  } catch (error) {
    console.error('Error decoding QR data:', error);
    return null;
  }
}

/**
 * Generate full calculator URL with encoded QR data
 * @param data Calculator data to encode
 * @param baseUrl Base URL of the application (e.g., 'https://puffinoffset.com')
 * @returns Full URL with encoded data as query parameter
 */
export function generateQRUrl(data: QRCalculatorData, baseUrl: string = window.location.origin): string {
  const encoded = encodeQRData(data);
  return `${baseUrl}/calculator?qr=${encoded}`;
}

/**
 * Extract QR data from URL query parameters
 * @param url URL string or URLSearchParams object
 * @returns Decoded calculator data or null
 */
export function extractQRDataFromUrl(url: string | URLSearchParams): QRCalculatorData | null {
  try {
    let params: URLSearchParams;

    if (typeof url === 'string') {
      // Parse URL string
      const urlObj = new URL(url);
      params = urlObj.searchParams;
    } else {
      params = url;
    }

    const qrParam = params.get('qr');
    if (!qrParam) {
      return null;
    }

    return decodeQRData(qrParam);
  } catch (error) {
    console.error('Error extracting QR data from URL:', error);
    return null;
  }
}
