'use client'; import { useEffect, useState } from 'react'; import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import CameraCapture from "@/components/CameraCapture"; import BottleGrid from "@/components/BottleGrid"; import AuthForm from "@/components/AuthForm"; import BuddyList from "@/components/BuddyList"; import SessionList from "@/components/SessionList"; import StatsDashboard from "@/components/StatsDashboard"; import DramOfTheDay from "@/components/DramOfTheDay"; import LanguageSwitcher from "@/components/LanguageSwitcher"; import { useI18n } from "@/i18n/I18nContext"; export default function Home() { const supabase = createClientComponentClient(); const [bottles, setBottles] = useState([]); const [isLoading, setIsLoading] = useState(true); const [user, setUser] = useState(null); const [fetchError, setFetchError] = useState(null); const { t } = useI18n(); useEffect(() => { // Check session const checkUser = async () => { try { // Proactively get session - this will trigger a refresh if needed const { data: { session }, error } = await supabase.auth.getSession(); if (session) { console.log('[Auth] Valid session found:', { userId: session.user.id, expiry: new Date(session.expires_at! * 1000).toLocaleString() }); } else { console.log('[Auth] No active session found.'); } if (error) { console.error('[Auth] Session check error:', error); } setUser(session?.user ?? null); if (session?.user) { fetchCollection(); } } catch (err) { console.error('[Auth] Unexpected error during session check:', err); setUser(null); } finally { setIsLoading(false); } }; checkUser(); // Listen for visibility change (wake up from sleep) const handleVisibilityChange = () => { if (document.visibilityState === 'visible') { console.log('[Auth] App became visible, refreshing session...'); checkUser(); } }; document.addEventListener('visibilitychange', handleVisibilityChange); // Listen for auth changes const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => { console.log('[Auth] State change event:', event, { hasSession: !!session, userId: session?.user?.id, email: session?.user?.email }); setUser(session?.user ?? null); if (session?.user) { if (event === 'SIGNED_IN' || event === 'INITIAL_SESSION' || event === 'TOKEN_REFRESHED') { fetchCollection(); } } else { setBottles([]); } }); return () => { subscription.unsubscribe(); document.removeEventListener('visibilitychange', handleVisibilityChange); }; }, []); const fetchCollection = async () => { setIsLoading(true); try { // Fetch bottles with their latest tasting date const { data, error } = await supabase .from('bottles') .select(` *, tastings ( created_at, rating ) `) .order('created_at', { ascending: false }); if (error) { console.error('Supabase fetch error:', error); throw error; } console.log(`Fetched ${data?.length || 0} bottles from Supabase`); // Process data to get the absolute latest tasting date for each bottle const processedBottles = (data || []).map(bottle => { const lastTasted = bottle.tastings && bottle.tastings.length > 0 ? bottle.tastings.reduce((latest: string, current: any) => new Date(current.created_at) > new Date(latest) ? current.created_at : latest, bottle.tastings[0].created_at ) : null; return { ...bottle, last_tasted: lastTasted }; }); setBottles(processedBottles); } catch (err: any) { console.error('Detailed fetch error:', err); setFetchError(err.message || JSON.stringify(err)); } finally { setIsLoading(false); } }; const handleLogout = async () => { await supabase.auth.signOut(); }; if (!user) { return (

WHISKYVAULT

{t('home.searchPlaceholder').replace('...', '')}

); } return (

WHISKYVAULT

{t('home.collection')} {bottles.length}

{isLoading ? (
) : fetchError ? (

{t('common.error')}

{fetchError}

) : ( )}
); }