"use client"; import { useEffect, useState } from "react"; import { collection, onSnapshot, query, orderBy, limit, where, FirestoreError } from "firebase/firestore"; import { onAuthStateChanged } from "firebase/auth"; import { db, auth } from "@/lib/firebase"; import type { CallRecord } from "@/lib/types"; export function useCalls(limitCount = 50) { const [calls, setCalls] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let unsubFirestore: (() => void) | undefined; const unsubAuth = onAuthStateChanged(auth, (user) => { if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; } if (!user) { setCalls([]); setLoading(false); return; } const q = query( collection(db, "calls"), orderBy("started_at", "desc"), limit(limitCount) ); unsubFirestore = onSnapshot(q, (snap) => { setCalls(snap.docs.map((d) => d.data() as CallRecord)); setLoading(false); }, (err: FirestoreError) => { console.error("useCalls:", err); setError(err.message); setLoading(false); }); }); return () => { unsubAuth(); if (unsubFirestore) unsubFirestore(); }; }, [limitCount]); return { calls, loading, error }; } export function useActiveCalls() { const [calls, setCalls] = useState([]); useEffect(() => { let unsubFirestore: (() => void) | undefined; const unsubAuth = onAuthStateChanged(auth, (user) => { if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; } if (!user) { setCalls([]); return; } const q = query(collection(db, "calls"), where("status", "==", "active")); unsubFirestore = onSnapshot(q, (snap) => { setCalls(snap.docs.map((d) => d.data() as CallRecord)); }, (err: FirestoreError) => { console.error("useActiveCalls:", err); }); }); return () => { unsubAuth(); if (unsubFirestore) unsubFirestore(); }; }, []); return calls; }