// Detect which Dezky environment we're running against, from the browser
// hostname. The env badge in the topbar reads this and uses it as a
// "you're about to make changes in prod" warning — so it must NOT be
// user-controllable.
//
// Rules:
//   - hostname ends in `.local` or is `localhost` → 'dev'
//   - hostname contains `staging` → 'staging'
//   - anything else → 'prod' (safest default — show the prod styling)
//
// SSR returns 'dev' by default because the server has no concept of the
// browser hostname. The first client tick re-evaluates and the env pill
// updates without a visible flash for the typical operator workflow
// (signed-in client-side navigation).

export type Env = 'prod' | 'staging' | 'dev'

function detect(hostname: string): Env {
  const h = hostname.toLowerCase()
  if (h === 'localhost' || h === '127.0.0.1' || h.endsWith('.local')) return 'dev'
  if (h.includes('staging')) return 'staging'
  return 'prod'
}

const current = ref<Env>('dev')
const hostname = ref<string>('')
let initialized = false

function init() {
  if (!import.meta.client || initialized) return
  hostname.value = window.location.hostname
  current.value = detect(hostname.value)
  initialized = true
}

export const useEnv = () => {
  if (import.meta.client) init()
  return { env: current, hostname }
}
