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

type ExpandedClientsContextValue = {
  expandedClients: Set<string>;
  toggleClient: (id: string) => void;
  expandClients: (ids: string[]) => void;
};

const ExpandedClientsContext = createContext<ExpandedClientsContextValue | null>(null);

export function ExpandedClientsProvider({ children }: { children: React.ReactNode }) {
  const [expandedClients, setExpandedClients] = useState<Set<string>>(new Set());

  function toggleClient(id: string) {
    setExpandedClients((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }

  function expandClients(ids: string[]) {
    setExpandedClients((prev) => {
      const next = new Set(prev);
      for (const id of ids) next.add(id);
      return next;
    });
  }

  return (
    <ExpandedClientsContext.Provider value={{ expandedClients, toggleClient, expandClients }}>
      {children}
    </ExpandedClientsContext.Provider>
  );
}

export function useExpandedClients() {
  const ctx = useContext(ExpandedClientsContext);
  if (!ctx) throw new Error('useExpandedClients must be used within ExpandedClientsProvider');
  return ctx;
}
