import { useCallback, useState } from 'react';

/**
 * Determines if state isExpanded (default: false)
 * @member isExpanded returns the current state
 * @member expand will set isExpanded to true
 * @member collapse will set isExpanded to false
 * @member toggleExpanded will toggle isExpanded state
 * @example
 * <div>
 *  <span>{String(isExpanded)}</span>
 *  <button id="expand" onClick={expand}></button>
 *  <button id="collapse" onClick={collapse}></button>
 *  <button id="toggle" onClick={toggleExpanded}></button>
 * </div>
 */
export const useExpand = (
  initialValue = false,
): {
  readonly isExpanded: boolean;
  readonly expand: () => void;
  readonly collapse: () => void;
  readonly toggleExpanded: () => void;
} => {
  const [isExpanded, setIsExpanded] = useState(initialValue);
  const expand = useCallback(() => {
    setIsExpanded(true);
  }, []);
  const collapse = useCallback(() => {
    setIsExpanded(false);
  }, []);

  const toggleExpanded = useCallback(() => {
    setIsExpanded((previous) => !previous);
  }, []);

  return {
    isExpanded,
    expand,
    collapse,
    toggleExpanded,
  } as const;
};
