/**
 * Image Optimization Utilities
 *
 * Helper functions for optimizing external image URLs
 * and generating responsive image srcsets.
 */

/**
 * Optimize Unsplash URL with WebP format and quality settings
 */
export function optimizeUnsplashUrl(
  url: string,
  options: {
    width?: number;
    height?: number;
    quality?: number;
    format?: 'webp' | 'auto';
  } = {}
): string {
  if (!url.includes('unsplash.com')) return url;

  const { width, height, quality = 80, format = 'webp' } = options;

  // Parse existing URL
  const urlObj = new URL(url);

  // Set optimization parameters
  if (width) urlObj.searchParams.set('w', width.toString());
  if (height) urlObj.searchParams.set('h', height.toString());
  urlObj.searchParams.set('q', quality.toString());
  urlObj.searchParams.set('fm', format);
  urlObj.searchParams.set('fit', 'crop');
  urlObj.searchParams.set('auto', 'format,compress');

  return urlObj.toString();
}

/**
 * Generate srcset for responsive images
 */
export function generateSrcset(
  url: string,
  widths: number[] = [320, 640, 960, 1280],
  aspectRatio?: number
): string {
  if (!url.includes('unsplash.com')) return '';

  return widths
    .map((w) => {
      const height = aspectRatio ? Math.round(w / aspectRatio) : undefined;
      const optimizedUrl = optimizeUnsplashUrl(url, { width: w, height });
      return `${optimizedUrl} ${w}w`;
    })
    .join(', ');
}

/**
 * Default image sizes attribute for responsive images
 */
export const defaultSizes = '(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw';

/**
 * Generate blur placeholder data URL (10x10 pixel)
 */
export function getBlurPlaceholder(color: string = '#1e293b'): string {
  return `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Crect fill='${encodeURIComponent(color)}' width='10' height='10'/%3E%3C/svg%3E`;
}
