'use client';

import React, { useContext, useEffect } from 'react';

interface MenuContextType {
  isMenuOpen: boolean;
  isClosing: boolean;
  closeMenu: () => void;
  openMenu: () => void;
  startClosing: () => void;
  resetClosing: () => void;
}

const MenuContext = React.createContext<MenuContextType | undefined>(undefined);

interface MenuProviderProps {
  children: React.ReactNode;
}

export const MenuProvider = ({ children }: MenuProviderProps) => {
  const [isMenuOpen, setIsMenuOpen] = React.useState(false);
  const [isClosing, setIsClosing] = React.useState(false);

  const closeMenu = () => setIsMenuOpen(false);
  const openMenu = () => setIsMenuOpen(true);
  const startClosing = () => setIsClosing(true);
  const resetClosing = () => setIsClosing(false);

  useEffect(() => {
    if (isMenuOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isMenuOpen]);

  return (
    <MenuContext.Provider
      value={{
        isMenuOpen,
        openMenu,
        closeMenu,
        isClosing,
        startClosing,
        resetClosing,
      }}
    >
      {children}
    </MenuContext.Provider>
  );
};

export const useMenu = () => {
  const context = useContext(MenuContext);
  if (context === undefined) {
    throw new Error('useMenu must be used within a MenuProvider');
  }
  return context;
};
