import { createContext, FC, ReactNode, useContext } from 'react';

/**
 * Exposes the row index of the enclosing virtualised List item to descendants.
 * Ported from yagami `@aldenui/components/Context/ListItemContext` so the List
 * package stays self-contained.
 */
interface ListItemContextType {
  listId: number;
}

const ListItemContext = createContext<ListItemContextType | undefined>(undefined);

interface ListItemProviderProps {
  children: ReactNode;
  listId: number;
}

export const ListItemProvider: FC<ListItemProviderProps> = ({ children, listId }) => {
  return <ListItemContext.Provider value={{ listId }}>{children}</ListItemContext.Provider>;
};

/**
 * Read the enclosing list row's id. Returns `{ listId: -1 }` if called
 * outside a `ListItemProvider`.
 */
export const useListItem = () => {
  const context = useContext(ListItemContext);
  if (context === undefined) {
    return { listId: -1 };
  }
  return context;
};
