import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';

type SidebarLayoutContextValue = {
  mobileOpen: boolean;
  openMobileSidebar: () => void;
  closeMobileSidebar: () => void;
};

const SidebarLayoutContext = createContext<SidebarLayoutContextValue | undefined>(undefined);

export const SidebarLayoutProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [mobileOpen, setMobileOpen] = useState(false);

  const openMobileSidebar = useCallback(() => setMobileOpen(true), []);
  const closeMobileSidebar = useCallback(() => setMobileOpen(false), []);

  const value = useMemo(
    () => ({ mobileOpen, openMobileSidebar, closeMobileSidebar }),
    [mobileOpen, openMobileSidebar, closeMobileSidebar]
  );

  return <SidebarLayoutContext.Provider value={value}>{children}</SidebarLayoutContext.Provider>;
};

export function useSidebarLayout(): SidebarLayoutContextValue {
  const context = useContext(SidebarLayoutContext);
  if (!context) {
    throw new Error('useSidebarLayout must be used within SidebarLayoutProvider');
  }
  return context;
}

export default SidebarLayoutContext;
