/**
 * Smart runtime backend URL resolver.
 *
 * Eliminates the need to manually update `.env` files when switching between:
 *  - Docker/Linux Production Web Server  → uses window.location.origin
 *  - Android APK (Capacitor WebView)     → forces absolute production domain
 *
 * Priority order:
 *  1. Explicit VITE_BACKEND_URL env variable (if set at build time)
 *  2. Android/Capacitor app detection    → https://yotrip.labz.io.vn
 *  3. Production web server              → window.location.origin
 */

const PRODUCTION_DOMAIN = 'https://yotrip.labz.io.vn';

const resolveBackendEndpoint = (): string => {
  // 1. Honour explicit build-time env override first
  const envUrl = import.meta.env.VITE_BACKEND_URL as string | undefined;
  if (envUrl) {
    return envUrl;
  }

  const origin = window.location.origin;
  const userAgent = navigator.userAgent.toLowerCase();

  // 2. Detect Android APK / Capacitor WebView environment
  //    These shells run on local/file:// origins, not the production domain.
  const isAndroidApp =
    origin.startsWith('http://localhost') ||
    origin.startsWith('capacitor://') ||
    origin.startsWith('file://') ||
    (userAgent.includes('android') && !origin.includes('yotrip.labz.io.vn'));

  if (isAndroidApp) {
    console.log('[Backend] 📱 Android/Capacitor environment detected — using production domain.');
    return PRODUCTION_DOMAIN;
  }

  // 3. Web production server: the origin IS the backend (same Docker host)
  return origin;
};

/** Resolved backend base URL for the current runtime environment. */
export const BACKEND_URL: string = resolveBackendEndpoint();

console.log(`[Backend] 🌐 Active endpoint: ${BACKEND_URL}`);
