export function displayCardValue(value: string | number | null | undefined) {
  if (value === null || value === undefined || value === '') return '-'
  return String(value).trim() || '-'
}

export function buildCardDownloadFileName(
  memberNumber: string | number | null | undefined,
  side: 'depan' | 'belakang',
) {
  const number = memberNumber ?? 'anggota'
  return `kad-digital-${number}-${side}.png`
}

export function toProxiedStorageUrl(url: string | null | undefined): string | null | undefined {
  if (!url) return url

  const apiBase = import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, '')

  try {
    const parsed = new URL(url, apiBase || window.location.origin)
    if (!parsed.pathname.startsWith('/storage/')) {
      return url
    }

    // Production serves the SPA from a different host than Laravel storage files.
    if (apiBase) {
      return `${apiBase}${parsed.pathname}${parsed.search}`
    }

    // Dev fallback: Vite proxies /storage to the API.
    return `${parsed.pathname}${parsed.search}`
  } catch {
    return url
  }
}
