function readPublicBaseUrl(envKey: string, fallback: string): string {
  const raw = import.meta.env[envKey] as string | undefined
  const s =
    typeof raw === 'string' && raw.trim() !== ''
      ? raw.trim().replace(/\/$/, '')
      : fallback.replace(/\/$/, '')
  return s
}

/**
 * Strips the Supabase PostgREST version path from a URL so that
 * `API_URL=http://127.0.0.1:54321/rest/v1` doesn't cause double-versioned
 * paths like `/rest/v1/v1/partners/...` when platform API routes append `/v1/`.
 * Also emits a dev-mode warning so the misconfiguration is visible early.
 */
function stripSupabaseRestPath(url: string): string {
  return url.replace(/\/rest\/v\d+\/?$/, '')
}

/** Default local auth origin (`nx serve auth` — see `apps/auth/vite.config.mts`). */
const DEV_AUTH_BASE_URL = 'http://localhost:3004'

/**
 * SSO / auth app origin (no trailing slash).
 * Set `AUTH_BASE_URL` in repo-root `.env` / `.env.local`.
 * In Vite dev, if unset, defaults to {@link DEV_AUTH_BASE_URL} instead of production.
 */
export const AUTH_BASE_URL = readPublicBaseUrl(
  'AUTH_BASE_URL',
  import.meta.env.DEV ? DEV_AUTH_BASE_URL : 'https://auth.lenserfight.com'
)

/** Main / arena app origin for battles, get-started, etc. Override with `ARENA_URL`. */
export const ARENA_BASE_URL = readPublicBaseUrl('ARENA_URL', 'https://lenserfight.com')

/** Community web origin (return URLs, links). Override with `WEB_BASE_URL`. */
export const WEB_BASE_URL = readPublicBaseUrl('WEB_BASE_URL', 'https://lenserfight.com')

/** Documentation site origin. Override with `DOCS_BASE_URL` (e.g. http://localhost:5174 in local dev). */
export const DOCS_BASE_URL = readPublicBaseUrl('DOCS_BASE_URL', 'https://docs.lenserfight.com')

/** Chainabit web app origin — used for deep-links to wallet top-up and partner attribution. Override with `CHAINABIT_APP_URL`. */
export const CHAINABIT_APP_URL = readPublicBaseUrl('CHAINABIT_APP_URL', 'https://app.chainabit.com')

/**
 * LenserFight API base URL (no trailing slash).
 * In development, defaults to the local dev URL above. To proxy through a
 * tunnel (e.g. ngrok) for CORS or webhook testing, set `API_URL` in your
 * `.env.local`. Production resolves to `https://api.lenserfight.com` unless
 * `API_URL` is provided.
 */
export const API_BASE_URL = stripSupabaseRestPath(
  readPublicBaseUrl('API_URL', 'https://api.lenserfight.com')
)

/**
 * Chainabit direct API base URL (no trailing slash, no version prefix).
 * All versioned endpoint construction goes through {@link chainabitUrl}.
 */
const _CHAINABIT_API_BASE = readPublicBaseUrl('CHAINABIT_API_URL', 'https://api.chainabit.com')

/**
 * Versioning adapter for all direct Chainabit API calls.
 * Builds `{base}/api/v{version}/{path}` — path must NOT start with a slash.
 * Change `defaultVersion` here to migrate all call sites at once.
 */
export function chainabitUrl(path: string, version = 1): string {
  return `${_CHAINABIT_API_BASE}/api/v${version}/${path}`
}

// Environment
export const MODE = import.meta.env.MODE // "development", "production", "test"
export const isProd = import.meta.env['ENV_MODE'] === 'production'

// Data Source — `supabase` (default) or `file` (planned lightweight workspace; use Supabase for full fidelity)
export type DataBackendKind = 'supabase' | 'file'

export const DATA_SOURCE = import.meta.env.DATA_SOURCE || 'supabase'

export const dataBackendKind: DataBackendKind =
  import.meta.env.DATA_SOURCE === 'file' ? 'file' : 'supabase'

export const isFileDataBackend = dataBackendKind === 'file'

/**
 * Public origin for Supabase API (tunnel to local :54321 in dev).
 * Used to rewrite signed storage URLs for external tools. See SUPABASE_PUBLIC_URL in apps/web/.env.example.
 */
export const SUPABASE_PUBLIC_URL = readPublicBaseUrl('SUPABASE_PUBLIC_URL', '')

// Local development flag (Vite dev server)
export const isLocal = import.meta.env['ENV_MODE'] === 'development'

export type LocalSeedCredentials = {
  email: string
  password: string
  displayName: string
}

/**
 * Loads local-only seed credentials for auto-filling the login/register forms
 * during development. The credentials live in a sibling module that is loaded
 * exclusively via dynamic `import()` behind an `import.meta.env.DEV` check, so
 * Vite's static replacement of `DEV` with `false` in production builds
 * eliminates the entire branch — the strings never reach the production bundle.
 *
 * Returns `null` in production / non-DEV builds.
 */
export async function loadDevSeedCredentials(): Promise<LocalSeedCredentials | null> {
  if (!import.meta.env.DEV) return null
  const mod = await import('./devSeedCredentials')
  return mod.LOCAL_SEED_CREDENTIALS
}

// Captcha
export const CAPTCHA_SITE_KEY = import.meta.env.CAPTCHA_SITE_KEY || ''

export const ENABLE_CAPTCHA = isProd

// Analytics
export const GA_MEASUREMENT_ID = import.meta.env.GA_MEASUREMENT_ID || ''
export const PUBLIC_POSTHOG_PROJECT_TOKEN =
  (import.meta.env['PUBLIC_POSTHOG_PROJECT_TOKEN'] as string | undefined) ?? ''
export const PUBLIC_POSTHOG_HOST =
  (import.meta.env['PUBLIC_POSTHOG_HOST'] as string | undefined) ?? 'https://us.i.posthog.com'
