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

interface TaskBriefingContextValue {
  isOpen: boolean;
  open: (taskId?: string) => void;
  close: () => void;
  initialTaskId: string | undefined;
}

const TaskBriefingContext = createContext<TaskBriefingContextValue | null>(null);

export function TaskBriefingProvider({ children }: { children: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);
  const [initialTaskId, setInitialTaskId] = useState<string | undefined>(undefined);

  const open = useCallback((taskId?: string) => {
    setInitialTaskId(taskId);
    setIsOpen(true);
  }, []);

  const close = useCallback(() => {
    setIsOpen(false);
  }, []);

  return (
    <TaskBriefingContext.Provider value={{ isOpen, open, close, initialTaskId }}>
      {children}
    </TaskBriefingContext.Provider>
  );
}

export function useTaskBriefing() {
  const ctx = useContext(TaskBriefingContext);
  if (!ctx) throw new Error('useTaskBriefing must be used inside TaskBriefingProvider');
  return ctx;
}
