import { useState, useEffect } from 'react' import { supabase } from './lib/supabase' import { Login } from './components/Login' import { Dashboard } from './components/Dashboard' import { CameraRoute } from './components/CameraRoute' function App() { const [isAuthenticated, setIsAuthenticated] = useState(null) const [loading, setLoading] = useState(true) const [currentRoute, setCurrentRoute] = useState(window.location.pathname) useEffect(() => { // Check initial auth state checkAuthState() // Listen for auth changes const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => { console.log('Auth state changed:', event, !!session) setIsAuthenticated(!!session) setLoading(false) // Handle signout route if (event === 'SIGNED_OUT') { setCurrentRoute('/') window.history.pushState({}, '', '/') } }) // Handle browser navigation const handlePopState = () => { setCurrentRoute(window.location.pathname) } window.addEventListener('popstate', handlePopState) return () => { subscription.unsubscribe() window.removeEventListener('popstate', handlePopState) } }, []) useEffect(() => { // Handle signout route if (currentRoute === '/signout') { handleLogout() } }, [currentRoute]) const checkAuthState = async () => { try { const { data: { session } } = await supabase.auth.getSession() setIsAuthenticated(!!session) } catch (error) { console.error('Error checking auth state:', error) setIsAuthenticated(false) } finally { setLoading(false) } } const handleLoginSuccess = () => { setIsAuthenticated(true) setCurrentRoute('/') window.history.pushState({}, '', '/') } const handleLogout = async () => { try { // Clear Supabase session await supabase.auth.signOut() // Clear any local storage items localStorage.removeItem('supabase.auth.token') // Reset state setIsAuthenticated(false) setCurrentRoute('/') window.history.pushState({}, '', '/') } catch (error) { console.error('Logout error:', error) // Still reset state even if there's an error setIsAuthenticated(false) setCurrentRoute('/') window.history.pushState({}, '', '/') } } // Check if current route is a camera live route const isCameraLiveRoute = (route: string) => { const cameraRoutePattern = /^\/camera(\d+)\/live$/ return cameraRoutePattern.test(route) } // Extract camera number from route const getCameraNumber = (route: string) => { const match = route.match(/^\/camera(\d+)\/live$/) return match ? `camera${match[1]}` : null } if (loading) { return (

Loading...

) } // Handle signout route if (currentRoute === '/signout') { return (

Signing out...

) } // Handle camera live routes (no authentication required) if (isCameraLiveRoute(currentRoute)) { const cameraNumber = getCameraNumber(currentRoute) if (cameraNumber) { return } } return ( <> {isAuthenticated ? ( ) : ( )} ) } export default App