async function api(endpoint, method = 'GET', data = null) {
  const opts = {
    method,
    headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
    credentials: 'same-origin',
  };
  if (data) opts.body = JSON.stringify(data);
  const res = await fetch(endpoint, opts);
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Network error' }));
    // Handle session expiry gracefully
    if (res.status === 401) {
      showToast('Your session has expired. Redirecting to login\u2026', 'warning');
      setTimeout(() => { window.location.href = '/login.php'; }, 2000);
      throw new Error('Session expired \u2014 please log in again');
    }
    throw new Error(err.error || 'Request failed');
  }
  return res.json();
}
</script>
