function csrfToken() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
}

export function studioSurface(pathname = window.location.pathname) {
  return String(pathname || '/studio').split('?')[0] || '/studio'
}

export function studioModule(pathname = window.location.pathname) {
  const segments = studioSurface(pathname).split('/').filter(Boolean)

  if (segments[0] !== 'studio') {
    return null
  }

  return segments[1] || 'overview'
}

export async function trackStudioEvent(eventType, payload = {}) {
  try {
    await fetch('/api/studio/events', {
      method: 'POST',
      credentials: 'same-origin',
      keepalive: true,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': csrfToken(),
        'X-Requested-With': 'XMLHttpRequest',
      },
      body: JSON.stringify({
        event_type: eventType,
        ...payload,
      }),
    })
  } catch {
    // Studio analytics hooks should never block the UI.
  }
}