/**
 * Blur placeholder utilities for next/image.
 *
 * Generates a tiny SVG or solid-colour data URI that shows while the real
 * image loads — removes the jarring "blank → image" flash.
 *
 * Usage:
 *   import { shimmerDataUrl, solidPlaceholder } from "@/lib/blurPlaceholder";
 *
 *   <Image
 *     src={car.image}
 *     placeholder="blur"
 *     blurDataURL={shimmerDataUrl(800, 450)}
 *   />
 *
 *   // Or with a solid colour that matches your card background:
 *   blurDataURL={solidPlaceholder("#f3f4f6")}
 */

/** Encode arbitrary SVG as a data URI (safe for blurDataURL). */
function svgToDataUri(svg: string): string {
  // Minimal encoding: replace only chars that break data URIs
  const encoded = svg
    .replace(/\n/g, " ")
    .replace(/"/g, "'")
    .replace(/%/g, "%25")
    .replace(/#/g, "%23")
    .replace(/{/g, "%7B")
    .replace(/}/g, "%7D")
    .replace(/</g, "%3C")
    .replace(/>/g, "%3E");
  return `data:image/svg+xml,${encoded}`;
}

/**
 * Returns a shimmer-gradient data URI for use as a blur placeholder.
 *
 * @param w  pixel width  (just affects the SVG viewBox; 10 is fine)
 * @param h  pixel height
 */
export function shimmerDataUrl(w = 10, h = 6): string {
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${w} ${h}'>
    <defs>
      <linearGradient id='g' x1='0' x2='1'>
        <stop offset='0%'   stop-color='%23e5e7eb' />
        <stop offset='50%'  stop-color='%23f9fafb' />
        <stop offset='100%' stop-color='%23e5e7eb' />
      </linearGradient>
    </defs>
    <rect width='${w}' height='${h}' fill='url(%23g)' />
  </svg>`;
  return svgToDataUri(svg);
}

/**
 * Returns a solid-colour data URI.
 * Useful when you know the dominant colour of the image.
 *
 * @param colour CSS hex colour, e.g. "#e5e7eb"
 */
export function solidPlaceholder(colour = "#e5e7eb"): string {
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'>
    <rect width='1' height='1' fill='${colour}' />
  </svg>`;
  return svgToDataUri(svg);
}

/** Default shimmer — 16:9 aspect ratio, light grey. */
export const DEFAULT_BLUR = shimmerDataUrl(16, 9);

/** Car card blur — wider than 16:9. */
export const CAR_CARD_BLUR = shimmerDataUrl(4, 3);

/** Hero banner blur — ultrawide. */
export const HERO_BLUR = shimmerDataUrl(1920, 700);

/** Brand logo blur — square. */
export const LOGO_BLUR = shimmerDataUrl(1, 1);
