const BACKEND_ORIGIN = (() => {
  try {
    return new URL(import.meta.env.VITE_BACKEND_URL ?? "http://localhost:8000").origin;
  } catch {
    return "http://localhost:8000";
  }
})();

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);
    if (url.origin === BACKEND_ORIGIN) return url.pathname + url.search;
  } catch {
    // already a relative path — return as-is
  }
  return src;
}
