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

const TrieSelectContext = createContext();

export const useTrieSelect = () => {
  const context = useContext(TrieSelectContext);
  if (context === undefined) {
    throw new Error("useTrieSelect must be used within a TrieSelectProvider");
  }

  return context;
}

export const TrieSelectProvider = ({ children, onChange }) => {
  const [selected, setSelected] = useState(new Set());

  const add = (ids) => setSelected(prev => new Set([...prev, ...ids]));
  const remove = (ids) => setSelected(prev => {
    for (const id of ids) {
      prev.delete(id);
    }
    return new Set(prev);
  });

  useEffect(() => {
    onChange(Array.from(selected));
  }, [onChange, selected]);

  return (
    <TrieSelectContext.Provider value={{
      selected: Array.from(selected),
      add,
      remove
    }}>
      {children}
    </TrieSelectContext.Provider>
  );
}
