export const useAuth = () => { const session = useState('auth-session', () => null) const status = useState<'loading' | 'authenticated' | 'unauthenticated'>('auth-status', () => 'loading') // Track if we've already fetched to prevent double-fetching const hasFetched = useState('auth-has-fetched', () => false) const fetchSession = async () => { try { status.value = 'loading' const data = await $fetch('/api/auth/session') session.value = data status.value = data.user ? 'authenticated' : 'unauthenticated' hasFetched.value = true } catch (error) { console.error('Error fetching session:', error) session.value = { user: null } status.value = 'unauthenticated' hasFetched.value = true } } const signIn = () => { window.location.href = '/api/auth/login' } const signOut = async () => { status.value = 'loading' await $fetch('/api/auth/logout', { method: 'POST' }) session.value = { user: null } status.value = 'unauthenticated' hasFetched.value = false window.location.href = '/' } // Only fetch once on client side, and only if we haven't already if (import.meta.client && !hasFetched.value) { fetchSession() } return { session: computed(() => session.value), user: computed(() => session.value?.user), status: computed(() => status.value), signIn, signOut, refresh: fetchSession } }