const _backendHost = (() => {
  try {
    return new URL(import.meta.env.VITE_BACKEND_URL || "").host;
  } catch {
    return "";
  }
})();

/**
 * Normalises a media URL:
 * - External hosts (S3, CDN): returned as-is.
 * - Backend / same-origin URLs: strip origin so the request goes through
 *   the Vite dev proxy or nginx in production.
 * - blob: / data: URLs: returned unchanged.
 * - null / undefined / empty: returns null.
 */
export function mediaUrl(src: string | null | undefined): string | null {
  if (!src) return null;
  if (src.startsWith("blob:") || src.startsWith("data:")) return src;
  try {
    const url = new URL(src);
    const isLocal =
      url.host === window.location.host || url.host === _backendHost;
    if (!isLocal) return src; // S3 / CDN — keep full URL
    return url.pathname + (url.search || "");
  } catch {
    return src.startsWith("/") ? src : `/${src}`;
  }
}
