const PROTECTED_ASSET_PREFIX = 'likei-protected:'
const PROTECTED_PATH_PREFIXES = ['Activities/', 'Ranking/']
const NON_PROTECTED_MODES = new Set(['development', 'test'])
const CURRENT_MODE = import.meta.env.VITE_NODE_ENV || import.meta.env.MODE || 'development'

function encodeBase64(value) {
  if (typeof globalThis.btoa === 'function') {
    return globalThis.btoa(unescape(encodeURIComponent(value)))
  }

  if (typeof globalThis.Buffer !== 'undefined') {
    return globalThis.Buffer.from(value, 'utf-8').toString('base64')
  }

  throw new Error('Base64 encoder is not available in the current runtime')
}

function decodeBase64(value) {
  if (typeof globalThis.atob === 'function') {
    return decodeURIComponent(escape(globalThis.atob(value)))
  }

  if (typeof globalThis.Buffer !== 'undefined') {
    return globalThis.Buffer.from(value, 'base64').toString('utf-8')
  }

  throw new Error('Base64 decoder is not available in the current runtime')
}

export function shouldProtectAssetPath(assetPath = '') {
  if (!assetPath || NON_PROTECTED_MODES.has(CURRENT_MODE)) {
    return false
  }

  return PROTECTED_PATH_PREFIXES.some((prefix) => assetPath.startsWith(prefix))
}

export function protectAssetUrl(url = '', assetPath = '') {
  if (!url || !shouldProtectAssetPath(assetPath)) {
    return url
  }

  return `${PROTECTED_ASSET_PREFIX}${encodeBase64(url)}`
}

export function isProtectedAssetUrl(url = '') {
  return typeof url === 'string' && url.startsWith(PROTECTED_ASSET_PREFIX)
}

export function resolveProtectedAssetUrl(url = '') {
  if (!isProtectedAssetUrl(url)) {
    return url
  }

  try {
    return decodeBase64(url.slice(PROTECTED_ASSET_PREFIX.length))
  } catch (error) {
    console.warn('Failed to decode protected asset url:', error)
    return url
  }
}

export function toCssBackgroundImage(url = '') {
  const resolvedUrl = resolveProtectedAssetUrl(url)
  return resolvedUrl ? `url(${resolvedUrl})` : 'none'
}
