import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { useLocation } from 'react-router-dom';

interface SidebarDrawerState {
  open: boolean;
  setOpen: (open: boolean) => void;
  toggle: () => void;
}

const Ctx = createContext<SidebarDrawerState | null>(null);

export function SidebarDrawerProvider({ children }: { children: ReactNode }) {
  const [open, setOpen] = useState(false);
  const location = useLocation();

  // Auto-close on navigation. Effect fires once on mount too (open default
  // is false, so no observable effect) and on every pathname change after.
  useEffect(() => {
    setOpen(false);
  }, [location.pathname]);

  const toggle = useCallback(() => setOpen((v) => !v), []);

  return <Ctx.Provider value={{ open, setOpen, toggle }}>{children}</Ctx.Provider>;
}

export function useSidebarDrawer(): SidebarDrawerState {
  const ctx = useContext(Ctx);
  if (!ctx) {
    // Soft fallback so consumers don't crash if rendered outside a provider.
    // In practice all top-level routes are inside the provider.
    return { open: false, setOpen: () => {}, toggle: () => {} };
  }
  return ctx;
}
