import { useState, useEffect, useCallback } from 'react'; import { useAuth } from '@/hooks/useAuth'; import { supabase } from '@/integrations/supabase/client'; import { UnitPreferences, getMeasurementSystemFromCountry } from '@/lib/units'; const DEFAULT_PREFERENCES: UnitPreferences = { measurement_system: 'metric', temperature: 'celsius', auto_detect: true }; export function useUnitPreferences() { const { user } = useAuth(); const [preferences, setPreferences] = useState(DEFAULT_PREFERENCES); const [loading, setLoading] = useState(true); useEffect(() => { loadPreferences(); }, [user]); const loadPreferences = async () => { try { if (user) { // Load from database for logged-in users const { data } = await supabase .from('user_preferences') .select('unit_preferences') .eq('user_id', user.id) .maybeSingle(); if (data?.unit_preferences && typeof data.unit_preferences === 'object') { setPreferences({ ...DEFAULT_PREFERENCES, ...(data.unit_preferences as unknown as UnitPreferences) }); } else { // Auto-detect for new users await autoDetectPreferences(); } } else { // Check localStorage for anonymous users const stored = localStorage.getItem('unit_preferences'); if (stored) { try { const parsed = JSON.parse(stored); setPreferences({ ...DEFAULT_PREFERENCES, ...parsed }); } catch (e) { await autoDetectPreferences(); } } else { await autoDetectPreferences(); } } } catch (error) { console.error('Error loading unit preferences:', error); await autoDetectPreferences(); } finally { setLoading(false); } }; const autoDetectPreferences = useCallback(async () => { try { const response = await supabase.functions.invoke('detect-location'); if (response.data && response.data.measurementSystem) { const newPreferences: UnitPreferences = { ...DEFAULT_PREFERENCES, measurement_system: response.data.measurementSystem, }; setPreferences(newPreferences); // Save to database for logged-in users, localStorage for anonymous users if (user) { // Use upsert with merge const { error } = await supabase .from('user_preferences') .upsert({ user_id: user.id, unit_preferences: newPreferences as any, updated_at: new Date().toISOString() }); if (error) { console.error('Error saving preferences to database:', error); } } else { localStorage.setItem('unit_preferences', JSON.stringify(newPreferences)); } return newPreferences; } } catch (error) { console.error('❌ Error auto-detecting location:', error); } // Fallback to default setPreferences(DEFAULT_PREFERENCES); return DEFAULT_PREFERENCES; }, [user]); const updatePreferences = async (newPreferences: Partial) => { const updated = { ...preferences, ...newPreferences }; setPreferences(updated); try { if (user) { // Save to database for logged-in users await supabase .from('user_preferences') .update({ unit_preferences: updated as any, updated_at: new Date().toISOString() }) .eq('user_id', user.id); } else { // Save to localStorage for anonymous users localStorage.setItem('unit_preferences', JSON.stringify(updated)); } } catch (error) { console.error('Error saving unit preferences:', error); // Revert on error setPreferences(preferences); throw error; } }; return { preferences, loading, updatePreferences, autoDetectPreferences }; }