import Image from "next/image";
import { photoFor } from "@/lib/photos";

/**
 * Resolves a CMS photo field: /uploads paths and http(s) URLs are used
 * directly, otherwise it's treated as a library kind ("living", "heroAlt"…).
 */
export function cmsPhotoSrc(value: string): string {
  if (!value) return photoFor("living");
  if (value.startsWith("/") || value.startsWith("http")) return value;
  return photoFor(value);
}

/** True when a CMS photo field should render unoptimized (non-library srcs). */
export function isCustomSrc(value: string): boolean {
  return Boolean(value) && (value.startsWith("/") || value.startsWith("http"));
}

/**
 * Fills a relative-positioned parent with a curated photo.
 * Always wrap in a container with `relative` + an aspect/size class.
 */
export function Photo({
  kind,
  alt,
  className = "",
  sizes = "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw",
  priority = false,
}: {
  kind: string;
  alt: string;
  className?: string;
  sizes?: string;
  priority?: boolean;
}) {
  return (
    <Image
      src={photoFor(kind)}
      alt={alt}
      fill
      sizes={sizes}
      priority={priority}
      className={`object-cover ${className}`}
    />
  );
}

/**
 * CMS-driven photo: accepts library kinds, /uploads paths and external URLs.
 * Falls back to the given library kind when `value` is empty.
 */
export function CMSImage({
  value,
  fallbackKind,
  alt,
  className = "",
  sizes = "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw",
  priority = false,
}: {
  value: string;
  fallbackKind: string;
  alt: string;
  className?: string;
  sizes?: string;
  priority?: boolean;
}) {
  const custom = isCustomSrc(value);
  return (
    <Image
      src={custom ? value : photoFor(value || fallbackKind)}
      alt={alt}
      fill
      sizes={sizes}
      priority={priority}
      unoptimized={custom}
      className={`object-cover ${className}`}
    />
  );
}
