import { useState, useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import { SidebarState, SidebarContextType } from './sidebarTypes';

// Custom hook for sidebar logic
export const useSidebarLogic = (): SidebarContextType => {
  const location = useLocation();
  
  // Simple React state instead of state machine
  const [state, setState] = useState<SidebarState>({
    openItemId: null,
    isMinimized: false,
  });

  // Toggle a specific menu item
  const toggleItem = useCallback((itemId: string) => {
    setState(prevState => ({
      ...prevState,
      openItemId: prevState.openItemId === itemId ? null : itemId,
    }));
  }, []);

  // Close all submenus
  const closeAll = useCallback(() => {
    setState(prevState => ({
      ...prevState,
      openItemId: null,
    }));
  }, []);

  // Check if a specific item is open
  const isItemOpen = useCallback((itemId: string) => {
    return state.openItemId === itemId;
  }, [state.openItemId]);

  // Check if an item is the active route
  // Supports exact match and prefix match (for parent items when child route is active)
  const isItemActive = useCallback((itemPath?: string) => {
    if (!itemPath) return false;
    
    const currentPath = location.pathname;
    
    // Exact match
    if (currentPath === itemPath) return true;
    
    // Prefix match: check if current path starts with the item path
    // This highlights parent items when a child/subpage is active
    // Ensure we match at path segment boundaries (e.g., /admin matches /admin/users but not /administrator)
    if (currentPath.startsWith(itemPath)) {
      // Check if the next character is either '/' or end of string
      const nextChar = currentPath[itemPath.length];
      if (nextChar === '/' || nextChar === undefined) {
        return true;
      }
    }
    
    return false;
  }, [location.pathname]);

  // Minimize sidebar
  const minimizeSidebar = useCallback(() => {
    setState(prevState => ({
      ...prevState,
      isMinimized: true,
      // Keep submenus open when minimizing - submenu state is independent
    }));
  }, []);

  // Expand sidebar
  const expandSidebar = useCallback(() => {
    setState(prevState => ({
      ...prevState,
      isMinimized: false,
    }));
  }, []);

  return {
    state,
    toggleItem,
    closeAll,
    isItemOpen,
    isItemActive,
    minimizeSidebar,
    expandSidebar,
  };
}; 