"use client"; import { createContext, useContext, useState, useEffect, ReactNode } from "react"; interface Site { id: string; name: string; } interface SiteContextType { sites: Site[]; selectedSiteId: string | null; selectedSite: Site | null; setSelectedSiteId: (siteId: string | null) => void; isLoading: boolean; } const SiteContext = createContext(undefined); export function SiteProvider({ children }: { children: ReactNode }) { const [sites, setSites] = useState([]); const [selectedSiteId, setSelectedSiteId] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { async function fetchSites() { try { const response = await fetch("/api/sites"); if (response.ok) { const data = await response.json(); setSites(data.data || []); } } catch (error) { console.error("Failed to fetch sites:", error); } finally { setIsLoading(false); } } fetchSites(); }, []); const selectedSite = sites.find((site) => site.id === selectedSiteId) || null; return ( {children} ); } export function useSite() { const context = useContext(SiteContext); if (context === undefined) { throw new Error("useSite must be used within a SiteProvider"); } return context; }