'use client';

const LOCAL_API_URL = 'http://localhost:3001/api/v1';
const SAME_ORIGIN_API_URL = '/api/v1';

export function getApiUrl() {
  const envApiUrl = process.env.NEXT_PUBLIC_API_URL?.trim();

  if (typeof window === 'undefined') {
    return envApiUrl || LOCAL_API_URL;
  }

  const host = window.location.hostname;
  if (host === 'localhost' || host === '127.0.0.1') {
    return LOCAL_API_URL;
  }

  if (envApiUrl && !envApiUrl.includes('localhost') && !envApiUrl.includes('127.0.0.1')) {
    return envApiUrl;
  }

  return SAME_ORIGIN_API_URL;
}
