---
// Server-side auth check for protected routes
import { supabase } from '../lib/supabase';

// This is a basic server-side auth check
// In production, you'd want more sophisticated session management
const cookies = Astro.request.headers.get('cookie');
let isAuthenticated = false;
let userSession = null;

if (cookies) {
  // Try to extract auth token from cookies
  // This is a simplified check - in production you'd validate the token
  const authCookie = cookies.split(';')
    .find(c => c.trim().startsWith('sb-access-token=') || c.trim().startsWith('supabase-auth-token='));
  
  if (authCookie) {
    isAuthenticated = true;
    // You would verify the token here in production
  }
}

// Redirect to login if not authenticated
if (!isAuthenticated && Astro.url.pathname !== '/') {
  return Astro.redirect('/');
}

export interface Props {
  title?: string;
  requireAdmin?: boolean;
}

const { title = "Protected Page", requireAdmin = false } = Astro.props;
---

<script>
  import { supabase } from '../lib/supabase';

  // Client-side auth verification as backup
  async function verifyAuth() {
    const { data: { session }, error } = await supabase.auth.getSession();
    
    if (error || !session) {
      console.warn('Authentication verification failed');
      window.location.pathname = '/';
      return;
    }

    // Store auth token for API calls
    const authToken = session.access_token;
    if (authToken) {
      // Set default authorization header for fetch requests
      const originalFetch = window.fetch;
      window.fetch = function(url, options = {}) {
        if (!options.headers) {
          options.headers = {};
        }
        
        // Add auth header to API calls
        if (typeof url === 'string' && url.startsWith('/api/')) {
          options.headers['Authorization'] = `Bearer ${authToken}`;
        }
        
        return originalFetch(url, options);
      };
    }
  }

  // Verify authentication on page load
  verifyAuth();

  // Listen for auth state changes
  supabase.auth.onAuthStateChange((event, session) => {
    if (event === 'SIGNED_OUT' || !session) {
      window.location.pathname = '/';
    }
  });
</script>

<style>
  /* Add loading state styles */
  .auth-loading {
    opacity: 0.5;
    pointer-events: none;
  }
</style>