// Utility to handle API calls in both dev and production
export async function apiCall(endpoint: string, options: RequestInit = {}) {
  const baseUrl = typeof window !== "undefined" ? window.location.origin : ""
  const url = `${baseUrl}${endpoint}`

  const defaultOptions: RequestInit = {
    headers: {
      "Content-Type": "application/json",
      "Cache-Control": "no-cache",
    },
    ...options,
  }

  try {
    const response = await fetch(url, defaultOptions)

    if (!response.ok) {
      throw new Error(`API call failed: ${response.status} ${response.statusText}`)
    }

    const text = await response.text()

    if (!text) {
      return null
    }

    try {
      return JSON.parse(text)
    } catch (parseError) {
      console.error("JSON parse error:", parseError, "Response text:", text)
      throw new Error("Invalid JSON response")
    }
  } catch (error) {
    console.error(`API call to ${endpoint} failed:`, error)
    throw error
  }
}
