"use client"; import { useEffect, useState } from "react"; import { collection, onSnapshot, query, where, FirestoreError } from "firebase/firestore"; import { onAuthStateChanged } from "firebase/auth"; import { db, auth } from "@/lib/firebase"; import { useAuth } from "@/components/AuthProvider"; import type { SystemRecord } from "@/lib/types"; export function useSystems() { const [systems, setSystems] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const { orgId } = useAuth(); useEffect(() => { let unsubFirestore: (() => void) | undefined; const unsubAuth = onAuthStateChanged(auth, (user) => { if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; } if (!user) { setSystems([]); setLoading(false); return; } if (!orgId) { setSystems([]); setLoading(false); return; } const q = query(collection(db, "systems"), where("org_id", "==", orgId)); unsubFirestore = onSnapshot(q, (snap) => { setSystems(snap.docs.map((d) => d.data() as SystemRecord)); setLoading(false); }, (err: FirestoreError) => { console.error("useSystems:", err); setError(err.message); setLoading(false); }); }); return () => { unsubAuth(); if (unsubFirestore) unsubFirestore(); }; }, [orgId]); return { systems, loading, error }; }