// This is a client-side script to prevent infinite redirect loops
// Import this in your BaseLayout component

export function handleLanguageRedirects() {
  // Only run in the browser
  if (typeof window === 'undefined') return;

  // Track redirects to prevent infinite loops
  const redirectCount = sessionStorage.getItem('redirectCount') || 0;
  
  // If we've redirected more than 3 times, stop redirecting to prevent infinite loops
  if (parseInt(redirectCount, 10) > 3) {
    console.warn('Too many redirects detected, stopping to prevent infinite loop');
    sessionStorage.setItem('redirectCount', '0');
    return;
  }

  // Add logic here if needed to handle redirects
  // For example, detect language from URL and redirect if needed
  
  // Increment redirect count when a redirect happens
  // This should be called right before redirecting
  function incrementRedirectCount() {
    const currentCount = parseInt(sessionStorage.getItem('redirectCount') || '0', 10);
    sessionStorage.setItem('redirectCount', (currentCount + 1).toString());
  }

  // Reset redirect count when navigation is complete
  window.addEventListener('load', () => {
    sessionStorage.setItem('redirectCount', '0');
  });

  return {
    incrementRedirectCount
  };
}

// Add the middleware function that Astro is expecting
export function onRequest(context, next) {
  // Pass through by default
  return next();
} 