"use client" import React, { useState, useEffect } from "react" import { View, Text, Image, TextInput, TouchableOpacity, FlatList, SafeAreaView, ActivityIndicator, Alert, } from "react-native" import { Feather, FontAwesome } from "@expo/vector-icons" import { router, useFocusEffect } from "expo-router" import { useAuth } from "../../context/auth-context" import { supabase } from "../../services/supabase" import { useFoods, useFoodStats, useFoodCreators, useUserInteractions, useLikeMutation, useSaveMutation, } from "../../hooks/use-foods" // Sort options const sortOptions = [ { id: "newest", name: "Newest", icon: "calendar" }, { id: "like_desc", name: "Most Liked", icon: "heart" }, ] export default function ForumScreen() { const { isAuthenticated } = useAuth() const [currentUserId, setCurrentUserId] = useState(null) const [searchQuery, setSearchQuery] = useState("") const [selectedCategory, setSelectedCategory] = useState("") const [selectedSort, setSelectedSort] = useState("newest") // Get current user ID from Supabase session useEffect(() => { async function getCurrentUser() { if (isAuthenticated) { const { data } = await supabase.auth.getSession() const userId = data.session?.user?.id console.log("Current user ID:", userId) setCurrentUserId(userId || null) } else { setCurrentUserId(null) } } getCurrentUser() }, [isAuthenticated]) // Use React Query hooks const { data: foods = [], isLoading: isLoadingFoods, refetch: refetchFoods, } = useFoods(selectedCategory, searchQuery, selectedSort) const foodIds = foods.map((food) => food.id) const { data: foodStats = {}, isLoading: isLoadingStats } = useFoodStats(foodIds) const creatorIds = foods.filter((food) => food.created_by).map((food) => food.created_by as string) const { data: foodCreators = {}, isLoading: isLoadingCreators } = useFoodCreators(creatorIds) const { data: userInteractions = {}, isLoading: isLoadingInteractions } = useUserInteractions(foodIds, currentUserId) const likeMutation = useLikeMutation() const saveMutation = useSaveMutation() // Refetch data when the screen comes into focus useFocusEffect( React.useCallback(() => { refetchFoods() }, [refetchFoods]), ) const handleSearch = (text: string) => { setSearchQuery(text) } const navigateToPostDetail = (food: { id: string }) => { router.push(`/post-detail/${food.id}`) } const handleLike = async (food: { id: string }) => { if (!isAuthenticated || !currentUserId) { Alert.alert("Authentication Required", "Please log in to like posts.") return } try { const isLiked = userInteractions[food.id]?.liked || false likeMutation.mutate({ foodId: food.id, userId: currentUserId, isLiked, }) } catch (error) { console.error("Error toggling like:", error) Alert.alert("Error", "Failed to update like. Please try again.") } } const handleSave = async (food: { id: string }) => { if (!isAuthenticated || !currentUserId) { Alert.alert("Authentication Required", "Please log in to save posts.") return } try { const isSaved = userInteractions[food.id]?.saved || false saveMutation.mutate({ foodId: food.id, userId: currentUserId, isSaved, }) } catch (error) { console.error("Error toggling save:", error) Alert.alert("Error", "Failed to update save. Please try again.") } } const renderFoodItem = ({ item }: { item: any }) => { // Get stats for this food const stats = foodStats[item.id] || { likes: 0, saves: 0, comments: 0 } // Get creator profile const creator = item.created_by ? foodCreators[item.created_by] : null // Get user interactions const interactions = userInteractions[item.id] || { liked: false, saved: false } return ( navigateToPostDetail(item)} > {/* User info and rating */} {creator?.avatar_url ? ( ) : ( {creator?.username?.charAt(0).toUpperCase() || "?"} )} {creator?.username || creator?.full_name || "Unknown Chef"} {/* Food image */} {/* Food title and description */} {item.name} {item.description} {/* Interaction buttons */} { e.stopPropagation() handleLike(item) }} > {stats.likes} navigateToPostDetail(item)}> {stats.comments} { e.stopPropagation() handleSave(item) }} > ) } const isLoading = isLoadingFoods || isLoadingStats || isLoadingCreators || isLoadingInteractions return ( {/* Search Bar */} {/* Sort Options */} item.id} renderItem={({ item }) => ( setSelectedSort(item.id)} > {item.name} )} /> {/* Food Posts */} {isLoading ? ( ) : ( item.id} renderItem={renderFoodItem} contentContainerStyle={{ padding: 16 }} showsVerticalScrollIndicator={false} /> )} ) }