import {
  createContext,
  type FC,
  type MutableRefObject,
  type PropsWithChildren,
  useContext,
  useRef,
} from 'react';

type TaskVisitContextType = {
  visitedTaskIdRef: MutableRefObject<string | null>;
};

const TaskVisitContext = createContext<TaskVisitContextType | null>(null);

/**
 * Coordinates the `visitTask` call between `ServiceItemDetails` and `Comments.tsx`
 * so a single call is fired per task open. The owner of the actual call is the
 * component that has the most accurate information at hand:
 * - `Comments.tsx` (when it mounts) — knows the real read state of comments.
 * - `ServiceItemDetails` (fallback) — when `Comments` is not rendered (agent side
 *   with a tab other than `request`).
 */
export const TaskVisitProvider: FC<PropsWithChildren> = ({ children }) => {
  const visitedTaskIdRef = useRef<string | null>(null);
  return (
    <TaskVisitContext.Provider value={{ visitedTaskIdRef }}>
      {children}
    </TaskVisitContext.Provider>
  );
};

/**
 * Access the shared `visitedTaskIdRef` used to deduplicate `visitTask` calls
 * across `ServiceItemDetails` and `Comments.tsx`.
 *
 * **Constraint**: must be called inside a `TaskVisitProvider`. Any consumer of
 * this hook (currently `ServiceItemDetails` and `Comments.tsx`) must be
 * rendered as a descendant of `TaskVisitProvider`, otherwise this hook throws.
 * If `Comments.tsx` is reused outside of `ServiceItemDetails` (e.g. in a
 * standalone view or a test harness), wrap it in `TaskVisitProvider`.
 */
export const useTaskVisit = (): TaskVisitContextType => {
  const ctx = useContext(TaskVisitContext);
  if (!ctx) {
    throw new Error('useTaskVisit must be used within a TaskVisitProvider');
  }
  return ctx;
};
