/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */

import { useCallback, useRef, useState } from 'react';
import { useLegendPosition } from './use_legend_position.hook';

/**
 * Interface representing the state and handlers for the legend component
 */

/**
 * Hook that manages legend state and positioning
 * @returns {LegendState} Object containing legend state and handlers
 */
export const useLegend = () => {
  // Initialize ref with null to match React.RefObject type
  const ref = useRef(null);
  const [isOpen, setIsOpen] = useState(false);

  // Get calculated position based relative to legend button position
  const position = useLegendPosition(isOpen, ref.current);

  // Toggles the legend open/closed state
  const onToggle = useCallback(e => {
    e.stopPropagation();
    setIsOpen(!isOpen);
  }, [isOpen, setIsOpen]);

  // Closes the legend
  const onClose = useCallback(() => setIsOpen(false), [setIsOpen]);
  return {
    ref,
    isOpen,
    position,
    onClose,
    onToggle
  };
};