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

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

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

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

  // Auto-close on route change. Same pattern as useSidebarDrawer — keeps the
  // drawer from leaking between sessions when the user navigates.
  useEffect(() => {
    setOpen(false);
  }, [location.pathname]);

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

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

export function useRightRailDrawer(): RightRailDrawerState {
  const ctx = useContext(Ctx);
  if (!ctx) {
    // Soft fallback so consumers don't crash if rendered outside a provider.
    return { open: false, setOpen: () => {}, toggle: () => {} };
  }
  return ctx;
}
