import imageUrlBuilder from '@sanity/image-url';
import { sanityConfig, usingSanity } from './content';

const builder = usingSanity ? imageUrlBuilder(sanityConfig) : null;

export type ImageValue = { src?: string; alt?: string; asset?: { _ref?: string }; [k: string]: any } | null | undefined;

export function hasImage(image: ImageValue): boolean {
  return Boolean(image && (image.src || image.asset?._ref));
}

/** URL for a seed image (`src`) or a Sanity image (`asset`), resized to `width`. */
export function imageUrl(image: ImageValue, width = 1200, height?: number): string {
  if (!image) return '';
  if (image.src) return image.src;
  if (!builder || !image.asset?._ref) return '';
  let b = builder.image(image).width(width).auto('format').fit('crop');
  if (height) b = b.height(height);
  return b.url();
}

/** srcset with a few widths; seed images are single-size. */
export function imageSrcSet(image: ImageValue, widths = [480, 800, 1200], aspect?: number): string | undefined {
  if (!image || image.src || !builder) return undefined;
  return widths.map((w) => `${imageUrl(image, w, aspect ? Math.round(w / aspect) : undefined)} ${w}w`).join(', ');
}
