export interface WordLoopRuntime {
  embedded: boolean
  apiBase: string
  iosApp: boolean
}

declare global {
  interface Window {
    __WORDLOOP_RUNTIME__?: Partial<WordLoopRuntime>
    __wordloopSetApiBase?: (base: string) => void
    __WORDLOOP_BOOT_ERROR__?: string
  }
}

export function getRuntime(): WordLoopRuntime {
  const injected = window.__WORDLOOP_RUNTIME__ ?? {}
  return {
    embedded: !!injected.embedded,
    apiBase: injected.apiBase || '/api',
    iosApp: !!injected.iosApp,
  }
}

export function currentAppPath(): string {
  if (getRuntime().embedded) {
    const hash = window.location.hash.replace(/^#/, '')
    return (hash.split('?')[0] || '/').trim() || '/'
  }
  return window.location.pathname
}

export function isAuthPath(): boolean {
  const path = currentAppPath()
  return path === '/login' || path === '/register'
}

/** iOS 内嵌 file:// 场景下不能用 location.href='/login'，会跳到 file:///login */
export function appNavigate(path: string) {
  const normalized = path.startsWith('/') ? path : `/${path}`
  if (getRuntime().embedded) {
    const base = `${window.location.pathname}${window.location.search}`
    window.location.replace(`${base}#${normalized}`)
    return
  }
  window.location.href = normalized
}
