import { createContext, useContext, useState, useEffect } from 'react';

const HostContext = createContext(null);

export function HostProvider({ children }) {
  const [hosts, setHosts] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/hosts', { credentials: 'include' })
      .then(res => res.json())
      .then(data => {
        const hostsMap = {};
        (data.hosts || []).forEach(host => {
          hostsMap[host.id] = host;
        });
        setHosts(hostsMap);
        setLoading(false);
      })
      .catch(err => {
        console.error('Failed to load hosts:', err);
        setLoading(false);
      });
  }, []);

  return (
    <HostContext.Provider value={{ hosts, loading }}>
      {children}
    </HostContext.Provider>
  );
}

export function useHosts() {
  const context = useContext(HostContext);
  if (!context) {
    return { hosts: {}, loading: false };
  }
  return context;
}

export function useHost(hostId) {
  const { hosts } = useHosts();
  return hosts[hostId] || null;
}
