"use client"; import { useEffect, useState } from "react"; import { collection, onSnapshot, query, orderBy } from "firebase/firestore"; import { onAuthStateChanged } from "firebase/auth"; import { db, auth } from "@/lib/firebase"; import type { TripRecord } from "@/lib/types"; export function useTrips() { const [trips, setTrips] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { let unsubFirestore: (() => void) | undefined; const unsubAuth = onAuthStateChanged(auth, (user) => { if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; } if (!user) { setTrips([]); setLoading(false); return; } const q = query(collection(db, "trips"), orderBy("start_date", "asc")); unsubFirestore = onSnapshot( q, (snap) => { setTrips(snap.docs.map((d) => d.data() as TripRecord)); setLoading(false); }, (err) => { console.error("useTrips:", err); setLoading(false); } ); }); return () => { unsubAuth(); if (unsubFirestore) unsubFirestore(); }; }, []); return { trips, loading }; }