import { useState, useCallback } from 'react';

/**
 * Manages collapsible group state.
 * @param defaultCollapsed When true, groups start collapsed (tracks expanded groups).
 *   When false (default), groups start expanded (tracks collapsed groups).
 */
export function useCollapsibleGroups(
  defaultCollapsed = false
): [(name: string) => boolean, (name: string) => void, (name: string) => void] {
  const [toggled, setToggled] = useState<Set<string>>(new Set());

  const isExpanded = useCallback(
    (name: string) => (defaultCollapsed ? toggled.has(name) : !toggled.has(name)),
    [toggled, defaultCollapsed]
  );

  const toggle = useCallback((name: string) => {
    setToggled((prev) => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name);
      else next.add(name);
      return next;
    });
  }, []);

  const expand = useCallback(
    (name: string) => {
      setToggled((prev) => {
        if (defaultCollapsed) {
          if (prev.has(name)) return prev;
          const next = new Set(prev);
          next.add(name);
          return next;
        } else {
          if (!prev.has(name)) return prev;
          const next = new Set(prev);
          next.delete(name);
          return next;
        }
      });
    },
    [defaultCollapsed]
  );

  return [isExpanded, toggle, expand];
}
